prompt
stringlengths
19
879k
completion
stringlengths
3
53.8k
api
stringlengths
8
59
import numpy as np import rlkit.torch.pytorch_util as ptu from multiworld.core.image_env import normalize_image from rlkit.core.eval_util import create_stats_ordered_dict from rlkit.data_management.obs_dict_replay_buffer import flatten_dict from rlkit.data_management.shared_obs_dict_replay_buffer import \ SharedObsDictRelabelingBuffer from ROLL.LSTM_wrapped_env import LSTMWrappedEnv from rlkit.torch.vae.vae_trainer import ( compute_p_x_np_to_np, relative_probs_from_log_probs, ) import copy import cv2 class OnlineLSTMRelabelingBuffer(SharedObsDictRelabelingBuffer): def __init__( self, vae_ori, lstm_seg, *args, decoded_obs_key='image_observation', decoded_achieved_goal_key='image_achieved_goal', decoded_desired_goal_key='image_desired_goal', exploration_rewards_type='None', exploration_rewards_scale=1.0, vae_priority_type='None', start_skew_epoch=0, power=1.0, internal_keys=[], priority_function_kwargs=None, relabeling_goal_sampling_mode='vae_prior', observation_mode='original_image', **kwargs ): if internal_keys is None: internal_keys = [] for key in [ decoded_obs_key, decoded_achieved_goal_key, decoded_desired_goal_key ]: if key not in internal_keys: internal_keys.append(key) super().__init__(internal_keys=internal_keys, segmentation=True, *args, **kwargs) assert isinstance(self.env, LSTMWrappedEnv) self.vae = vae_ori self.lstm_seg = lstm_seg self.decoded_obs_key = decoded_obs_key self.decoded_obs_key_seg = decoded_obs_key + '_segmented' self.decoded_desired_goal_key = decoded_desired_goal_key self.decoded_achieved_goal_key = decoded_achieved_goal_key self.exploration_rewards_type = exploration_rewards_type self.exploration_rewards_scale = exploration_rewards_scale self.start_skew_epoch = start_skew_epoch self.vae_priority_type = vae_priority_type self.power = power self._relabeling_goal_sampling_mode = relabeling_goal_sampling_mode self._give_explr_reward_bonus = ( exploration_rewards_type != 'None' and exploration_rewards_scale != 0. ) self._exploration_rewards = np.zeros((self.max_size, 1)) self._prioritize_vae_samples = ( vae_priority_type != 'None' and power != 0. ) self._vae_sample_priorities = np.zeros((self.max_size, 1)) self._vae_sample_probs = None self._vae_sample_priorities_seg = np.zeros((self.max_size, 1)) self._vae_sample_probs_seg = None type_to_function = { 'vae_prob': self.vae_prob, 'None': self.no_reward, } self.exploration_reward_func = ( type_to_function[self.exploration_rewards_type] ) self.vae_prioritization_func = ( type_to_function[self.vae_priority_type] ) if priority_function_kwargs is None: self.priority_function_kwargs = dict() else: self.priority_function_kwargs = priority_function_kwargs self.epoch = 0 self._register_mp_array("_exploration_rewards") self._register_mp_array("_vae_sample_priorities") self._register_mp_array("_vae_sample_priorities_seg") self.observation_mode = observation_mode def add_path(self, path): self.add_decoded_vae_goals_to_path(path) super().add_path(path) def add_decoded_vae_goals_to_path(self, path): # decoding the self-sampled vae images should be done in batch (here) # rather than in the env for efficiency desired_goals = flatten_dict( path['observations'], [self.desired_goal_key] )[self.desired_goal_key] desired_decoded_goals = self.env._decode(desired_goals, self.env.lstm_segmented) desired_decoded_goals = desired_decoded_goals.reshape( len(desired_decoded_goals), -1 ) for idx, next_obs in enumerate(path['observations']): path['observations'][idx][self.decoded_desired_goal_key] = \ desired_decoded_goals[idx] path['next_observations'][idx][self.decoded_desired_goal_key] = \ desired_decoded_goals[idx] def get_diagnostics(self): if self._vae_sample_probs is None or self._vae_sample_priorities is None: stats = create_stats_ordered_dict( 'VAE Sample Weights', np.zeros(self._size), ) stats.update(create_stats_ordered_dict( 'VAE Sample Probs', np.zeros(self._size), )) else: vae_sample_priorities = self._vae_sample_priorities[:self._size] vae_sample_probs = self._vae_sample_probs[:self._size] stats = create_stats_ordered_dict( 'VAE Sample Weights', vae_sample_priorities, ) stats.update(create_stats_ordered_dict( 'VAE Sample Probs', vae_sample_probs, )) vae_sample_priorities_seg = self._vae_sample_priorities_seg[:self._size] vae_sample_probs_seg = self._vae_sample_probs_seg[:self._size] stats.update(create_stats_ordered_dict( 'VAE Seg Sample Probs', vae_sample_probs_seg, )) stats.update(create_stats_ordered_dict( 'VAE Seg Weights', vae_sample_priorities_seg, )) return stats def show_obs(self, normalized_img_vec_, name='img'): print(name) normalized_img_vec = copy.deepcopy(normalized_img_vec_) img = (normalized_img_vec * 255).astype(np.uint8) img = img.reshape(3, 48, 48).transpose() img = img[::-1, :, ::-1] cv2.imshow(name, img) cv2.waitKey() def refresh_latents(self, epoch, refresh_goals=False): self.epoch = epoch self.skew = (self.epoch > self.start_skew_epoch) batch_size = 512 next_idx = min(batch_size, self._size) if self.exploration_rewards_type == 'hash_count': # you have to count everything then compute exploration rewards cur_idx = 0 next_idx = min(batch_size, self._size) while cur_idx < self._size: idxs = np.arange(cur_idx, next_idx) normalized_imgs = ( normalize_image(self._next_obs[self.decoded_obs_key][idxs]) ) cur_idx = next_idx next_idx += batch_size next_idx = min(next_idx, self._size) cur_idx = 0 obs_sum = np.zeros(self.vae.representation_size) obs_square_sum = np.zeros(self.vae.representation_size) while cur_idx < self._size: idxs = np.arange(cur_idx, next_idx) if self.observation_mode == 'original_image': # NOTE yufei: observation should use env.vae_original (non-segmented images) self._obs[self.observation_key][idxs] = \ self.env._encode( normalize_image(self._obs[self.decoded_obs_key][idxs]), self.env.vae_original ) self._next_obs[self.observation_key][idxs] = \ self.env._encode( normalize_image(self._next_obs[self.decoded_obs_key][idxs]), self.env.vae_original ) elif self.observation_mode == 'segmentation_proprio_cross_weight': latent_dim = self.env.lstm_segmented.representation_size self._obs[self.observation_key][idxs][:, -latent_dim:] = \ self.env._encode_lstm( normalize_image(self._obs[self.decoded_obs_key_seg][idxs]), self.env.lstm_segmented ) self._next_obs[self.observation_key][idxs][:, -latent_dim:] = \ self.env._encode_lstm( normalize_image(self._next_obs[self.decoded_obs_key_seg][idxs]), self.env.lstm_segmented ) elif self.observation_mode == 'segmentation_proprio_conv_concat': # cur_obj_image = self._obs[self.decoded_desired_goal_key][idxs] # normalized_cur_obj_image = normalize_image(cur_obj_image) # cur_gripper_pos = self._obs['state_observation'] # cur_gripper_x = cur_gripper_pos[:, 0] # cur_gripper_y = cur_gripper_pos[:, 1] # segmented_object_with_gripper = np.concatenate([normalized_cur_obj_image, cur_gripper_x], axis=1) # segmented_object_with_gripper = np.concatenate([segmented_object_with_gripper, cur_gripper_y], axis=1) # self._obs[self.observation_key][idxs] = \ # self.env._encode( # segmented_object_with_gripper, self.env.vae_original # ) # next_obj_image = self._next_obs[self.decoded_desired_goal_key][idxs] # normalized_next_obj_image = normalize_image(next_obj_image) # next_gripper_pos = self._next_obs['state_observation'] # next_gripper_x = next_gripper_pos[:, 0] # next_gripper_y = next_gripper_pos[:, 1] # segmented_object_with_gripper = np.concatenate([normalized_next_obj_image, next_gripper_x], axis=1) # segmented_object_with_gripper = np.concatenate([segmented_object_with_gripper, next_gripper_y], axis=1) # self._next_obs[self.observation_key][idxs] = \ # self.env._encode( # segmented_object_with_gripper, self.env.vae_original # ) pass else: raise NotImplementedError # WARNING: we only refresh the desired/achieved latents for # "next_obs". This means that obs[desired/achieve] will be invalid, # so make sure there's no code that references this. # TODO: enforce this with code and not a comment # NOTE yufei: for desired_goal_key we use env.lstm_segmented if refresh_goals: # NOTE LSTM: if you really want to keep training LSTM during RL learning and re-encode the latent goals, # better store the hiddens (but hiddens also change, how to handle this?) self._next_obs[self.desired_goal_key][idxs] = \ self.env._encode_lstm( normalize_image(self._next_obs[self.decoded_desired_goal_key][idxs]), self.env.lstm_segmented ) self._next_obs[self.achieved_goal_key][idxs] = \ self.env._encode_lstm( normalize_image(self._next_obs[self.decoded_achieved_goal_key][idxs]), self.env.lstm_segmented ) if 'segmentation_proprio' not in self.observation_mode: normalized_imgs = ( normalize_image(self._next_obs[self.decoded_obs_key][idxs]) ) normalized_imgs_seg = ( normalize_image(self._next_obs[self.decoded_obs_key_seg][idxs]) ) if self._give_explr_reward_bonus: rewards = self.exploration_reward_func( normalized_imgs, idxs, **self.priority_function_kwargs ) self._exploration_rewards[idxs] = rewards.reshape(-1, 1) if self._prioritize_vae_samples: if ( self.exploration_rewards_type == self.vae_priority_type and self._give_explr_reward_bonus ): self._vae_sample_priorities[idxs] = ( self._exploration_rewards[idxs] ) else: # NOTE yufei: this is what actually being used. So I only updated this. self._vae_sample_priorities[idxs] = ( self.vae_prioritization_func( self.vae, normalized_imgs, idxs, **self.priority_function_kwargs ).reshape(-1, 1) ) obs_sum+= self._obs[self.observation_key][idxs][:, :self.vae.representation_size].sum(axis=0) obs_square_sum+= np.power(self._obs[self.observation_key][idxs][:, :self.vae.representation_size], 2).sum(axis=0) cur_idx = next_idx next_idx += batch_size next_idx = min(next_idx, self._size) self.vae.dist_mu = obs_sum/self._size self.vae.dist_std = np.sqrt(obs_square_sum/self._size - np.power(self.vae.dist_mu, 2)) if self._prioritize_vae_samples: """ priority^power is calculated in the priority function for image_bernoulli_prob or image_gaussian_inv_prob and directly here if not. """ if self.vae_priority_type == 'vae_prob': self._vae_sample_priorities[:self._size] = relative_probs_from_log_probs( self._vae_sample_priorities[:self._size] ) self._vae_sample_probs = self._vae_sample_priorities[:self._size] self._vae_sample_priorities_seg[:self._size] = relative_probs_from_log_probs( self._vae_sample_priorities_seg[:self._size] ) self._vae_sample_probs_seg = self._vae_sample_priorities_seg[:self._size] else: self._vae_sample_probs = self._vae_sample_priorities[:self._size] ** self.power self._vae_sample_probs_seg = self._vae_sample_priorities_seg[:self._size] ** self.power p_sum = np.sum(self._vae_sample_probs) assert p_sum > 0, "Unnormalized p sum is {}".format(p_sum) self._vae_sample_probs /= np.sum(self._vae_sample_probs) self._vae_sample_probs = self._vae_sample_probs.flatten() p_sum = np.sum(self._vae_sample_probs_seg) assert p_sum > 0, "Unnormalized p sum is {}".format(p_sum) self._vae_sample_probs_seg /= np.sum(self._vae_sample_probs_seg) self._vae_sample_probs_seg = self._vae_sample_probs_seg.flatten() def sample_weighted_indices(self, batch_size, key=None, skew=True): if key == 'image_observation_segmented': _vae_sample_probs = self._vae_sample_probs_seg else: _vae_sample_probs = self._vae_sample_probs if ( self._prioritize_vae_samples and _vae_sample_probs is not None and self.skew and skew ): indices = np.random.choice( len(_vae_sample_probs), batch_size, p=_vae_sample_probs, ) assert ( np.max(_vae_sample_probs) <= 1 and np.min(_vae_sample_probs) >= 0 ) else: indices = self._sample_indices(batch_size) return indices def _sample_goals_from_env(self, batch_size): self.env.goal_sampling_mode = self._relabeling_goal_sampling_mode return self.env.sample_goals(batch_size) def sample_buffer_goals(self, batch_size, skew=True, key='image_observation_segmented'): """ Samples goals from weighted replay buffer for relabeling or exploration. Returns None if replay buffer is empty. Example of what might be returned: dict( image_desired_goals: image_achieved_goals[weighted_indices], latent_desired_goals: latent_desired_goals[weighted_indices], ) """ if self._size == 0: return None weighted_idxs = self.sample_weighted_indices( batch_size, skew=skew ) # NOTE yufei: this is the original RLkit code, I think it does not make sense in the segmentation case, # because self.decoded_obs_key is just 'image_observation', which can not serve as the 'image_desired_goal' # here. # next_image_obs = normalize_image( # self._next_obs[self.decoded_obs_key][weighted_idxs] # ) next_latent_obs = self._next_obs[self.achieved_goal_key][weighted_idxs] next_img_obs = normalize_image( self._next_obs[key][weighted_idxs] ) # we should use the segmented images as the image_desired_goal # NOTE LSTM: if we ever want to change the key, remember to pass a key in! return { self.decoded_desired_goal_key: next_img_obs, self.desired_goal_key: next_latent_obs } def random_lstm_training_data(self, batch_size, key=None): if key is None: key = self.decoded_obs_key traj_idxes = np.random.randint(0, self._traj_num, batch_size) imlen = self._next_obs[key].shape[-1] data =
np.zeros((batch_size, self.max_path_length, imlen), dtype=np.uint8)
numpy.zeros
#%% import numpy as np import math import scipy from scipy.optimize import curve_fit from scipy.interpolate import interp1d from scipy.interpolate import CloughTocher2DInterpolator from scipy.integrate import quad import sys sys.path.append('../') import SQ_calcs # Constants pi = math.pi heV = 4.14e-15 # eV*s c = 2.99792e8 # m/s kbeV = 8.6173e-5 # eV/K keV = 8.6173e-5 # eV/K h = 6.626e-34 kb = 1.38065e-23 q = 1.60218e-19 #%% # This module contains functions for Photoluminescence data analysis and modeling def aipl(data, dark, grating): """ This function takes PL data in cts/second units and converts to AIPL based on a laser power and grating calibration file. Functionality is built in to handle both single and map files INPUTS: data - data matrix containing input wavelength and PL cts/sec data if m x 2 matrix, treats as single spectra file if m x n matrix, treats as map along m if n x m matrix, treats as map along n dark - can be 0 grating - specifies which grating used, a string either '500nm' or '1200nm' or '1200nm-InGaAs' OUTPUTS: aipl_data - data converted to absolute units , [=] photons/m^2-s-eV """ #Get grating calibration file, then calculate conversion factor def BBPhotonFluxPerNM(lam,T): a = 2*pi/(h**3*c**2)*((h*c/(lam*1e-9))**2/(np.exp((h*c/(lam*1e-9))/(kb*T))-1))*(h*c/(lam*1e-9)**2)*1e-9 return a if grating == '500nm': BB1050 = np.loadtxt('../../data/PLdata/grating_calibration_files/150 500' 'blaze BB files/BB 1050 10 um hole 10x SiCCD 532 LP' 'F No Duoscan Autoscanning_2.txt') BB_raw_photon_data = BB1050[:,1]/np.insert(BB1050[1:,0]-BB1050[:-1,0], 0,BB1050[1,0]-BB1050[0,0]) AbsFluxesPerNM = np.zeros(BB1050.shape[0]) Ts = 1050; for ii in range(BB1050.shape[0]): AbsFluxesPerNM[ii] = BBPhotonFluxPerNM(BB1050[ii,0],Ts+273.15) AbsPhotonRate = pi*(10/2*1e-6)**2*AbsFluxesPerNM #photons/sec-nm Conversion_factor = AbsPhotonRate/BB_raw_photon_data Ave_conv_factors = np.zeros([BB1050.shape[0],2]) Ave_conv_factors[:,0] = BB1050[:,0] Ave_conv_factors[:,1] = Conversion_factor f2 = interp1d(Ave_conv_factors[:,0], Ave_conv_factors[:,1], kind='cubic') elif grating == '1200nm': BB850 = np.loadtxt('../../data/PLdata/grating_calibration_files/BB 850C 10 um hole D0 10x 150 grating CCD 532 nm NoDS.txt') BB950 = np.loadtxt('../../data/PLdata/grating_calibration_files/BB 950C 10 um hole D0 10x 150 grating CCD 532 nm NoDS.txt') BB1050 = np.loadtxt('../../data/PLdata/grating_calibration_files/BB 1050C 10 um hole D0 10x 150 grating CCD 532 nm NoDS.txt') BB_raw_photon_data_1 = BB850[:,1]/np.insert(BB1050[1:,0]-BB1050[:-1,0], 0,BB1050[1,0]-BB1050[0,0]) BB_raw_photon_data_2 = BB950[:,1]/np.insert(BB1050[1:,0]-BB1050[:-1,0], 0,BB1050[1,0]-BB1050[0,0]) BB_raw_photon_data_3 = BB1050[:,1]/np.insert(BB1050[1:,0]-BB1050[:-1,0], 0,BB1050[1,0]-BB1050[0,0]) BB_raw_photon_data = np.array([BB_raw_photon_data_1,BB_raw_photon_data_2,BB_raw_photon_data_3]) AbsFluxesPerNM = np.zeros(BB_raw_photon_data.shape) for lam in range(len(BB_raw_photon_data_1)): tt = 0 for T in (850,950,1050): AbsFluxesPerNM[tt,lam] = BBPhotonFluxPerNM(BB850[lam,0],T+273.15) tt += 1 AbsPhotonRate = pi*(10/2*1e-6)**2*AbsFluxesPerNM #photons/sec-nm Conversion_factor = AbsPhotonRate/BB_raw_photon_data Ave_conv_factors = np.zeros([BB850.shape[0],2]) Ave_conv_factors[:,0] = BB850[:,0] Ave_conv_factors[:,1] = np.mean(Conversion_factor,0) f2 = interp1d(Ave_conv_factors[:,0], Ave_conv_factors[:,1], kind='cubic') elif grating == '1200nm-InGaAs': BB850 = np.loadtxt('../../data/PLdata/grating_calibration_files/Response_Synapse CCD2_784_150_Objective_x10_UV_0_Detector_Second_InjRej_Edge 785nm PL.txt') BB_raw_photon_data = BB850[:,1]/np.insert(BB850[1:,0]-BB850[:-1,0], 0,BB850[1,0]-BB850[0,0]) AbsFluxesPerNM = np.zeros(BB850.shape[0]) Ts = 850; for ii in range(BB850.shape[0]): AbsFluxesPerNM[ii] = BBPhotonFluxPerNM(BB850[ii,0],Ts+273.15) AbsPhotonRate = pi*(10/2*1e-6)**2*AbsFluxesPerNM #photons/sec-nm Conversion_factor = AbsPhotonRate/BB_raw_photon_data Ave_conv_factors =
np.zeros([BB850.shape[0],2])
numpy.zeros
# 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])
numpy.array
#!/usr/bin/env python # coding: utf-8 # In[1]: # Imports import random import sys import numpy as np import time import matplotlib.pyplot as plt import seaborn as sns import pandas as pd import torch.nn as nn import torch.optim as optim import torchvision.utils as vutils import matplotlib.animation as animation from IPython.display import HTML import model_v4_small as model import torch import keijzer_exogan as ke # initialize random seeds manualSeed = 999 random.seed(manualSeed) torch.manual_seed(manualSeed) #get_ipython().run_line_magic('matplotlib', 'inline') #get_ipython().run_line_magic('config', 'InlineBackend.print_figure_kwargs={\'facecolor\' : "w"} # Make sure the axis background of plots is white, this is usefull for the black theme in JupyterLab') # Initialize default seaborn layout sns.set_palette(sns.hls_palette(8, l=.3, s=.8)) sns.set(style='ticks') """ Local variables """ workers = 0 # Number of workers for dataloader, 0 when to_vram is enabled batch_size = 1 # using one image ofcourse image_size = 32 nz = 100 # size of latent vector n_iters = 1000 #25*10**3 # number of iterations to do for inpainting torch.backends.cudnn.benchmark=True # Uses udnn auto-tuner to find the best algorithm to use for your hardware, speeds up training by almost 50% lr = 1e-1 lamb1 = 1 #1e4 lamb2 = 1e-1 # 1 , total_loss = lamb1*loss_context + lamb2*loss_perceptual beta1 = 0.5 # Beta1 hyperparam for Adam optimizers selected_gpus = [3] # Number of GPUs available. Use 0 for CPU mode. #n_images = 500 inpaint_n_times = 15 save_array_results = True load_array_results = False filename = 'debug_0_1000_1e-1_15_wgan_simple' # 0:100 lamb1=10, lamb2=1 # debug_0_5000_1_1e-1_* c is exogan data with original brian mask, d is with binary mask # In[2]: path = '/datb/16011015/ExoGAN_data/selection//' #notice how you dont put the last folder in here... # # Load all ASPAs images = np.load(path+'last_chunks_25_percent_images_v4.npy').astype('float32') np.random.shuffle(images) len(images) # np.save(path+'last_chunks_mini_selection.npy', images[:3000]) # # Load smaller selection of ASPAs # In[3]: #images = np.load(path+'last_chunks_25_percent_images_v4.1.npy') # 4.1 is a random selection of 5k images images = np.load(path+'last_chunks_25_percent_images_v4.2.npy') print('Loaded %s images' % len(images)) print('Batch size: ', batch_size) # Number of training epochs # Learning rate for optimizers ngpu = len(selected_gpus) print('Number of GPUs used: ', ngpu) """ Load data and prepare DataLoader """ shuffle = False if shuffle: np.random.shuffle(images) # shuffles the images images = images[0:1000] n_images = len(images) #images = images[:int(len(images)*0.005)] print('Number of images: ', n_images) dataset = ke.numpy_dataset(data=images, to_vram=True) # to_vram pins it to all GPU's #dataset = numpy_dataset(data=images, to_vram=True, transform=transforms.Compose([transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])) # to_vram pins it to all GPU's # Create the dataloader dataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, shuffle=True, num_workers=workers, pin_memory=False) # In[4]: """ Load and setup models """ # Initialize cuda device = torch.device("cuda:"+str(selected_gpus[0]) if (torch.cuda.is_available() and ngpu > 0) else "cpu") # Load models, set to evaluation mode since training is not needed (this also allows batchsize 1 to work with batchnorm2d layers) netG = model.Generator(ngpu).eval().to(device) netD = model.Discriminator(ngpu).eval().to(device) # Apply weights print('Loading weights...') try: # Load saved weights netG.load_state_dict(torch.load('gan_data//weights//netG_state_dict_wgan_model_v4_small', map_location=device)) #net.module..load_... for parallel model , net.load_... for single gpu model netD.load_state_dict(torch.load('gan_data//weights//netD_state_dict_wgan_model_v4_small', map_location=device)) except: print('Could not load saved weights.') sys.exit() """ Define input training stuff (fancy this up) """ G = netG D = netD z = torch.randn(1, nz, 1, 1, requires_grad=True, device=device) # Handle multi-gpu if desired if (device.type == 'cuda') and (ngpu > 1): G = nn.DataParallel(G, device_ids=selected_gpus, output_device=device) D = nn.DataParallel(D, device_ids=selected_gpus, output_device=device) #z = nn.DataParallel(z, device_ids=selected_gpus, output_device=device) # Setup Adam optimizers for both G and D optimizerD = optim.Adam(netD.parameters(), lr=lr, betas=(beta1, 0.999)) # should be sgd optimizerG = optim.Adam(netG.parameters(), lr=lr, betas=(beta1, 0.999)) print('done') # # Show generated images # In[ ]: from sklearn.preprocessing import MinMaxScaler z_tests = [torch.randn(1, nz, 1, 1, device=device) for _ in range(9)] #plt.figure(figsize=(10,10)) for i in range(9): img = G(z_tests[i]).detach().cpu()[0, 0, :, :] #plt.subplot(3,3,i+1) #scaler = MinMaxScaler((0, 1.2)) #img = scaler.fit_transform(img) #plt.imshow(img, cmap='gray', vmin=-1.2, vmax=1.2) #plt.imshow(img, cmap='gray') #plt.tight_layout() img.min(), img.max(), img.mean(), img.std() # # Show first 9 selected images # In[ ]: #plt.figure(figsize=(10,10)) for i in range(9): try: img = images[i] #plt.subplot(3,3,i+1) #plt.imshow(img[0, :, :], cmap='gray', vmin=-1.2, vmax=1.2) except: pass #plt.tight_layout() img.min(), img.max(), img.mean(), img.std() # # Visualizing the weights # In[ ]: weights = [param.data.cpu().numpy().flatten() for param in netD.parameters()] """ plt.figure(figsize=(10,10)) for i,layer_weights in enumerate(weights): print('Layer: %s \t n_weights: %s \t std: %.4f \t mean: %.4f' % (i, len(layer_weights), layer_weights.std(), layer_weights.mean())) plt.subplot(3,2,i+1) plt.title('netD layer %s weights' % i) plt.hist(layer_weights, bins=100) plt.grid() plt.tight_layout() """ # In[ ]: weights = [param.data.cpu().numpy().flatten() for param in netG.parameters()] # where param.data are the weights of the i-th layer """ plt.figure(figsize=(10,10)) for i,layer_weights in enumerate(weights): print('Layer: %s \t n_weights: %s \t std: %.4f \t mean: %.4f' % (i, len(layer_weights), layer_weights.std(), layer_weights.mean())) plt.subplot(3,2,i+1) plt.title('netG layer %s weights' % i) plt.hist(layer_weights, bins=100) plt.grid() plt.tight_layout() """ # # Inpainting # The corrupted image $y$ is mapped to the closest $z$ in the latent representation space, this mapping is denoted as $\hat{z}$. # # $\hat{z} = \operatorname{arg\,min}_z \{ \mathcal{L}_c(z |y, M) + \mathcal{L}_p (z) \}$ # # where # # $\mathcal{L}_c(z |y, M) = || M \bigodot G(z) - M \bigodot y||_1 = || M \bigodot (G(z)-y) ||_1 $ # # with $\mathcal{L}_c$ being contextual loss and $M$ being a binary mask with the same size as $y$, # # $\mathcal{L}_p (z) = \lambda \operatorname{log}(1-D(G(z)))$ # # with $\mathcal{L}_p$ being perceptual loss and $D$ being the discriminator. # # Once $G(\hat{z})$ is generated, the final solution $\hat{x}$ is calculated as # # $\hat{x} = \operatorname{arg\, min}_x ||\nabla x - \nabla G(\hat{z}) ||^2_2$ # # (substitute $x_i = y_i$ for $M_i = 1$). # # ----- # # $|| ... ||$ is done by `torch.norm()`. # $... \bigodot ...$ is done by `torch.mul()`. # ----- # TODO: Implement $\hat{x} = \operatorname{arg\, min}_x ||\nabla x - \nabla G(\hat{z}) ||^2_2$ # Currently $\hat{x} = G(\hat{z}) \bigodot (1 -M)+y$ # ## Create the mask # In[ ]: def create_mask(): mask = np.full([1,1,32,32], 1) # init array with 0.5's mask = torch.from_numpy(mask).to(device) #mask = torch.ones([1, 1, 32, 32]).to(device) # create mask with 1's in the shape of image #print("mask.shape", mask.shape) # use a random 'easy' mask # set all params to 0 mask[:, :, :16, 25:] = 0 # set noise to 0 mask[:, :, 18:, :] = 0 """Weighted mask""" # Normalization factors mask[:, :, 16:18, :] = 6 #6 # Planet mass mask[:, :, :16, 25:26] = 0 mask = mask.float() # make sure dtype is float, torch was complaining during inpainting that this is a double return mask # In[ ]: m = create_mask().cpu()[0, 0, :, :] #plt.imshow(m, cmap='gray', vmin=0, vmax=2) # # Inpaiting functions # In[ ]: def save_inpainting_results(): # save real aspa's all_reals = [] for selected_aspa in range(len(real_images)): reals = np.array([real_images[selected_aspa][i].detach().cpu().numpy()[0, 0, :, :] for i in range(inpaint_n_times)]) all_reals.append(reals) all_reals = np.array(all_reals) np.save('gan_data//val_errors//'+filename+'_reals.npy', all_reals) # save inpained aspa's all_inpainteds = [] for selected_aspa in range(len(real_images)): inpainteds = np.array([final_inpainted_images[selected_aspa][i].detach().cpu().numpy()[0, 0, :, :] for i in range(inpaint_n_times)]) all_inpainteds.append(inpainteds) all_inpainteds = np.array(all_inpainteds) np.save('gan_data//val_errors//'+filename+'_inpainteds.npy', all_inpainteds) np.save('gan_data//val_errors//'+filename+'_n_iterations.npy', n_iteration)
np.save('gan_data//val_errors//'+filename+'_contextual_losses.npy', contextual_losses)
numpy.save
# -*- coding: utf-8 -*- """ @author: <NAME> <<EMAIL>> """ import numpy as np import random from sklearn.base import BaseEstimator, ClassifierMixin from scipy.optimize import fmin_l_bfgs_b from sklearn.gaussian_process.gpc import _BinaryGaussianProcessClassifierLaplace as BinaryGPC from sklearn.gaussian_process.kernels import Matern, RBF, ConstantKernel as C __all__ = ['SharedKernelClassifier'] class SharedKernelClassifier(BaseEstimator, ClassifierMixin): def __init__(self, n_iter=100, kernel='rbf', ard=True, ardinit=True, n_restarts=0, model_batch_size=None, verbose=False): # Check and store parameters assert n_iter > 0 assert n_restarts >= 0 assert kernel in ['rbf', 'matern52', 'matern32'] assert type(ard) is bool self.n_iter = n_iter self.n_restarts = n_restarts self.kernel = kernel self.ard = ard self.ardinit = ardinit self.verbose = verbose self.model_batch_size = model_batch_size # Container for the sub models self.models_ = dict() # Stores likelihoods of optimizations self.convergence_ = list() @property def classes_(self): return list(self.models_.keys()) @property def log_likelihood_(self): likelihood = list() for m in self.models_.values(): likelihood.append(m.log_marginal_likelihood()) return
np.mean(likelihood)
numpy.mean
import numpy as np from alg_parameters import * from util import swap_flat class Runner(object): """Run multiple episode in multiprocessing environments.""" def __init__(self, env, model): """Initialize environments""" self.env = env self.model = model self.episode_rewards = np.zeros((N_ENVS,)) self.env.reset() self.obs = env.get_obs() self.state = env.get_state() self.state = np.repeat(self.state, N_AGENTS, axis=1) self.cent_state = np.concatenate((self.obs, self.state), axis=-1) self.dones = [False for _ in range(N_ENVS)] self.actor_hidden_state_c = np.zeros((N_ENVS * N_AGENTS, ACTOR_LAYER2)) self.actor_hidden_state_h = np.zeros((N_ENVS * N_AGENTS, ACTOR_LAYER2)) self.critic_hidden_state_c = np.zeros((N_ENVS * N_AGENTS, CRITIC_LAYER2)) self.critic_hidden_state_h = np.zeros((N_ENVS * N_AGENTS, CRITIC_LAYER2)) def run(self): # Use to store experiences mb_obs, mb_cent_state, mb_rewards, mb_values, mb_dones, \ ep_infos, mb_actions, mb_ps = [], [], [], [], [], [], [], [] mb_actor_hidden_state_c, mb_actor_hidden_state_h, \ mb_critic_hidden_state_c, mb_critic_hidden_state_h = [], [], [], [] episode_rewrads_info = [] for _ in range(N_STEPS): mb_obs.append(self.obs) mb_cent_state.append(self.cent_state) mb_actor_hidden_state_c.append(self.actor_hidden_state_c) mb_critic_hidden_state_c.append(self.critic_hidden_state_c) mb_actor_hidden_state_h.append(self.actor_hidden_state_h) mb_critic_hidden_state_h.append(self.critic_hidden_state_h) valid_action = self.env.get_avail_actions() actions, values, ps, critic_hidden_state, actor_hidden_state = self.model.step(self.obs, self.cent_state, valid_action, self.critic_hidden_state_c, self.critic_hidden_state_h, self.actor_hidden_state_c, self.actor_hidden_state_h) self.critic_hidden_state_c, self.critic_hidden_state_h = critic_hidden_state self.actor_hidden_state_c, self.actor_hidden_state_h = actor_hidden_state mb_values.append(values) mb_ps.append(ps) mb_actions.append(actions) mb_dones.append(self.dones) rewards, self.dones, infos = self.env.step(actions) self.obs = self.env.get_obs() self.state = self.env.get_state() self.state = np.repeat(self.state, N_AGENTS, axis=1) self.cent_state = np.concatenate((self.obs, self.state), axis=-1) self.episode_rewards += rewards true_index = np.argwhere(self.dones) if len(true_index) != 0: # Initialize memory true_index = np.squeeze(true_index) self.actor_hidden_state_c = np.reshape(self.actor_hidden_state_c, (-1, N_AGENTS, ACTOR_LAYER2)) self.actor_hidden_state_h = np.reshape(self.actor_hidden_state_h, (-1, N_AGENTS, ACTOR_LAYER2)) self.critic_hidden_state_c = np.reshape(self.critic_hidden_state_c, (-1, N_AGENTS, CRITIC_LAYER2)) self.critic_hidden_state_h = np.reshape(self.critic_hidden_state_h, (-1, N_AGENTS, CRITIC_LAYER2)) self.actor_hidden_state_c[true_index] = np.zeros(self.actor_hidden_state_c[true_index].shape) self.actor_hidden_state_h[true_index] = np.zeros(self.actor_hidden_state_h[true_index].shape) self.critic_hidden_state_c[true_index] = np.zeros(self.critic_hidden_state_c[true_index].shape) self.critic_hidden_state_h[true_index] = np.zeros(self.critic_hidden_state_h[true_index].shape) self.actor_hidden_state_c = np.reshape(self.actor_hidden_state_c, (-1, ACTOR_LAYER2)) self.actor_hidden_state_h = np.reshape(self.actor_hidden_state_h, (-1, ACTOR_LAYER2)) self.critic_hidden_state_c = np.reshape(self.critic_hidden_state_c, (-1, CRITIC_LAYER2)) self.critic_hidden_state_h = np.reshape(self.critic_hidden_state_h, (-1, CRITIC_LAYER2)) # Record information of the episode when it ends episode_rewrads_info.append(np.nanmean(self.episode_rewards[true_index])) self.episode_rewards[true_index] = np.zeros(self.episode_rewards[true_index].shape) if true_index.shape == (): ep_infos.append(infos[true_index]) else: for item in true_index: ep_infos.append(infos[item]) mb_rewards.append(rewards) mb_obs = np.asarray(mb_obs, dtype=np.float32) mb_cent_state = np.asarray(mb_cent_state, dtype=np.float32) mb_rewards = np.asarray(mb_rewards, dtype=np.float32) mb_rewards = np.expand_dims(mb_rewards, axis=-1) mb_rewards = np.repeat(mb_rewards, N_AGENTS, axis=-1) mb_values = np.asarray(mb_values, dtype=np.float32) mb_dones = np.asarray(mb_dones, dtype=np.bool) mb_actions =
np.asarray(mb_actions, dtype=np.int32)
numpy.asarray
""" This module is an example of a barebones function plugin for napari It implements the ``napari_experimental_provide_function`` hook specification. see: https://napari.org/docs/dev/plugins/hook_specifications.html Replace code below according to your needs. """ from __future__ import print_function, division from typing import TYPE_CHECKING, DefaultDict from unicodedata import name import six # import modules import sys # input, output, errors, and files import os # interacting with file systems import time # getting time import datetime import inspect # get passed parameters import yaml # parameter importing import json # for importing tiff metadata try: import cPickle as pickle # loading and saving python objects except: import pickle import numpy as np # numbers package import struct # for interpretting strings as binary data import re # regular expressions from pprint import pprint # for human readable file output import traceback # for error messaging import warnings # error messaging import copy # not sure this is needed import h5py # working with HDF5 files import pandas as pd import networkx as nx import collections # scipy and image analysis from scipy.signal import find_peaks_cwt # used in channel finding from scipy.optimize import curve_fit # fitting ring profile from scipy.optimize import leastsq # fitting 2d gaussian from scipy import ndimage as ndi # labeling and distance transform from skimage import io from skimage import segmentation # used in make_masks and segmentation from skimage.transform import rotate from skimage.feature import match_template # used to align images from skimage.feature import blob_log # used for foci finding from skimage.filters import threshold_otsu, median # segmentation from skimage import filters from skimage import morphology # many functions is segmentation used from this from skimage.measure import regionprops # used for creating lineages from skimage.measure import profile_line # used for ring an nucleoid analysis from skimage import util, measure, transform, feature import tifffile as tiff from sklearn import metrics # deep learning import tensorflow as tf # ignore message about how tf was compiled from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.keras import models from tensorflow.keras import losses from tensorflow.keras import utils from tensorflow.keras import backend as K # os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # supress warnings # Parralelization modules import multiprocessing from multiprocessing import Pool # Plotting for debug import matplotlib as mpl font = {'family' : 'sans-serif', 'weight' : 'normal', 'size' : 12} mpl.rc('font', **font) mpl.rcParams['pdf.fonttype'] = 42 from matplotlib.patches import Ellipse from pathlib import Path import time import matplotlib.pyplot as plt # import modules import os import glob import re import numpy as np import tifffile as tiff import pims_nd2 from skimage import io, measure, morphology import tifffile as tiff from scipy import stats from pprint import pprint # for human readable file output import multiprocessing from multiprocessing import Pool import numpy as np import warnings from tensorflow.python.keras import models from enum import Enum import numpy as np import multiprocessing from multiprocessing import Pool import os from napari_plugin_engine import napari_hook_implementation from skimage.filters import threshold_otsu # segmentation from skimage import morphology # many functions is segmentation used from this from skimage import segmentation # used in make_masks and segmentation from scipy import ndimage as ndi # labeling and distance transform import matplotlib.gridspec as gridspec from skimage.exposure import rescale_intensity # for displaying in GUI from skimage import io, morphology, segmentation # import mm3_helpers as mm3 import napari # This is the actual plugin function, where we export our function # (The functions themselves are defined below) @napari_hook_implementation def napari_experimental_provide_function(): # we can return a single function # or a tuple of (function, magicgui_options) # or a list of multiple functions with or without options, as shown here: #return [Segment, threshold, image_arithmetic] return [Compile, ChannelPicker, Segment] # 1. First example, a simple function that thresholds an image and creates a labels layer def threshold(data: "napari.types.ImageData", threshold: int) -> "napari.types.LabelsData": """Threshold an image and return a mask.""" return (data > threshold).astype(int) # print a warning def warning(*objs): print(time.strftime("%H:%M:%S WARNING:", time.localtime()), *objs, file=sys.stderr) # print information def information(*objs): print(time.strftime("%H:%M:%S", time.localtime()), *objs, file=sys.stdout) def julian_day_number(): """ Need this to solve a bug in pims_nd2.nd2reader.ND2_Reader instance initialization. The bug is in /usr/local/lib/python2.7/site-packages/pims_nd2/ND2SDK.py in function `jdn_to_datetime_local`, when the year number in the metadata (self._lim_metadata_desc) is not in the correct range. This causes a problem when calling self.metadata. https://en.wikipedia.org/wiki/Julian_day """ dt=datetime.datetime.now() tt=dt.timetuple() jdn=(1461.*(tt.tm_year + 4800. + (tt.tm_mon - 14.)/12))/4. + (367.*(tt.tm_mon - 2. - 12.*((tt.tm_mon -14.)/12)))/12. - (3.*((tt.tm_year + 4900. + (tt.tm_mon - 14.)/12.)/100.))/4. + tt.tm_mday - 32075 return jdn def get_plane(filepath): pattern = r'(c\d+).tif' res = re.search(pattern,filepath) if (res != None): return res.group(1) else: return None def get_fov(filepath): pattern = r'xy(\d+)\w*.tif' res = re.search(pattern,filepath) if (res != None): return int(res.group(1)) else: return None def get_time(filepath): pattern = r't(\d+)xy\w+.tif' res = re.search(pattern,filepath) if (res != None): return np.int_(res.group(1)) else: return None # loads and image stack from TIFF or HDF5 using mm3 conventions def load_stack(fov_id, peak_id, color='c1', image_return_number=None): ''' Loads an image stack. Supports reading TIFF stacks or HDF5 files. Parameters ---------- fov_id : int The FOV id peak_id : int The peak (channel) id. Dummy None value incase color='empty' color : str The image stack type to return. Can be: c1 : phase stack cN : where n is an integer for arbitrary color channel sub : subtracted images seg : segmented images empty : get the empty channel for this fov, slightly different Returns ------- image_stack : np.ndarray The image stack through time. Shape is (t, y, x) ''' # things are slightly different for empty channels if 'empty' in color: if params['output'] == 'TIFF': img_filename = params['experiment_name'] + '_xy%03d_%s.tif' % (fov_id, color) with tiff.TiffFile(os.path.join(params['empty_dir'],img_filename)) as tif: img_stack = tif.asarray() if params['output'] == 'HDF5': with h5py.File(os.path.join(params['hdf5_dir'],'xy%03d.hdf5' % fov_id), 'r') as h5f: img_stack = h5f[color][:] return img_stack # load normal images for either TIFF or HDF5 if params['output'] == 'TIFF': if color[0] == 'c': img_dir = params['chnl_dir'] elif 'sub' in color: img_dir = params['sub_dir'] elif 'foci' in color: img_dir = params['foci_seg_dir'] elif 'seg' in color: img_dir = params['seg_dir'] img_filename = params['experiment_name'] + '_xy%03d_p%04d_%s.tif' % (fov_id, peak_id, color) with tiff.TiffFile(os.path.join(img_dir, img_filename)) as tif: img_stack = tif.asarray() if params['output'] == 'HDF5': with h5py.File(os.path.join(params['hdf5_dir'], 'xy%03d.hdf5' % fov_id), 'r') as h5f: # normal naming # need to use [:] to get a copy, else it references the closed hdf5 dataset img_stack = h5f['channel_%04d/p%04d_%s' % (peak_id, peak_id, color)][:] return img_stack # load the time table and add it to the global params def load_time_table(): '''Add the time table dictionary to the params global dictionary. This is so it can be used during Cell creation. ''' # try first for yaml, then for pkl try: with open(os.path.join(params['ana_dir'], 'time_table.yaml'), 'rb') as time_table_file: params['time_table'] = yaml.safe_load(time_table_file) except: with open(os.path.join(params['ana_dir'], 'time_table.pkl'), 'rb') as time_table_file: params['time_table'] = pickle.load(time_table_file) return # function for loading the channel masks def load_channel_masks(): '''Load channel masks dictionary. Should be .yaml but try pickle too. ''' information("Loading channel masks dictionary.") # try loading from .yaml before .pkl try: information('Path:', os.path.join(params['ana_dir'], 'channel_masks.yaml')) with open(os.path.join(params['ana_dir'], 'channel_masks.yaml'), 'r') as cmask_file: channel_masks = yaml.safe_load(cmask_file) except: warning('Could not load channel masks dictionary from .yaml.') try: information('Path:', os.path.join(params['ana_dir'], 'channel_masks.pkl')) with open(os.path.join(params['ana_dir'], 'channel_masks.pkl'), 'rb') as cmask_file: channel_masks = pickle.load(cmask_file) except ValueError: warning('Could not load channel masks dictionary from .pkl.') return channel_masks # function for loading the specs file def load_specs(): '''Load specs file which indicates which channels should be analyzed, used as empties, or ignored.''' try: with open(os.path.join(params['ana_dir'], 'specs.yaml'), 'r') as specs_file: specs = yaml.safe_load(specs_file) except: try: with open(os.path.join(params['ana_dir'], 'specs.pkl'), 'rb') as specs_file: specs = pickle.load(specs_file) except ValueError: warning('Could not load specs file.') return specs ### functions for dealing with raw TIFF images # get params is the major function which processes raw TIFF images def get_initial_tif_params(image_filename): '''This is a function for getting the information out of an image for later trap identification, cropping, and aligning with Unet. It loads a tiff file and pulls out the image metadata. it returns a dictionary like this for each image: 'filename': image_filename, 'fov' : image_metadata['fov'], # fov id 't' : image_metadata['t'], # time point 'jdn' : image_metadata['jdn'], # absolute julian time 'x' : image_metadata['x'], # x position on stage [um] 'y' : image_metadata['y'], # y position on stage [um] 'plane_names' : image_metadata['plane_names'] # list of plane names Called by mm3_Compile.py __main__ Calls mm3.extract_metadata mm3.find_channels ''' try: # open up file and get metadata with tiff.TiffFile(os.path.join(params['TIFF_dir'],image_filename)) as tif: image_data = tif.asarray() #print(image_data.shape) # uncomment for debug #if len(image_data.shape) == 2: # img_shape = [image_data.shape[0],image_data.shape[1]] #else: img_shape = [image_data.shape[1],image_data.shape[2]] plane_list = [str(i+1) for i in range(image_data.shape[0])] #print(plane_list) # uncomment for debug if params['TIFF_source'] == 'elements': image_metadata = get_tif_metadata_elements(tif) elif params['TIFF_source'] == 'nd2ToTIFF': image_metadata = get_tif_metadata_nd2ToTIFF(tif) else: image_metadata = get_tif_metadata_filename(tif) information('Analyzed %s' % image_filename) # return the file name, the data for the channels in that image, and the metadata return {'filepath': os.path.join(params['TIFF_dir'], image_filename), 'fov' : image_metadata['fov'], # fov id 't' : image_metadata['t'], # time point 'jd' : image_metadata['jd'], # absolute julian time 'x' : image_metadata['x'], # x position on stage [um] 'y' : image_metadata['y'], # y position on stage [um] 'planes' : plane_list, # list of plane names 'shape' : img_shape} # image shape x y in pixels except: warning('Failed get_params for ' + image_filename.split("/")[-1]) print(sys.exc_info()[0]) print(sys.exc_info()[1]) print(traceback.print_tb(sys.exc_info()[2])) return {'filepath': os.path.join(params['TIFF_dir'],image_filename), 'analyze_success': False} # get params is the major function which processes raw TIFF images def get_tif_params(image_filename, find_channels=True): '''This is a damn important function for getting the information out of an image. It loads a tiff file, pulls out the image data, and the metadata, including the location of the channels if flagged. it returns a dictionary like this for each image: 'filename': image_filename, 'fov' : image_metadata['fov'], # fov id 't' : image_metadata['t'], # time point 'jdn' : image_metadata['jdn'], # absolute julian time 'x' : image_metadata['x'], # x position on stage [um] 'y' : image_metadata['y'], # y position on stage [um] 'plane_names' : image_metadata['plane_names'] # list of plane names 'channels': cp_dict, # dictionary of channel locations, in the case of Unet-based channel segmentation, it's a dictionary of channel labels Called by mm3_Compile.py __main__ Calls mm3.extract_metadata mm3.find_channels ''' try: # open up file and get metadata with tiff.TiffFile(os.path.join(params['TIFF_dir'],image_filename)) as tif: image_data = tif.asarray() if params['TIFF_source'] == 'elements': image_metadata = get_tif_metadata_elements(tif) elif params['TIFF_source'] == 'nd2ToTIFF': image_metadata = get_tif_metadata_nd2ToTIFF(tif) else: image_metadata = get_tif_metadata_filename(tif) # look for channels if flagged if find_channels: # fix the image orientation and get the number of planes image_data = fix_orientation(image_data) # if the image data has more than 1 plane restrict image_data to phase, # which should have highest mean pixel data if len(image_data.shape) > 2: #ph_index = np.argmax([np.mean(image_data[ci]) for ci in range(image_data.shape[0])]) ph_index = int(params['phase_plane'][1:]) - 1 image_data = image_data[ph_index] # get shape of single plane img_shape = [image_data.shape[0], image_data.shape[1]] # find channels on the processed image chnl_loc_dict = find_channel_locs(image_data) information('Analyzed %s' % image_filename) # return the file name, the data for the channels in that image, and the metadata return {'filepath': os.path.join(params['TIFF_dir'], image_filename), 'fov' : image_metadata['fov'], # fov id 't' : image_metadata['t'], # time point 'jd' : image_metadata['jd'], # absolute julian time 'x' : image_metadata['x'], # x position on stage [um] 'y' : image_metadata['y'], # y position on stage [um] 'planes' : image_metadata['planes'], # list of plane names 'shape' : img_shape, # image shape x y in pixels # 'channels' : {1 : {'A' : 1, 'B' : 2}, 2 : {'C' : 3, 'D' : 4}}} 'channels' : chnl_loc_dict} # dictionary of channel locations except: warning('Failed get_params for ' + image_filename.split("/")[-1]) print(sys.exc_info()[0]) print(sys.exc_info()[1]) print(traceback.print_tb(sys.exc_info()[2])) return {'filepath': os.path.join(params['TIFF_dir'],image_filename), 'analyze_success': False} # finds metdata in a tiff image which has been expoted with Nikon Elements. def get_tif_metadata_elements(tif): '''This function pulls out the metadata from a tif file and returns it as a dictionary. This if tiff files as exported by Nikon Elements as a stacked tiff, each for one tpoint. tif is an opened tif file (using the package tifffile) arguments: fname (tifffile.TiffFile): TIFF file object from which data will be extracted returns: dictionary of values: 'jdn' (float) 'x' (float) 'y' (float) 'plane_names' (list of strings) Called by mm3.Compile ''' # image Metadata idata = { 'fov': -1, 't' : -1, 'jd': -1 * 0.0, 'x': -1 * 0.0, 'y': -1 * 0.0, 'planes': []} # get the fov and t simply from the file name idata['fov'] = int(tif.fname.split('xy')[1].split('.tif')[0]) idata['t'] = int(tif.fname.split('xy')[0].split('t')[-1]) # a page is plane, or stack, in the tiff. The other metdata is hidden down in there. for page in tif: for tag in page.tags.values(): #print("Checking tag",tag.name,tag.value) t = tag.name, tag.value t_string = u"" time_string = u"" # Interesting tag names: 65330, 65331 (binary data; good stuff), 65332 # we wnat to work with the tag of the name 65331 # if the tag name is not in the set of tegs we find interesting then skip this cycle of the loop if tag.name not in ('65331', '65332', 'strip_byte_counts', 'image_width', 'orientation', 'compression', 'new_subfile_type', 'fill_order', 'max_sample_value', 'bits_per_sample', '65328', '65333'): #print("*** " + tag.name) #print(tag.value) pass #if tag.name == '65330': # return tag.value if tag.name in ('65331'): # make info list a list of the tag values 0 to 65535 by zipoing up a paired list of two bytes, at two byte intervals i.e. fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b # note that 0X100 is hex for 256 infolist = [a+b*0x100 for a,b in zip(tag.value[0::2], tag.value[1::2])] # get char values for each element in infolist for c_entry in range(0, len(infolist)): # the element corresponds to an ascii char for a letter or bracket (and a few other things) if infolist[c_entry] < 127 and infolist[c_entry] > 64: # add the letter to the unicode string t_string t_string += chr(infolist[c_entry]) #elif infolist[c_entry] == 0: # continue else: t_string += " " # this block will find the dTimeAbsolute and print the subsequent integers # index 170 is counting seconds, and rollover of index 170 leads to increment of index 171 # rollover of index 171 leads to increment of index 172 # get the position of the array by finding the index of the t_string at which dTimeAbsolute is listed not that 2*len(dTimeAbsolute)=26 #print(t_string) arraypos = t_string.index("dXPos") * 2 + 16 xarr = tag.value[arraypos:arraypos+4] b = ''.join(chr(i) for i in xarr) idata['x'] = float(struct.unpack('<f', b)[0]) arraypos = t_string.index("dYPos") * 2 + 16 yarr = tag.value[arraypos:arraypos+4] b = ''.join(chr(i) for i in yarr) idata['y'] = float(struct.unpack('<f', b)[0]) arraypos = t_string.index("dTimeAbsolute") * 2 + 26 shortarray = tag.value[arraypos+2:arraypos+10] b = ''.join(chr(i) for i in shortarray) idata['jd'] = float(struct.unpack('<d', b)[0]) # extract plane names il = [a+b*0x100 for a,b in zip(tag.value[0::2], tag.value[1::2])] li = [a+b*0x100 for a,b in zip(tag.value[1::2], tag.value[2::2])] strings = list(zip(il, li)) allchars = "" for c_entry in range(0, len(strings)): if 31 < strings[c_entry][0] < 127: allchars += chr(strings[c_entry][0]) elif 31 < strings[c_entry][1] < 127: allchars += chr(strings[c_entry][1]) else: allchars += " " allchars = re.sub(' +',' ', allchars) words = allchars.split(" ") planes = [] for idx in [i for i, x in enumerate(words) if x == "sOpticalConfigName"]: planes.append(words[idx+1]) idata['planes'] = planes return idata # finds metdata in a tiff image which has been expoted with nd2ToTIFF.py. def get_tif_metadata_nd2ToTIFF(tif): '''This function pulls out the metadata from a tif file and returns it as a dictionary. This if tiff files as exported by the mm3 function mm3_nd2ToTIFF.py. All the metdata is found in that script and saved in json format to the tiff, so it is simply extracted here Paramters: tif: TIFF file object from which data will be extracted Returns: dictionary of values: 'fov': int, 't' : int, 'jdn' (float) 'x' (float) 'y' (float) 'planes' (list of strings) Called by mm3_Compile.get_tif_params ''' # get the first page of the tiff and pull out image description # this dictionary should be in the above form for tag in tif.pages[0].tags: if tag.name=="ImageDescription": idata=tag.value break #print(idata) idata = json.loads(idata) return idata # Finds metadata from the filename def get_tif_metadata_filename(tif): '''This function pulls out the metadata from a tif file and returns it as a dictionary. This just gets the tiff metadata from the filename and is a backup option when the known format of the metadata is not known. Paramters: tif: TIFF file object from which data will be extracted Returns: dictionary of values: 'fov': int, 't' : int, 'jdn' (float) 'x' (float) 'y' (float) Called by mm3_Compile.get_tif_params ''' idata = {'fov' : get_fov(tif.filename), # fov id 't' : get_time(tif.filename), # time point 'jd' : -1 * 0.0, # absolute julian time 'x' : -1 * 0.0, # x position on stage [um] 'y' : -1 * 0.0} # y position on stage [um] return idata # make a lookup time table for converting nominal time to elapsed time in seconds def make_time_table(analyzed_imgs): ''' Loops through the analyzed images and uses the jd time in the metadata to find the elapsed time in seconds that each picture was taken. This is later used for more accurate elongation rate calculation. Parametrs --------- analyzed_imgs : dict The output of get_tif_params. params['use_jd'] : boolean If set to True, 'jd' time will be used from the image metadata to use to create time table. Otherwise the 't' index will be used, and the parameter 'seconds_per_time_index' will be used from the parameters.yaml file to convert to seconds. Returns ------- time_table : dict Look up dictionary with keys for the FOV and then the time point. ''' information('Making time table...') # initialize time_table = {} first_time = float('inf') # need to go through the data once to find the first time for iname, idata in six.iteritems(analyzed_imgs): if params['use_jd']: if idata['jd'] < first_time: first_time = idata['jd'] else: if idata['t'] < first_time: first_time = idata['t'] # init dictionary for specific times per FOV if idata['fov'] not in time_table: time_table[idata['fov']] = {} for iname, idata in six.iteritems(analyzed_imgs): if params['use_jd']: # convert jd time to elapsed time in seconds t_in_seconds = np.around((idata['jd'] - first_time) * 24*60*60, decimals=0).astype('uint32') else: t_in_seconds = np.around((idata['t'] - first_time) * params['moviemaker']['seconds_per_time_index'], decimals=0).astype('uint32') time_table[int(idata['fov'])][int(idata['t'])] = int(t_in_seconds) # save to .pkl. This pkl will be loaded into the params # with open(os.path.join(params['ana_dir'], 'time_table.pkl'), 'wb') as time_table_file: # pickle.dump(time_table, time_table_file, protocol=pickle.HIGHEST_PROTOCOL) # with open(os.path.join(params['ana_dir'], 'time_table.txt'), 'w') as time_table_file: # pprint(time_table, stream=time_table_file) with open(os.path.join(params['ana_dir'], 'time_table.yaml'), 'w') as time_table_file: yaml.dump(data=time_table, stream=time_table_file, default_flow_style=False, tags=None) information('Time table saved.') return time_table # saves traps sliced via Unet def save_tiffs(imgDict, analyzed_imgs, fov_id): savePath = os.path.join(params['experiment_directory'], params['analysis_directory'], params['chnl_dir']) img_names = [key for key in analyzed_imgs.keys()] image_params = analyzed_imgs[img_names[0]] for peak,img in six.iteritems(imgDict): img = img.astype('uint16') if not os.path.isdir(savePath): os.mkdir(savePath) for planeNumber in image_params['planes']: channel_filename = os.path.join(savePath, params['experiment_name'] + '_xy{0:0=3}_p{1:0=4}_c{2}.tif'.format(fov_id, peak, planeNumber)) io.imsave(channel_filename, img[:,:,:,int(planeNumber)-1]) # slice_and_write cuts up the image files one at a time and writes them out to tiff stacks def tiff_stack_slice_and_write(images_to_write, channel_masks, analyzed_imgs): '''Writes out 4D stacks of TIFF images per channel. Loads all tiffs from and FOV into memory and then slices all time points at once. Called by __main__ ''' # make an array of images and then concatenate them into one big stack image_fov_stack = [] # go through list of images and get the file path for n, image in enumerate(images_to_write): # analyzed_imgs dictionary will be found in main scope. [0] is the key, [1] is jd image_params = analyzed_imgs[image[0]] information("Loading %s." % image_params['filepath'].split('/')[-1]) if n == 1: # declare identification variables for saving using first image fov_id = image_params['fov'] # load the tif and store it in array with tiff.TiffFile(image_params['filepath']) as tif: image_data = tif.asarray() # channel finding was also done on images after orientation was fixed image_data = fix_orientation(image_data) # add additional axis if the image is flat if len(image_data.shape) == 2: image_data = np.expand_dims(image_data, 0) # change axis so it goes Y, X, Plane image_data = np.rollaxis(image_data, 0, 3) # add it to list. The images should be in time order image_fov_stack.append(image_data) # concatenate the list into one big ass stack image_fov_stack = np.stack(image_fov_stack, axis=0) # cut out the channels as per channel masks for this fov for peak, channel_loc in six.iteritems(channel_masks[fov_id]): #information('Slicing and saving channel peak %s.' % channel_filename.split('/')[-1]) information('Slicing and saving channel peak %d.' % peak) # channel masks should only contain ints, but you can use this for hard fix # for i in range(len(channel_loc)): # for j in range(len(channel_loc[i])): # channel_loc[i][j] = int(channel_loc[i][j]) # slice out channel. # The function should recognize the shape length as 4 and cut all time points channel_stack = cut_slice(image_fov_stack, channel_loc) # save a different time stack for all colors for color_index in range(channel_stack.shape[3]): # this is the filename for the channel # # chnl_dir and p will be looked for in the scope above (__main__) channel_filename = os.path.join(params['chnl_dir'], params['experiment_name'] + '_xy%03d_p%04d_c%1d.tif' % (fov_id, peak, color_index+1)) # save stack tiff.imsave(channel_filename, channel_stack[:,:,:,color_index], compress=4) return # saves traps sliced via Unet to an hdf5 file def save_hdf5(imgDict, img_names, analyzed_imgs, fov_id, channel_masks): '''Writes out 4D stacks of images to an HDF5 file. Called by mm3_Compile.py ''' savePath = params['hdf5_dir'] if not os.path.isdir(savePath): os.mkdir(savePath) img_times = [analyzed_imgs[key]['t'] for key in img_names] img_jds = [analyzed_imgs[key]['jd'] for key in img_names] fov_ids = [analyzed_imgs[key]['fov'] for key in img_names] # get image_params from first image from current fov image_params = analyzed_imgs[img_names[0]] # establish some variables for hdf5 attributes fov_id = image_params['fov'] x_loc = image_params['x'] y_loc = image_params['y'] image_shape = image_params['shape'] image_planes = image_params['planes'] fov_channel_masks = channel_masks[fov_id] with h5py.File(os.path.join(savePath,'{}_xy{:0=2}.hdf5'.format(params['experiment_name'],fov_id)), 'w', libver='earliest') as h5f: # add in metadata for this FOV # these attributes should be common for all channel h5f.attrs.create('fov_id', fov_id) h5f.attrs.create('stage_x_loc', x_loc) h5f.attrs.create('stage_y_loc', y_loc) h5f.attrs.create('image_shape', image_shape) # encoding is because HDF5 has problems with numpy unicode h5f.attrs.create('planes', [plane.encode('utf8') for plane in image_planes]) h5f.attrs.create('peaks', sorted([key for key in imgDict.keys()])) # this is for things that change across time, for these create a dataset img_names = np.asarray(img_names) img_names = np.expand_dims(img_names, 1) img_names = img_names.astype('S100') h5ds = h5f.create_dataset(u'filenames', data=img_names, chunks=True, maxshape=(None, 1), dtype='S100', compression="gzip", shuffle=True, fletcher32=True) h5ds = h5f.create_dataset(u'times', data=np.expand_dims(img_times, 1), chunks=True, maxshape=(None, 1), compression="gzip", shuffle=True, fletcher32=True) h5ds = h5f.create_dataset(u'times_jd', data=np.expand_dims(img_jds, 1), chunks=True, maxshape=(None, 1), compression="gzip", shuffle=True, fletcher32=True) # cut out the channels as per channel masks for this fov for peak,channel_stack in six.iteritems(imgDict): channel_stack = channel_stack.astype('uint16') # create group for this trap h5g = h5f.create_group('channel_%04d' % peak) # add attribute for peak_id, channel location # add attribute for peak_id, channel location h5g.attrs.create('peak_id', peak) channel_loc = fov_channel_masks[peak] h5g.attrs.create('channel_loc', channel_loc) # save a different dataset for all colors for color_index in range(channel_stack.shape[3]): # create the dataset for the image. Review docs for these options. h5ds = h5g.create_dataset(u'p%04d_c%1d' % (peak, color_index+1), data=channel_stack[:,:,:,color_index], chunks=(1, channel_stack.shape[1], channel_stack.shape[2]), maxshape=(None, channel_stack.shape[1], channel_stack.shape[2]), compression="gzip", shuffle=True, fletcher32=True) # h5ds.attrs.create('plane', image_planes[color_index].encode('utf8')) # write the data even though we have more to write (free up memory) h5f.flush() return # same thing as tiff_stack_slice_and_write but do it for hdf5 def hdf5_stack_slice_and_write(images_to_write, channel_masks, analyzed_imgs): '''Writes out 4D stacks of TIFF images to an HDF5 file. Called by __main__ ''' # make an array of images and then concatenate them into one big stack image_fov_stack = [] # make arrays for filenames and times image_filenames = [] image_times = [] # times is still an integer but may be indexed arbitrarily image_jds = [] # jds = julian dates (times) # go through list of images, load and fix them, and create arrays of metadata for n, image in enumerate(images_to_write): image_name = image[0] # [0] is the key, [1] is jd # analyzed_imgs dictionary will be found in main scope. image_params = analyzed_imgs[image_name] information("Loading %s." % image_params['filepath'].split('/')[-1]) # add information to metadata arrays image_filenames.append(image_name) image_times.append(image_params['t']) image_jds.append(image_params['jd']) # declare identification variables for saving using first image if n == 1: # same across fov fov_id = image_params['fov'] x_loc = image_params['x'] y_loc = image_params['y'] image_shape = image_params['shape'] image_planes = image_params['planes'] # load the tif and store it in array with tiff.TiffFile(image_params['filepath']) as tif: image_data = tif.asarray() # channel finding was also done on images after orientation was fixed image_data = fix_orientation(image_data) # add additional axis if the image is flat if len(image_data.shape) == 2: image_data = np.expand_dims(image_data, 0) #change axis so it goes X, Y, Plane image_data = np.rollaxis(image_data, 0, 3) # add it to list. The images should be in time order image_fov_stack.append(image_data) # concatenate the list into one big ass stack image_fov_stack = np.stack(image_fov_stack, axis=0) # create the HDF5 file for the FOV, first time this is being done. with h5py.File(os.path.join(params['hdf5_dir'],'xy%03d.hdf5' % fov_id), 'w', libver='earliest') as h5f: # add in metadata for this FOV # these attributes should be common for all channel h5f.attrs.create('fov_id', fov_id) h5f.attrs.create('stage_x_loc', x_loc) h5f.attrs.create('stage_y_loc', y_loc) h5f.attrs.create('image_shape', image_shape) # encoding is because HDF5 has problems with numpy unicode h5f.attrs.create('planes', [plane.encode('utf8') for plane in image_planes]) h5f.attrs.create('peaks', sorted(channel_masks[fov_id].keys())) # this is for things that change across time, for these create a dataset h5ds = h5f.create_dataset(u'filenames', data=np.expand_dims(image_filenames, 1), chunks=True, maxshape=(None, 1), dtype='S100', compression="gzip", shuffle=True, fletcher32=True) h5ds = h5f.create_dataset(u'times', data=np.expand_dims(image_times, 1), chunks=True, maxshape=(None, 1), compression="gzip", shuffle=True, fletcher32=True) h5ds = h5f.create_dataset(u'times_jd', data=np.expand_dims(image_jds, 1), chunks=True, maxshape=(None, 1), compression="gzip", shuffle=True, fletcher32=True) # cut out the channels as per channel masks for this fov for peak, channel_loc in six.iteritems(channel_masks[fov_id]): #information('Slicing and saving channel peak %s.' % channel_filename.split('/')[-1]) information('Slicing and saving channel peak %d.' % peak) # create group for this channel h5g = h5f.create_group('channel_%04d' % peak) # add attribute for peak_id, channel location h5g.attrs.create('peak_id', peak) h5g.attrs.create('channel_loc', channel_loc) # channel masks should only contain ints, but you can use this for a hard fix # for i in range(len(channel_loc)): # for j in range(len(channel_loc[i])): # channel_loc[i][j] = int(channel_loc[i][j]) # slice out channel. # The function should recognize the shape length as 4 and cut all time points channel_stack = cut_slice(image_fov_stack, channel_loc) # save a different dataset for all colors for color_index in range(channel_stack.shape[3]): # create the dataset for the image. Review docs for these options. h5ds = h5g.create_dataset(u'p%04d_c%1d' % (peak, color_index+1), data=channel_stack[:,:,:,color_index], chunks=(1, channel_stack.shape[1], channel_stack.shape[2]), maxshape=(None, channel_stack.shape[1], channel_stack.shape[2]), compression="gzip", shuffle=True, fletcher32=True) # h5ds.attrs.create('plane', image_planes[color_index].encode('utf8')) # write the data even though we have more to write (free up memory) h5f.flush() return def tileImage(img, subImageNumber): divisor = int(np.sqrt(subImageNumber)) M = img.shape[0]//divisor N = img.shape[0]//divisor print(img.shape, M, N, divisor, subImageNumber) ans = ([img[x:x+M,y:y+N] for x in range(0,img.shape[0],M) for y in range(0,img.shape[1],N)]) tiles=[] for m in ans: if m.shape[0]==512 and m.shape[1]==512: tiles.append(m) tiles=np.asarray(tiles) #print(tiles) return(tiles) def get_weights(img, subImageNumber): divisor = int(np.sqrt(subImageNumber)) M = img.shape[0]//divisor N = img.shape[0]//divisor weights = np.ones((img.shape[0],img.shape[1]),dtype='uint8') for i in range(divisor-1): weights[(M*(i+1))-25:(M*(i+1)+25),:] = 0 weights[:,(N*(i+1))-25:(N*(i+1)+25)] = 0 return(weights) def permute_image(img, trap_align_metadata): # are there three dimensions? if len(img.shape) == 3: if img.shape[0] < 3: # for tifs with fewer than three imageing channels, the first dimension separates channels # img = np.transpose(img, (1,2,0)) img = img[trap_align_metadata['phase_plane_index'],:,:] # grab just the phase channel else: img = img[:,:,trap_align_metadata['phase_plane_index']] # grab just the phase channel return(img) def imageConcatenatorFeatures(imgStack, subImageNumber = 64): rowNumPerImage = int(np.sqrt(subImageNumber)) # here I'm assuming our large images are square, with equal number of crops in each dimension #print(rowNumPerImage) imageNum = int(imgStack.shape[0]/subImageNumber) # total number of sub-images divided by the number of sub-images in each original large image iterNum = int(imageNum*rowNumPerImage) imageDims = int(np.sqrt(imgStack.shape[1]*imgStack.shape[2]*subImageNumber)) featureNum = int(imgStack.shape[3]) bigImg = np.zeros(shape=(imageNum, imageDims, imageDims, featureNum), dtype='float32') # create array to store reconstructed images featureRowDicts = [] for j in range(featureNum): rowDict = {} for i in range(iterNum): baseNum = int(i*iterNum/imageNum) # concatenate columns of 256x256 images to build each 256x2048 row rowDict[i] = np.column_stack((imgStack[baseNum,:,:,j],imgStack[baseNum+1,:,:,j], imgStack[baseNum+2,:,:,j], imgStack[baseNum+3,:,:,j]))#, #imgStack[baseNum+4,:,:,j],imgStack[baseNum+5,:,:,j], #imgStack[baseNum+6,:,:,j],imgStack[baseNum+7,:,:,j])) featureRowDicts.append(rowDict) for j in range(featureNum): for i in range(imageNum): baseNum = int(i*rowNumPerImage) # concatenate appropriate 256x2048 rows to build a 2048x2048 image and place it into bigImg bigImg[i,:,:,j] = np.row_stack((featureRowDicts[j][baseNum],featureRowDicts[j][baseNum+1], featureRowDicts[j][baseNum+2],featureRowDicts[j][baseNum+3]))#, #featureRowDicts[j][baseNum+4],featureRowDicts[j][baseNum+5], #featureRowDicts[j][baseNum+6],featureRowDicts[j][baseNum+7])) return(bigImg) def imageConcatenatorFeatures2(imgStack, subImageNumber = 81): rowNumPerImage = int(np.sqrt(subImageNumber)) # here I'm assuming our large images are square, with equal number of crops in each dimension imageNum = int(imgStack.shape[0]/subImageNumber) # total number of sub-images divided by the number of sub-images in each original large image iterNum = int(imageNum*rowNumPerImage) imageDims = int(np.sqrt(imgStack.shape[1]*imgStack.shape[2]*subImageNumber)) featureNum = int(imgStack.shape[3]) bigImg = np.zeros(shape=(imageNum, imageDims, imageDims, featureNum), dtype='float32') # create array to store reconstructed images featureRowDicts = [] for j in range(featureNum): rowDict = {} for i in range(iterNum): baseNum = int(i*iterNum/imageNum) # concatenate columns of 256x256 images to build each 256x2048 row rowDict[i] = np.column_stack((imgStack[baseNum,:,:,j],imgStack[baseNum+1,:,:,j], imgStack[baseNum+2,:,:,j], imgStack[baseNum+3,:,:,j], imgStack[baseNum+4,:,:,j]))#,imgStack[baseNum+5,:,:,j], #imgStack[baseNum+6,:,:,j],imgStack[baseNum+7,:,:,j], #imgStack[baseNum+8,:,:,j])) featureRowDicts.append(rowDict) for j in range(featureNum): for i in range(imageNum): baseNum = int(i*rowNumPerImage) # concatenate appropriate 256x2048 rows to build a 2048x2048 image and place it into bigImg bigImg[i,:,:,j] = np.row_stack((featureRowDicts[j][baseNum],featureRowDicts[j][baseNum+1], featureRowDicts[j][baseNum+2],featureRowDicts[j][baseNum+3], featureRowDicts[j][baseNum+4]))#,featureRowDicts[j][baseNum+5], #featureRowDicts[j][baseNum+6],featureRowDicts[j][baseNum+7], #featureRowDicts[j][baseNum+8])) return(bigImg) def get_weights_array(arr=np.zeros((2048,2048)), shiftDistance=128, subImageNumber=64, padSubImageNumber=81): originalImageWeights = get_weights(arr, subImageNumber=subImageNumber) shiftLeftWeights = np.pad(originalImageWeights, pad_width=((0,0),(0,shiftDistance)), mode='constant', constant_values=((0,0),(0,0)))[:,shiftDistance:] shiftRightWeights = np.pad(originalImageWeights, pad_width=((0,0),(shiftDistance,0)), mode='constant', constant_values=((0,0),(0,0)))[:,:(-1*shiftDistance)] shiftUpWeights = np.pad(originalImageWeights, pad_width=((0,shiftDistance),(0,0)), mode='constant', constant_values=((0,0),(0,0)))[shiftDistance:,:] shiftDownWeights = np.pad(originalImageWeights, pad_width=((shiftDistance,0),(0,0)), mode='constant', constant_values=((0,0),(0,0)))[:(-1*shiftDistance),:] expandedImageWeights = get_weights(np.zeros((arr.shape[0]+2*shiftDistance,arr.shape[1]+2*shiftDistance)), subImageNumber=padSubImageNumber)[shiftDistance:-shiftDistance,shiftDistance:-shiftDistance] allWeights = np.stack((originalImageWeights, expandedImageWeights, shiftUpWeights, shiftDownWeights, shiftLeftWeights,shiftRightWeights), axis=-1) stackWeights = np.stack((allWeights,allWeights),axis=0) stackWeights = np.stack((stackWeights,stackWeights,stackWeights),axis=3) return(stackWeights) # predicts locations of channels in an image using deep learning model def get_frame_predictions(img,model,stackWeights, shiftDistance=256, subImageNumber=16, padSubImageNumber=25, debug=False): pred = predict_first_image_channels(img, model, shiftDistance=shiftDistance, subImageNumber=subImageNumber, padSubImageNumber=padSubImageNumber, debug=debug)[0,...] # print(pred.shape) if debug: print(pred.shape) compositePrediction = np.average(pred, axis=3, weights=stackWeights) # print(compositePrediction.shape) padSize = (compositePrediction.shape[0]-img.shape[0])//2 compositePrediction = util.crop(compositePrediction,((padSize,padSize), (padSize,padSize), (0,0))) # print(compositePrediction.shape) return(compositePrediction) def apply_median_filter_normalize(imgs): selem = morphology.disk(3) for i in range(imgs.shape[0]): # Store sample tmpImg = imgs[i,:,:,0] medImg = median(tmpImg, selem) tmpImg = medImg/np.max(medImg) tmpImg = np.expand_dims(tmpImg, axis=-1) imgs[i,:,:,:] = tmpImg return(imgs) def predict_first_image_channels(img, model, subImageNumber=16, padSubImageNumber=25, shiftDistance=128, batchSize=1, debug=False): imgSize = img.shape[0] padSize = (2048-imgSize)//2 # how much to pad on each side to get up to 2048x2048? imgStack = np.pad(img, pad_width=((padSize,padSize),(padSize,padSize)), mode='constant', constant_values=((0,0),(0,0))) # pad the images to make them 2048x2048 # pad the stack by 128 pixels on each side to get complemetary crops that I can run the network on. This # should help me fill in low-confidence regions where the crop boundaries were for the original image imgStackExpand = np.pad(imgStack, pad_width=((shiftDistance,shiftDistance),(shiftDistance,shiftDistance)), mode='constant', constant_values=((0,0),(0,0))) imgStackShiftRight = np.pad(imgStack, pad_width=((0,0),(0,shiftDistance)), mode='constant', constant_values=((0,0),(0,0)))[:,shiftDistance:] imgStackShiftLeft = np.pad(imgStack, pad_width=((0,0),(shiftDistance,0)), mode='constant', constant_values=((0,0),(0,0)))[:,:-shiftDistance] imgStackShiftDown = np.pad(imgStack, pad_width=((0,shiftDistance),(0,0)), mode='constant', constant_values=((0,0),(0,0)))[shiftDistance:,:] imgStackShiftUp = np.pad(imgStack, pad_width=((shiftDistance,0),(0,0)), mode='constant', constant_values=((0,0),(0,0)))[:-shiftDistance,:] #print(imgStackShiftUp.shape) crops = tileImage(imgStack, subImageNumber=subImageNumber) print("Crops: ", crops.shape) crops = np.expand_dims(crops, -1) data_gen_args = {'batch_size':params['compile']['channel_prediction_batch_size'], 'n_channels':1, 'normalize_to_one':True, 'shuffle':False} predict_gen_args = {'verbose':1, 'use_multiprocessing':True, 'workers':params['num_analyzers']} img_generator = TrapSegmentationDataGenerator(crops, **data_gen_args) predictions = model.predict_generator(img_generator, **predict_gen_args) prediction = imageConcatenatorFeatures(predictions, subImageNumber=subImageNumber) #print(prediction.shape) cropsExpand = tileImage(imgStackExpand, subImageNumber=padSubImageNumber) cropsExpand = np.expand_dims(cropsExpand, -1) img_generator = TrapSegmentationDataGenerator(cropsExpand, **data_gen_args) predictions = model.predict_generator(img_generator, **predict_gen_args) predictionExpand = imageConcatenatorFeatures2(predictions, subImageNumber=padSubImageNumber) predictionExpand = util.crop(predictionExpand, ((0,0),(shiftDistance,shiftDistance),(shiftDistance,shiftDistance),(0,0))) #print(predictionExpand.shape) cropsShiftLeft = tileImage(imgStackShiftLeft, subImageNumber=subImageNumber) cropsShiftLeft = np.expand_dims(cropsShiftLeft, -1) img_generator = TrapSegmentationDataGenerator(cropsShiftLeft, **data_gen_args) predictions = model.predict_generator(img_generator, **predict_gen_args) predictionLeft = imageConcatenatorFeatures(predictions, subImageNumber=subImageNumber) predictionLeft = np.pad(predictionLeft, pad_width=((0,0),(0,0),(0,shiftDistance),(0,0)), mode='constant', constant_values=((0,0),(0,0),(0,0),(0,0)))[:,:,shiftDistance:,:] #print(predictionLeft.shape) cropsShiftRight = tileImage(imgStackShiftRight, subImageNumber=subImageNumber) cropsShiftRight = np.expand_dims(cropsShiftRight, -1) img_generator = TrapSegmentationDataGenerator(cropsShiftRight, **data_gen_args) predictions = model.predict_generator(img_generator, **predict_gen_args) predictionRight = imageConcatenatorFeatures(predictions, subImageNumber=subImageNumber) predictionRight = np.pad(predictionRight, pad_width=((0,0),(0,0),(shiftDistance,0),(0,0)), mode='constant', constant_values=((0,0),(0,0),(0,0),(0,0)))[:,:,:(-1*shiftDistance),:] #print(predictionRight.shape) cropsShiftUp = tileImage(imgStackShiftUp, subImageNumber=subImageNumber) #print(cropsShiftUp.shape) cropsShiftUp = np.expand_dims(cropsShiftUp, -1) img_generator = TrapSegmentationDataGenerator(cropsShiftUp, **data_gen_args) predictions = model.predict_generator(img_generator, **predict_gen_args) predictionUp = imageConcatenatorFeatures(predictions, subImageNumber=subImageNumber) predictionUp = np.pad(predictionUp, pad_width=((0,0),(0,shiftDistance),(0,0),(0,0)), mode='constant', constant_values=((0,0),(0,0),(0,0),(0,0)))[:,shiftDistance:,:,:] #print(predictionUp.shape) cropsShiftDown = tileImage(imgStackShiftDown, subImageNumber=subImageNumber) cropsShiftDown = np.expand_dims(cropsShiftDown, -1) img_generator = TrapSegmentationDataGenerator(cropsShiftDown, **data_gen_args) predictions = model.predict_generator(img_generator, **predict_gen_args) predictionDown = imageConcatenatorFeatures(predictions, subImageNumber=subImageNumber) predictionDown = np.pad(predictionDown, pad_width=((0,0),(shiftDistance,0),(0,0),(0,0)), mode='constant', constant_values=((0,0),(0,0),(0,0),(0,0)))[:,:(-1*shiftDistance),:,:] #print(predictionDown.shape) allPredictions = np.stack((prediction, predictionExpand, predictionUp, predictionDown, predictionLeft, predictionRight), axis=-1) return(allPredictions) # takes initial U-net centroids for trap locations, and creats bounding boxes for each trap at the defined height and width def get_frame_trap_bounding_boxes(trapLabels, trapProps, trapAreaThreshold=2000, trapWidth=27, trapHeight=256): badTrapLabels = [reg.label for reg in trapProps if reg.area < trapAreaThreshold] # filter out small "trap" regions goodTraps = trapLabels.copy() for label in badTrapLabels: goodTraps[goodTraps == label] = 0 # re-label bad traps as background (0) goodTrapProps = measure.regionprops(goodTraps) trapCentroids = [(int(np.round(reg.centroid[0])),int(np.round(reg.centroid[1]))) for reg in goodTrapProps] # get centroids as integers trapBboxes = [] for centroid in trapCentroids: rowIndex = centroid[0] colIndex = centroid[1] minRow = rowIndex-trapHeight//2 maxRow = rowIndex+trapHeight//2 minCol = colIndex-trapWidth//2 maxCol = colIndex+trapWidth//2 if trapWidth % 2 != 0: maxCol += 1 coordArray = np.array([minRow,maxRow,minCol,maxCol]) # remove any traps at edges of image if np.any(coordArray > goodTraps.shape[0]): continue if np.any(coordArray < 0): continue trapBboxes.append((minRow,minCol,maxRow,maxCol)) return(trapBboxes) # this function performs image alignment as defined by the shifts passed as an argument def crop_traps(fileNames, trapProps, labelledTraps, bboxesDict, trap_align_metadata): frameNum = trap_align_metadata['frame_count'] channelNum = trap_align_metadata['plane_number'] trapImagesDict = {key:np.zeros((frameNum, trap_align_metadata['trap_height'], trap_align_metadata['trap_width'], channelNum)) for key in bboxesDict} trapClosedEndPxDict = {} flipImageDict = {} trapMask = labelledTraps for frame in range(frameNum): if (frame+1) % 20 == 0: print("Cropping trap regions for frame number {} of {}.".format(frame+1, frameNum)) imgPath = os.path.join(params['experiment_directory'],params['image_directory'],fileNames[frame]) fullFrameImg = io.imread(imgPath) if len(fullFrameImg.shape) == 3: if fullFrameImg.shape[0] < 3: # for tifs with less than three imaging channels, the first dimension separates channels fullFrameImg = np.transpose(fullFrameImg, (1,2,0)) trapClosedEndPxDict[fileNames[frame]] = {key:{} for key in bboxesDict.keys()} for key in trapImagesDict.keys(): bbox = bboxesDict[key][frame] trapImagesDict[key][frame,:,:,:] = fullFrameImg[bbox[0]:bbox[2],bbox[1]:bbox[3],:] #tmpImg = np.reshape(fullFrameImg[trapMask==key], (trapHeight,trapWidth,channelNum)) if frame == 0: medianProfile = np.median(trapImagesDict[key][frame,:,:,0],axis=1) # get intensity of middle column of trap maxIntensityRow = np.argmax(medianProfile) if maxIntensityRow > trap_align_metadata['trap_height']//2: flipImageDict[key] = 0 else: flipImageDict[key] = 1 if flipImageDict[key] == 1: trapImagesDict[key][frame,:,:,:] = trapImagesDict[key][frame,::-1,:,:] trapClosedEndPxDict[fileNames[frame]][key]['closed_end_px'] = bbox[0] trapClosedEndPxDict[fileNames[frame]][key]['open_end_px'] = bbox[2] else: trapClosedEndPxDict[fileNames[frame]][key]['closed_end_px'] = bbox[2] trapClosedEndPxDict[fileNames[frame]][key]['open_end_px'] = bbox[0] continue return(trapImagesDict, trapClosedEndPxDict) # gets shifted bounding boxes to crop traps through time def shift_bounding_boxes(bboxesDict, shifts, imgSize): bboxesShiftDict = {} for key in bboxesDict.keys(): bboxesShiftDict[key] = [] bboxes = bboxesDict[key] for i in range(shifts.shape[0]): if i == 0: bboxesShiftDict[key].append(bboxes) else: minRow = bboxes[0]+shifts[i,0] minCol = bboxes[1]+shifts[i,1] maxRow = bboxes[2]+shifts[i,0] maxCol = bboxes[3]+shifts[i,1] bboxesShiftDict[key].append((minRow, minCol, maxRow, maxCol)) if np.any(np.asarray([minRow,minCol,maxRow,maxCol]) < 0): print("channel {} removed: out of frame".format(key)) del bboxesShiftDict[key] break if np.any(np.asarray([minRow,minCol,maxRow,maxCol]) > imgSize): print("channel {} removed: out of frame".format(key)) del bboxesShiftDict[key] break return(bboxesShiftDict) # finds the location of channels in a tif def find_channel_locs(image_data): '''Finds the location of channels from a phase contrast image. The channels are returned in a dictionary where the key is the x position of the channel in pixel and the value is a dicionary with the open and closed end in pixels in y. Called by mm3_Compile.get_tif_params ''' # declare temp variables from yaml parameter dict. chan_w = params['compile']['channel_width'] chan_sep = params['compile']['channel_separation'] crop_wp = int(params['compile']['channel_width_pad'] + chan_w/2) chan_snr = params['compile']['channel_detection_snr'] # Detect peaks in the x projection (i.e. find the channels) projection_x = image_data.sum(axis=0).astype(np.int32) # find_peaks_cwt is a function which attempts to find the peaks in a 1-D array by # convolving it with a wave. here the wave is the default Mexican hat wave # but the minimum signal to noise ratio is specified # *** The range here should be a parameter or changed to a fraction. peaks = find_peaks_cwt(projection_x, np.arange(chan_w-5,chan_w+5), min_snr=chan_snr) # If the left-most peak position is within half of a channel separation, # discard the channel from the list. if peaks[0] < (chan_sep / 2): peaks = peaks[1:] # If the diference between the right-most peak position and the right edge # of the image is less than half of a channel separation, discard the channel. if image_data.shape[1] - peaks[-1] < (chan_sep / 2): peaks = peaks[:-1] # Find the average channel ends for the y-projected image projection_y = image_data.sum(axis=1) # find derivative, must use int32 because it was unsigned 16b before. proj_y_d = np.diff(projection_y.astype(np.int32)) # use the top third to look for closed end, is pixel location of highest deriv onethirdpoint_y = int(projection_y.shape[0]/3.0) default_closed_end_px = proj_y_d[:onethirdpoint_y].argmax() # use bottom third to look for open end, pixel location of lowest deriv twothirdpoint_y = int(projection_y.shape[0]*2.0/3.0) default_open_end_px = twothirdpoint_y + proj_y_d[twothirdpoint_y:].argmin() default_length = default_open_end_px - default_closed_end_px # used for checks # go through peaks and assign information # dict for channel dimensions chnl_loc_dict = {} # key is peak location, value is dict with {'closed_end_px': px, 'open_end_px': px} for peak in peaks: # set defaults chnl_loc_dict[peak] = {'closed_end_px': default_closed_end_px, 'open_end_px': default_open_end_px} # redo the previous y projection finding with just this channel channel_slice = image_data[:, peak-crop_wp:peak+crop_wp] slice_projection_y = channel_slice.sum(axis = 1) slice_proj_y_d = np.diff(slice_projection_y.astype(np.int32)) slice_closed_end_px = slice_proj_y_d[:onethirdpoint_y].argmax() slice_open_end_px = twothirdpoint_y + slice_proj_y_d[twothirdpoint_y:].argmin() slice_length = slice_open_end_px - slice_closed_end_px # check if these values make sense. If so, use them. If not, use default # make sure lenght is not 30 pixels bigger or smaller than default # *** This 15 should probably be a parameter or at least changed to a fraction. if slice_length + 15 < default_length or slice_length - 15 > default_length: continue # make sure ends are greater than 15 pixels from image edge if slice_closed_end_px < 15 or slice_open_end_px > image_data.shape[0] - 15: continue # if you made it to this point then update the entry chnl_loc_dict[peak] = {'closed_end_px' : slice_closed_end_px, 'open_end_px' : slice_open_end_px} return chnl_loc_dict # make masks from initial set of images (same images as clusters) def make_masks(analyzed_imgs): ''' Make masks goes through the channel locations in the image metadata and builds a consensus Mask for each image per fov, which it returns as dictionary named channel_masks. The keys in this dictionary are fov id, and the values is a another dictionary. This dict's keys are channel locations (peaks) and the values is a [2][2] array: [[minrow, maxrow],[mincol, maxcol]] of pixel locations designating the corner of each mask for each channel on the whole image One important consequence of these function is that the channel ids and the size of the channel slices are decided now. Updates to mask must coordinate with these values. Parameters analyzed_imgs : dict image information created by get_params Returns channel_masks : dict dictionary of consensus channel masks. Called By mm3_Compile.py Calls ''' information("Determining initial channel masks...") # declare temp variables from yaml parameter dict. crop_wp = int(params['compile']['channel_width_pad'] + params['compile']['channel_width']/2) chan_lp = int(params['compile']['channel_length_pad']) #intiaize dictionary channel_masks = {} # get the size of the images (hope they are the same) for img_k in analyzed_imgs.keys(): img_v = analyzed_imgs[img_k] image_rows = img_v['shape'][0] # x pixels image_cols = img_v['shape'][1] # y pixels break # just need one. using iteritems mean the whole dict doesn't load # get the fov ids fovs = [] for img_k in analyzed_imgs.keys(): img_v = analyzed_imgs[img_k] if img_v['fov'] not in fovs: fovs.append(img_v['fov']) # max width and length across all fovs. channels will get expanded by these values # this important for later updates to the masks, which should be the same max_chnl_mask_len = 0 max_chnl_mask_wid = 0 # for each fov make a channel_mask dictionary from consensus mask for fov in fovs: # initialize a the dict and consensus mask channel_masks_1fov = {} # dict which holds channel masks {peak : [[y1, y2],[x1,x2]],...} consensus_mask = np.zeros([image_rows, image_cols]) # mask for labeling # bring up information for each image for img_k in analyzed_imgs.keys(): img_v = analyzed_imgs[img_k] # skip this one if it is not of the current fov if img_v['fov'] != fov: continue # for each channel in each image make a single mask img_chnl_mask = np.zeros([image_rows, image_cols]) # and add the channel mask to it for chnl_peak, peak_ends in six.iteritems(img_v['channels']): # pull out the peak location and top and bottom location # and expand by padding (more padding done later for width) x1 = max(chnl_peak - crop_wp, 0) x2 = min(chnl_peak + crop_wp, image_cols) y1 = max(peak_ends['closed_end_px'] - chan_lp, 0) y2 = min(peak_ends['open_end_px'] + chan_lp, image_rows) # add it to the mask for this image img_chnl_mask[y1:y2, x1:x2] = 1 # add it to the consensus mask consensus_mask += img_chnl_mask # Normalize concensus mask between 0 and 1. consensus_mask = consensus_mask.astype('float32') / float(np.amax(consensus_mask)) # threshhold and homogenize each channel mask within the mask, label them # label when value is above 0.1 (so 90% occupancy), transpose. # the [0] is for the array ([1] is the number of regions) # It transposes and then transposes again so regions are labeled left to right # clear border it to make sure the channels are off the edge consensus_mask = ndi.label(consensus_mask)[0] # go through each label for label in np.unique(consensus_mask): if label == 0: # label zero is the background continue binary_core = consensus_mask == label # clean up the rough edges poscols = np.any(binary_core, axis = 0) # column positions where true (any) posrows = np.any(binary_core, axis = 1) # row positions where true (any) # channel_id givin by horizontal position # this is important. later updates to the positions will have to check # if their channels contain this median value to match up channel_id = int(np.median(np.where(poscols)[0])) # store the edge locations of the channel mask in the dictionary. Will be ints min_row = np.min(np.where(posrows)[0]) max_row = np.max(np.where(posrows)[0]) min_col = np.min(np.where(poscols)[0]) max_col = np.max(np.where(poscols)[0]) # if the min/max cols are within the image bounds, # add the mask, as 4 points, to the dictionary if min_col > 0 and max_col < image_cols: channel_masks_1fov[channel_id] = [[min_row, max_row], [min_col, max_col]] # find the largest channel width and height while you go round max_chnl_mask_len = int(max(max_chnl_mask_len, max_row - min_row)) max_chnl_mask_wid = int(max(max_chnl_mask_wid, max_col - min_col)) # add channel_mask dictionary to the fov dictionary, use copy to play it safe channel_masks[fov] = channel_masks_1fov.copy() # update all channel masks to be the max size cm_copy = channel_masks.copy() for fov, peaks in six.iteritems(channel_masks): # f_id = int(fov) for peak, chnl_mask in six.iteritems(peaks): # p_id = int(peak) # just add length to the open end (bottom of image, low column) if chnl_mask[0][1] - chnl_mask[0][0] != max_chnl_mask_len: cm_copy[fov][peak][0][1] = chnl_mask[0][0] + max_chnl_mask_len # enlarge widths around the middle, but make sure you don't get floats if chnl_mask[1][1] - chnl_mask[1][0] != max_chnl_mask_wid: wid_diff = max_chnl_mask_wid - (chnl_mask[1][1] - chnl_mask[1][0]) if wid_diff % 2 == 0: cm_copy[fov][peak][1][0] = max(chnl_mask[1][0] - wid_diff/2, 0) cm_copy[fov][peak][1][1] = min(chnl_mask[1][1] + wid_diff/2, image_cols - 1) else: cm_copy[fov][peak][1][0] = max(chnl_mask[1][0] - (wid_diff-1)/2, 0) cm_copy[fov][peak][1][1] = min(chnl_mask[1][1] + (wid_diff+1)/2, image_cols - 1) # convert all values to ints chnl_mask[0][0] = int(chnl_mask[0][0]) chnl_mask[0][1] = int(chnl_mask[0][1]) chnl_mask[1][0] = int(chnl_mask[1][0]) chnl_mask[1][1] = int(chnl_mask[1][1]) # cm_copy[fov][peak] = {'y_top': chnl_mask[0][0], # 'y_bot': chnl_mask[0][1], # 'x_left': chnl_mask[1][0], # 'x_right': chnl_mask[1][1]} # print(type(cm_copy[fov][peak][1][0]), cm_copy[fov][peak][1][0]) #save the channel mask dictionary to a pickle and a text file # with open(os.path.join(params['ana_dir'], 'channel_masks.pkl'), 'wb') as cmask_file: # pickle.dump(cm_copy, cmask_file, protocol=pickle.HIGHEST_PROTOCOL) with open(os.path.join(params['ana_dir'], 'channel_masks.txt'), 'w') as cmask_file: pprint(cm_copy, stream=cmask_file) with open(os.path.join(params['ana_dir'], 'channel_masks.yaml'), 'w') as cmask_file: yaml.dump(data=cm_copy, stream=cmask_file, default_flow_style=False, tags=None) information("Channel masks saved.") return cm_copy # get each fov_id, peak_id, frame's mask bounding box from bounding boxes arrived at by convolutional neural network def make_channel_masks_CNN(bboxes_dict): ''' The keys in this dictionary are peak_ids and the values of each is an array of shape (frameNumber,2,2): Each frameNumber's 2x2 slice of the array represents the given peak_id's [[minrow, maxrow],[mincol, maxcol]]. One important consequence of these function is that the channel ids and the size of the channel slices are decided now. Updates to mask must coordinate with these values. Parameters analyzed_imgs : dict image information created by get_params Returns channel_masks : dict dictionary of consensus channel masks. Called By mm3_Compile.py Calls ''' # initialize the new channel_masks dict channel_masks = {} # reorder elements of tuples in bboxes_dict to match [[minrow, maxrow], [mincol, maxcol]] convention above peak_ids = [peak_id for peak_id in bboxes_dict.keys()] peak_ids.sort() bbox_array = np.zeros((len(bboxes_dict[peak_ids[0]]),2,2), dtype='uint16') for peak_id in peak_ids: # get each frame's bounding boxes for the given peak_id frame_bboxes = bboxes_dict[peak_id] for frame_index in range(len(frame_bboxes)): # replace the values in bbox_array with the proper ones from frame_bboxes minrow = frame_bboxes[frame_index][0] maxrow = frame_bboxes[frame_index][2] mincol = frame_bboxes[frame_index][1] maxcol = frame_bboxes[frame_index][3] bbox_array[frame_index,0,0] = minrow bbox_array[frame_index,0,1] = maxrow bbox_array[frame_index,1,0] = mincol bbox_array[frame_index,1,1] = maxcol channel_masks[peak_id] = bbox_array return(channel_masks) ### functions about trimming, padding, and manipulating images # define function for flipping the images on an FOV by FOV basis def fix_orientation(image_data): ''' Fix the orientation. The standard direction for channels to open to is down. called by process_tif get_params ''' # user parameter indicates how things should be flipped image_orientation = params['compile']['image_orientation'] # if this is just a phase image give in an extra layer so rest of code is fine flat = False # flag for if the image is flat or multiple levels if len(image_data.shape) == 2: image_data = np.expand_dims(image_data, 0) flat = True # setting image_orientation to 'auto' will use autodetection if image_orientation == "auto": # use 'phase_plane' to find the phase plane in image_data, assuming c1, c2, c3... naming scheme here. try: ph_channel = int(re.search('[0-9]', params['phase_plane']).group(0)) - 1 except: # Pick the plane to analyze with the highest mean px value (should be phase) ph_channel = np.argmax([np.mean(image_data[ci]) for ci in range(image_data.shape[0])]) # flip based on the index of the higest average row value # this should be closer to the opening if np.argmax(image_data[ph_channel].mean(axis = 1)) < image_data[ph_channel].shape[0] / 2: image_data = image_data[:,::-1,:] else: pass # no need to do anything # flip if up is chosen elif image_orientation == "up": return image_data[:,::-1,:] # do not flip the images if "down is the specified image orientation" elif image_orientation == "down": pass if flat: image_data = image_data[0] # just return that first layer return image_data # cuts out channels from the image def cut_slice(image_data, channel_loc): '''Takes an image and cuts out the channel based on the slice location slice location is the list with the peak information, in the form [][y1, y2],[x1, x2]]. Returns the channel slice as a numpy array. The numpy array will be a stack if there are multiple planes. if you want to slice all the channels from a picture with the channel_masks dictionary use a loop like this: for channel_loc in channel_masks[fov_id]: # fov_id is the fov of the image channel_slice = cut_slice[image_pixel_data, channel_loc] # ... do something with the slice NOTE: this function will try to determine what the shape of your image is and slice accordingly. It expects the images are in the order [t, x, y, c]. It assumes images with three dimensions are [x, y, c] not [t, x, y]. ''' # case where image is in form [x, y] if len(image_data.shape) == 2: # make slice object channel_slicer = np.s_[channel_loc[0][0]:channel_loc[0][1], channel_loc[1][0]:channel_loc[1][1]] # case where image is in form [x, y, c] elif len(image_data.shape) == 3: channel_slicer = np.s_[channel_loc[0][0]:channel_loc[0][1], channel_loc[1][0]:channel_loc[1][1],:] # case where image in form [t, x , y, c] elif len(image_data.shape) == 4: channel_slicer = np.s_[:,channel_loc[0][0]:channel_loc[0][1], channel_loc[1][0]:channel_loc[1][1],:] # slice based on appropriate slicer object. channel_slice = image_data[channel_slicer] # pad y of channel if slice happened to be outside of image y_difference = (channel_loc[0][1] - channel_loc[0][0]) - channel_slice.shape[1] if y_difference > 0: paddings = [[0, 0], # t [0, y_difference], # y [0, 0], # x [0, 0]] # c channel_slice = np.pad(channel_slice, paddings, mode='edge') return channel_slice # calculate cross correlation between pixels in channel stack def channel_xcorr(fov_id, peak_id): ''' Function calculates the cross correlation of images in a stack to the first image in the stack. The output is an array that is the length of the stack with the best cross correlation between that image and the first image. The very first value should be 1. ''' pad_size = params['subtract']['alignment_pad'] # Use this number of images to calculate cross correlations number_of_images = 20 # load the phase contrast images image_data = load_stack(fov_id, peak_id, color=params['phase_plane']) # if there are more images than number_of_images, use number_of_images images evenly # spaced across the range if image_data.shape[0] > number_of_images: spacing = int(image_data.shape[0] / number_of_images) image_data = image_data[::spacing,:,:] if image_data.shape[0] > number_of_images: image_data = image_data[:number_of_images,:,:] # we will compare all images to this one, needs to be padded to account for image drift first_img = np.pad(image_data[0,:,:], pad_size, mode='reflect') xcorr_array = [] # array holds cross correlation vaues for img in image_data: # use match_template to find all cross correlations for the # current image against the first image. xcorr_array.append(np.max(match_template(first_img, img))) return xcorr_array ### functions about subtraction # average empty channels from stacks, making another TIFF stack def average_empties_stack(fov_id, specs, color='c1', align=True): '''Takes the fov file name and the peak names of the designated empties, averages them and saves the image Parameters fov_id : int FOV number specs : dict specifies whether a channel should be analyzed (1), used for making an average empty (0), or ignored (-1). color : string Which plane to use. align : boolean Flag that is passed to the worker function average_empties, indicates whether images should be aligned be for averaging (use False for fluorescent images) Returns True if succesful. Saves empty stack to analysis folder ''' information("Creating average empty channel for FOV %d." % fov_id) # get peak ids of empty channels for this fov empty_peak_ids = [] for peak_id, spec in six.iteritems(specs[fov_id]): if spec == 0: # 0 means it should be used for empty empty_peak_ids.append(peak_id) empty_peak_ids = sorted(empty_peak_ids) # sort for repeatability # depending on how many empties there are choose what to do # if there is no empty the user is going to have to copy another empty stack if len(empty_peak_ids) == 0: information("No empty channel designated for FOV %d." % fov_id) return False # if there is just one then you can just copy that channel elif len(empty_peak_ids) == 1: peak_id = empty_peak_ids[0] information("One empty channel (%d) designated for FOV %d." % (peak_id, fov_id)) # load the one phase contrast as the empties avg_empty_stack = load_stack(fov_id, peak_id, color=color) # but if there is more than one empty you need to align and average them per timepoint elif len(empty_peak_ids) > 1: # load the image stacks into memory empty_stacks = [] # list which holds phase image stacks of designated empties for peak_id in empty_peak_ids: # load data and append to list image_data = load_stack(fov_id, peak_id, color=color) empty_stacks.append(image_data) information("%d empty channels designated for FOV %d." % (len(empty_stacks), fov_id)) # go through time points and create list of averaged empties avg_empty_stack = [] # list will be later concatentated into numpy array time_points = range(image_data.shape[0]) # index is time for t in time_points: # get images from one timepoint at a time and send to alignment and averaging imgs = [stack[t] for stack in empty_stacks] avg_empty = average_empties(imgs, align=align) # function is in mm3 avg_empty_stack.append(avg_empty) # concatenate list and then save out to tiff stack avg_empty_stack = np.stack(avg_empty_stack, axis=0) # save out data if params['output'] == 'TIFF': # make new name and save it empty_filename = params['experiment_name'] + '_xy%03d_empty_%s.tif' % (fov_id, color) tiff.imsave(os.path.join(params['empty_dir'],empty_filename), avg_empty_stack, compress=4) if params['output'] == 'HDF5': h5f = h5py.File(os.path.join(params['hdf5_dir'],'xy%03d.hdf5' % fov_id), 'r+') # delete the dataset if it exists (important for debug) if 'empty_%s' % color in h5f: del h5f[u'empty_%s' % color] # the empty channel should be it's own dataset h5ds = h5f.create_dataset(u'empty_%s' % color, data=avg_empty_stack, chunks=(1, avg_empty_stack.shape[1], avg_empty_stack.shape[2]), maxshape=(None, avg_empty_stack.shape[1], avg_empty_stack.shape[2]), compression="gzip", shuffle=True, fletcher32=True) # give attribute which says which channels contribute h5ds.attrs.create('empty_channels', empty_peak_ids) h5f.close() information("Saved empty channel for FOV %d." % fov_id) return True # averages a list of empty channels def average_empties(imgs, align=True): ''' This function averages a set of images (empty channels) and returns a single image of the same size. It first aligns the images to the first image before averaging. Alignment is done by enlarging the first image using edge padding. Subsequent images are then aligned to this image and the offset recorded. These images are padded such that they are the same size as the first (padded) image but with the image in the correct (aligned) place. Edge padding is again used. The images are then placed in a stack and aveaged. This image is trimmed so it is the size of the original images Called by average_empties_stack ''' aligned_imgs = [] # list contains the aligned, padded images if align: # pixel size to use for padding (ammount that alignment could be off) pad_size = params['subtract']['alignment_pad'] for n, img in enumerate(imgs): # if this is the first image, pad it and add it to the stack if n == 0: ref_img = np.pad(img, pad_size, mode='reflect') # padded reference image aligned_imgs.append(ref_img) # otherwise align this image to the first padded image else: # find correlation between a convolution of img against the padded reference match_result = match_template(ref_img, img) # find index of highest correlation (relative to top left corner of img) y, x = np.unravel_index(np.argmax(match_result), match_result.shape) # pad img so it aligns and is the same size as reference image pad_img = np.pad(img, ((y, ref_img.shape[0] - (y + img.shape[0])), (x, ref_img.shape[1] - (x + img.shape[1]))), mode='reflect') aligned_imgs.append(pad_img) else: # don't align, just link the names to go forward easily aligned_imgs = imgs # stack the aligned data along 3rd axis aligned_imgs = np.dstack(aligned_imgs) # get a mean image along 3rd axis avg_empty = np.nanmean(aligned_imgs, axis=2) # trim off the padded edges (only if images were alinged, otherwise there was no padding) if align: avg_empty = avg_empty[pad_size:-1*pad_size, pad_size:-1*pad_size] # change type back to unsigned 16 bit not floats avg_empty = avg_empty.astype(dtype='uint16') return avg_empty # this function is used when one FOV doesn't have an empty def copy_empty_stack(from_fov, to_fov, color='c1'): '''Copy an empty stack from one FOV to another''' # load empty stack from one FOV information('Loading empty stack from FOV {} to save for FOV {}.'.format(from_fov, to_fov)) avg_empty_stack = load_stack(from_fov, 0, color='empty_{}'.format(color)) # save out data if params['output'] == 'TIFF': # make new name and save it empty_filename = params['experiment_name'] + '_xy%03d_empty_%s.tif' % (to_fov, color) tiff.imsave(os.path.join(params['empty_dir'],empty_filename), avg_empty_stack, compress=4) if params['output'] == 'HDF5': h5f = h5py.File(os.path.join(params['hdf5_dir'],'xy%03d.hdf5' % to_fov), 'r+') # delete the dataset if it exists (important for debug) if 'empty_%s' % color in h5f: del h5f[u'empty_%s' % color] # the empty channel should be it's own dataset h5ds = h5f.create_dataset(u'empty_%s' % color, data=avg_empty_stack, chunks=(1, avg_empty_stack.shape[1], avg_empty_stack.shape[2]), maxshape=(None, avg_empty_stack.shape[1], avg_empty_stack.shape[2]), compression="gzip", shuffle=True, fletcher32=True) # give attribute which says which channels contribute. Just put 0 h5ds.attrs.create('empty_channels', [0]) h5f.close() information("Saved empty channel for FOV %d." % to_fov) # Do subtraction for an fov over many timepoints def subtract_fov_stack(fov_id, specs, color='c1', method='phase'): ''' For a given FOV, loads the precomputed empty stack and does subtraction on all peaks in the FOV designated to be analyzed Parameters ---------- color : string, 'c1', 'c2', etc. This is the channel to subtraction. will be appended to the word empty. Called by mm3_Subtract.py Calls mm3.subtract_phase ''' information('Subtracting peaks for FOV %d.' % fov_id) # load empty stack feed dummy peak number to get empty avg_empty_stack = load_stack(fov_id, 0, color='empty_{}'.format(color)) # determine which peaks are to be analyzed ana_peak_ids = [] for peak_id, spec in six.iteritems(specs[fov_id]): if spec == 1: # 0 means it should be used for empty, -1 is ignore ana_peak_ids.append(peak_id) ana_peak_ids = sorted(ana_peak_ids) # sort for repeatability information("Subtracting %d channels for FOV %d." % (len(ana_peak_ids), fov_id)) # just break if there are to peaks to analize if not ana_peak_ids: return False # load images for the peak and get phase images for peak_id in ana_peak_ids: information('Subtracting peak %d.' % peak_id) image_data = load_stack(fov_id, peak_id, color=color) # make a list for all time points to send to a multiprocessing pool # list will length of image_data with tuples (image, empty) subtract_pairs = zip(image_data, avg_empty_stack) # # set up multiprocessing pool to do subtraction. Should wait until finished # pool = Pool(processes=params['num_analyzers']) # if method == 'phase': # subtracted_imgs = pool.map(subtract_phase, subtract_pairs, chunksize=10) # elif method == 'fluor': # subtracted_imgs = pool.map(subtract_fluor, subtract_pairs, chunksize=10) # pool.close() # tells the process nothing more will be added. # pool.join() # blocks script until everything has been processed and workers exit # linear loop for debug subtracted_imgs = [subtract_phase(subtract_pair) for subtract_pair in subtract_pairs] # stack them up along a time axis subtracted_stack = np.stack(subtracted_imgs, axis=0) # save out the subtracted stack if params['output'] == 'TIFF': sub_filename = params['experiment_name'] + '_xy%03d_p%04d_sub_%s.tif' % (fov_id, peak_id, color) tiff.imsave(os.path.join(params['sub_dir'],sub_filename), subtracted_stack, compress=4) # save it if fov_id==1 and peak_id<50: napari.current_viewer().add_image(subtracted_stack, name='Subtracted' + '_xy1_p'+str(peak_id)+'_sub_'+str(color)+'.tif', visible=True) if params['output'] == 'HDF5': h5f = h5py.File(os.path.join(params['hdf5_dir'],'xy%03d.hdf5' % fov_id), 'r+') # put subtracted channel in correct group h5g = h5f['channel_%04d' % peak_id] # delete the dataset if it exists (important for debug) if 'p%04d_sub_%s' % (peak_id, color) in h5g: del h5g['p%04d_sub_%s' % (peak_id, color)] h5ds = h5g.create_dataset(u'p%04d_sub_%s' % (peak_id, color), data=subtracted_stack, chunks=(1, subtracted_stack.shape[1], subtracted_stack.shape[2]), maxshape=(None, subtracted_stack.shape[1], subtracted_stack.shape[2]), compression="gzip", shuffle=True, fletcher32=True) information("Saved subtracted channel %d." % peak_id) if params['output'] == 'HDF5': h5f.close() return True # subtracts one phase contrast image from another. def subtract_phase(image_pair): '''subtract_phase aligns and subtracts a . Modified from subtract_phase_only by jt on 20160511 The subtracted image returned is the same size as the image given. It may however include data points around the edge that are meaningless but not marked. We align the empty channel to the phase channel, then subtract. Parameters image_pair : tuple of length two with; (image, empty_mean) Returns channel_subtracted : np.array The subtracted image Called by subtract_fov_stack ''' # get out data and pad cropped_channel, empty_channel = image_pair # [channel slice, empty slice] # this is for aligning the empty channel to the cell channel. ### Pad cropped channel. pad_size = params['subtract']['alignment_pad'] # pixel size to use for padding (ammount that alignment could be off) padded_chnl = np.pad(cropped_channel, pad_size, mode='reflect') # ### Align channel to empty using match template. # use match template to get a correlation array and find the position of maximum overlap match_result = match_template(padded_chnl, empty_channel) # get row and colum of max correlation value in correlation array y, x = np.unravel_index(np.argmax(match_result), match_result.shape) # pad the empty channel according to alignment to be overlayed on padded channel. empty_paddings = [[y, padded_chnl.shape[0] - (y + empty_channel.shape[0])], [x, padded_chnl.shape[1] - (x + empty_channel.shape[1])]] aligned_empty = np.pad(empty_channel, empty_paddings, mode='reflect') # now trim it off so it is the same size as the original channel aligned_empty = aligned_empty[pad_size:-1*pad_size, pad_size:-1*pad_size] ### Compute the difference between the empty and channel phase contrast images # subtract cropped cell image from empty channel. channel_subtracted = aligned_empty.astype('int32') - cropped_channel.astype('int32') # channel_subtracted = cropped_channel.astype('int32') - aligned_empty.astype('int32') # just zero out anything less than 0. This is what Sattar does channel_subtracted[channel_subtracted < 0] = 0 channel_subtracted = channel_subtracted.astype('uint16') # change back to 16bit return channel_subtracted # subtract one fluorescence image from another. def subtract_fluor(image_pair): ''' subtract_fluor does a simple subtraction of one image to another. Unlike subtract_phase, there is no alignment. Also, the empty channel is subtracted from the full channel. Parameters image_pair : tuple of length two with; (image, empty_mean) Returns channel_subtracted : np.array The subtracted image. Called by subtract_fov_stack ''' # get out data and pad cropped_channel, empty_channel = image_pair # [channel slice, empty slice] # check frame size of cropped channel and background, always keep crop channel size the same crop_size = np.shape(cropped_channel)[:2] empty_size = np.shape(empty_channel)[:2] if crop_size != empty_size: if crop_size[0] > empty_size[0] or crop_size[1] > empty_size[1]: pad_row_length = max(crop_size[0] - empty_size[0], 0) # prevent negatives pad_column_length = max(crop_size[1] - empty_size[1], 0) empty_channel = np.pad(empty_channel, [[np.int(.5*pad_row_length), pad_row_length-np.int(.5*pad_row_length)], [np.int(.5*pad_column_length), pad_column_length-np.int(.5*pad_column_length)], [0,0]], 'edge') # mm3.information('size adjusted 1') empty_size = np.shape(empty_channel)[:2] if crop_size[0] < empty_size[0] or crop_size[1] < empty_size[1]: empty_channel = empty_channel[:crop_size[0], :crop_size[1],] ### Compute the difference between the empty and channel phase contrast images # subtract cropped cell image from empty channel. channel_subtracted = cropped_channel.astype('int32') - empty_channel.astype('int32') # channel_subtracted = cropped_channel.astype('int32') - aligned_empty.astype('int32') # just zero out anything less than 0. channel_subtracted[channel_subtracted < 0] = 0 channel_subtracted = channel_subtracted.astype('uint16') # change back to 16bit return channel_subtracted ### functions that deal with segmentation and lineages # Do segmentation for an channel time stack def segment_chnl_stack(fov_id, peak_id): ''' For a given fov and peak (channel), do segmentation for all images in the subtracted .tif stack. Called by mm3_Segment.py Calls mm3.segment_image ''' information('Segmenting FOV %d, channel %d.' % (fov_id, peak_id)) # load subtracted images sub_stack = load_stack(fov_id, peak_id, color='sub_{}'.format(params['phase_plane'])) # set up multiprocessing pool to do segmentation. Will do everything before going on. #pool = Pool(processes=params['num_analyzers']) # send the 3d array to multiprocessing #segmented_imgs = pool.map(segment_image, sub_stack, chunksize=8) #pool.close() # tells the process nothing more will be added. #pool.join() # blocks script until everything has been processed and workers exit # image by image for debug segmented_imgs = [] for sub_image in sub_stack: segmented_imgs.append(segment_image(sub_image)) # stack them up along a time axis segmented_imgs = np.stack(segmented_imgs, axis=0) segmented_imgs = segmented_imgs.astype('uint8') # save out the segmented stack if params['output'] == 'TIFF': seg_filename = params['experiment_name'] + '_xy%03d_p%04d_%s.tif' % (fov_id, peak_id, params['seg_img']) tiff.imsave(os.path.join(params['seg_dir'],seg_filename), segmented_imgs, compress=5) if fov_id==1 and peak_id<50: napari.current_viewer().add_image(segmented_imgs, name='Segmented' + '_xy1_p'+str(peak_id)+'_sub_'+str(params['seg_img'])+'.tif', visible=True) if params['output'] == 'HDF5': h5f = h5py.File(os.path.join(params['hdf5_dir'],'xy%03d.hdf5' % fov_id), 'r+') # put segmented channel in correct group h5g = h5f['channel_%04d' % peak_id] # delete the dataset if it exists (important for debug) if 'p%04d_%s' % (peak_id, params['seg_img']) in h5g: del h5g['p%04d_%s' % (peak_id, params['seg_img'])] h5ds = h5g.create_dataset(u'p%04d_%s' % (peak_id, params['seg_img']), data=segmented_imgs, chunks=(1, segmented_imgs.shape[1], segmented_imgs.shape[2]), maxshape=(None, segmented_imgs.shape[1], segmented_imgs.shape[2]), compression="gzip", shuffle=True, fletcher32=True) h5f.close() information("Saved segmented channel %d." % peak_id) return True # segmentation algorithm def segment_image(image): '''Segments a subtracted image and returns a labeled image Parameters image : a ndarray which is an image. This should be the subtracted image Returns labeled_image : a ndarray which is also an image. Labeled values, which should correspond to cells, all have the same integer value starting with 1. Non labeled area should have value zero. ''' # load in segmentation parameters OTSU_threshold = params['segment']['otsu']['OTSU_threshold'] first_opening_size = params['segment']['otsu']['first_opening_size'] distance_threshold = params['segment']['otsu']['distance_threshold'] second_opening_size = params['segment']['otsu']['second_opening_size'] min_object_size = params['segment']['otsu']['min_object_size'] # threshold image try: thresh = threshold_otsu(image) # finds optimal OTSU threshhold value except: return np.zeros_like(image) threshholded = image > OTSU_threshold*thresh # will create binary image # if there are no cells, good to clear the border # because otherwise the OTSU is just for random bullshit, most # likely on the side of the image threshholded = segmentation.clear_border(threshholded) # Opening = erosion then dialation. # opening smooths images, breaks isthmuses, and eliminates protrusions. # "opens" dark gaps between bright features. morph = morphology.binary_opening(threshholded, morphology.disk(first_opening_size)) # if this image is empty at this point (likely if there were no cells), just return # zero array if np.amax(morph) == 0: return np.zeros_like(image) ### Calculate distance matrix, use as markers for random walker (diffusion watershed) # Generate the markers based on distance to the background distance = ndi.distance_transform_edt(morph) # threshold distance image distance_thresh = np.zeros_like(distance) distance_thresh[distance < distance_threshold] = 0 distance_thresh[distance >= distance_threshold] = 1 # do an extra opening on the distance distance_opened = morphology.binary_opening(distance_thresh, morphology.disk(second_opening_size)) # remove artifacts connected to image border cleared = segmentation.clear_border(distance_opened) # remove small objects. Remove small objects wants a # labeled image and will fail if there is only one label. Return zero image in that case # could have used try/except but remove_small_objects loves to issue warnings. cleared, label_num = morphology.label(cleared, connectivity=1, return_num=True) if label_num > 1: cleared = morphology.remove_small_objects(cleared, min_size=min_object_size) else: # if there are no labels, then just return the cleared image as it is zero return np.zeros_like(image) # relabel now that small objects and labels on edges have been cleared markers = morphology.label(cleared, connectivity=1) # just break if there is no label if np.amax(markers) == 0: return np.zeros_like(image) # the binary image for the watershed, which uses the unmodified OTSU threshold threshholded_watershed = threshholded threshholded_watershed = segmentation.clear_border(threshholded_watershed) # label using the random walker (diffusion watershed) algorithm try: # set anything outside of OTSU threshold to -1 so it will not be labeled markers[threshholded_watershed == 0] = -1 # here is the main algorithm labeled_image = segmentation.random_walker(-1*image, markers) # put negative values back to zero for proper image labeled_image[labeled_image == -1] = 0 except: return np.zeros_like(image) return labeled_image # loss functions for model def dice_coeff(y_true, y_pred): smooth = 1. # Flatten y_true_f = tf.reshape(y_true, [-1]) y_pred_f = tf.reshape(y_pred, [-1]) intersection = tf.reduce_sum(y_true_f * y_pred_f) score = (2. * intersection + smooth) / (tf.reduce_sum(y_true_f) + tf.reduce_sum(y_pred_f) + smooth) return score def dice_loss(y_true, y_pred): loss = 1 - dice_coeff(y_true, y_pred) return loss def bce_dice_loss(y_true, y_pred): loss = losses.binary_crossentropy(y_true, y_pred) + dice_loss(y_true, y_pred) return loss def tversky_loss(y_true, y_pred): alpha = 0.5 beta = 0.5 ones = K.ones((512,512,3)) #K.ones(K.shape(y_true)) p0 = y_pred # proba that voxels are class i p1 = ones-y_pred # proba that voxels are not class i g0 = y_true g1 = ones-y_true num = K.sum(p0*g0, (0,1,2)) den = num + alpha*K.sum(p0*g1,(0,1,2)) + beta*K.sum(p1*g0,(0,1,2)) T = K.sum(num/den) # when summing over classes, T has dynamic range [0 Ncl] Ncl = K.cast(K.shape(y_true)[-1], 'float32') return Ncl-T def cce_tversky_loss(y_true, y_pred): loss = losses.categorical_crossentropy(y_true, y_pred) + tversky_loss(y_true, y_pred) return loss def get_pad_distances(unet_shape, img_height, img_width): '''Finds padding and trimming sizes to make the input image the same as the size expected by the U-net model. Padding is done evenly to the top and bottom of the image. Trimming is only done from the right or bottom. ''' half_width_pad = (unet_shape[1]-img_width)/2 if half_width_pad > 0: left_pad = int(np.floor(half_width_pad)) right_pad = int(np.ceil(half_width_pad)) right_trim = 0 else: left_pad = 0 right_pad = 0 right_trim = img_width - unet_shape[1] half_height_pad = (unet_shape[0]-img_height)/2 if half_height_pad > 0: top_pad = int(np.floor(half_height_pad)) bottom_pad = int(np.ceil(half_height_pad)) bottom_trim = 0 else: top_pad = 0 bottom_pad = 0 bottom_trim = img_height - unet_shape[0] pad_dict = {'top_pad' : top_pad, 'bottom_pad' : bottom_pad, 'right_pad' : right_pad, 'left_pad' : left_pad, 'bottom_trim' : bottom_trim, 'right_trim' : right_trim} return pad_dict #@profile def segment_cells_unet(ana_peak_ids, fov_id, pad_dict, unet_shape, model): batch_size = params['segment']['batch_size'] cellClassThreshold = params['segment']['cell_class_threshold'] if cellClassThreshold == 'None': # yaml imports None as a string cellClassThreshold = False min_object_size = params['segment']['min_object_size'] # arguments to data generator # data_gen_args = {'batch_size':batch_size, # 'n_channels':1, # 'normalize_to_one':False, # 'shuffle':False} # arguments to predict_generator predict_args = dict(use_multiprocessing=True, workers=params['num_analyzers'], verbose=1) for peak_id in ana_peak_ids: information('Segmenting peak {}.'.format(peak_id)) img_stack = load_stack(fov_id, peak_id, color=params['phase_plane']) if params['segment']['normalize_to_one']: med_stack = np.zeros(img_stack.shape) selem = morphology.disk(1) for frame_idx in range(img_stack.shape[0]): tmpImg = img_stack[frame_idx,...] med_stack[frame_idx,...] = median(tmpImg, selem) # robust normalization of peak's image stack to 1 max_val = np.max(med_stack) img_stack = img_stack/max_val img_stack[img_stack > 1] = 1 # trim and pad image to correct size img_stack = img_stack[:, :unet_shape[0], :unet_shape[1]] img_stack = np.pad(img_stack, ((0,0), (pad_dict['top_pad'],pad_dict['bottom_pad']), (pad_dict['left_pad'],pad_dict['right_pad'])), mode='constant') img_stack = np.expand_dims(img_stack, -1) # TF expects images to be 4D # set up image generator # image_generator = CellSegmentationDataGenerator(img_stack, **data_gen_args) image_datagen = ImageDataGenerator() image_generator = image_datagen.flow(x=img_stack, batch_size=batch_size, shuffle=False) # keep same order # predict cell locations. This has multiprocessing built in but I need to mess with the parameters to see how to best utilize it. *** predictions = model.predict_generator(image_generator, **predict_args) # post processing # remove padding including the added last dimension predictions = predictions[:, pad_dict['top_pad']:unet_shape[0]-pad_dict['bottom_pad'], pad_dict['left_pad']:unet_shape[1]-pad_dict['right_pad'], 0] # pad back incase the image had been trimmed predictions = np.pad(predictions, ((0,0), (0,pad_dict['bottom_trim']), (0,pad_dict['right_trim'])), mode='constant') if params['segment']['save_predictions']: pred_filename = params['experiment_name'] + '_xy%03d_p%04d_%s.tif' % (fov_id, peak_id, params['pred_img']) if not os.path.isdir(params['pred_dir']): os.makedirs(params['pred_dir']) int_preds = (predictions * 255).astype('uint8') tiff.imsave(os.path.join(params['pred_dir'], pred_filename), int_preds, compress=4) # binarized and label (if there is a threshold value, otherwise, save a grayscale for debug) if cellClassThreshold: predictions[predictions >= cellClassThreshold] = 1 predictions[predictions < cellClassThreshold] = 0 predictions = predictions.astype('uint8') segmented_imgs = np.zeros(predictions.shape, dtype='uint8') # process and label each frame of the channel for frame in range(segmented_imgs.shape[0]): # get rid of small holes predictions[frame,:,:] = morphology.remove_small_holes(predictions[frame,:,:], min_object_size) # get rid of small objects. predictions[frame,:,:] = morphology.remove_small_objects(morphology.label(predictions[frame,:,:], connectivity=1), min_size=min_object_size) # remove labels which touch the boarder predictions[frame,:,:] = segmentation.clear_border(predictions[frame,:,:]) # relabel now segmented_imgs[frame,:,:] = morphology.label(predictions[frame,:,:], connectivity=1) else: # in this case you just want to scale the 0 to 1 float image to 0 to 255 information('Converting predictions to grayscale.') segmented_imgs = np.around(predictions * 100) # both binary and grayscale should be 8bit. This may be ensured above and is unneccesary segmented_imgs = segmented_imgs.astype('uint8') # save out the segmented stacks if params['output'] == 'TIFF': seg_filename = params['experiment_name'] + '_xy%03d_p%04d_%s.tif' % (fov_id, peak_id, params['seg_img']) tiff.imsave(os.path.join(params['seg_dir'], seg_filename), segmented_imgs, compress=4) if params['output'] == 'HDF5': h5f = h5py.File(os.path.join(params['hdf5_dir'],'xy%03d.hdf5' % fov_id), 'r+') # put segmented channel in correct group h5g = h5f['channel_%04d' % peak_id] # delete the dataset if it exists (important for debug) if 'p%04d_%s' % (peak_id, params['seg_img']) in h5g: del h5g['p%04d_%s' % (peak_id, params['seg_img'])] h5ds = h5g.create_dataset(u'p%04d_%s' % (peak_id, params['seg_img']), data=segmented_imgs, chunks=(1, segmented_imgs.shape[1], segmented_imgs.shape[2]), maxshape=(None, segmented_imgs.shape[1], segmented_imgs.shape[2]), compression="gzip", shuffle=True, fletcher32=True) h5f.close() #@profile def segment_fov_unet(fov_id, specs, model, color=None): ''' Segments the channels from one fov using the U-net CNN model. Parameters ---------- fov_id : int specs : dict model : TensorFlow model ''' information('Segmenting FOV {} with U-net.'.format(fov_id)) if color is None: color = params['phase_plane'] # load segmentation parameters unet_shape = (params['segment']['trained_model_image_height'], params['segment']['trained_model_image_width']) ### determine stitching of images. # need channel shape, specifically the width. load first for example # this assumes that all channels are the same size for this FOV, which they should for peak_id, spec in six.iteritems(specs[fov_id]): if spec == 1: break # just break out with the current peak_id img_stack = load_stack(fov_id, peak_id, color=color) img_height = img_stack.shape[1] img_width = img_stack.shape[2] pad_dict = get_pad_distances(unet_shape, img_height, img_width) # dermine how many channels we have to analyze for this FOV ana_peak_ids = [] for peak_id, spec in six.iteritems(specs[fov_id]): if spec == 1: ana_peak_ids.append(peak_id) ana_peak_ids.sort() # sort for repeatability #ana_peak_ids = ana_peak_ids[:2] segment_cells_unet(ana_peak_ids, fov_id, pad_dict, unet_shape, model) information("Finished segmentation for FOV {}.".format(fov_id)) return def segment_foci_unet(ana_peak_ids, fov_id, pad_dict, unet_shape, model): # batch_size = params['foci']['batch_size'] focusClassThreshold = params['foci']['focus_threshold'] if focusClassThreshold == 'None': # yaml imports None as a string focusClassThreshold = False # arguments to data generator data_gen_args = {'batch_size':params['foci']['batch_size'], 'n_channels':1, 'normalize_to_one':False, 'shuffle':False} # arguments to predict_generator predict_args = dict(use_multiprocessing=False, # workers=params['num_analyzers'], verbose=1) for peak_id in ana_peak_ids: information('Segmenting foci in peak {}.'.format(peak_id)) # print(peak_id) # debugging a shape error at some traps img_stack = load_stack(fov_id, peak_id, color=params['foci']['foci_plane']) # pad image to correct size img_stack = np.pad(img_stack, ((0,0), (pad_dict['top_pad'],pad_dict['bottom_pad']), (pad_dict['left_pad'],pad_dict['right_pad'])), mode='constant') img_stack = np.expand_dims(img_stack, -1) # set up image generator image_generator = FocusSegmentationDataGenerator(img_stack, **data_gen_args) # predict foci locations. predictions = model.predict_generator(image_generator, **predict_args) # post processing # remove padding including the added last dimension predictions = predictions[:, pad_dict['top_pad']:unet_shape[0]-pad_dict['bottom_pad'], pad_dict['left_pad']:unet_shape[1]-pad_dict['right_pad'], 0] if params['foci']['save_predictions']: pred_filename = params['experiment_name'] + '_xy%03d_p%04d_%s.tif' % (fov_id, peak_id, params['pred_img']) if not os.path.isdir(params['foci_pred_dir']): os.makedirs(params['foci_pred_dir']) int_preds = (predictions * 255).astype('uint8') tiff.imsave(os.path.join(params['foci_pred_dir'], pred_filename), int_preds, compress=4) # binarized and label (if there is a threshold value, otherwise, save a grayscale for debug) if focusClassThreshold: predictions[predictions >= focusClassThreshold] = 1 predictions[predictions < focusClassThreshold] = 0 predictions = predictions.astype('uint8') segmented_imgs = np.zeros(predictions.shape, dtype='uint8') # process and label each frame of the channel for frame in range(segmented_imgs.shape[0]): # get rid of small holes # predictions[frame,:,:] = morphology.remove_small_holes(predictions[frame,:,:], min_object_size) # get rid of small objects. # predictions[frame,:,:] = morphology.remove_small_objects(morphology.label(predictions[frame,:,:], connectivity=1), min_size=min_object_size) # remove labels which touch the boarder predictions[frame,:,:] = segmentation.clear_border(predictions[frame,:,:]) # relabel now segmented_imgs[frame,:,:] = morphology.label(predictions[frame,:,:], connectivity=2) else: # in this case you just want to scale the 0 to 1 float image to 0 to 255 information('Converting predictions to grayscale.') segmented_imgs = np.around(predictions * 100) # both binary and grayscale should be 8bit. This may be ensured above and is unneccesary segmented_imgs = segmented_imgs.astype('uint8') # save out the segmented stacks if params['output'] == 'TIFF': seg_filename = params['experiment_name'] + '_xy%03d_p%04d_%s.tif' % (fov_id, peak_id, params['seg_img']) tiff.imsave(os.path.join(params['foci_seg_dir'], seg_filename), segmented_imgs, compress=4) if params['output'] == 'HDF5': h5f = h5py.File(os.path.join(params['hdf5_dir'],'xy%03d.hdf5' % fov_id), 'r+') # put segmented channel in correct group h5g = h5f['channel_%04d' % peak_id] # delete the dataset if it exists (important for debug) if 'p%04d_%s' % (peak_id, params['seg_img']) in h5g: del h5g['p%04d_%s' % (peak_id, params['seg_img'])] h5ds = h5g.create_dataset(u'p%04d_%s' % (peak_id, params['seg_img']), data=segmented_imgs, chunks=(1, segmented_imgs.shape[1], segmented_imgs.shape[2]), maxshape=(None, segmented_imgs.shape[1], segmented_imgs.shape[2]), compression="gzip", shuffle=True, fletcher32=True) h5f.close() def segment_fov_foci_unet(fov_id, specs, model, color=None): ''' Segments the channels from one fov using the U-net CNN model. Parameters ---------- fov_id : int specs : dict model : TensorFlow model ''' information('Segmenting FOV {} with U-net.'.format(fov_id)) if color is None: color = params['phase_plane'] # load segmentation parameters unet_shape = (params['segment']['trained_model_image_height'], params['segment']['trained_model_image_width']) ### determine stitching of images. # need channel shape, specifically the width. load first for example # this assumes that all channels are the same size for this FOV, which they should for peak_id, spec in six.iteritems(specs[fov_id]): if spec == 1: break # just break out with the current peak_id img_stack = load_stack(fov_id, peak_id, color=color) img_height = img_stack.shape[1] img_width = img_stack.shape[2] # find padding and trimming distances pad_dict = get_pad_distances(unet_shape, img_height, img_width) # timepoints = img_stack.shape[0] # dermine how many channels we have to analyze for this FOV ana_peak_ids = [] for peak_id, spec in six.iteritems(specs[fov_id]): if spec == 1: ana_peak_ids.append(peak_id) ana_peak_ids.sort() # sort for repeatability k = segment_foci_unet(ana_peak_ids, fov_id, pad_dict, unet_shape, model) information("Finished segmentation for FOV {}.".format(fov_id)) return(k) # class for image generation for predicting cell locations in phase-contrast images class CellSegmentationDataGenerator(utils.Sequence): 'Generates data for Keras' def __init__(self, img_array, batch_size=32, n_channels=1, shuffle=False, normalize_to_one=False): 'Initialization' self.dim = (img_array.shape[1], img_array.shape[2]) self.batch_size = batch_size self.img_array = img_array self.img_number = img_array.shape[0] self.n_channels = n_channels self.shuffle = shuffle self.on_epoch_end() self.normalize_to_one = normalize_to_one if normalize_to_one: self.selem = morphology.disk(1) def __len__(self): 'Denotes the number of batches per epoch' return(int(np.ceil(self.img_number / self.batch_size))) def __getitem__(self, index): 'Generate one batch of data' # Generate indexes of the batch indexes = self.indexes[index*self.batch_size:(index+1)*self.batch_size] # Find list of IDs array_list_temp = [self.img_array[k,:,:,0] for k in indexes] # Generate data X = self.__data_generation(array_list_temp) return X def on_epoch_end(self): 'Updates indexes after each epoch' self.indexes = np.arange(self.img_number) if self.shuffle == True: np.random.shuffle(self.indexes) def __data_generation(self, array_list_temp): 'Generates data containing batch_size samples' # X : (n_samples, *dim, n_channels) # Initialization X = np.zeros((self.batch_size, self.dim[0], self.dim[1], self.n_channels)) # Generate data for i in range(self.batch_size): # Store sample try: tmpImg = array_list_temp[i] except IndexError: X = X[:i,...] break # ensure image is uint8 if tmpImg.dtype=="uint16": tmpImg = tmpImg / 2**16 * 2**8 tmpImg = tmpImg.astype('uint8') if self.normalize_to_one: with warnings.catch_warnings(): warnings.simplefilter('ignore') medImg = median(tmpImg, self.selem) tmpImg = tmpImg/np.max(medImg) tmpImg[tmpImg > 1] = 1 X[i,:,:,0] = tmpImg return (X) class TemporalCellDataGenerator(utils.Sequence): 'Generates data for Keras' def __init__(self, fileName, batch_size=32, dim=(32,32,32), n_channels=1, n_classes=10, shuffle=False, normalize_to_one=False): 'Initialization' self.dim = dim self.batch_size = batch_size self.fileName = fileName self.n_channels = n_channels self.n_classes = n_classes self.shuffle = shuffle self.on_epoch_end() self.normalize_to_one = normalize_to_one if normalize_to_one: self.selem = morphology.disk(1) def __len__(self): 'Denotes the number of batches per epoch' return int(np.ceil(self.batch_size / self.batch_size)) def __getitem__(self, index): 'Generate one batch of data' # Generate data X = self.__data_generation() return X def on_epoch_end(self): 'Updates indexes after each epoch' pass def __data_generation(self): 'Generates data containing batch_size samples' # X : (n_samples, *dim, n_channels) # Initialization X = np.zeros((self.batch_size, self.dim[0], self.dim[1], self.dim[2], self.n_channels)) full_stack = io.imread(self.fileName) if full_stack.dtype=="uint16": full_stack = full_stack / 2**16 * 2**8 full_stack = full_stack.astype('uint8') img_height = full_stack.shape[1] img_width = full_stack.shape[2] pad_dict = get_pad_distances(self.dim, img_height, img_width) full_stack = np.pad(full_stack, ((0,0), (pad_dict['top_pad'],pad_dict['bottom_pad']), (pad_dict['left_pad'],pad_dict['right_pad']) ), mode='constant') full_stack = full_stack.transpose(1,2,0) # Generate data for i in range(self.batch_size): if i == 0: tmpImg = np.zeros((self.dim[0], self.dim[1], self.dim[2], 1)) tmpImg[:,:,0,0] = full_stack[:,:,0] for j in range(1,self.dim[2]): tmpImg[:,:,j,0] = full_stack[:,:,j] elif i == (self.batch_size - 1): tmpImg = np.zeros((self.dim[0], self.dim[1], self.dim[2], 1)) tmpImg[:,:,-1,0] = full_stack[:,:,-1] for j in range(self.dim[2]-1): tmpImg[:,:,j,0] = full_stack[:,:,j] else: tmpImg = np.zeros((self.dim[0], self.dim[1], self.dim[2], 1)) tmpImg[:,:,:,0] = full_stack[:,:,(i-1):(i+2)] X[i,:,:,:,:] = tmpImg return X # class for image generation for predicting cell locations in phase-contrast images class FocusSegmentationDataGenerator(utils.Sequence): 'Generates data for Keras' def __init__(self, img_array, batch_size=32, n_channels=1, shuffle=False, normalize_to_one=False): 'Initialization' self.dim = (img_array.shape[1], img_array.shape[2]) self.batch_size = batch_size self.img_array = img_array self.img_number = img_array.shape[0] self.n_channels = n_channels self.shuffle = shuffle self.on_epoch_end() self.normalize_to_one = normalize_to_one if normalize_to_one: self.selem = morphology.disk(1) def __len__(self): 'Denotes the number of batches per epoch' return(int(np.ceil(self.img_number / self.batch_size))) def __getitem__(self, index): 'Generate one batch of data' # Generate indexes of the batch indexes = self.indexes[index*self.batch_size:(index+1)*self.batch_size] # Find list of IDs array_list_temp = [self.img_array[k,:,:,0] for k in indexes] # Generate data X = self.__data_generation(array_list_temp) return X def on_epoch_end(self): 'Updates indexes after each epoch' self.indexes = np.arange(self.img_number) if self.shuffle == True: np.random.shuffle(self.indexes) def __data_generation(self, array_list_temp): 'Generates data containing batch_size samples' # X : (n_samples, *dim, n_channels) # Initialization X = np.zeros((self.batch_size, self.dim[0], self.dim[1], self.n_channels), 'uint16') if self.normalize_to_one: max_pixels = [] # Generate data for i in range(self.batch_size): # Store sample try: tmpImg = array_list_temp[i] if self.normalize_to_one: # tmpMedian = filters.median(tmpImg, self.selem) tmpMax = np.max(tmpImg) max_pixels.append(tmpMax) except IndexError: X = X[:i,...] break # ensure image is uint8 # if tmpImg.dtype=="uint16": # tmpImg = tmpImg / 2**16 * 2**8 # tmpImg = tmpImg.astype('uint8') # if self.normalize_to_one: # with warnings.catch_warnings(): # warnings.simplefilter('ignore') # medImg = median(tmpImg, self.selem) # tmpImg = tmpImg/np.max(medImg) # tmpImg[tmpImg > 1] = 1 X[i,:,:,0] = tmpImg if self.normalize_to_one: channel_max = np.max(max_pixels) / (2**8 - 1) # print("Channel max: {}".format(channel_max)) # print("Array max: {}".format(np.max(X))) X = X/channel_max # print("Normalized array max: {}".format(np.max(X))) X[X > 1] = 1 return (X) # class for image generation for predicting trap locations in phase-contrast images class TrapSegmentationDataGenerator(utils.Sequence): 'Generates data for Keras' def __init__(self, img_array, batch_size=32, n_channels=1, normalize_to_one=False, shuffle=False): 'Initialization' self.dim = (img_array.shape[1], img_array.shape[2]) self.img_number = img_array.shape[0] self.img_array = img_array self.batch_size = batch_size self.n_channels = n_channels self.shuffle = shuffle self.on_epoch_end() self.normalize_to_one = normalize_to_one if normalize_to_one: self.selem = morphology.disk(3) def __len__(self): 'Denotes the number of batches per epoch' return int(np.ceil(self.img_number / self.batch_size)) def __getitem__(self, index): 'Generate one batch of data' # Generate indexes of the batch indexes = self.indexes[index*self.batch_size:(index+1)*self.batch_size] # Find list of IDs array_list_temp = [self.img_array[k,:,:,0] for k in indexes] # Generate data X = self.__data_generation(array_list_temp) return X def on_epoch_end(self): 'Updates indexes after each epoch' self.indexes = np.arange(self.img_number) if self.shuffle == True: np.random.shuffle(self.indexes) def __data_generation(self, array_list_temp): 'Generates data containing batch_size samples' # X : (n_samples, *dim, n_channels) # Initialization X = np.zeros((self.batch_size, self.dim[0], self.dim[1], self.n_channels)) # Generate data for i in range(self.batch_size): # Store sample try: tmpImg = array_list_temp[i] except IndexError: X = X[:i,...] break if self.normalize_to_one: medImg = median(tmpImg, self.selem) tmpImg = medImg/np.max(medImg) X[i,:,:,0] = tmpImg return (X) # class for image generation for classifying traps as good, empty, out-of-focus, or defective class TrapKymographPredictionDataGenerator(utils.Sequence): 'Generates data for Keras' def __init__(self, list_fileNames, batch_size=32, dim=(32,32,32), n_channels=1, n_classes=10, shuffle=False): 'Initialization' self.dim = dim self.batch_size = batch_size self.list_fileNames = list_fileNames self.n_channels = n_channels self.n_classes = n_classes self.shuffle = shuffle self.on_epoch_end() def __len__(self): 'Denotes the number of batches per epoch' return int(np.ceil(len(self.list_fileNames) / self.batch_size)) def __getitem__(self, index): 'Generate one batch of data' # Generate indexes of the batch indexes = self.indexes[index*self.batch_size:(index+1)*self.batch_size] # Find list of IDs list_fileNames_temp = [self.list_fileNames[k] for k in indexes] # Generate data X = self.__data_generation(list_fileNames_temp) return X def on_epoch_end(self): 'Updates indexes after each epoch' self.indexes = np.arange(len(self.list_fileNames)) if self.shuffle == True: np.random.shuffle(self.indexes) def __data_generation(self, list_fileNames_temp): 'Generates data containing batch_size samples' # X : (n_samples, *dim, n_channels) # Initialization X = np.zeros((self.batch_size, self.dim[0], self.dim[1], self.n_channels)) # Generate data for i, fName in enumerate(list_fileNames_temp): # Store sample tmpImg = io.imread(fName) tmpImgShape = tmpImg.shape if tmpImgShape[0] < self.dim[0]: t_end = tmpImgShape[0] else: t_end = self.dim[0] X[i,:t_end,:,:] = np.expand_dims(tmpImg[:t_end,:,tmpImg.shape[-1]//2], axis=-1) return X def absolute_diff(y_true, y_pred): y_true_sum = K.sum(y_true) y_pred_sum = K.sum(y_pred) diff = K.abs(y_pred_sum - y_true_sum)/tf.to_float(tf.size(y_true)) return diff def all_loss(y_true, y_pred): loss = losses.binary_crossentropy(y_true, y_pred) + dice_loss(y_true, y_pred) + absolute_diff(y_true, y_pred) return loss def absolute_dice_loss(y_true, y_pred): loss = dice_loss(y_true, y_pred) + absolute_diff(y_true, y_pred) return loss def recall_m(y_true, y_pred): true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) possible_positives = K.sum(K.round(K.clip(y_true, 0, 1))) recall = true_positives / (possible_positives + K.epsilon()) return recall def precision_m(y_true, y_pred): true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1))) precision = true_positives / (predicted_positives + K.epsilon()) return precision def f1_m(y_true, y_pred): precision = precision_m(y_true, y_pred) recall = recall_m(y_true, y_pred) return 2*((precision*recall)/(precision+recall+K.epsilon())) def f2_m(y_true, y_pred, beta=2): precision = precision_m(y_true, y_pred) recall = recall_m(y_true, y_pred) numer = (1+beta**2)*recall*precision denom = recall + (beta**2)*precision + K.epsilon() return numer/denom def f_precision_m(y_true, y_pred, beta=0.5): precision = precision_m(y_true, y_pred) recall = recall_m(y_true, y_pred) numer = (1+beta**2)*recall*precision denom = recall + (beta**2)*precision + K.epsilon() return numer/denom # finds lineages for all peaks in a fov def make_lineages_fov(fov_id, specs): ''' For a given fov, create the lineages from the segmented images. Called by mm3_Segment.py Calls mm3.make_lineage_chnl_stack ''' ana_peak_ids = [] # channels to be analyzed for peak_id, spec in six.iteritems(specs[fov_id]): if spec == 1: # 1 means analyze ana_peak_ids.append(peak_id) ana_peak_ids = sorted(ana_peak_ids) # sort for repeatability information('Creating lineage for FOV %d with %d channels.' % (fov_id, len(ana_peak_ids))) # just break if there are no peaks to analize if not ana_peak_ids: # returning empty dictionary will add nothing to current cells dictionary return {} # This is a list of tuples (fov_id, peak_id) to send to the Pool command fov_and_peak_ids_list = [(fov_id, peak_id) for peak_id in ana_peak_ids] # set up multiprocessing pool. will complete pool before going on #pool = Pool(processes=params['num_analyzers']) # create the lineages for each peak individually # the output is a list of dictionaries #lineages = pool.map(make_lineage_chnl_stack, fov_and_peak_ids_list, chunksize=8) #pool.close() # tells the process nothing more will be added. #pool.join() # blocks script until everything has been processed and workers exit # This is the non-parallelized version (useful for debug) lineages = [] for fov_and_peak_ids in fov_and_peak_ids_list: lineages.append(make_lineage_chnl_stack(fov_and_peak_ids)) # combine all dictionaries into one dictionary Cells = {} # create dictionary to hold all information for cell_dict in lineages: # for all the other dictionaries in the list Cells.update(cell_dict) # updates Cells with the entries in cell_dict return Cells # get number of cells in each frame and total number of pairwise interactions def get_cell_counts(regionprops_list): cell_count_list = [len(time_regions) for time_regions in regionprops_list] interaction_count_list = [] for i,cell_count in enumerate(cell_count_list): if i+1 == len(cell_count_list): break interaction_count_list.append(cell_count*cell_count_list[i+1]) total_cells = np.sum(cell_count_list) total_interactions = np.sum(interaction_count_list) return(total_cells, total_interactions, cell_count_list, interaction_count_list) # get cells' information for track prediction def gather_interactions_and_events(regionprops_list): total_cells, total_interactions, cell_count_list, interaction_count_list = get_cell_counts(regionprops_list) # instantiate an array with a 2x4 array for each pair of cells' # min_y, max_y, centroid_y, and area # in reality it would be much, much more efficient to # look this information up in the data generator at run time # for now, this will work pairwise_cell_data = np.zeros((total_interactions,2,5,1)) # make a dictionary, the keys of which will be row indices so that we # can quickly look up which timepoints/cells correspond to which # rows of our model's ouput pairwise_cell_lookup = {} # populate arrays interaction_count = 0 cell_count = 0 for frame, frame_regions in enumerate(regionprops_list): for region in frame_regions: cell_label = region.label y,x = region.centroid bbox = region.bbox orientation = region.orientation min_y = bbox[0] max_y = bbox[2] area = region.area cell_label = region.label cell_info = (min_y, max_y, y, area, orientation) cell_count += 1 try: frame_plus_one_regions = regionprops_list[frame+1] except IndexError as e: # print(e) break for region_plus_one in frame_plus_one_regions: paired_cell_label = region_plus_one.label y,x = region_plus_one.centroid bbox = region_plus_one.bbox min_y = bbox[0] max_y = bbox[2] area = region_plus_one.area paired_cell_label = region_plus_one.label pairwise_cell_data[interaction_count,0,:,0] = cell_info pairwise_cell_data[interaction_count,1,:,0] = (min_y, max_y, y, area, orientation) pairwise_cell_lookup[interaction_count] = {'frame':frame, 'cell_label':cell_label, 'paired_cell_label':paired_cell_label} interaction_count += 1 return(pairwise_cell_data, pairwise_cell_lookup) # look up which cells are interacting according to the track model def cell_interaction_lookup(predictions, lookup_table): ''' Accepts prediction matrix and ''' frame = [] cell_label = [] paired_cell_label = [] interaction_type = [] # loop over rows of predictions for row_index in range(predictions.shape[0]): row_predictions = predictions[row_index] row_relationship = np.where(row_predictions > 0.95)[0] if row_relationship.size == 0: continue elif row_relationship[0] == 3: continue elif row_relationship[0] == 0: interaction_type.append('migration') elif row_relationship[0] == 1: interaction_type.append('child') elif row_relationship[0] == 2: interaction_type.append('false_join') frame.append(lookup_table[row_index]['frame']) cell_label.append(lookup_table[row_index]['cell_label']) paired_cell_label.append(lookup_table[row_index]['paired_cell_label']) track_df = pd.DataFrame(data={'frame':frame, 'cell_label':cell_label, 'paired_cell_label':paired_cell_label, 'interaction_type':interaction_type}) return(track_df) def get_tracking_model_dict(): model_dict = {} if not 'migrate_model' in model_dict: model_dict['migrate_model'] = models.load_model(params['tracking']['migrate_model'], custom_objects={'all_loss':all_loss, 'f2_m':f2_m}) if not 'child_model' in model_dict: model_dict['child_model'] = models.load_model(params['tracking']['child_model'], custom_objects={'bce_dice_loss':bce_dice_loss, 'f2_m':f2_m}) if not 'appear_model' in model_dict: model_dict['appear_model'] = models.load_model(params['tracking']['appear_model'], custom_objects={'all_loss':all_loss, 'f2_m':f2_m}) if not 'die_model' in model_dict: model_dict['die_model'] = models.load_model(params['tracking']['die_model'], custom_objects={'all_loss':all_loss, 'f2_m':f2_m}) if not 'disappear_model' in model_dict: model_dict['disappear_model'] = models.load_model(params['tracking']['disappear_model'], custom_objects={'all_loss':all_loss, 'f2_m':f2_m}) if not 'born_model' in model_dict: model_dict['born_model'] = models.load_model(params['tracking']['born_model'], custom_objects={'all_loss':all_loss, 'f2_m':f2_m}) # if not 'zero_cell_model' in model_dict: # model_dict['zero_cell_model'] = models.load_model(params['tracking']['zero_cell_model'], # custom_objects={'absolute_dice_loss':absolute_dice_loss, # 'f2_m':f2_m}) # if not 'one_cell_model' in model_dict: # model_dict['one_cell_model'] = models.load_model(params['tracking']['one_cell_model'], # custom_objects={'bce_dice_loss':bce_dice_loss, # 'f2_m':f2_m}) # if not 'two_cell_model' in model_dict: # model_dict['two_cell_model'] = models.load_model(params['tracking']['two_cell_model'], # custom_objects={'all_loss':all_loss, # 'f2_m':f2_m}) # if not 'geq_three_cell_model' in model_dict: # model_dict['geq_three_cell_model'] = models.load_model(params['tracking']['geq_three_cell_model'], # custom_objects={'bce_dice_loss':bce_dice_loss, # 'f2_m':f2_m}) return(model_dict) # Creates lineage for a single channel def make_lineage_chnl_stack(fov_and_peak_id): ''' Create the lineage for a set of segmented images for one channel. Start by making the regions in the first time points potenial cells. Go forward in time and map regions in the timepoint to the potential cells in previous time points, building the life of a cell. Used basic checks such as the regions should overlap, and grow by a little and not shrink too much. If regions do not link back in time, discard them. If two regions map to one previous region, check if it is a sensible division event. Parameters ---------- fov_and_peak_ids : tuple. (fov_id, peak_id) Returns ------- Cells : dict A dictionary of all the cells from this lineage, divided and undivided ''' # load in parameters # if leaf regions see no action for longer than this, drop them lost_cell_time = params['track']['lost_cell_time'] # only cells with y positions below this value will recieve the honor of becoming new # cells, unless they are daughters of current cells new_cell_y_cutoff = params['track']['new_cell_y_cutoff'] # only regions with labels less than or equal to this value will be considered to start cells new_cell_region_cutoff = params['track']['new_cell_region_cutoff'] # get the specific ids from the tuple fov_id, peak_id = fov_and_peak_id # start time is the first time point for this series of TIFFs. start_time_index = min(params['time_table'][fov_id].keys()) information('Creating lineage for FOV %d, channel %d.' % (fov_id, peak_id)) # load segmented data image_data_seg = load_stack(fov_id, peak_id, color=params['track']['seg_img']) # image_data_seg = load_stack(fov_id, peak_id, color='seg') # Calculate all data for all time points. # this list will be length of the number of time points regions_by_time = [regionprops(label_image=timepoint) for timepoint in image_data_seg] # removed coordinates='xy' # Set up data structures. Cells = {} # Dict that holds all the cell objects, divided and undivided cell_leaves = [] # cell ids of the current leaves of the growing lineage tree # go through regions by timepoint and build lineages # timepoints start with the index of the first image for t, regions in enumerate(regions_by_time, start=start_time_index): # if there are cell leaves who are still waiting to be linked, but # too much time has passed, remove them. for leaf_id in cell_leaves: if t - Cells[leaf_id].times[-1] > lost_cell_time: cell_leaves.remove(leaf_id) # make all the regions leaves if there are no current leaves if not cell_leaves: for region in regions: if region.centroid[0] < new_cell_y_cutoff and region.label <= new_cell_region_cutoff: # Create cell and put in cell dictionary cell_id = create_cell_id(region, t, peak_id, fov_id) Cells[cell_id] = Cell(cell_id, region, t, parent_id=None) # add thes id to list of current leaves cell_leaves.append(cell_id) # Determine if the regions are children of current leaves else: ### create mapping between regions and leaves leaf_region_map = {} leaf_region_map = {leaf_id : [] for leaf_id in cell_leaves} # get the last y position of current leaves and create tuple with the id current_leaf_positions = [(leaf_id, Cells[leaf_id].centroids[-1][0]) for leaf_id in cell_leaves] # go through regions, they will come off in Y position order for r, region in enumerate(regions): # create tuple which is cell_id of closest leaf, distance current_closest = (None, float('inf')) # check this region against all positions of all current leaf regions, # find the closest one in y. for leaf in current_leaf_positions: # calculate distance between region and leaf y_dist_region_to_leaf = abs(region.centroid[0] - leaf[1]) # if the distance is closer than before, update if y_dist_region_to_leaf < current_closest[1]: current_closest = (leaf[0], y_dist_region_to_leaf) # update map with the closest region leaf_region_map[current_closest[0]].append((r, y_dist_region_to_leaf)) # go through the current leaf regions. # limit by the closest two current regions if there are three regions to the leaf for leaf_id, region_links in six.iteritems(leaf_region_map): if len(region_links) > 2: closest_two_regions = sorted(region_links, key=lambda x: x[1])[:2] # but sort by region order so top region is first closest_two_regions = sorted(closest_two_regions, key=lambda x: x[0]) # replace value in dictionary leaf_region_map[leaf_id] = closest_two_regions # for the discarded regions, put them as new leaves # if they are near the closed end of the channel discarded_regions = sorted(region_links, key=lambda x: x[1])[2:] for discarded_region in discarded_regions: region = regions[discarded_region[0]] if region.centroid[0] < new_cell_y_cutoff and region.label <= new_cell_region_cutoff: cell_id = create_cell_id(region, t, peak_id, fov_id) Cells[cell_id] = Cell(cell_id, region, t, parent_id=None) cell_leaves.append(cell_id) # add to leaves else: # since the regions are ordered, none of the remaining will pass break ### iterate over the leaves, looking to see what regions connect to them. for leaf_id, region_links in six.iteritems(leaf_region_map): # if there is just one suggested descendant, # see if it checks out and append the data if len(region_links) == 1: region = regions[region_links[0][0]] # grab the region from the list # check if the pairing makes sense based on size and position # this function returns true if things are okay if check_growth_by_region(Cells[leaf_id], region): # grow the cell by the region in this case Cells[leaf_id].grow(region, t) # there may be two daughters, or maybe there is just one child and a new cell elif len(region_links) == 2: # grab these two daughters region1 = regions[region_links[0][0]] region2 = regions[region_links[1][0]] # check_division returns 3 if cell divided, # 1 if first region is just the cell growing and the second is trash # 2 if the second region is the cell, and the first is trash # or 0 if it cannot be determined. check_division_result = check_division(Cells[leaf_id], region1, region2) if check_division_result == 3: # create two new cells and divide the mother daughter1_id = create_cell_id(region1, t, peak_id, fov_id) daughter2_id = create_cell_id(region2, t, peak_id, fov_id) Cells[daughter1_id] = Cell(daughter1_id, region1, t, parent_id=leaf_id) Cells[daughter2_id] = Cell(daughter2_id, region2, t, parent_id=leaf_id) Cells[leaf_id].divide(Cells[daughter1_id], Cells[daughter2_id], t) # remove mother from current leaves cell_leaves.remove(leaf_id) # add the daughter ids to list of current leaves if they pass cutoffs if region1.centroid[0] < new_cell_y_cutoff and region1.label <= new_cell_region_cutoff: cell_leaves.append(daughter1_id) if region2.centroid[0] < new_cell_y_cutoff and region2.label <= new_cell_region_cutoff: cell_leaves.append(daughter2_id) # 1 means that daughter 1 is just a continuation of the mother # The other region should be a leaf it passes the requirements elif check_division_result == 1: Cells[leaf_id].grow(region1, t) if region2.centroid[0] < new_cell_y_cutoff and region2.label <= new_cell_region_cutoff: cell_id = create_cell_id(region2, t, peak_id, fov_id) Cells[cell_id] = Cell(cell_id, region2, t, parent_id=None) cell_leaves.append(cell_id) # add to leaves # ditto for 2 elif check_division_result == 2: Cells[leaf_id].grow(region2, t) if region1.centroid[0] < new_cell_y_cutoff and region1.label <= new_cell_region_cutoff: cell_id = create_cell_id(region1, t, peak_id, fov_id) Cells[cell_id] = Cell(cell_id, region1, t, parent_id=None) cell_leaves.append(cell_id) # add to leaves # return the dictionary with all the cells return Cells ### Cell class and related functions # this is the object that holds all information for a detection class Detection(): ''' The Detection is a single detection in a single frame. ''' # initialize (birth) the cell def __init__(self, detection_id, region, t): '''The detection must be given a unique detection_id and passed the region information from the segmentation Parameters __________ detection_id : str detection_id is a string in the form fXpXtXrX f is 3 digit FOV number p is 4 digit peak number t is 4 digit time point r is region label for that segmentation Use the function create_detection_id to return a proper string. region : region properties object Information about the labeled region from skimage.measure.regionprops() ''' # create all the attributes # id self.id = detection_id # identification convenience self.fov = int(detection_id.split('f')[1].split('p')[0]) self.peak = int(detection_id.split('p')[1].split('t')[0]) self.t = t self.cell_count = 1 # self.abs_times = [params['time_table'][self.fov][t]] # elapsed time in seconds if region is not None: self.label = region.label self.bbox = region.bbox self.area = region.area # calculating cell length and width by using Feret Diamter. These values are in pixels length_tmp, width_tmp = feretdiameter(region) if length_tmp == None: warning('feretdiameter() failed for ' + self.id + ' at t=' + str(t) + '.') self.length = length_tmp self.width = width_tmp # calculate cell volume as cylinder plus hemispherical ends (sphere). Unit is px^3 self.volume = (length_tmp - width_tmp) * np.pi * (width_tmp/2)**2 + (4/3) * np.pi * (width_tmp/2)**3 # angle of the fit elipsoid and centroid location self.orientation = region.orientation self.centroid = region.centroid else: self.label = None self.bbox = None self.area = None # calculating cell length and width by using Feret Diamter. These values are in pixels length_tmp, width_tmp = (None, None) self.length = None self.width = None # calculate cell volume as cylinder plus hemispherical ends (sphere). Unit is px^3 self.volume = None # angle of the fit elipsoid and centroid location self.orientation = None self.centroid = None # this is the object that holds all information for a cell class Cell(): ''' The Cell class is one cell that has been born. It is not neccesarily a cell that has divided. ''' # initialize (birth) the cell def __init__(self, cell_id, region, t, parent_id=None): '''The cell must be given a unique cell_id and passed the region information from the segmentation Parameters __________ cell_id : str cell_id is a string in the form fXpXtXrX f is 3 digit FOV number p is 4 digit peak number t is 4 digit time point at time of birth r is region label for that segmentation Use the function create_cell_id to do return a proper string. region : region properties object Information about the labeled region from skimage.measure.regionprops() parent_id : str id of the parent if there is one. ''' # create all the attributes # id self.id = cell_id # identification convenience self.fov = int(cell_id.split('f')[1].split('p')[0]) self.peak = int(cell_id.split('p')[1].split('t')[0]) self.birth_label = int(cell_id.split('r')[1]) # parent id may be none self.parent = parent_id # daughters is updated when cell divides # if this is none then the cell did not divide self.daughters = None # birth and division time self.birth_time = t self.division_time = None # filled out if cell divides # the following information is on a per timepoint basis self.times = [t] self.abs_times = [params['time_table'][self.fov][t]] # elapsed time in seconds self.labels = [region.label] self.bboxes = [region.bbox] self.areas = [region.area] # calculating cell length and width by using Feret Diamter. These values are in pixels length_tmp, width_tmp = feretdiameter(region) if length_tmp == None: warning('feretdiameter() failed for ' + self.id + ' at t=' + str(t) + '.') self.lengths = [length_tmp] self.widths = [width_tmp] # calculate cell volume as cylinder plus hemispherical ends (sphere). Unit is px^3 self.volumes = [(length_tmp - width_tmp) * np.pi * (width_tmp/2)**2 + (4/3) * np.pi * (width_tmp/2)**3] # angle of the fit elipsoid and centroid location self.orientations = [region.orientation] self.centroids = [region.centroid] # these are special datatype, as they include information from the daugthers for division # computed upon division self.times_w_div = None self.lengths_w_div = None self.widths_w_div = None # this information is the "production" information that # we want to extract at the end. Some of this is for convenience. # This is only filled out if a cell divides. self.sb = None # in um self.sd = None # this should be combined lengths of daughters, in um self.delta = None self.tau = None self.elong_rate = None self.septum_position = None self.width = None self.death = None def grow(self, region, t): '''Append data from a region to this cell. use cell.times[-1] to get most current value''' self.times.append(t) self.abs_times.append(params['time_table'][self.fov][t]) self.labels.append(region.label) self.bboxes.append(region.bbox) self.areas.append(region.area) #calculating cell length and width by using <NAME> length_tmp, width_tmp = feretdiameter(region) if length_tmp == None: warning('feretdiameter() failed for ' + self.id + ' at t=' + str(t) + '.') self.lengths.append(length_tmp) self.widths.append(width_tmp) self.volumes.append((length_tmp - width_tmp) * np.pi * (width_tmp/2)**2 + (4/3) * np.pi * (width_tmp/2)**3) self.orientations.append(region.orientation) self.centroids.append(region.centroid) def die(self, region, t): ''' Annotate cell as dying from current t to next t. ''' self.death = t def divide(self, daughter1, daughter2, t): '''Divide the cell and update stats. daugther1 and daugther2 are instances of the Cell class. daughter1 is the daugther closer to the closed end.''' # put the daugther ids into the cell self.daughters = [daughter1.id, daughter2.id] # give this guy a division time self.division_time = daughter1.birth_time # update times self.times_w_div = self.times + [self.division_time] self.abs_times.append(params['time_table'][self.fov][self.division_time]) # flesh out the stats for this cell # size at birth self.sb = self.lengths[0] * params['pxl2um'] # force the division length to be the combined lengths of the daughters self.sd = (daughter1.lengths[0] + daughter2.lengths[0]) * params['pxl2um'] # delta is here for convenience self.delta = self.sd - self.sb # generation time. Use more accurate times and convert to minutes self.tau = np.float64((self.abs_times[-1] - self.abs_times[0]) / 60.0) # include the data points from the daughters self.lengths_w_div = [l * params['pxl2um'] for l in self.lengths] + [self.sd] self.widths_w_div = [w * params['pxl2um'] for w in self.widths] + [((daughter1.widths[0] + daughter2.widths[0])/2) * params['pxl2um']] # volumes for all timepoints, in um^3 self.volumes_w_div = [] for i in range(len(self.lengths_w_div)): self.volumes_w_div.append((self.lengths_w_div[i] - self.widths_w_div[i]) * np.pi * (self.widths_w_div[i]/2)**2 + (4/3) * np.pi * (self.widths_w_div[i]/2)**3) # calculate elongation rate. try: times = np.float64((np.array(self.abs_times) - self.abs_times[0]) / 60.0) log_lengths = np.float64(np.log(self.lengths_w_div)) p = np.polyfit(times, log_lengths, 1) # this wants float64 self.elong_rate = p[0] * 60.0 # convert to hours except: self.elong_rate = np.float64('NaN') warning('Elongation rate calculate failed for {}.'.format(self.id)) # calculate the septum position as a number between 0 and 1 # which indicates the size of daughter closer to the closed end # compared to the total size self.septum_position = daughter1.lengths[0] / (daughter1.lengths[0] + daughter2.lengths[0]) # calculate single width over cell's life self.width = np.mean(self.widths_w_div) # convert data to smaller floats. No need for float64 # see https://docs.scipy.org/doc/numpy-1.13.0/user/basics.types.html convert_to = 'float16' # numpy datatype to convert to self.sb = self.sb.astype(convert_to) self.sd = self.sd.astype(convert_to) self.delta = self.delta.astype(convert_to) self.elong_rate = self.elong_rate.astype(convert_to) self.tau = self.tau.astype(convert_to) self.septum_position = self.septum_position.astype(convert_to) self.width = self.width.astype(convert_to) self.lengths = [length.astype(convert_to) for length in self.lengths] self.lengths_w_div = [length.astype(convert_to) for length in self.lengths_w_div] self.widths = [width.astype(convert_to) for width in self.widths] self.widths_w_div = [width.astype(convert_to) for width in self.widths_w_div] self.volumes = [vol.astype(convert_to) for vol in self.volumes] self.volumes_w_div = [vol.astype(convert_to) for vol in self.volumes_w_div] # note the float16 is hardcoded here self.orientations = [np.float16(orientation) for orientation in self.orientations] self.centroids = [(y.astype(convert_to), x.astype(convert_to)) for y, x in self.centroids] def print_info(self): '''prints information about the cell''' print('id = %s' % self.id) print('times = {}'.format(', '.join('{}'.format(t) for t in self.times))) print('lengths = {}'.format(', '.join('{:.2f}'.format(l) for l in self.lengths))) class CellTree(): def __init__(self): self.cells = {} self.scores = [] # probably needs to be different self.score = 0 self.cell_id_list = [] def add_cell(self, cell): self.cells[cell.id] = cell self.cell_id_list.append(cell.id) self.cell_id_list.sort() def update_score(self): pass def get_cell(self, cell_id): return(self.cells[cell_id]) def get_top_from_cell(self, cell_id): pass # this is the object that holds all information for a cell class CellFromGraph(): ''' The CellFromGraph class is one cell that has been born. It is not neccesarily a cell that has divided. ''' # initialize (birth) the cell def __init__(self, cell_id, region, t, parent=None): '''The cell must be given a unique cell_id and passed the region information from the segmentation Parameters __________ cell_id : str cell_id is a string in the form fXpXtXrX f is 3 digit FOV number p is 4 digit peak number t is 4 digit time point at time of birth r is region label for that segmentation Use the function create_cell_id to do return a proper string. region : region properties object Information about the labeled region from skimage.measure.regionprops() parent_id : str id of the parent if there is one. ''' # create all the attributes # id self.id = cell_id # identification convenience self.fov = int(cell_id.split('f')[1].split('p')[0]) self.peak = int(cell_id.split('p')[1].split('t')[0]) self.birth_label = int(region.label) self.regions = [region] # parent is a CellFromGraph object, can be None self.parent = parent # daughters is updated when cell divides # if this is none then the cell did not divide self.daughters = None # birth and division time self.birth_time = t self.division_time = None # filled out if cell divides # the following information is on a per timepoint basis self.times = [t] self.abs_times = [params['time_table'][self.fov][t]] # elapsed time in seconds self.labels = [region.label] self.bboxes = [region.bbox] self.areas = [region.area] # calculating cell length and width by using Feret Diamter. These values are in pixels length_tmp, width_tmp = feretdiameter(region) if length_tmp == None: warning('feretdiameter() failed for ' + self.id + ' at t=' + str(t) + '.') self.lengths = [length_tmp] self.widths = [width_tmp] # calculate cell volume as cylinder plus hemispherical ends (sphere). Unit is px^3 self.volumes = [(length_tmp - width_tmp) * np.pi * (width_tmp/2)**2 + (4/3) * np.pi * (width_tmp/2)**3] # angle of the fit elipsoid and centroid location self.orientations = [region.orientation] self.centroids = [region.centroid] # these are special datatype, as they include information from the daugthers for division # computed upon division self.times_w_div = None self.lengths_w_div = None self.widths_w_div = None # this information is the "production" information that # we want to extract at the end. Some of this is for convenience. # This is only filled out if a cell divides. self.sb = None # in um self.sd = None # this should be combined lengths of daughters, in um self.delta = None self.tau = None self.elong_rate = None self.septum_position = None self.width = None self.death = None self.disappear = None self.area_mean_fluorescence = {} self.volume_mean_fluorescence = {} self.total_fluorescence = {} self.foci = {} def __len__(self): return(len(self.times)) def add_parent(self, parent): self.parent = parent def grow(self, region, t): '''Append data from a region to this cell. use cell.times[-1] to get most current value''' self.times.append(t) self.abs_times.append(params['time_table'][self.fov][t]) self.labels.append(region.label) self.bboxes.append(region.bbox) self.areas.append(region.area) self.regions.append(region) #calculating cell length and width by using Feret Diamter length_tmp, width_tmp = feretdiameter(region) if length_tmp == None: warning('feretdiameter() failed for ' + self.id + ' at t=' + str(t) + '.') self.lengths.append(length_tmp) self.widths.append(width_tmp) self.volumes.append((length_tmp - width_tmp) * np.pi * (width_tmp/2)**2 + (4/3) * np.pi * (width_tmp/2)**3) self.orientations.append(region.orientation) self.centroids.append(region.centroid) def die(self, region, t): ''' Annotate cell as dying from current t to next t. ''' self.death = t def disappears(self, region, t): ''' Annotate cell as disappearing from current t to next t. ''' self.disappear = t def add_daughter(self, daughter, t): if self.daughters is None: self.daughters = [daughter] else: self.daughters.append(daughter) assert len(self.daughters) < 3, "Too many daughter cells in cell {}".format(self.id) # sort daughters by y position, with smaller y-value first. # this will cause the daughter closer to the closed end of the trap to be listed first. self.daughters.sort(key=lambda cell: cell.centroids[0][0]) self.divide(t) def divide(self, t): '''Divide the cell and update stats. daughter1 is the daugther closer to the closed end.''' # put the daugther ids into the cell # self.daughters = [daughter1.id, daughter2.id] # give this guy a division time self.division_time = self.daughters[0].birth_time # update times self.times_w_div = self.times + [self.division_time] self.abs_times.append(params['time_table'][self.fov][self.division_time]) # flesh out the stats for this cell # size at birth self.sb = self.lengths[0] * params['pxl2um'] # force the division length to be the combined lengths of the daughters self.sd = (self.daughters[0].lengths[0] + self.daughters[1].lengths[0]) * params['pxl2um'] # delta is here for convenience self.delta = self.sd - self.sb # generation time. Use more accurate times and convert to minutes self.tau = np.float64((self.abs_times[-1] - self.abs_times[0]) / 60.0) # include the data points from the daughters self.lengths_w_div = [l * params['pxl2um'] for l in self.lengths] + [self.sd] self.widths_w_div = [w * params['pxl2um'] for w in self.widths] + [((self.daughters[0].widths[0] + self.daughters[1].widths[0])/2) * params['pxl2um']] # volumes for all timepoints, in um^3 self.volumes_w_div = [] for i in range(len(self.lengths_w_div)): self.volumes_w_div.append((self.lengths_w_div[i] - self.widths_w_div[i]) * np.pi * (self.widths_w_div[i]/2)**2 + (4/3) * np.pi * (self.widths_w_div[i]/2)**3) # calculate elongation rate. try: times = np.float64((np.array(self.abs_times) - self.abs_times[0]) / 60.0) # convert times to minutes log_lengths = np.float64(np.log(self.lengths_w_div)) p = np.polyfit(times, log_lengths, 1) # this wants float64 self.elong_rate = p[0] * 60.0 # convert to hours except: self.elong_rate = np.float64('NaN') warning('Elongation rate calculate failed for {}.'.format(self.id)) # calculate the septum position as a number between 0 and 1 # which indicates the size of daughter closer to the closed end # compared to the total size self.septum_position = self.daughters[0].lengths[0] / (self.daughters[0].lengths[0] + self.daughters[1].lengths[0]) # calculate single width over cell's life self.width = np.mean(self.widths_w_div) # convert data to smaller floats. No need for float64 # see https://docs.scipy.org/doc/numpy-1.13.0/user/basics.types.html convert_to = 'float16' # numpy datatype to convert to self.sb = self.sb.astype(convert_to) self.sd = self.sd.astype(convert_to) self.delta = self.delta.astype(convert_to) self.elong_rate = self.elong_rate.astype(convert_to) self.tau = self.tau.astype(convert_to) self.septum_position = self.septum_position.astype(convert_to) self.width = self.width.astype(convert_to) self.lengths = [length.astype(convert_to) for length in self.lengths] self.lengths_w_div = [length.astype(convert_to) for length in self.lengths_w_div] self.widths = [width.astype(convert_to) for width in self.widths] self.widths_w_div = [width.astype(convert_to) for width in self.widths_w_div] self.volumes = [vol.astype(convert_to) for vol in self.volumes] self.volumes_w_div = [vol.astype(convert_to) for vol in self.volumes_w_div] # note the float16 is hardcoded here self.orientations = [np.float16(orientation) for orientation in self.orientations] self.centroids = [(y.astype(convert_to), x.astype(convert_to)) for y, x in self.centroids] def add_focus(self, focus, t): '''Adds a focus to the cell. See function foci_info_unet''' self.foci[focus.id] = focus def print_info(self): '''prints information about the cell''' print('id = %s' % self.id) print('times = {}'.format(', '.join('{}'.format(t) for t in self.times))) print('lengths = {}'.format(', '.join('{:.2f}'.format(l) for l in self.lengths))) if self.daughters is not None: print('daughters = {}'.format(', '.join('{}'.format(daughter.id) for daughter in self.daughters))) if self.parent is not None: print('parent = {}'.format(self.parent.id)) def make_wide_df(self): data = {} data['id'] = self.id data['fov'] = self.fov data['trap'] = self.peak data['parent'] = self.parent data['child1'] = None data['child2'] = None data['division_time'] = self.division_time data['birth_label'] = self.birth_label data['birth_time'] = self.birth_time data['sb'] = self.sb data['sd'] = self.sd data['delta'] = self.delta data['tau'] = self.tau data['elong_rate'] = self.elong_rate data['septum_position'] = self.septum_position data['death'] = self.death data['disappear'] = self.disappear if self.daughters is not None: data['child1'] = self.daughters[0] if len(self.daughters) == 2: data['child2'] = self.daughters[1] df = pd.DataFrame(data, index=[self.id]) return(df) def make_long_df(self): data = {} data['id'] = [self.id]*len(self.times) data['times'] = self.times data['length'] = self.lengths data['volume'] = self.volumes data['area'] = self.areas # if a cell divides then there is one extra value in abs_times if self.division_time is None: data['seconds'] = self.abs_times else: data['seconds'] = self.abs_times[:-1] # if there is fluorescence data, place it into the dataframe if len(self.area_mean_fluorescence.keys()) != 0: for fluorescence_channel in self.area_mean_fluorescence.keys(): data['{}_area_mean_fluorescence'.format(fluorescence_channel)] = self.area_mean_fluorescence[fluorescence_channel] data['{}_volume_mean_fluorescence'.format(fluorescence_channel)] = self.volume_mean_fluorescence[fluorescence_channel] data['{}_total_fluorescence'.format(fluorescence_channel)] = self.total_fluorescence[fluorescence_channel] df = pd.DataFrame(data, index=data['id']) return(df) # this is the object that holds all information for a fluorescent focus # this class can eventually be used in focus tracking, much like the Cell class # is used for cell tracking class Focus(): ''' The Focus class holds information on fluorescent foci. A single focus can be present in multiple different cells. ''' # initialize the focus def __init__(self, cell, region, seg_img, intensity_image, t): '''The cell must be given a unique cell_id and passed the region information from the segmentation Parameters __________ cell : a Cell object region : region properties object Information about the labeled region from skimage.measure.regionprops() seg_img : 2D numpy array Labelled image of cell segmentations intensity_image : 2D numpy array Fluorescence image with foci ''' # create all the attributes # id focus_id = create_focus_id(region, t, cell.peak, cell.fov, experiment_name=params['experiment_name']) self.id = focus_id # identification convenience self.appear_label = int(region.label) self.regions = [region] self.fov = cell.fov self.peak = cell.peak # cell is a CellFromGraph object # cells are added later using the .add_cell method self.cells = [cell] # daughters is updated when focus splits # if this is none then the focus did not split self.parent = None self.daughters = None self.merger_partner = None # appearance and split time self.appear_time = t self.split_time = None # filled out if focus splits # the following information is on a per timepoint basis self.times = [t] self.abs_times = [params['time_table'][cell.fov][t]] # elapsed time in seconds self.labels = [region.label] self.bboxes = [region.bbox] self.areas = [region.area] # calculating focus length and width by using Feret Diamter. # These values are in pixels # NOTE: in the future, update to straighten a focus an get straightened length/width # print(region) length_tmp = region.major_axis_length width_tmp = region.minor_axis_length # length_tmp, width_tmp = feretdiameter(region) # if length_tmp == None: # warning('feretdiameter() failed for ' + self.id + ' at t=' + str(t) + '.') self.lengths = [length_tmp] self.widths = [width_tmp] # calculate focus volume as cylinder plus hemispherical ends (sphere). Unit is px^3 self.volumes = [(length_tmp - width_tmp) * np.pi * (width_tmp/2)**2 + (4/3) * np.pi * (width_tmp/2)**3] # angle of the fit elipsoid and centroid location self.orientations = [region.orientation] self.centroids = [region.centroid] # special information for focci self.elong_rate = None self.disappear = None self.area_mean_fluorescence = [] self.volume_mean_fluorescence = [] self.total_fluorescence = [] self.median_fluorescence = [] self.sd_fluorescence = [] self.disp_l = [] self.disp_w = [] self.calculate_fluorescence(seg_img, intensity_image, region) def __len__(self): return(len(self.times)) def __str__(self): return(self.print_info()) def add_cell(self, cell): self.cells.append(cell) def add_parent_focus(self, parent): self.parent = parent def merge(self, partner): self.merger_partner = partner def grow(self, region, t, seg_img, intensity_image, current_cell): '''Append data from a region to this focus. use self.times[-1] to get most current value.''' if current_cell is not self.cells[-1]: self.add_cell(current_cell) self.times.append(t) self.abs_times.append(params['time_table'][self.cells[-1].fov][t]) self.labels.append(region.label) self.bboxes.append(region.bbox) self.areas.append(region.area) self.regions.append(region) #calculating focus length and width by using Feret Diamter length_tmp = region.major_axis_length width_tmp = region.minor_axis_length # length_tmp, width_tmp = feretdiameter(region) # if length_tmp == None: # warning('feretdiameter() failed for ' + self.id + ' at t=' + str(t) + '.') self.lengths.append(length_tmp) self.widths.append(width_tmp) self.volumes.append((length_tmp - width_tmp) * np.pi * (width_tmp/2)**2 + (4/3) * np.pi * (width_tmp/2)**3) self.orientations.append(region.orientation) self.centroids.append(region.centroid) self.calculate_fluorescence(seg_img, intensity_image, region) def calculate_fluorescence(self, seg_img, intensity_image, region): total_fluor = np.sum(intensity_image[seg_img == region.label]) self.total_fluorescence.append(total_fluor) self.area_mean_fluorescence.append(total_fluor/self.areas[-1]) self.volume_mean_fluorescence.append(total_fluor/self.volumes[-1]) self.median_fluorescence.append(np.median(intensity_image[seg_img == region.label])) self.sd_fluorescence.append(np.std(intensity_image[seg_img == region.label])) # get the focus' displacement from center of cell # find x and y position relative to the whole image (convert from small box) # calculate distance of foci from middle of cell (scikit image) orientation = region.orientation if orientation < 0: orientation = np.pi+orientation cell_idx = self.cells[-1].times.index(self.times[-1]) # final time in self.times is current time cell_centroid = self.cells[-1].centroids[cell_idx] focus_centroid = region.centroid disp_y = (focus_centroid[0]-cell_centroid[0])*np.sin(orientation) - (focus_centroid[1]-cell_centroid[1])*np.cos(orientation) disp_x = (focus_centroid[0]-cell_centroid[0])*np.cos(orientation) + (focus_centroid[1]-cell_centroid[1])*np.sin(orientation) # append foci information to the list self.disp_l = np.append(self.disp_l, disp_y) self.disp_w = np.append(self.disp_w, disp_x) def disappears(self, region, t): ''' Annotate focus as disappearing from current t to next t. ''' self.disappear = t def add_daughter(self, daughter, t): if self.daughters is None: self.daughters = [daughter] else: self.daughters.append(daughter) # sort daughters by y position, with smaller y-value first. # this will cause the daughter closer to the closed end of the trap to be listed first. self.daughters.sort(key=lambda focus: focus.centroids[0][0]) self.divide(t) def divide(self, t): '''Divide the cell and update stats. daughter1 is the daugther closer to the closed end.''' # put the daugther ids into the cell # self.daughters = [daughter1.id, daughter2.id] # give this guy a division time self.split_time = self.daughters[0].appear_time # convert data to smaller floats. No need for float64 # see https://docs.scipy.org/doc/numpy-1.13.0/user/basics.types.html convert_to = 'float16' # numpy datatype to convert to self.lengths = [length.astype(convert_to) for length in self.lengths] self.widths = [width.astype(convert_to) for width in self.widths] self.volumes = [vol.astype(convert_to) for vol in self.volumes] # note the float16 is hardcoded here self.orientations = [np.float16(orientation) for orientation in self.orientations] self.centroids = [(y.astype(convert_to), x.astype(convert_to)) for y, x in self.centroids] def print_info(self): '''prints information about the focus''' print('id = %s' % self.id) print('times = {}'.format(', '.join('{}'.format(t) for t in self.times))) print('lengths = {}'.format(', '.join('{:.2f}'.format(l) for l in self.lengths))) if self.daughters is not None: print('daughters = {}'.format(', '.join('{}'.format(daughter.id) for daughter in self.daughters))) if self.cells is not None: print('cells = {}'.format([cell.id for cell in self.cells])) def make_wide_df(self): data = {} data['id'] = self.id data['cells'] = self.cells data['parent'] = self.parent data['child1'] = None data['child2'] = None # data['division_time'] = self.division_time data['appear_label'] = self.appear_label data['appear_time'] = self.appear_time data['disappear'] = self.disappear if self.daughters is not None: data['child1'] = self.daughters[0] if len(self.daughters) == 2: data['child2'] = self.daughters[1] df = pd.DataFrame(data, index=[self.id]) return(df) def make_long_df(self): data = {} data['id'] = [self.id]*len(self.times) data['time'] = self.times # data['cell'] = self.cells data['length'] = self.lengths data['volume'] = self.volumes data['area'] = self.areas data['seconds'] = self.abs_times data['area_mean_fluorescence'] = self.area_mean_fluorescence data['volume_mean_fluorescence'] = self.volume_mean_fluorescence data['total_fluorescence'] = self.total_fluorescence data['median_fluorescence'] = self.median_fluorescence data['sd_fluorescence'] = self.sd_fluorescence data['disp_l'] = self.disp_l data['disp_w'] = self.disp_w # print(data['id']) df = pd.DataFrame(data, index=data['id']) return(df) class PredictTrackDataGenerator(utils.Sequence): '''Generates data for running tracking class preditions Input is a stack of labeled images''' def __init__(self, data, batch_size=32, dim=(4,5,9)): 'Initialization' self.batch_size = batch_size self.data = data self.dim = dim self.on_epoch_end() def __len__(self): 'Denotes the number of batches per epoch' return int(np.ceil(len(self.data) / self.batch_size)) def __getitem__(self, index): 'Generate one batch of data' # Generate keys of the batch batch_indices = self.indices[index*self.batch_size:(index+1)*self.batch_size] # Generate data X = self.__data_generation(batch_indices) return X def on_epoch_end(self): 'Updates indexes after each epoch' self.indices = np.arange(len(self.data)) def __data_generation(self, batch_indices): 'Generates data containing batch_size samples' # X : (n_samples, *dim, n_channels) # Initialization # shape is (batch_size, max_cell_num, frame_num, cell_feature_num, 1) X = np.zeros((self.batch_size, self.dim[0], self.dim[1], self.dim[2], 1)) # Generate data for idx in batch_indices: start_idx = idx-2 end_idx = idx+3 # print(start_idx, end_idx) if start_idx < 0: batch_frame_list = [] for empty_idx in range(abs(start_idx)): batch_frame_list.append([]) batch_frame_list.extend(self.data[0:end_idx]) elif end_idx > len(self.data): batch_frame_list = self.data[start_idx:len(self.data)+1] for empty_idx in range(abs(end_idx - len(self.data))): batch_frame_list.extend([]) else: batch_frame_list = self.data[start_idx:end_idx] for i,frame_region_list in enumerate(batch_frame_list): # shape is (max_cell_num, frame_num, cell_feature_num) # tmp_x = np.zeros((self.dim[0], self.dim[1], self.dim[2])) if not frame_region_list: continue for region_idx, region, in enumerate(frame_region_list): y,x = region.centroid bbox = region.bbox orientation = region.orientation min_y = bbox[0] max_y = bbox[2] min_x = bbox[1] max_x = bbox[3] area = region.area length = region.major_axis_length cell_label = region.label cell_index = cell_label - 1 cell_info = (min_x, max_x, x, min_y, max_y, y, orientation, area, length) if region_idx + 1 > self.dim[0]: continue # supplement tmp_x at (region_idx, ) # tmp_x[region_idx, i, :] = cell_info X[idx, cell_index, i, :,0] = cell_info # tmp_x return X def get_greatest_score_info(first_node, second_node, graph): '''A function that is useful for track linking ''' score_names = [k for k in graph.get_edge_data(first_node, second_node).keys()] pred_scores = [val['score'] for k,val in graph.get_edge_data(first_node, second_node).items()] max_score_index = np.argmax(pred_scores) max_name = score_names[max_score_index] max_score = pred_scores[max_score_index] return(max_name, max_score) def get_score_by_type(first_node, second_node, graph, score_type='child'): '''A function useful in track linking ''' pred_score = graph.get_edge_data(first_node, second_node)[score_type]['score'] return(pred_score) def count_unvisited(G, experiment_name): count = 0 for node_id in G.nodes: if node_id.startswith(experiment_name): if not G.nodes[node_id]['visited']: count += 1 return(count) def create_lineages_from_graph(graph, graph_df, fov_id, peak_id, ): ''' This function iterates through nodes in a graph of detections to link the nodes as "CellFromGraph" objects, eventually leading to the ultimate goal of returning a CellTree object with each cell's information for the experiment. For now it ignores the number of cells in a detection and simply assumes a 1:1 relationship between detections and cell number. ''' # iterate through all nodes in graph # graph_score = 0 # track_dict = {} # tracks = CellTree() tracks = {} for node_id in graph.nodes: graph.nodes[node_id]['visited'] = False graph_df['visited'] = False num_unvisited = count_unvisited(graph, params['experiment_name']) while num_unvisited > 0: # which detection nodes are not yet visited unvisited_detection_nodes = graph_df[(~(graph_df.visited) & graph_df.node_id.str.startswith(params['experiment_name']))] # grab the first unvisited node_id from the dataframe prior_node_id = unvisited_detection_nodes.iloc[0,1] prior_node_time = graph.nodes[prior_node_id]['time'] prior_node_region = graph.nodes[prior_node_id]['region'] cell_id = create_cell_id(prior_node_region, prior_node_time, peak_id, fov_id, experiment_name=params['experiment_name']) current_cell = CellFromGraph(cell_id, prior_node_region, prior_node_time, parent=None) if not cell_id in tracks.keys(): tracks[cell_id] = current_cell else: current_cell = tracks[cell_id] # for use later in establishing predecessors current_node_id = prior_node_id # set this detection's "visited" status to True in the graph and in the dataframe graph.nodes[prior_node_id]['visited'] = True graph_df.iloc[np.where(graph_df.node_id==prior_node_id)[0][0],3] = True # build current_track list to this detection's node current_track = collections.deque() current_track.append(current_node_id) predecessors_list = [k for k in graph.predecessors(prior_node_id)] unvisited_predecessors_list = [k for k in predecessors_list if not graph.nodes[k]['visited']] while len(unvisited_predecessors_list) != 0: # initialize a scores array to select highest score from the available options predecessor_scores = np.zeros(len(unvisited_predecessors_list)) # populate array with scores for i in range(len(unvisited_predecessors_list)): predecessor_node_id = unvisited_predecessors_list[i] edge_type, edge_score = get_greatest_score_info(predecessor_node_id, current_node_id, graph) predecessor_scores[i] = edge_score # find highest score max_index = np.argmax(predecessor_scores) # grab the node_id corresponding to traversing the highest-scoring edge from the prior node current_node_id = unvisited_predecessors_list[max_index] current_track.appendleft(current_node_id) predecessors_list = [k for k in graph.predecessors(current_node_id)] unvisited_predecessors_list = [k for k in predecessors_list if not graph.nodes[k]['visited']] while prior_node_id is not 'B': # which nodes succeed our current node? successor_node_ids = [node_id for node_id in graph.successors(prior_node_id)] # keep only the potential successor detections that have not yet been visited unvisited_node_ids = [] for i,successor_node_id in enumerate(successor_node_ids): # if it starts with params['experiment_name'], it is a detection node, and not born, appear, etc. if successor_node_id.startswith(params['experiment_name']): # if it has been used in the cell track graph, i.e., if 'visited' is True, # move on. Otherwise, append to our list if graph.nodes[successor_node_id]['visited']: continue else: unvisited_node_ids.append(successor_node_id) # if it doesn't start with params['experiment_name'], it is a born, appear, etc., and should always be appended else: unvisited_node_ids.append(successor_node_id) # initialize a scores array to select highest score from the available options successor_scores = np.zeros(len(unvisited_node_ids)) successor_edge_types = [] # populate array with scores for i in range(len(unvisited_node_ids)): successor_node_id = unvisited_node_ids[i] edge_type, edge_score = get_greatest_score_info(prior_node_id, successor_node_id, graph) successor_scores[i] = edge_score successor_edge_types.append(edge_type) # find highest score max_score = np.max(successor_scores) max_index = np.argmax(successor_scores) # grab the node_id corresponding to traversing the highest-scoring edge from the prior node next_node_id = unvisited_node_ids[max_index] max_edge_type = successor_edge_types[max_index] # if the max_score in successor_scores isn't greater than log(0.1), just make the cell disappear for now. if max_score < np.log(0.1): max_edge_type = 'disappear' next_node_id = [n_id for n_id in unvisited_node_ids if n_id.startswith('disappear')][0] # if this is a division event, add child node as a new cell, # add the new cell as a daughter to current_cell, # add current_cell as a parent to new cell. # Then, search for the second child cell, add it to current_cell, etc. if max_edge_type == 'child': new_cell_time = graph.nodes[next_node_id]['time'] new_cell_region = graph.nodes[next_node_id]['region'] new_cell_id = create_cell_id(new_cell_region, new_cell_time, peak_id, fov_id, experiment_name=params['experiment_name']) new_cell = CellFromGraph(new_cell_id, new_cell_region, new_cell_time, parent=current_cell) tracks[new_cell_id] = new_cell current_cell.add_daughter(new_cell, new_cell_time) # initialize a scores array to select highest score from the available options unvisited_detection_nodes = [unvisited_node_id for unvisited_node_id in unvisited_node_ids if unvisited_node_id.startswith(params['experiment_name'])] child_scores = np.zeros(len(unvisited_detection_nodes)) # populate array with scores for i in range(len(unvisited_detection_nodes)): successor_node_id = unvisited_detection_nodes[i] if successor_node_id == next_node_id: child_scores[i] = -np.inf continue child_score = get_score_by_type(prior_node_id, successor_node_id, graph, score_type='child') child_scores[i] = child_score try: second_daughter_score = np.max(child_scores) # sometimes a second daughter doesn't exist: perhaps parent is at mouth of a trap and one # daughter is lost to the central channel at division time. In this case, do the following: if second_daughter_score < np.log(0.5): current_cell = new_cell else: second_daughter_index = np.argmax(child_scores) # grab the node_id corresponding to traversing the highest-scoring edge from the prior node other_daughter_node_id = unvisited_detection_nodes[second_daughter_index] other_daughter_cell_time = graph.nodes[other_daughter_node_id]['time'] other_daughter_cell_region = graph.nodes[other_daughter_node_id]['region'] other_daughter_cell_id = create_cell_id(other_daughter_cell_region, other_daughter_cell_time, peak_id, fov_id, experiment_name=params['experiment_name']) other_daughter_cell = CellFromGraph(other_daughter_cell_id, other_daughter_cell_region, other_daughter_cell_time, parent=current_cell) tracks[other_daughter_cell_id] = other_daughter_cell current_cell.add_daughter(other_daughter_cell, new_cell_time) # now we remove current_cell, since it's done, and move on to one of the daughters current_cell = new_cell # sometimes a second daughter doesn't exist: perhaps parent is at mouth of a trap and one # daughter is lost to the central channel at division time. In this case, do the following: except IndexError: current_cell = new_cell # if this is a migration, grow the current_cell. elif max_edge_type == 'migrate': cell_time = graph.nodes[next_node_id]['time'] cell_region = graph.nodes[next_node_id]['region'] current_cell.grow(cell_region, cell_time) # if the event represents death, kill the cell elif max_edge_type == 'die': if prior_node_id.startswith(params['experiment_name']): death_time = graph.nodes[prior_node_id]['time'] death_region = graph.nodes[prior_node_id]['region'] current_cell.die(death_region, death_time) # if the event represents disappearance, end the cell elif max_edge_type == 'disappear': if prior_node_id.startswith(params['experiment_name']): disappear_time = graph.nodes[prior_node_id]['time'] disappear_region = graph.nodes[prior_node_id]['region'] current_cell.disappears(disappear_region, disappear_time) # set the next node to 'visited' graph.nodes[next_node_id]['visited'] = True if next_node_id != 'B': graph_df.iloc[np.where(graph_df.node_id==next_node_id)[0][0],3] = True # reset prior_node_id to iterate to next frame and append node_id to current track prior_node_id = next_node_id if num_unvisited != count_unvisited(graph, params['experiment_name']): same_iter_num = 0 else: same_iter_num += 1 num_unvisited = count_unvisited(graph, params['experiment_name']) print("{} detections remain unvisited.".format(num_unvisited)) if same_iter_num > 10: print("WARNING: Ten iterations surpassed without decreasing the number of visited nodes.\n \ Breaking tracking loop now. You should probably not trust these results.") break return tracks def viterbi_create_lineages_from_graph(graph, graph_df, fov_id, peak_id, ): ''' This function iterates through nodes in a graph of detections to link the nodes as "CellFromGraph" objects, eventually leading to the ultimate goal of returning a maximally-scoring CellTree object with each cell's information for the experiment. For now it ignores the number of cells in a detection and simply assumes a 1:1 relationship between detections and cell number. ''' # iterate through all nodes in G graph_score = 0 # track_dict = {} tracks = CellTree() max_time = np.max([node.timepoint for node in graph.nodes]) print(max_time) for node_id in graph.nodes: graph.nodes[node_id]['visited'] = False graph_df['visited'] = False num_unvisited = count_unvisited(graph, params['experiment_name']) for t in range(1,max_time+1): if t > 1: prior_time_nodes = time_nodes if t == 1: time_nodes = [node for node in G.nodes if node.time == t] else: time_nodes = next_time_nodes if t != max_time: next_time_nodes = [node for node in G.nodes if node.time == t+1] for node in time_nodes: pass while num_unvisited > 0: # which detection nodes are not yet visited unvisited_detection_nodes = graph_df[(~(graph_df.visited) & graph_df.node_id.str.startswith(params['experiment_name']))] # grab the first unvisited node_id from the dataframe prior_node_id = unvisited_detection_nodes.iloc[0,1] prior_node_time = graph.nodes[prior_node_id]['time'] prior_node_region = graph.nodes[prior_node_id]['region'] cell_id = create_cell_id(prior_node_region, prior_node_time, peak_id, fov_id, experiment_name=params['experiment_name']) current_cell = CellFromGraph(cell_id, prior_node_region, prior_node_time, parent=None) if not cell_id in tracks.cell_id_list: tracks.add_cell(current_cell) else: current_cell = tracks.get_cell(cell_id) # track_dict_key = prior_node_id # for use later in establishing predecessors current_node_id = prior_node_id # set this detection's "visited" status to True in the graph and in the dataframe graph.nodes[prior_node_id]['visited'] = True graph_df.iloc[np.where(graph_df.node_id==prior_node_id)[0][0],3] = True # build current_track list to this detection's node current_track = collections.deque() current_track.append(current_node_id) predecessors_list = [k for k in graph.predecessors(prior_node_id)] unvisited_predecessors_list = [k for k in predecessors_list if not graph.nodes[k]['visited']] while len(unvisited_predecessors_list) != 0: # initialize a scores array to select highest score from the available options predecessor_scores = np.zeros(len(unvisited_predecessors_list)) # populate array with scores for i in range(len(unvisited_predecessors_list)): predecessor_node_id = unvisited_predecessors_list[i] edge_type, edge_score = get_greatest_score_info(predecessor_node_id, current_node_id, graph) predecessor_scores[i] = edge_score # find highest score max_index = np.argmax(predecessor_scores) # grab the node_id corresponding to traversing the highest-scoring edge from the prior node current_node_id = unvisited_predecessors_list[max_index] current_track.appendleft(current_node_id) predecessors_list = [k for k in graph.predecessors(current_node_id)] unvisited_predecessors_list = [k for k in predecessors_list if not graph.nodes[k]['visited']] while prior_node_id is not 'B': # which nodes succeed our current node? successor_node_ids = [node_id for node_id in graph.successors(prior_node_id)] # keep only the potential successor detections that have not yet been visited unvisited_node_ids = [] for i,successor_node_id in enumerate(successor_node_ids): # if it starts with params['experiment_name'], it is a detection node, and not born, appear, etc. if successor_node_id.startswith(params['experiment_name']): # if it has been used in the cell track graph, i.e., if 'visited' is True, # move on. Otherwise, append to our list if graph.nodes[successor_node_id]['visited']: continue else: unvisited_node_ids.append(successor_node_id) # if it doesn't start with params['experiment_name'], it is a born, appear, etc., and should always be appended else: unvisited_node_ids.append(successor_node_id) # initialize a scores array to select highest score from the available options successor_scores = np.zeros(len(unvisited_node_ids)) successor_edge_types = [] # populate array with scores for i in range(len(unvisited_node_ids)): successor_node_id = unvisited_node_ids[i] edge_type, edge_score = get_greatest_score_info(prior_node_id, successor_node_id, graph) successor_scores[i] = edge_score successor_edge_types.append(edge_type) # find highest score max_index = np.argmax(successor_scores) # grab the node_id corresponding to traversing the highest-scoring edge from the prior node next_node_id = unvisited_node_ids[max_index] max_edge_type = successor_edge_types[max_index] # if this is a division event, add child node as a new cell, # add the new cell as a daughter to current_cell, # add current_cell as a parent to new cell. # Then, search for the second child cell, add it to current_cell, etc. if max_edge_type == 'child': new_cell_time = graph.nodes[next_node_id]['time'] new_cell_region = graph.nodes[next_node_id]['region'] new_cell_id = create_cell_id(new_cell_region, new_cell_time, peak_id, fov_id, experiment_name=params['experiment_name']) new_cell = CellFromGraph(new_cell_id, new_cell_region, new_cell_time, parent=current_cell) tracks.add_cell(new_cell) current_cell.add_daughter(new_cell, new_cell_time) # print("First daughter", current_cell.id, new_cell.id) # initialize a scores array to select highest score from the available options unvisited_detection_nodes = [unvisited_node_id for unvisited_node_id in unvisited_node_ids if unvisited_node_id.startswith(params['experiment_name'])] child_scores = np.zeros(len(unvisited_detection_nodes)) # populate array with scores for i in range(len(unvisited_detection_nodes)): successor_node_id = unvisited_detection_nodes[i] if successor_node_id == next_node_id: child_scores[i] = -np.inf continue child_score = get_score_by_type(prior_node_id, successor_node_id, graph, score_type='child') child_scores[i] = child_score # print(child_scores) try: second_daughter_index = np.argmax(child_scores) # grab the node_id corresponding to traversing the highest-scoring edge from the prior node other_daughter_node_id = unvisited_detection_nodes[second_daughter_index] other_daughter_cell_time = graph.nodes[other_daughter_node_id]['time'] other_daughter_cell_region = graph.nodes[other_daughter_node_id]['region'] other_daughter_cell_id = create_cell_id(other_daughter_cell_region, other_daughter_cell_time, peak_id, fov_id, experiment_name=params['experiment_name']) other_daughter_cell = CellFromGraph(other_daughter_cell_id, other_daughter_cell_region, other_daughter_cell_time, parent=current_cell) tracks.add_cell(other_daughter_cell) current_cell.add_daughter(other_daughter_cell, new_cell_time) # now we remove current_cell, since it's done, and move on to one of the daughters current_cell = new_cell # print("Second daughter", current_cell.parent.id, other_daughter_cell.id) # sometimes a second daughter doesn't exist: perhaps parent is at mouth of a trap and one # daughter is lost to the central channel at division time. In this case, do the following: except IndexError: current_cell = new_cell # if this is a migration, grow the current_cell. elif max_edge_type == 'migrate': cell_time = graph.nodes[next_node_id]['time'] cell_region = graph.nodes[next_node_id]['region'] current_cell.grow(cell_region, cell_time) # if the event represents death, kill the cell elif max_edge_type == 'die': if prior_node_id.startswith(params['experiment_name']): death_time = graph.nodes[prior_node_id]['time'] death_region = graph.nodes[prior_node_id]['region'] current_cell.die(death_region, death_time) # if the event represents disappearance, end the cell elif max_edge_type == 'disappear': if prior_node_id.startswith(params['experiment_name']): disappear_time = graph.nodes[prior_node_id]['time'] disappear_region = graph.nodes[prior_node_id]['region'] current_cell.disappears(disappear_region, disappear_time) # set the next node to 'visited' graph.nodes[next_node_id]['visited'] = True if next_node_id != 'B': graph_df.iloc[np.where(graph_df.node_id==next_node_id)[0][0],3] = True # reset prior_node_id to iterate to next frame and append node_id to current track # current_track.append(next_node_id) prior_node_id = next_node_id # print(current_cell.id, current_cell.parent.id) # track_dict[track_dict_key][:] = current_track if num_unvisited != count_unvisited(graph, params['experiment_name']): same_iter_num = 0 else: same_iter_num += 1 num_unvisited = count_unvisited(graph, params['experiment_name']) print("{} detections remain unvisited.".format(num_unvisited)) if same_iter_num > 10: break return(tracks) def create_lineages_from_graph_2(graph, graph_df, fov_id, peak_id, ): ''' This function iterates through nodes in a graph of detections to link the nodes as "CellFromGraph" objects, eventually leading to the ultimate goal of returning a CellTree object with each cell's information for the experiment. For now it ignores the number of cells in a detection and simply assumes a 1:1 relationship between detections and cell number. ''' # iterate through all nodes in G # graph_score = 0 # track_dict = {} tracks = CellTree() for node_id in graph.nodes: graph.nodes[node_id]['visited'] = False graph_df['visited'] = False num_unvisited = count_unvisited(graph, params['experiment_name']) while num_unvisited > 0: # which detection nodes are not yet visited unvisited_detection_nodes = graph_df[(~(graph_df.visited) & graph_df.node_id.str.startswith(params['experiment_name']))] # grab the first unvisited node_id from the dataframe prior_node_id = unvisited_detection_nodes.iloc[0,1] prior_node_time = graph.nodes[prior_node_id]['time'] prior_node_region = graph.nodes[prior_node_id]['region'] cell_id = create_cell_id(prior_node_region, prior_node_time, peak_id, fov_id, experiment_name=params['experiment_name']) current_cell = CellFromGraph(cell_id, prior_node_region, prior_node_time, parent=None) if not cell_id in tracks.cell_id_list: tracks.add_cell(current_cell) else: current_cell = tracks.get_cell(cell_id) # track_dict_key = prior_node_id # for use later in establishing predecessors current_node_id = prior_node_id # set this detection's "visited" status to True in the graph and in the dataframe graph.nodes[prior_node_id]['visited'] = True graph_df.iloc[np.where(graph_df.node_id==prior_node_id)[0][0],3] = True # build current_track list to this detection's node current_track = collections.deque() current_track.append(current_node_id) predecessors_list = [k for k in graph.predecessors(prior_node_id)] unvisited_predecessors_list = [k for k in predecessors_list if not graph.nodes[k]['visited']] while len(unvisited_predecessors_list) != 0: # initialize a scores array to select highest score from the available options predecessor_scores = np.zeros(len(unvisited_predecessors_list)) # populate array with scores for i in range(len(unvisited_predecessors_list)): predecessor_node_id = unvisited_predecessors_list[i] edge_type, edge_score = get_greatest_score_info(predecessor_node_id, current_node_id, graph) predecessor_scores[i] = edge_score # find highest score max_index = np.argmax(predecessor_scores) # grab the node_id corresponding to traversing the highest-scoring edge from the prior node current_node_id = unvisited_predecessors_list[max_index] current_track.appendleft(current_node_id) predecessors_list = [k for k in graph.predecessors(current_node_id)] unvisited_predecessors_list = [k for k in predecessors_list if not graph.nodes[k]['visited']] while prior_node_id is not 'B': # which nodes succeed our current node? successor_node_ids = [node_id for node_id in graph.successors(prior_node_id)] # keep only the potential successor detections that have not yet been visited unvisited_node_ids = [] for i,successor_node_id in enumerate(successor_node_ids): # if it starts with params['experiment_name'], it is a detection node, and not born, appear, etc. if successor_node_id.startswith(params['experiment_name']): # if it has been used in the cell track graph, i.e., if 'visited' is True, # move on. Otherwise, append to our list if graph.nodes[successor_node_id]['visited']: continue else: unvisited_node_ids.append(successor_node_id) # if it doesn't start with params['experiment_name'], it is a born, appear, etc., and should always be appended else: unvisited_node_ids.append(successor_node_id) # initialize a scores array to select highest score from the available options successor_scores = np.zeros(len(unvisited_node_ids)) successor_edge_types = [] # populate array with scores for i in range(len(unvisited_node_ids)): successor_node_id = unvisited_node_ids[i] edge_type, edge_score = get_greatest_score_info(prior_node_id, successor_node_id, graph) successor_scores[i] = edge_score successor_edge_types.append(edge_type) # find highest score max_index = np.argmax(successor_scores) # grab the node_id corresponding to traversing the highest-scoring edge from the prior node next_node_id = unvisited_node_ids[max_index] max_edge_type = successor_edge_types[max_index] # if this is a division event, add child node as a new cell, # add the new cell as a daughter to current_cell, # add current_cell as a parent to new cell. # Then, search for the second child cell, add it to current_cell, etc. if max_edge_type == 'child': new_cell_time = graph.nodes[next_node_id]['time'] new_cell_region = graph.nodes[next_node_id]['region'] new_cell_id = create_cell_id(new_cell_region, new_cell_time, peak_id, fov_id, experiment_name=params['experiment_name']) new_cell = CellFromGraph(new_cell_id, new_cell_region, new_cell_time, parent=current_cell) tracks.add_cell(new_cell) current_cell.add_daughter(new_cell, new_cell_time) # print("First daughter", current_cell.id, new_cell.id) # initialize a scores array to select highest score from the available options unvisited_detection_nodes = [unvisited_node_id for unvisited_node_id in unvisited_node_ids if unvisited_node_id.startswith(params['experiment_name'])] child_scores = np.zeros(len(unvisited_detection_nodes)) # populate array with scores for i in range(len(unvisited_detection_nodes)): successor_node_id = unvisited_detection_nodes[i] if successor_node_id == next_node_id: child_scores[i] = -np.inf continue child_score = get_score_by_type(prior_node_id, successor_node_id, graph, score_type='child') child_scores[i] = child_score # print(child_scores) try: second_daughter_index = np.argmax(child_scores) # grab the node_id corresponding to traversing the highest-scoring edge from the prior node other_daughter_node_id = unvisited_detection_nodes[second_daughter_index] other_daughter_cell_time = graph.nodes[other_daughter_node_id]['time'] other_daughter_cell_region = graph.nodes[other_daughter_node_id]['region'] other_daughter_cell_id = create_cell_id(other_daughter_cell_region, other_daughter_cell_time, peak_id, fov_id, experiment_name=params['experiment_name']) other_daughter_cell = CellFromGraph(other_daughter_cell_id, other_daughter_cell_region, other_daughter_cell_time, parent=current_cell) tracks.add_cell(other_daughter_cell) current_cell.add_daughter(other_daughter_cell, new_cell_time) # now we remove current_cell, since it's done, and move on to one of the daughters current_cell = new_cell # print("Second daughter", current_cell.parent.id, other_daughter_cell.id) # sometimes a second daughter doesn't exist: perhaps parent is at mouth of a trap and one # daughter is lost to the central channel at division time. In this case, do the following: except IndexError: current_cell = new_cell # if this is a migration, grow the current_cell. elif max_edge_type == 'migrate': cell_time = graph.nodes[next_node_id]['time'] cell_region = graph.nodes[next_node_id]['region'] current_cell.grow(cell_region, cell_time) # if the event represents death, kill the cell elif max_edge_type == 'die': if prior_node_id.startswith(params['experiment_name']): death_time = graph.nodes[prior_node_id]['time'] death_region = graph.nodes[prior_node_id]['region'] current_cell.die(death_region, death_time) # if the event represents disappearance, end the cell elif max_edge_type == 'disappear': if prior_node_id.startswith(params['experiment_name']): disappear_time = graph.nodes[prior_node_id]['time'] disappear_region = graph.nodes[prior_node_id]['region'] current_cell.disappears(disappear_region, disappear_time) # set the next node to 'visited' graph.nodes[next_node_id]['visited'] = True if next_node_id != 'B': graph_df.iloc[np.where(graph_df.node_id==next_node_id)[0][0],3] = True # reset prior_node_id to iterate to next frame and append node_id to current track # current_track.append(next_node_id) prior_node_id = next_node_id # print(current_cell.id, current_cell.parent.id) # track_dict[track_dict_key][:] = current_track if num_unvisited != count_unvisited(graph, params['experiment_name']): same_iter_num = 0 else: same_iter_num += 1 num_unvisited = count_unvisited(graph, params['experiment_name']) print("{} detections remain unvisited.".format(num_unvisited)) if same_iter_num > 10: break return(tracks) # obtains cell length and width of the cell using the feret diameter def feretdiameter(region): ''' feretdiameter calculates the length and width of the binary region shape. The cell orientation from the ellipsoid is used to find the major and minor axis of the cell. See https://en.wikipedia.org/wiki/Feret_diameter. ''' # y: along vertical axis of the image; x: along horizontal axis of the image; # calculate the relative centroid in the bounding box (non-rotated) # print(region.centroid) y0, x0 = region.centroid y0 = y0 - np.int16(region.bbox[0]) + 1 x0 = x0 - np.int16(region.bbox[1]) + 1 cosorient = np.cos(region.orientation) sinorient = np.sin(region.orientation) # print(cosorient, sinorient) amp_param = 1.2 #amplifying number to make sure the axis is longer than actual cell length # coordinates relative to bounding box # r_coords = region.coords - [np.int16(region.bbox[0]), np.int16(region.bbox[1])] # limit to perimeter coords. pixels are relative to bounding box region_binimg = np.pad(region.image, 1, 'constant') # pad region binary image by 1 to avoid boundary non-zero pixels distance_image = ndi.distance_transform_edt(region_binimg) r_coords = np.where(distance_image == 1) r_coords = list(zip(r_coords[0], r_coords[1])) # coordinates are already sorted by y. partion into top and bottom to search faster later # if orientation > 0, L1 is closer to top of image (lower Y coord) if region.orientation > 0: L1_coords = r_coords[:int(np.round(len(r_coords)/4))] L2_coords = r_coords[int(np.round(len(r_coords)/4)):] else: L1_coords = r_coords[int(np.round(len(r_coords)/4)):] L2_coords = r_coords[:int(np.round(len(r_coords)/4))] ##################### # calculte cell length L1_pt = np.zeros((2,1)) L2_pt = np.zeros((2,1)) # define the two end points of the the long axis line # one pole. L1_pt[1] = x0 + cosorient * 0.5 * region.major_axis_length*amp_param L1_pt[0] = y0 - sinorient * 0.5 * region.major_axis_length*amp_param # the other pole. L2_pt[1] = x0 - cosorient * 0.5 * region.major_axis_length*amp_param L2_pt[0] = y0 + sinorient * 0.5 * region.major_axis_length*amp_param # calculate the minimal distance between the points at both ends of 3 lines # aka calcule the closest coordiante in the region to each of the above points. # pt_L1 = r_coords[np.argmin([np.sqrt(np.power(Pt[0]-L1_pt[0],2) + np.power(Pt[1]-L1_pt[1],2)) for Pt in r_coords])] # pt_L2 = r_coords[np.argmin([np.sqrt(np.power(Pt[0]-L2_pt[0],2) + np.power(Pt[1]-L2_pt[1],2)) for Pt in r_coords])] try: pt_L1 = L1_coords[np.argmin([np.sqrt(np.power(Pt[0]-L1_pt[0],2) + np.power(Pt[1]-L1_pt[1],2)) for Pt in L1_coords])] pt_L2 = L2_coords[np.argmin([np.sqrt(np.power(Pt[0]-L2_pt[0],2) + np.power(Pt[1]-L2_pt[1],2)) for Pt in L2_coords])] length = np.sqrt(np.power(pt_L1[0]-pt_L2[0],2) + np.power(pt_L1[1]-pt_L2[1],2)) except: length = None ##################### # calculate cell width # draw 2 parallel lines along the short axis line spaced by 0.8*quarter of length = 0.4, to avoid in midcell # limit to points in each half W_coords = [] if region.orientation > 0: W_coords.append(r_coords[:int(np.round(len(r_coords)/2))]) # note the /2 here instead of /4 W_coords.append(r_coords[int(np.round(len(r_coords)/2)):]) else: W_coords.append(r_coords[int(np.round(len(r_coords)/2)):]) W_coords.append(r_coords[:int(np.round(len(r_coords)/2))]) # starting points x1 = x0 + cosorient * 0.5 * length*0.4 y1 = y0 - sinorient * 0.5 * length*0.4 x2 = x0 - cosorient * 0.5 * length*0.4 y2 = y0 + sinorient * 0.5 * length*0.4 W1_pts = np.zeros((2,2)) W2_pts = np.zeros((2,2)) # now find the ends of the lines # one side W1_pts[0,1] = x1 - sinorient * 0.5 * region.minor_axis_length*amp_param W1_pts[0,0] = y1 - cosorient * 0.5 * region.minor_axis_length*amp_param W1_pts[1,1] = x2 - sinorient * 0.5 * region.minor_axis_length*amp_param W1_pts[1,0] = y2 - cosorient * 0.5 * region.minor_axis_length*amp_param # the other side W2_pts[0,1] = x1 + sinorient * 0.5 * region.minor_axis_length*amp_param W2_pts[0,0] = y1 + cosorient * 0.5 * region.minor_axis_length*amp_param W2_pts[1,1] = x2 + sinorient * 0.5 * region.minor_axis_length*amp_param W2_pts[1,0] = y2 + cosorient * 0.5 * region.minor_axis_length*amp_param # calculate the minimal distance between the points at both ends of 3 lines pt_W1 = np.zeros((2,2)) pt_W2 = np.zeros((2,2)) d_W = np.zeros((2,1)) i = 0 for W1_pt, W2_pt in zip(W1_pts, W2_pts): # # find the points closest to the guide points # pt_W1[i,0], pt_W1[i,1] = r_coords[np.argmin([np.sqrt(np.power(Pt[0]-W1_pt[0],2) + np.power(Pt[1]-W1_pt[1],2)) for Pt in r_coords])] # pt_W2[i,0], pt_W2[i,1] = r_coords[np.argmin([np.sqrt(np.power(Pt[0]-W2_pt[0],2) + np.power(Pt[1]-W2_pt[1],2)) for Pt in r_coords])] # find the points closest to the guide points pt_W1[i,0], pt_W1[i,1] = W_coords[i][np.argmin([np.sqrt(np.power(Pt[0]-W1_pt[0],2) + np.power(Pt[1]-W1_pt[1],2)) for Pt in W_coords[i]])] pt_W2[i,0], pt_W2[i,1] = W_coords[i][np.argmin([np.sqrt(np.power(Pt[0]-W2_pt[0],2) + np.power(Pt[1]-W2_pt[1],2)) for Pt in W_coords[i]])] # calculate the actual width d_W[i] = np.sqrt(np.power(pt_W1[i,0]-pt_W2[i,0],2) + np.power(pt_W1[i,1]-pt_W2[i,1],2)) i += 1 # take the average of the two at quarter positions width = np.mean([d_W[0],d_W[1]]) return length, width # take info and make string for cell id def create_focus_id(region, t, peak, fov, experiment_name=None): '''Make a unique focus id string for a new focus''' if experiment_name is None: focus_id = 'f{:0=2}p{:0=4}t{:0=4}r{:0=2}'.format(fov, peak, t, region.label) else: focus_id = '{}f{:0=2}p{:0=4}t{:0=4}r{:0=2}'.format(experiment_name, fov, peak, t, region.label) return focus_id # take info and make string for cell id def create_cell_id(region, t, peak, fov, experiment_name=None): '''Make a unique cell id string for a new cell''' # cell_id = ['f', str(fov), 'p', str(peak), 't', str(t), 'r', str(region.label)] if experiment_name is None: cell_id = ['f', '%02d' % fov, 'p', '%04d' % peak, 't', '%04d' % t, 'r', '%02d' % region.label] cell_id = ''.join(cell_id) else: cell_id = '{}f{:0=2}p{:0=4}t{:0=4}r{:0=2}'.format(experiment_name, fov, peak, t, region.label) return cell_id def create_detection_id(t, peak, fov, region_label, experiment_name=None, max_cell_number=6): '''Make a unique cell id string for a new cell''' # cell_id = ['f', str(fov), 'p', str(peak), 't', str(t), 'r', str(region.label)] if experiment_name is None: det_id = ['f', '%02d' % fov, 'p', '%04d' % peak, 't', '%04d' % t, 'r', '%02d' % region_label] det_id = ''.join(det_id) else: det_id = '{}f{:0=2}p{:0=4}t{:0=4}r{:0=2}'.format(experiment_name, fov, peak, t, region_label) return det_id def initialize_track_graph(peak_id, fov_id, experiment_name, predictions_dict, regions_by_time, max_cell_number=6, born_threshold=0.75, appear_threshold=0.75): detection_dict = {} frame_num = predictions_dict['migrate_model_predictions'].shape[0] ebunch = [] G = nx.MultiDiGraph() # create common start point G.add_node('A') # create common end point G.add_node('B') last_frame = False node_id_list = [] timepoint_list = [] region_label_list = [] for frame_idx in range(frame_num): timepoint = frame_idx + 1 paired_detection_time = timepoint+1 # get detections for this frame frame_regions_list = regions_by_time[frame_idx] # if we're at the end of the imaging, make all cells migrate to node 'B' if timepoint == frame_num: last_frame = True else: paired_frame_regions_list = regions_by_time[frame_idx+1] # get state change probabilities (class predictions) for this frame frame_prediction_dict = {key:val[frame_idx,...] for key,val in predictions_dict.items() if key != 'general_model_predictions'} # for i in range(len(predictions_dict['general_model_predictions'])): # frame_general_prediction = predictions_dict['general_model_predictions'][] # create the "will be born" and "will appear" nodes for this frame prior_born_state = 'born_{:0=4}'.format(timepoint-1) born_state = 'born_{:0=4}'.format(timepoint) G.add_node(born_state, visited=False, time=timepoint) prior_appear_state = 'appear_{:0=4}'.format(timepoint-1) appear_state = 'appear_{:0=4}'.format(timepoint) G.add_node(appear_state, visited=False, time=timepoint) if frame_idx == 0: ebunch.append(('A', appear_state, 'start', {'weight':appear_threshold, 'score':1*np.log(appear_threshold)})) ebunch.append(('A', born_state, 'start', {'weight':born_threshold, 'score':1*np.log(born_threshold)})) # create the "Dies" and "Disappeared" nodes to link from prior frame prior_dies_state = 'dies_{:0=4}'.format(timepoint-1) dies_state = 'dies_{:0=4}'.format(timepoint) next_dies_state = 'dies_{:0=4}'.format(timepoint+1) G.add_node(dies_state, visited=False, time=timepoint) prior_disappear_state = 'disappear_{:0=4}'.format(timepoint-1) disappear_state = 'disappear_{:0=4}'.format(timepoint) next_disappear_state = 'disappear_{:0=4}'.format(timepoint+1) G.add_node(disappear_state, visited=False, time=timepoint) node_id_list.extend([born_state, dies_state, appear_state, disappear_state]) timepoint_list.extend([timepoint, timepoint, timepoint, timepoint]) region_label_list.extend([0,0,0,0]) if frame_idx > 0: ebunch.append((prior_dies_state, dies_state, 'die', {'weight':1.1, 'score':1*np.log(1.1)})) # impossible to move out of dies track ebunch.append((prior_disappear_state, disappear_state, 'disappear', {'weight':1.1, 'score':1*np.log(1.1)})) # impossible to move out of disappear track ebunch.append((prior_born_state, born_state, 'born', {'weight':born_threshold, 'score':1*np.log(born_threshold)})) ebunch.append((prior_appear_state, appear_state, 'appear', {'weight':appear_threshold, 'score':1*np.log(appear_threshold)})) if last_frame: ebunch.append((appear_state, 'B', 'end', {'weight':1, 'score':1*np.log(1)})) ebunch.append((disappear_state, 'B', 'end', {'weight':1, 'score':1*np.log(1)})) ebunch.append((born_state, 'B', 'end', {'weight':1, 'score':1*np.log(1)})) ebunch.append((dies_state, 'B', 'end', {'weight':1, 'score':1*np.log(1)})) for region_idx in range(max_cell_number): # the tracking models assume there are 6 detections in each frame, regardless of how many # are actually there. Therefore, this try/except logic will catch cases where there # were fewer than 6 detections in a frame. try: region = frame_regions_list[region_idx] region_label = region.label except IndexError: region = None region_label = region_idx + 1 # create the name for this detection detection_id = create_detection_id(timepoint, peak_id, fov_id, region_label, experiment_name=experiment_name) det = Detection(detection_id, region, timepoint) detection_dict[det.id] = det if det.area is not None: # if the detection represents a segmentation from our imaging, add its ID, # which is also its key in detection_dict, as a node in G G.add_node(det.id, visited=False, cell_count=1, region=region, time=timepoint) timepoint_list.append(timepoint) node_id_list.append(detection_id) region_label_list.append(region.label) # also set up all edges for this detection's node in our ebunch # loop through prediction types and add each to the ebunch for key,val in frame_prediction_dict.items(): if frame_idx == 0: ebunch.append(('A', detection_id, 'start', {'weight':1, 'score':1*np.log(1)})) if last_frame: ebunch.append((detection_id, 'B', 'end', {'weight':1, 'score':1*np.log(1)})) if val.shape[0] == max_cell_number ** 2: continue else: frame_predictions = val detection_prediction = frame_predictions[region_idx] if key == 'appear_model_predictions': if frame_idx == 0: continue elem = (prior_appear_state, detection_id, 'appear', {'weight':detection_prediction, 'score':1*np.log(detection_prediction)}) elif 'born' in key: if frame_idx == 0: continue elem = (prior_born_state, detection_id, 'born', {'weight':detection_prediction, 'score':1*np.log(detection_prediction)}) elif 'zero_cell' in key: G.nodes[det.id]['zero_cell_weight'] = detection_prediction G.nodes[det.id]['zero_cell_score'] = 1*np.log(detection_prediction) elif 'one_cell' in key: G.nodes[det.id]['one_cell_weight'] = detection_prediction G.nodes[det.id]['zero_cell_score'] = 1*np.log(detection_prediction) elif 'two_cell' in key: G.nodes[det.id]['two_cell_weight'] = detection_prediction G.nodes[det.id]['zero_cell_score'] = 1*np.log(detection_prediction) ebunch.append(elem) else: # if the array is cell_number^2, reshape it to cell_number x cell_number # Then slice our detection's row and iterate over paired_cells if val.shape[0] == max_cell_number**2: frame_predictions = val.reshape((max_cell_number,max_cell_number)) detection_predictions = frame_predictions[region_idx,:] # loop through paired detection predictions, test whether paired detection exists # then append the edge to our ebunch for paired_cell_idx in range(detection_predictions.size): # attempt to grab the paired detection. If we get an IndexError, it doesn't exist. try: paired_detection = paired_frame_regions_list[paired_cell_idx] except IndexError: continue # create the paired detection's id for use in our ebunch paired_detection_id = create_detection_id(paired_detection_time, peak_id, fov_id, paired_detection.label, experiment_name=experiment_name) paired_prediction = detection_predictions[paired_cell_idx] if 'child_' in key: child_weight = paired_prediction elem = (detection_id, paired_detection_id, 'child', {'child_weight':child_weight, 'score':1*np.log(child_weight)}) ebunch.append(elem) if 'migrate_' in key: migrate_weight = paired_prediction elem = (detection_id, paired_detection_id, 'migrate', {'migrate_weight':migrate_weight, 'score':1*np.log(migrate_weight)}) ebunch.append(elem) # if 'interaction_' in key: # interaction_weight = paired_prediction # elem = (detection_id, paired_detection_id, 'interaction', {'weight':interaction_weight, 'score':1*np.log(interaction_weight)}) # ebunch.append(elem) # if the array is cell_number long, do similar stuff as above. elif val.shape[0] == max_cell_number: frame_predictions = val detection_prediction = frame_predictions[region_idx] if key == 'appear_model_predictions': if frame_idx == 0: continue # print("Linking {} to {}.".format(prior_appear_state, detection_id)) elem = (prior_appear_state, detection_id, 'appear', {'weight':detection_prediction, 'score':1*np.log(detection_prediction)}) elif 'disappear_' in key: if last_frame: continue # print("Linking {} to {}.".format(detection_id, next_disappear_state)) elem = (detection_id, next_disappear_state, 'disappear', {'weight':detection_prediction, 'score':1*np.log(detection_prediction)}) elif 'born_' in key: if frame_idx == 0: continue # print("Linking {} to {}.".format(prior_born_state, detection_id)) elem = (prior_born_state, detection_id, 'born', {'weight':detection_prediction, 'score':1*np.log(detection_prediction)}) elif 'die_model' in key: if last_frame: continue # print("Linking {} to {}.".format(detection_id, next_dies_state)) elem = (detection_id, next_dies_state, 'die', {'weight':detection_prediction, 'score':1*np.log(detection_prediction)}) # the following classes aren't yet implemented elif 'zero_cell' in key: G.nodes[det.id]['zero_cell_weight'] = detection_prediction G.nodes[det.id]['zero_cell_score'] = 1*np.log(detection_prediction) elif 'one_cell' in key: G.nodes[det.id]['one_cell_weight'] = detection_prediction G.nodes[det.id]['one_cell_score'] = 1*np.log(detection_prediction) elif 'two_cell' in key: G.nodes[det.id]['two_cell_weight'] = detection_prediction G.nodes[det.id]['two_cell_score'] = 1*np.log(detection_prediction) ebunch.append(elem) G.add_edges_from(ebunch) graph_df = pd.DataFrame(data={'timepoint':timepoint_list, 'node_id':node_id_list, 'region_label':region_label_list}) return(G, graph_df) # function for a growing cell, used to calculate growth rate def cell_growth_func(t, sb, elong_rate): ''' Assumes you have taken log of the data. It also allows the size at birth to be a free parameter, rather than fixed at the actual size at birth (but still uses that as a guess) Assumes natural log, not base 2 (though I think that makes less sense) old form: sb*2**(alpha*t) ''' return sb+elong_rate*t # functions for checking if a cell has divided or not # this function should also take the variable t to # weight the allowed changes by the difference in time as well def check_growth_by_region(cell, region): '''Checks to see if it makes sense to grow a cell by a particular region''' # load parameters for checking max_growth_length = params['track']['max_growth_length'] min_growth_length = params['track']['min_growth_length'] max_growth_area = params['track']['max_growth_area'] min_growth_area = params['track']['min_growth_area'] # check if length is not too much longer if cell.lengths[-1]*max_growth_length < region.major_axis_length: return False # check if it is not too short (cell should not shrink really) if cell.lengths[-1]*min_growth_length > region.major_axis_length: return False # check if area is not too great if cell.areas[-1]*max_growth_area < region.area: return False # check if area is not too small if cell.lengths[-1]*min_growth_area > region.area: return False # # check if y position of region is within # # the quarter positions of the bounding box # lower_quarter = cell.bboxes[-1][0] + (region.major_axis_length / 4) # upper_quarter = cell.bboxes[-1][2] - (region.major_axis_length / 4) # if lower_quarter > region.centroid[0] or upper_quarter < region.centroid[0]: # return False # check if y position of region is within the bounding box of previous region lower_bound = cell.bboxes[-1][0] upper_bound = cell.bboxes[-1][2] if lower_bound > region.centroid[0] or upper_bound < region.centroid[0]: return False # return true if you get this far return True # see if a cell has reasonably divided def check_division(cell, region1, region2): '''Checks to see if it makes sense to divide a cell into two new cells based on two regions. Return 0 if nothing should happend and regions ignored Return 1 if cell should grow by region 1 Return 2 if cell should grow by region 2 Return 3 if cell should divide into the regions.''' # load in parameters max_growth_length = params['track']['max_growth_length'] min_growth_length = params['track']['min_growth_length'] # see if either region just could be continued growth, # if that is the case then just return # these shouldn't return true if the cells are divided # as they would be too small if check_growth_by_region(cell, region1): return 1 if check_growth_by_region(cell, region2): return 2 # make sure combined size of daughters is not too big combined_size = region1.major_axis_length + region2.major_axis_length # check if length is not too much longer if cell.lengths[-1]*max_growth_length < combined_size: return 0 # and not too small if cell.lengths[-1]*min_growth_length > combined_size: return 0 # centroids of regions should be in the upper and lower half of the # of the mother's bounding box, respectively # top region within top half of mother bounding box if cell.bboxes[-1][0] > region1.centroid[0] or cell.centroids[-1][0] < region1.centroid[0]: return 0 # bottom region with bottom half of mother bounding box if cell.centroids[-1][0] > region2.centroid[0] or cell.bboxes[-1][2] < region2.centroid[0]: return 0 # if you got this far then divide the mother return 3 ### functions for pruning a dictionary of cells # find cells with both a mother and two daughters def find_complete_cells(Cells): '''Go through a dictionary of cells and return another dictionary that contains just those with a parent and daughters''' Complete_Cells = {} for cell_id in Cells: if Cells[cell_id].daughters and Cells[cell_id].parent: Complete_Cells[cell_id] = Cells[cell_id] return Complete_Cells # finds cells whose birth label is 1 def find_mother_cells(Cells): '''Return only cells whose starting region label is 1.''' Mother_Cells = {} for cell_id in Cells: if Cells[cell_id].birth_label == 1: Mother_Cells[cell_id] = Cells[cell_id] return Mother_Cells def filter_foci(Foci, label, t, debug=False): Filtered_Foci = {} for focus_id, focus in Foci.items(): # copy the times list so as not to update it in-place times = focus.times if debug: print(times) match_inds = [i for i,time in enumerate(times) if time == t] labels = [focus.labels[idx] for idx in match_inds] if label in labels: Filtered_Foci[focus_id] = focus return Filtered_Foci def filter_cells(Cells, attr, val, idx=None, debug=False): '''Return only cells whose designated attribute equals "val".''' Filtered_Cells = {} for cell_id, cell in Cells.items(): at_val = getattr(cell, attr) if debug: print(at_val) print("Times: ", cell.times) if idx is not None: at_val = at_val[idx] if at_val == val: Filtered_Cells[cell_id] = cell return Filtered_Cells def filter_cells_containing_val_in_attr(Cells, attr, val): '''Return only cells that have val in list attribute, attr.''' Filtered_Cells = {} for cell_id, cell in Cells.items(): at_list = getattr(cell, attr) if val in at_list: Filtered_Cells[cell_id] = cell return Filtered_Cells ### functions for additional cell centric analysis def compile_cell_info_df(Cells): # count the number of rows that will be in the long dataframe quant_fluor = False long_df_row_number = 0 for cell in Cells.values(): # first time through, evaluate whether we quantified cells' fluorescence if long_df_row_number == 0: if len(cell.area_mean_fluorescence.keys()) != 0: quant_fluor = True fluorescence_channels = [k for k in cell.area_mean_fluorescence.keys()] long_df_row_number += len(cell.times) # initialize some arrays for filling with data data = { # ids can be up to 100 characters long 'id': np.chararray(long_df_row_number, itemsize=100), 'times': np.zeros(long_df_row_number, dtype='uint16'), 'lengths': np.zeros(long_df_row_number), 'volumes': np.zeros(long_df_row_number), 'areas': np.zeros(long_df_row_number), 'abs_times': np.zeros(long_df_row_number, dtype='uint32') } if quant_fluor: for fluorescence_channel in fluorescence_channels: data['{}_area_mean_fluorescence'.format(fluorescence_channel)] = np.zeros(long_df_row_number) data['{}_volume_mean_fluorescence'.format(fluorescence_channel)] = np.zeros(long_df_row_number) data['{}_total_fluorescence'.format(fluorescence_channel)] = np.zeros(long_df_row_number) data = populate_focus_arrays(Cells, data, cell_quants=True) long_df = pd.DataFrame(data=data) wide_df_row_number = len(Cells) data = { # ids can be up to 100 characters long 'id': np.chararray(wide_df_row_number, itemsize=100), 'fov': np.zeros(wide_df_row_number, dtype='uint8'), 'peak': np.zeros(wide_df_row_number, dtype='uint16'), 'parent_id': np.chararray(wide_df_row_number, itemsize=100), 'child1_id': np.chararray(wide_df_row_number, itemsize=100), 'child2_id': np.chararray(wide_df_row_number, itemsize=100), 'division_time': np.zeros(wide_df_row_number), 'birth_label': np.zeros(wide_df_row_number, dtype='uint8'), 'birth_time': np.zeros(wide_df_row_number, dtype='uint16'), 'sb': np.zeros(wide_df_row_number), 'sd': np.zeros(wide_df_row_number), 'delta': np.zeros(wide_df_row_number), 'tau': np.zeros(wide_df_row_number), 'elong_rate': np.zeros(wide_df_row_number), 'septum_position': np.zeros(wide_df_row_number), 'death': np.zeros(wide_df_row_number), 'disappear': np.zeros(wide_df_row_number) } data = populate_focus_arrays(Cells, data, cell_quants=True, wide=True) # data['parent_id'] = data['parent_id'].decode() # data['child1_id'] = data['child1_id'].decode() # data['child2_id'] = data['child2_id'].decode() wide_df = pd.DataFrame(data=data) return(wide_df,long_df) def populate_focus_arrays(Foci, data_dict, cell_quants=False, wide=False): focus_counter = 0 focus_count = len(Foci) end_idx = 0 for i,focus in enumerate(Foci.values()): if wide: start_idx = i end_idx = i + 1 else: start_idx = end_idx end_idx = len(focus) + start_idx if focus_counter % 100 == 0: print("Generating focus information for focus {} out of {}.".format(focus_counter+1, focus_count)) # loop over keys in data dictionary, and set # values in appropriate array, at appropriate indices # to those we find in the focus. for key in data_dict.keys(): if '_id' in key: if key == 'parent_id': if focus.parent is None: data_dict[key][start_idx:end_idx] = '' else: data_dict[key][start_idx:end_idx] = focus.parent.id if focus.daughters is None: if key == 'child1_id' or key == 'child2_id': data_dict[key][start_idx:end_idx] = '' elif len(focus.daughters) == 1: if key == 'child2_id': data_dict[key][start_idx:end_idx] = '' elif key == 'child1_id': data_dict[key][start_idx:end_idx] = focus.daughters[0].id elif key == 'child2_id': data_dict[key][start_idx:end_idx] = focus.daughters[1].id else: attr_vals = getattr(focus, key) if (cell_quants and key=='abs_times'): if len(attr_vals) == end_idx-start_idx: data_dict[key][start_idx:end_idx] = attr_vals else: data_dict[key][start_idx:end_idx] = attr_vals[:-1] else: # print(key) # print(attr_vals) data_dict[key][start_idx:end_idx] = attr_vals focus_counter += 1 data_dict['id'] = data_dict['id'].decode() return(data_dict) def compile_foci_info_long_df(Foci): ''' Parameters ---------------- Foci : dictionary, keys of which are focus_ids, values of which are objects of class Focus Returns ---------------------- A long DataFrame with detailed information about each timepoint for each focus. ''' # count the number of rows that will be in the long dataframe long_df_row_number = 0 for focus in Foci.values(): long_df_row_number += len(focus) # initialize some arrays for filling with data data = { # ids can be up to 100 characters long 'id': np.chararray(long_df_row_number, itemsize=100), 'times': np.zeros(long_df_row_number, dtype='uint16'), 'lengths': np.zeros(long_df_row_number), 'volumes': np.zeros(long_df_row_number), 'areas': np.zeros(long_df_row_number), 'abs_times': np.zeros(long_df_row_number, dtype='uint32'), 'area_mean_fluorescence': np.zeros(long_df_row_number), 'volume_mean_fluorescence': np.zeros(long_df_row_number), 'total_fluorescence': np.zeros(long_df_row_number), 'median_fluorescence': np.zeros(long_df_row_number), 'sd_fluorescence': np.zeros(long_df_row_number), 'disp_l': np.zeros(long_df_row_number), 'disp_w': np.zeros(long_df_row_number) } data = populate_focus_arrays(Foci, data) long_df = pd.DataFrame(data=data) return(long_df) def find_all_cell_intensities(Cells, specs, time_table, channel_name='sub_c2', apply_background_correction=True): ''' Finds fluorescenct information for cells. All the cells in Cells should be from one fov/peak. ''' # iterate over each fov in specs for fov_id,fov_peaks in specs.items(): # iterate over each peak in fov for peak_id,peak_value in fov_peaks.items(): # if peak_id's value is not 1, go to next peak if peak_value != 1: continue print("Quantifying channel {} fluorescence in cells in fov {}, peak {}.".format(channel_name, fov_id, peak_id)) # Load fluorescent images and segmented images for this channel fl_stack = load_stack(fov_id, peak_id, color=channel_name) corrected_stack = np.zeros(fl_stack.shape) for frame in range(fl_stack.shape[0]): # median filter will be applied to every image with warnings.catch_warnings(): warnings.simplefilter("ignore") median_filtered = median(fl_stack[frame,...], selem=morphology.disk(1)) # subtract the gaussian-filtered image from true image to correct # uneven background fluorescence if apply_background_correction: blurred = filters.gaussian(median_filtered, sigma=10, preserve_range=True) corrected_stack[frame,:,:] = median_filtered-blurred else: corrected_stack[frame,:,:] = median_filtered seg_stack = load_stack(fov_id, peak_id, color='seg_unet') # evaluate whether each cell is in this fov/peak combination for cell_id,cell in Cells.items(): cell_fov = cell.fov if cell_fov != fov_id: continue cell_peak = cell.peak if cell_peak != peak_id: continue cell_times = cell.times cell_labels = cell.labels cell.area_mean_fluorescence[channel_name] = [] cell.volume_mean_fluorescence[channel_name] = [] cell.total_fluorescence[channel_name] = [] # loop through cell's times for i,t in enumerate(cell_times): frame = t-1 cell_label = cell_labels[i] total_fluor = np.sum(corrected_stack[frame, seg_stack[frame, :,:] == cell_label]) cell.area_mean_fluorescence[channel_name].append(total_fluor/cell.areas[i]) cell.volume_mean_fluorescence[channel_name].append(total_fluor/cell.volumes[i]) cell.total_fluorescence[channel_name].append(total_fluor) # The cell objects in the original dictionary will be updated, # no need to return anything specifically. return def find_cell_intensities_worker(fov_id, peak_id, Cells, midline=True, channel='sub_c3'): ''' Finds fluorescenct information for cells. All the cells in Cells should be from one fov/peak. See the function organize_cells_by_channel() This version is the same as find_cell_intensities but return the Cells object for collection by the pool. The original find_cell_intensities is kept for compatibility. ''' information('Processing peak {} in FOV {}'.format(peak_id, fov_id)) # Load fluorescent images and segmented images for this channel fl_stack = load_stack(fov_id, peak_id, color=channel) seg_stack = load_stack(fov_id, peak_id, color='seg_otsu') # determine absolute time index time_table = params['time_table'] times_all = [] for fov in params['time_table']: times_all = np.append(times_all, [int(x) for x in time_table[fov].keys()]) times_all = np.unique(times_all) times_all = np.sort(times_all) times_all = np.array(times_all,np.int_) t0 = times_all[0] # first time index # Loop through cells for Cell in Cells.values(): # give this cell two lists to hold new information Cell.fl_tots = [] # total fluorescence per time point Cell.fl_area_avgs = [] # avg fluorescence per unit area by timepoint Cell.fl_vol_avgs = [] # avg fluorescence per unit volume by timepoint if midline: Cell.mid_fl = [] # avg fluorescence of midline # and the time points that make up this cell's life for n, t in enumerate(Cell.times): # create fluorescent image only for this cell and timepoint. fl_image_masked = np.copy(fl_stack[t-t0]) fl_image_masked[seg_stack[t-t0] != Cell.labels[n]] = 0 # append total flourescent image Cell.fl_tots.append(np.sum(fl_image_masked)) # and the average fluorescence Cell.fl_area_avgs.append(np.sum(fl_image_masked) / Cell.areas[n]) Cell.fl_vol_avgs.append(np.sum(fl_image_masked) / Cell.volumes[n]) if midline: # add the midline average by first applying morphology transform bin_mask = np.copy(seg_stack[t-t0]) bin_mask[bin_mask != Cell.labels[n]] = 0 med_mask, _ = morphology.medial_axis(bin_mask, return_distance=True) # med_mask[med_dist < np.floor(cap_radius/2)] = 0 # print(img_fluo[med_mask]) if (np.shape(fl_image_masked[med_mask])[0] > 0): Cell.mid_fl.append(np.nanmean(fl_image_masked[med_mask])) else: Cell.mid_fl.append(0) # return the cell object to the pool initiated by mm3_Colors. return Cells def find_cell_intensities(fov_id, peak_id, Cells, midline=False, channel_name='sub_c2'): ''' Finds fluorescenct information for cells. All the cells in Cells should be from one fov/peak. See the function organize_cells_by_channel() ''' # Load fluorescent images and segmented images for this channel fl_stack = load_stack(fov_id, peak_id, color=channel_name) seg_stack = load_stack(fov_id, peak_id, color='seg_unet') # determine absolute time index times_all = [] for fov in params['time_table']: times_all = np.append(times_all, time_table[fov].keys()) times_all = np.unique(times_all) times_all = np.sort(times_all) times_all = np.array(times_all,np.int_) t0 = times_all[0] # first time index # Loop through cells for Cell in Cells.values(): # give this cell two lists to hold new information Cell.fl_tots = [] # total fluorescence per time point Cell.fl_area_avgs = [] # avg fluorescence per unit area by timepoint Cell.fl_vol_avgs = [] # avg fluorescence per unit volume by timepoint if midline: Cell.mid_fl = [] # avg fluorescence of midline # and the time points that make up this cell's life for n, t in enumerate(Cell.times): # create fluorescent image only for this cell and timepoint. fl_image_masked = np.copy(fl_stack[t-t0]) fl_image_masked[seg_stack[t-t0] != Cell.labels[n]] = 0 # append total flourescent image Cell.fl_tots.append(np.sum(fl_image_masked)) # and the average fluorescence Cell.fl_area_avgs.append(np.sum(fl_image_masked) / Cell.areas[n]) Cell.fl_vol_avgs.append(np.sum(fl_image_masked) / Cell.volumes[n]) if midline: # add the midline average by first applying morphology transform bin_mask = np.copy(seg_stack[t-t0]) bin_mask[bin_mask != Cell.labels[n]] = 0 med_mask, _ = morphology.medial_axis(bin_mask, return_distance=True) # med_mask[med_dist < np.floor(cap_radius/2)] = 0 # print(img_fluo[med_mask]) if (np.shape(fl_image_masked[med_mask])[0] > 0): Cell.mid_fl.append(np.nanmean(fl_image_masked[med_mask])) else: Cell.mid_fl.append(0) # The cell objects in the original dictionary will be updated, # no need to return anything specifically. return # find foci using a difference of gaussians method def foci_analysis(fov_id, peak_id, Cells): '''Find foci in cells using a fluorescent image channel. This function works on a single peak and all the cells therein.''' # make directory for foci debug # foci_dir = os.path.join(params['ana_dir'], 'overlay/') # if not os.path.exists(foci_dir): # os.makedirs(foci_dir) # Import segmented and fluorescenct images try: image_data_seg = load_stack(fov_id, peak_id, color='seg_unet') except IOError: image_data_seg = load_stack(fov_id, peak_id, color='seg_otsu') image_data_FL = load_stack(fov_id, peak_id, color='sub_{}'.format(params['foci']['foci_plane'])) # determine absolute time index times_all = [] for fov, times in params['time_table'].items(): times_all = np.append(times_all, list(times.keys())) times_all = np.unique(times_all) times_all = np.sort(times_all) times_all = np.array(times_all, np.int_) t0 = times_all[0] # first time index for cell_id, cell in six.iteritems(Cells): information('Extracting foci information for %s.' % (cell_id)) # declare lists holding information about foci. disp_l = [] disp_w = [] foci_h = [] # foci_stack = np.zeros((np.size(cell.times), # image_data_seg[0,:,:].shape[0], image_data_seg[0,:,:].shape[1])) # Go through each time point of this cell for t in cell.times: # retrieve this timepoint and images. image_data_temp = image_data_FL[t-t0,:,:] image_data_temp_seg = image_data_seg[t-t0,:,:] # find foci as long as there is information in the fluorescent image if np.sum(image_data_temp) != 0: disp_l_tmp, disp_w_tmp, foci_h_tmp = foci_lap(image_data_temp_seg, image_data_temp, cell, t) disp_l.append(disp_l_tmp) disp_w.append(disp_w_tmp) foci_h.append(foci_h_tmp) # if there is no information, append an empty list. # Should this be NaN? else: disp_l.append([]) disp_w.append([]) foci_h.append([]) # foci_stack[i] = image_data_temp_seg # add information to the cell (will replace old data) cell.disp_l = disp_l cell.disp_w = disp_w cell.foci_h = foci_h # Create a stack of the segmented images with marked foci # This should poentially be changed to the fluorescent images with marked foci # foci_stack = np.uint16(foci_stack) # foci_stack = np.stack(foci_stack, axis=0) # # Export overlaid images # foci_filename = params['experiment_name'] + 't%04d_xy%03d_p%04d_r%02d_overlay.tif' % (Cells[cell_id].birth_time, Cells[cell_id].fov, Cells[cell_id].peak, Cells[cell_id].birth_label) # foci_filepath = foci_dir + foci_filename # # tiff.imsave(foci_filepath, foci_stack, compress=3) # save it # test # sys.exit() return # foci pool (for parallel analysis) def foci_analysis_pool(fov_id, peak_id, Cells): '''Find foci in cells using a fluorescent image channel. This function works on a single peak and all the cells therein.''' # make directory for foci debug # foci_dir = os.path.join(params['ana_dir'], 'overlay/') # if not os.path.exists(foci_dir): # os.makedirs(foci_dir) # Import segmented and fluorescenct images image_data_seg = load_stack(fov_id, peak_id, color='seg_unet') image_data_FL = load_stack(fov_id, peak_id, color='sub_{}'.format(params['foci']['foci_plane'])) # Load time table to determine first image index. times_all = np.array(np.sort(params['time_table'][fov_id].keys()), np.int_) t0 = times_all[0] # first time index tN = times_all[-1] # last time index # call foci_cell for each cell object pool = Pool(processes=params['num_analyzers']) [pool.apply_async(foci_cell(cell_id, cell, t0, image_data_seg, image_data_FL)) for cell_id, cell in six.iteritems(Cells)] pool.close() pool.join() # parralel function for each cell def foci_cell(cell_id, cell, t0, image_data_seg, image_data_FL): '''find foci in a cell, single instance to be called by the foci_analysis_pool for parallel processing. ''' disp_l = [] disp_w = [] foci_h = [] # foci_stack = np.zeros((np.size(cell.times), # image_data_seg[0,:,:].shape[0], image_data_seg[0,:,:].shape[1])) # Go through each time point of this cell for t in cell.times: # retrieve this timepoint and images. image_data_temp = image_data_FL[t-t0,:,:] image_data_temp_seg = image_data_seg[t-t0,:,:] # find foci as long as there is information in the fluorescent image if np.sum(image_data_temp) != 0: disp_l_tmp, disp_w_tmp, foci_h_tmp = foci_lap(image_data_temp_seg, image_data_temp, cell, t) disp_l.append(disp_l_tmp) disp_w.append(disp_w_tmp) foci_h.append(foci_h_tmp) # if there is no information, append an empty list. # Should this be NaN? else: disp_l.append(np.nan) disp_w.append(np.nan) foci_h.append(np.nan) # foci_stack[i] = image_data_temp_seg # add information to the cell (will replace old data) cell.disp_l = disp_l cell.disp_w = disp_w cell.foci_h = foci_h # actual worker function for foci detection def foci_lap(img, img_foci, cell, t): '''foci_lap finds foci using a laplacian convolution then fits a 2D Gaussian. The returned information are the parameters of this Gaussian. All the information is returned in the form of np.arrays which are the length of the number of found foci across all cells in the image. Parameters ---------- img : 2D np.array phase contrast or bright field image. Only used for debug img_foci : 2D np.array fluorescent image with foci. cell : cell object t : int time point to which the images correspond Returns ------- disp_l : 1D np.array displacement on long axis, in px, of a foci from the center of the cell disp_w : 1D np.array displacement on short axis, in px, of a foci from the center of the cell foci_h : 1D np.array Foci "height." Sum of the intensity of the gaussian fitting area. ''' # pull out useful information for just this time point i = cell.times.index(t) # find position of the time point in lists (time points may be missing) bbox = cell.bboxes[i] orientation = cell.orientations[i] centroid = cell.centroids[i] region = cell.labels[i] # declare arrays which will hold foci data disp_l = [] # displacement in length of foci from cell center disp_w = [] # displacement in width of foci from cell center foci_h = [] # foci total amount (from raw image) # define parameters for foci finding minsig = params['foci']['foci_log_minsig'] maxsig = params['foci']['foci_log_maxsig'] thresh = params['foci']['foci_log_thresh'] peak_med_ratio = params['foci']['foci_log_peak_med_ratio'] debug_foci = params['foci']['debug_foci'] # test #print ("minsig={:d} maxsig={:d} thres={:.4g} peak_med_ratio={:.2g}".format(minsig,maxsig,thresh,peak_med_ratio)) # test # calculate median cell intensity. Used to filter foci img_foci_masked = np.copy(img_foci).astype(np.float) img_foci_masked[img != region] = np.nan cell_fl_median = np.nanmedian(img_foci_masked) cell_fl_mean = np.nanmean(img_foci_masked) img_foci_masked[img != region] = 0 # subtract this value from the cell if False: img_foci = img_foci.astype('int32') - cell_fl_median.astype('int32') img_foci[img_foci < 0] = 0 img_foci = img_foci.astype('uint16') # int_mask = np.zeros(img_foci.shape, np.uint8) # avg_int = cv2.mean(img_foci, mask=int_mask) # avg_int = avg_int[0] # print('median', cell_fl_median) # find blobs using difference of gaussian over_lap = .95 # if two blobs overlap by more than this fraction, smaller blob is cut numsig = (maxsig - minsig + 1) # number of division to consider between min ang max sig blobs = blob_log(img_foci_masked, min_sigma=minsig, max_sigma=maxsig, overlap=over_lap, num_sigma=numsig, threshold=thresh) # these will hold information about foci position temporarily x_blob, y_blob, r_blob = [], [], [] x_gaus, y_gaus, w_gaus = [], [], [] # loop through each potential foci for blob in blobs: yloc, xloc, sig = blob # x location, y location, and sigma of gaus xloc = int(np.around(xloc)) # switch to int for slicing images yloc = int(np.around(yloc)) radius = int(np.ceil(np.sqrt(2)*sig)) # will be used to slice out area around foci # ensure blob is inside the bounding box # this might be better to check if (xloc, yloc) is in regions.coords if yloc > np.int16(bbox[0]) and yloc < np.int16(bbox[2]) and xloc >
np.int16(bbox[1])
numpy.int16
import numpy as np import onnx from tests.tools import expect class Tile: @staticmethod def export_tile(): # type: () -> None node = onnx.helper.make_node('Tile', inputs=['x', 'y'], outputs=['z']) x = np.random.rand(2, 3, 4, 5).astype(np.float32) repeats = np.random.randint(low=1, high=10, size=(np.ndim(x),)).astype(np.int64) z = np.tile(x, repeats) expect(node, inputs=[x, repeats], outputs=[z], name='test_tile') @staticmethod def export_tile_precomputed(): # type: () -> None node = onnx.helper.make_node('Tile', inputs=['x', 'y'], outputs=['z']) x =
np.array([[0, 1], [2, 3]], dtype=np.float32)
numpy.array
# Digital Signal Processing - Lab 1 - Part 4 (BONUS) # <NAME> - 03117037 # <NAME> - 03117165 import numpy as np import matplotlib.pyplot as plt import scipy as sp import librosa import sounddevice as sd plt.close('all') counter = 0 # Part 4 (Bonus) #4.1 Open .wav file of salsa music signal 1 salsa1, fs = librosa.load('salsa_excerpt1.mp3') sd.play(salsa1, fs) #kommatara :) Ts = 1/fs # fs = 22050Hz sampling frequency segment = salsa1[10000:75536] #segment of 2^16=65536 samples t = np.arange(0,np.size(segment)*Ts, Ts) #time index counter = counter+1 plt.figure(counter) plt.plot(t,segment, 'b', label = 'Samples L=2^16') plt.xlabel('Time [sec]') plt.ylabel('Amplitude') plt.title('Segment of "salsa_excerpt1.mp3"') plt.legend() #4.2 Discrete Wavelet Transform from pywt import wavedec coeffs = wavedec(segment, 'db1', level=7)/np.sqrt(2) ya7, yd7, yd6, yd5, yd4, yd3, yd2, yd1 = coeffs #4.3 Envelope Detection #(a) Absolute Value absolutes = np.abs(coeffs) za7 = absolutes[0] zd7 = absolutes[1] zd6 = absolutes[2] zd5 = absolutes[3] zd4 = absolutes[4] zd3 = absolutes[5] zd2 = absolutes[6] zd1 = absolutes[7] #(b) Lowpass Filter a0 = 0.006 a = np.zeros(7) for i in range(1,8): a[i-1] = a0*(2**(i+1)) def envelope(signal, absolute, a): x = np.zeros(np.size(signal)) x[0] = a*absolute[0] for i in range(1,np.size(x)): x[i] = (1-a)*x[i-1] + a*absolute[i] x = x - np.mean(x) return x xa7 = envelope(ya7, za7, a[6]) xd7 = envelope(yd7, zd7, a[6]) xd6 = envelope(yd6, zd6, a[5]) xd5 = envelope(yd5, zd5, a[4]) xd4 = envelope(yd4, zd4, a[3]) xd3 = envelope(yd3, zd3, a[2]) xd2 = envelope(yd2, zd2, a[1]) xd1 = envelope(yd1, zd1, a[0]) n = np.arange(0,np.size(yd3),1) #number of samples counter=counter+1 plt.figure(counter) plt.plot(n, yd3, 'b', label = 'Detal yd3[n]') plt.plot(n, xd3, 'r', label = 'Envelope xd3[n]') plt.xlabel('Samples (2^13 = 8192)') plt.ylabel('Amplitude') plt.title('Envelope Detection of Detail yd3') plt.show() plt.legend() counter=counter+1 plt.figure(counter) n = np.arange(0,np.size(yd6),1) #number of samples plt.plot(n, yd6, 'b', label = 'Detail yd6[n]') plt.plot(n, xd6, 'r', label = 'Envelope xd6[n]') plt.xlabel('Samples (2^10 = 1024)') plt.ylabel('Amplitude') plt.title('Envelope Detection of Detail yd6') plt.show() plt.legend() #4.4 Sum of Envelopes and Autocorrelation nvalues = np.arange(0, 32768, 1) n = np.arange(0, 32768, 1) xd1 = np.interp(nvalues, n, xd1) n = np.arange(0, 16384, 1) xd2 = np.interp(nvalues, n, xd2) n = np.arange(0, 8192, 1) xd3 = np.interp(nvalues, n, xd3) n = np.arange(0, 4096, 1) xd4 = np.interp(nvalues, n, xd4) n = np.arange(0, 2048, 1) xd5 = np.interp(nvalues, n, xd5) n = np.arange(0, 1024, 1) xd6 = np.interp(nvalues, n, xd6) n = np.arange(0, 512, 1) xd7 = np.interp(nvalues, n, xd7) n = np.arange(0, 512, 1) xa7 = np.interp(nvalues, n, xa7) xsum = xd1+xd2+xd3+xd4+xd5+xd6+xd7+xa7 autocorrelation = np.correlate(xsum,xsum, 'full')[len(xsum)-1:] autocorrelation = sp.ndimage.filters.gaussian_filter1d(autocorrelation,150) counter = counter+1 plt.figure(counter) t = np.arange(Ts,np.size(autocorrelation)*Ts*2, 2*Ts) #time index plt.plot(t, autocorrelation) plt.xlabel('Time [sec]') plt.title('Autocorrelation of Salsa Excerpt 1') #Find the maximums of Autocorrelation maximums = np.array(sp.signal.argrelextrema(autocorrelation, np.greater)) #Keep every two of them - Maximums of great amplitude will show as the beat maximums = maximums[0,::2] #Calculate number of samples between every two peaks of autocorrelation samplesbetween = np.zeros(np.size(maximums)) for i in range(1,np.size(maximums)): samplesbetween[i] = maximums[i]-maximums[i-1] samplesbetween = samplesbetween[1:(np.size(samplesbetween))] #Find the mean number of samples between every two peaks of autocorrelation samplebeat = np.mean(samplesbetween) print('Salsa1: Autocorrelation peaks every %i samples.' %samplebeat) #Convert to time timebeat = samplebeat*2*Ts*1000 #msec print('Salsa1: Autocorrelation peaks approximately every %d msec.' %timebeat) #Calculate BPM os salsa1 bpm_rate = 60*(1000/(timebeat)) print('Salsa1: Beats Per Minute Rate = %d bpm.' %bpm_rate) #Visualise BPM of salsa1 with help of plotting counter = counter+1 plt.figure(counter) plt.plot(60/t,autocorrelation) plt.xlim(20, 180) plt.xlabel('Beats Per Minute (BPM)') plt.ylabel('Autocorrelation') plt.title('BPM of Salsa Excerpt 1') #################### SALSA 2 ##################### #4.1 Open .wav file of salsa music signal 2 salsa2, fs = librosa.load('salsa_excerpt2.mp3') #sd.play(salsa2, fs) Ts = 1/fs # fs = 22050Hz sampling frequency segment = salsa2[60000:125536] #segment of 2^16=65536 samples t = np.arange(0,np.size(segment)*Ts, Ts) #time index counter = counter+1 plt.figure(counter) plt.plot(t,segment, 'b', label = 'Samples L=2^16') plt.xlabel('Time [sec]') plt.ylabel('Amplitude') plt.title('Segment of "salsa_excerpt2.mp3"') plt.legend() #4.2 Discrete Wavelet Transform from pywt import wavedec coeffs = wavedec(segment, 'db1', level=7)/np.sqrt(2) ya7, yd7, yd6, yd5, yd4, yd3, yd2, yd1 = coeffs #4.3 Envelope Detection #(a) Absolute Value absolutes = np.abs(coeffs) za7 = absolutes[0] zd7 = absolutes[1] zd6 = absolutes[2] zd5 = absolutes[3] zd4 = absolutes[4] zd3 = absolutes[5] zd2 = absolutes[6] zd1 = absolutes[7] #(b) Lowpass Filter a0 = 0.003 a = np.zeros(7) for i in range(1,8): a[i-1] = a0*(2**(i+1)) def envelope(signal, absolute, a): x = np.zeros(np.size(signal)) x[0] = a*absolute[0] for i in range(1,np.size(x)): x[i] = (1-a)*x[i-1] + a*absolute[i] x = x - np.mean(x) return x xa7 = envelope(ya7, za7, a[6]) xd7 = envelope(yd7, zd7, a[6]) xd6 = envelope(yd6, zd6, a[5]) xd5 = envelope(yd5, zd5, a[4]) xd4 = envelope(yd4, zd4, a[3]) xd3 = envelope(yd3, zd3, a[2]) xd2 = envelope(yd2, zd2, a[1]) xd1 = envelope(yd1, zd1, a[0]) n = np.arange(0,np.size(yd3),1) #number of samples counter=counter+1 plt.figure(counter) plt.plot(n, yd3, 'b', label = 'Detal yd3[n]') plt.plot(n, xd3, 'r', label = 'Envelope xd3[n]') plt.xlabel('Samples (2^13 = 8192)') plt.ylabel('Amplitude') plt.title('Envelope Detection of Detail yd3') plt.show() plt.legend() counter=counter+1 plt.figure(counter) n = np.arange(0,np.size(yd6),1) #number of samples plt.plot(n, yd6, 'b', label = 'Detail yd6[n]') plt.plot(n, xd6, 'r', label = 'Envelope xd6[n]') plt.xlabel('Samples (2^10 = 1024)') plt.ylabel('Amplitude') plt.title('Envelope Detection of Detail yd6') plt.show() plt.legend() #4.4 Sum of Envelopes and Autocorrelation nvalues = np.arange(0, 32768, 1) n = np.arange(0, 32768, 1) xd1 = np.interp(nvalues, n, xd1) n = np.arange(0, 16384, 1) xd2 = np.interp(nvalues, n, xd2) n = np.arange(0, 8192, 1) xd3 = np.interp(nvalues, n, xd3) n = np.arange(0, 4096, 1) xd4 = np.interp(nvalues, n, xd4) n = np.arange(0, 2048, 1) xd5 = np.interp(nvalues, n, xd5) n = np.arange(0, 1024, 1) xd6 = np.interp(nvalues, n, xd6) n = np.arange(0, 512, 1) xd7 = np.interp(nvalues, n, xd7) n = np.arange(0, 512, 1) xa7 =
np.interp(nvalues, n, xa7)
numpy.interp
import numpy as np from numpy.linalg import norm from functools import lru_cache from tqdm import tqdm from scipy.optimize import linprog from sklearn.metrics import accuracy_score, f1_score import matplotlib import matplotlib.pyplot as plt matplotlib.rcParams.update({'errorbar.capsize': 2}) def sq(a): return np.dot(a, a) def cluster_score(data, target, score_type='trace_w'): # target 0...max num_class = target.max() + 1 score = 0 for i in range(num_class): s = 0 sub_data = data[target==i] mean_vector = sub_data.mean(axis=0) for x in sub_data: s += sq(x-mean_vector) if score_type != 'trace_w': s /= len(sub_data) score += s return score def get_weights_gap(code_matrix, dich_classifiers=None, weights_type=None): l, N = code_matrix.shape c = np.zeros(N+1) c[-1] = -1 # размер A Nx (l*(l-1)/2) A_ub = [] b_ub = np.zeros(l*(l-1)//2) for nu in range(l): for mu in range(nu+1, l): A_arr = [] for j in range(N): # кол-во дихотомий diff_munu = code_matrix[nu][j] - code_matrix[mu][j] if weights_type is not None: if weights_type == 'confusion_list': score = dich_classifiers[j][weights_type][mu]#, nu].mean() #maybe dirty hack else: score = dich_classifiers[j][weights_type] if diff_munu == 1: diff_munu = score else: diff_munu = 1-score A_arr.append(-np.abs(diff_munu)) A_arr.append(1) A_ub.append(A_arr) A_ub = np.array(A_ub) A_ub = np.vstack([A_ub, -np.eye(N+1)[:-1]]) # x_i >= 0 b_ub = np.append(b_ub, np.zeros(N)) A_eq = np.ones(N+1).reshape((1, -1)) A_eq[0][-1] = 0 b_eq = np.array(N).reshape((-1)) opt_result = linprog(c, A_ub, b_ub, A_eq, b_eq, options={'disp': False}) return opt_result['x'][:-1] # last value is gap def ex(arr, j, i): return np.exp(-norm(arr[i] - arr[j])**2) def p(arr, j, i): a = ex(arr, j, i) b = sum(ex(arr, k, i) for k in range(len(arr)) if k!=i) return a / b def d(arr, i, i1, i2): # return np.abs(arr[i, i2] - arr[j, i2]) return 2*(arr[i1, i2] - arr[i, i2]) def norm1(i, j): return norm(arr1[i] - arr1[j])**2 def cost(arr1, arr2): @lru_cache(maxsize=None) def norm1(i, j): return norm(arr1[i] - arr1[j])**2 @lru_cache(maxsize=None) def ex1(i, j): return np.exp(-norm1(i, j)) @lru_cache(maxsize=None) def p1(j, i): a = ex1(j, i) b = sum(ex1(k, i) for k in range(len(arr1)) if k!=i) return a / b @lru_cache(maxsize=None) def norm2(i, j): return norm(arr2[i] - arr2[j])**2 @lru_cache(maxsize=None) def ex2(i, j): return np.exp(-norm2(i, j)) @lru_cache(maxsize=None) def p2(j, i): a = ex2(j, i) b = sum(ex2(k, i) for k in range(len(arr2)) if k!=i) return a / b s = 0 for i in range(len(arr1)): for j in range(len(arr1)): s += p1(j, i) * np.log(p1(j, i) / p2(j, i)) return s def get_grad(arr1, arr2, i1, i2): ''' arr1 - массив без пропусков(укороченный) arr2 - массив с прочерками(удлиенный) i1, i2 - координаты nan ''' @lru_cache(maxsize=None) def norm1(i, j): return norm(arr1[i] - arr1[j]) @lru_cache(maxsize=None) def ex1(i, j): return np.exp(-norm1(i, j)) @lru_cache(maxsize=None) def p1(j, i): a = ex1(j, i) b = sum(ex1(k, i) for k in range(len(arr1)) if k!=i) return a / b @lru_cache(maxsize=None) def norm2(i, j): return norm(arr2[i] - arr2[j]) @lru_cache(maxsize=None) def ex2(i, j): return np.exp(-norm2(i, j)) @lru_cache(maxsize=None) def p2(j, i): a = ex2(j, i) b = sum(ex2(k, i) for k in range(len(arr2)) if k!=i) return a / b @lru_cache(maxsize=None) def d(i, i1): ''' "Дистанция после дифференцирования" - то же самое, только arr == arr2 и i2 == i2 ''' dist = 2*(arr2[i1, i2] - arr2[i, i2]) return dist def get_i_part(i): ''' считаем i часть суммы ''' s = 0 s += p1(i1, i) + p1(i, i1) s -= p2(i1, i)*(1 + p1(i, i)) s -= p2(i, i1)*(1 + p1(i1, i1)) return s * d(i, i1) # if verbose: # grad = sum(get_i_part(i) for i in tqdm(range(len(arr1))) if i!=i1) # else: grad = sum(get_i_part(i) for i in range(len(arr1)) if i!=i1) return grad def get_full_grad(arr1, arr2, nan_coords, verbose=False): ''' arr1 - массив без пропусков(укороченный) arr2 - массив с прочерками(удлиенный) i1, i2 - координаты nan ''' grads = [] if verbose: for i1, i2 in tqdm(nan_coords): grads.append(get_grad(arr1, arr2, i1, i2)) else: for i1, i2 in nan_coords: grads.append(get_grad(arr1, arr2, i1, i2)) return
np.array(grads)
numpy.array
#!/usr/bin/env python # -*- coding: utf-8 -*- '''oldpf.py - <NAME> (<EMAIL>) - Jan 2017 This contains deprecated and incomplete period-finding tools from periodbase.py: - dworetsky period finder - scipy LSP - townsend LSP Kept around just in case. ''' ############# ## LOGGING ## ############# import logging from datetime import datetime from traceback import format_exc # setup a logger LOGGER = None LOGMOD = __name__ DEBUG = False def set_logger_parent(parent_name): globals()['LOGGER'] = logging.getLogger('%s.%s' % (parent_name, LOGMOD)) def LOGDEBUG(message): if LOGGER: LOGGER.debug(message) elif DEBUG: print('[%s - DBUG] %s' % ( datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ'), message) ) def LOGINFO(message): if LOGGER: LOGGER.info(message) else: print('[%s - INFO] %s' % ( datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ'), message) ) def LOGERROR(message): if LOGGER: LOGGER.error(message) else: print('[%s - ERR!] %s' % ( datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ'), message) ) def LOGWARNING(message): if LOGGER: LOGGER.warning(message) else: print('[%s - WRN!] %s' % ( datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ'), message) ) def LOGEXCEPTION(message): if LOGGER: LOGGER.exception(message) else: print( '[%s - EXC!] %s\nexception was: %s' % ( datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ'), message, format_exc() ) ) ############# ## IMPORTS ## ############# from multiprocessing import Pool, cpu_count import numpy as np # import these to avoid lookup overhead from numpy import nan as npnan, sum as npsum, abs as npabs, \ roll as nproll, isfinite as npisfinite, std as npstd, \ sign as npsign, sqrt as npsqrt, median as npmedian, \ array as nparray, percentile as nppercentile, \ polyfit as nppolyfit, var as npvar, max as npmax, min as npmin, \ log10 as nplog10, arange as nparange, pi as MPI, floor as npfloor, \ argsort as npargsort, cos as npcos, sin as npsin, tan as nptan, \ where as npwhere, linspace as nplinspace, \ zeros_like as npzeros_like, full_like as npfull_like, \ arctan as nparctan, nanargmax as npnanargmax, nanargmin as npnanargmin, \ empty as npempty, ceil as npceil, mean as npmean, \ digitize as npdigitize, unique as npunique, \ argmax as npargmax, argmin as npargmin from scipy.signal import lombscargle, find_peaks_cwt ################### ## LOCAL IMPORTS ## ################### from ..lcmath import phase_magseries, sigclip_magseries, time_bin_magseries, \ phase_bin_magseries ############ ## CONFIG ## ############ NCPUS = cpu_count() ####################### ## UTILITY FUNCTIONS ## ####################### def get_frequency_grid(times, samplesperpeak=5, nyquistfactor=5, minfreq=None, maxfreq=None, returnf0dfnf=False): '''This calculates a frequency grid for the period finding functions in this module. Based on the autofrequency function in astropy.stats.lombscargle. http://docs.astropy.org/en/stable/_modules/astropy/stats/lombscargle/core.html#LombScargle.autofrequency ''' baseline = times.max() - times.min() nsamples = times.size df = 1. / baseline / samplesperpeak if minfreq is not None: f0 = minfreq else: f0 = 0.5 * df if maxfreq is not None: Nf = int(npceil((maxfreq - f0) / df)) else: Nf = int(0.5 * samplesperpeak * nyquistfactor * nsamples) if returnf0dfnf: return f0, df, Nf, f0 + df * nparange(Nf) else: return f0 + df * nparange(Nf) ############################################### ## DWORETSKY STRING LENGTH (Dworetsky+ 1983) ## ## (don't use this -- it's very slow) ## ############################################### def dworetsky_period_find(time, mag, err, init_p, end_p, f_step, verbose=False): ''' This is the super-slow naive version taken from my thesis work. Uses the string length method in Dworetsky 1983 to calculate the period of a time-series of magnitude measurements and associated magnitude errors. Searches in linear frequency space (which obviously doesn't correspond to a linear period space). PARAMETERS: time: series of times at which mags were measured (usually some form of JD) mag: timeseries of magnitudes (np.array) err: associated errs per magnitude measurement (np.array) init_p, end_p: interval to search for periods between (both ends inclusive) f_step: step in frequency [days^-1] to use RETURNS: tuple of the following form: (periods (np.array), string_lengths (np.array), good_period_mask (boolean array)) ''' mod_mag = (mag - npmin(mag))/(2.0*(npmax(mag) - npmin(mag))) - 0.25 fold_time = npmin(time) # fold at the first time element init_f = 1.0/end_p end_f = 1.0/init_p n_freqs = npceil((end_f - init_f)/f_step) if verbose: print('searching %s frequencies between %s and %s days^-1...' % (n_freqs,init_f,end_f)) out_periods = npempty(n_freqs,dtype=np.float64) out_strlens = npempty(n_freqs,dtype=np.float64) p_goodflags = npempty(n_freqs,dtype=bool) j_range = len(mag)-1 for i in range(int(n_freqs)): period = 1.0/init_f # print('P: %s, f: %s, i: %s, n_freqs: %s, maxf: %s' % # (period, init_f, i, n_freqs, end_f)) phase = (time - fold_time)/period - npfloor((time - fold_time)/period) phase_sort_ind = npargsort(phase) phase_sorted = phase[phase_sort_ind] mod_mag_sorted = mod_mag[phase_sort_ind] strlen = 0.0 epsilon = 2.0 * npmean(err) delta_l = 0.34 * (epsilon - 0.5*(epsilon**2)) * (len(time) - npsqrt(10.0/epsilon)) keep_threshold_1 = 1.6 + 1.2*delta_l l = 0.212*len(time) sig_l = len(time)/37.5 keep_threshold_2 = l + 4.0*sig_l # now calculate the string length for j in range(j_range): strlen += npsqrt( (mod_mag_sorted[j+1] - mod_mag_sorted[j])**2 + (phase_sorted[j+1] - phase_sorted[j])**2 ) strlen += npsqrt( (mod_mag_sorted[0] - mod_mag_sorted[-1])**2 + (phase_sorted[0] - phase_sorted[-1] + 1)**2 ) if ((strlen < keep_threshold_1) or (strlen < keep_threshold_2)): p_goodflags[i] = True out_periods[i] = period out_strlens[i] = strlen init_f += f_step return (out_periods,out_strlens,p_goodflags) def pwd_phasebin(phases, mags, binsize=0.002, minbin=9): ''' This bins the phased mag series using the given binsize. ''' bins = np.arange(0.0, 1.0, binsize) binnedphaseinds = npdigitize(phases, bins) binnedphases, binnedmags = [], [] for x in npunique(binnedphaseinds): thisbin_inds = binnedphaseinds == x thisbin_phases = phases[thisbin_inds] thisbin_mags = mags[thisbin_inds] if thisbin_inds.size > minbin: binnedphases.append(npmedian(thisbin_phases)) binnedmags.append(npmedian(thisbin_mags)) return np.array(binnedphases), np.array(binnedmags) def pdw_worker(task): ''' This is the parallel worker for the function below. task[0] = frequency for this worker task[1] = times array task[2] = mags array task[3] = fold_time task[4] = j_range task[5] = keep_threshold_1 task[6] = keep_threshold_2 task[7] = phasebinsize we don't need errs for the worker. ''' frequency = task[0] times, modmags = task[1], task[2] fold_time = task[3] j_range = range(task[4]) keep_threshold_1 = task[5] keep_threshold_2 = task[6] phasebinsize = task[7] try: period = 1.0/frequency # use the common phaser to phase and sort the mag phased = phase_magseries(times, modmags, period, fold_time, wrap=False, sort=True) # bin in phase if requested, this turns this into a sort of PDM method if phasebinsize is not None and phasebinsize > 0: bphased = pwd_phasebin(phased['phase'], phased['mags'], binsize=phasebinsize) phase_sorted = bphased[0] mod_mag_sorted = bphased[1] j_range = range(len(mod_mag_sorted) - 1) else: phase_sorted = phased['phase'] mod_mag_sorted = phased['mags'] # now calculate the string length rolledmags = nproll(mod_mag_sorted,1) rolledphases = nproll(phase_sorted,1) strings = ( (rolledmags - mod_mag_sorted)*(rolledmags - mod_mag_sorted) + (rolledphases - phase_sorted)*(rolledphases - phase_sorted) ) strings[0] = ( ((mod_mag_sorted[0] - mod_mag_sorted[-1]) * (mod_mag_sorted[0] - mod_mag_sorted[-1])) + ((phase_sorted[0] - phase_sorted[-1] + 1) * (phase_sorted[0] - phase_sorted[-1] + 1)) ) strlen = npsum(npsqrt(strings)) if (keep_threshold_1 < strlen < keep_threshold_2): p_goodflag = True else: p_goodflag = False return (period, strlen, p_goodflag) except Exception as e: LOGEXCEPTION('error in DWP') return(period, npnan, False) def pdw_period_find(times, mags, errs, autofreq=True, init_p=None, end_p=None, f_step=1.0e-4, phasebinsize=None, sigclip=10.0, nworkers=None, verbose=False): '''This is the parallel version of the function above. Uses the string length method in Dworetsky 1983 to calculate the period of a time-series of magnitude measurements and associated magnitude errors. This can optionally bin in phase to try to speed up the calculation. PARAMETERS: time: series of times at which mags were measured (usually some form of JD) mag: timeseries of magnitudes (np.array) err: associated errs per magnitude measurement (np.array) init_p, end_p: interval to search for periods between (both ends inclusive) f_step: step in frequency [days^-1] to use RETURNS: tuple of the following form: (periods (np.array), string_lengths (np.array), good_period_mask (boolean array)) ''' # remove nans find = npisfinite(times) & npisfinite(mags) & npisfinite(errs) ftimes, fmags, ferrs = times[find], mags[find], errs[find] mod_mags = (fmags - npmin(fmags))/(2.0*(npmax(fmags) -
npmin(fmags)
numpy.min
import time import numpy as np #from scipy.fftpack import fft,ifft,fft2,ifft2 import pyfftw from numpy import cos,sin from numpy.fft import fft, ifft,fft2,ifft2 from math import pi #from pyfftw.interfaces.numpy_fft import fft #from pyfftw.interfaces.numpy_fft import fft2 #from pyfftw.interfaces.numpy_fft import ifft #from pyfftw.interfaces.numpy_fft import ifft2 import pdb def unring_1d(data,nsh,minW,maxW): n = data.shape[1] numlines= data.shape[0] shifts =
np.zeros([2*nsh+1],dtype=np.float64)
numpy.zeros
""" Tests for inequality.py """ import numpy as np from numpy.testing import assert_allclose, assert_raises from scipy.stats import linregress from quantecon import lorenz_curve, gini_coefficient, \ shorrocks_index, rank_size def test_lorenz_curve(): """ Tests `lorenz` function, which calculates the lorenz curve An income distribution where everyone has almost the same wealth should be similar to a straight line An income distribution where one person has almost the wealth should be flat and then shoot straight up when it approaches one """ n = 3000 # Almost Equal distribution y = np.repeat(1, n) + np.random.normal(scale=0.0001, size=n) cum_people, cum_income = lorenz_curve(y) assert_allclose(cum_people, cum_income, rtol=1e-03) # Very uneven distribution y = np.repeat(0.001, n) y[4] = 100000 pop_cum, income_cum = lorenz_curve(y) expected_income_cum = np.repeat(0., n + 1) expected_income_cum[-1] = 1. assert_allclose(expected_income_cum, income_cum, atol=1e-4) def test_gini_coeff(): """ Tests how the function `gini_coefficient` calculates the Gini coefficient with the Pareto and the Weibull distribution. Analytically, we know that Pareto with parameter `a` has G = 1 / (2*a - 1) Likewise, for the Weibull distribution with parameter `a` we know that G = 1 - 2**(-1/a) """ n = 10000 # Tests Pareto: G = 1 / (2*a - 1) a = np.random.randint(2, 15) expected = 1 / (2 * a - 1) y = (np.random.pareto(a, size=n) + 1) * 2 coeff = gini_coefficient(y) assert_allclose(expected, coeff, rtol=1e-01) # Tests Weibull: G = 1 - 2**(-1/a) a = np.random.randint(2, 15) expected = 1 - 2 ** (-1 / a) y = np.random.weibull(a, size=n) coeff = gini_coefficient(y) assert_allclose(expected, coeff, rtol=1e-01) def test_shorrocks_index(): """ Test Shorrocks mobility index function against the example used in 'Wealth distribution and social mobility in the US: A quantitative approach' (Benhabib, <NAME>, 2017).'' https://www.econ.nyu.edu/user/bisina/RevisionAugust.pdf """ # Construct the mobility matrix from Benhabib et al. P = [[0.222, 0.222, 0.215, 0.187, 0.081, 0.038, 0.029, 0.006], [0.221, 0.220, 0.215, 0.188, 0.082, 0.039, 0.029, 0.006], [0.207, 0.209, 0.210, 0.194, 0.090, 0.046, 0.036, 0.008], [0.198, 0.201, 0.207, 0.198, 0.095, 0.052, 0.040, 0.009], [0.175, 0.178, 0.197, 0.207, 0.110, 0.067, 0.054, 0.012], [0.182, 0.184, 0.200, 0.205, 0.106, 0.062, 0.050, 0.011], [0.123, 0.125, 0.166, 0.216, 0.141, 0.114, 0.094, 0.021], [0.084, 0.084, 0.142, 0.228, 0.170, 0.143, 0.121, 0.028]] expected = 0.98 # result from paper index = shorrocks_index(P) assert_allclose(expected, index, rtol=1e-2) def test_rank_size(): """ Tests `rank_size` function, which generates rank-size data for a Pareto distribution. The rank-size plot for a sample drawn from a Pareto distribution should be a straight line. The length of the `rank_data` array should be within (c x 100)% of the size of the distribution. """ np.random.seed(15) sample_size = 10000 c = 0.74 # Tests Pareto; r_squared ~ 1 pareto_draw = np.exp(np.random.exponential(scale=1.0, size=sample_size)) rank_data, size_data = rank_size(pareto_draw, c=c) assert len(rank_data) == len(size_data) assert_allclose(c*sample_size, len(rank_data), rtol=1e-3) _, _, r_value, _, _ = linregress(
np.log(rank_data)
numpy.log
import numpy as np import cv2 import random import threading import os import time import logging import tensorflow as tf import matplotlib.pyplot as plt from PIL import Image def fold(image): rows,cols,channel = image.shape new_row = int (rows/2) dst = image[0:new_row, 0:cols] return dst def Rotation(image): rows,cols,channel = image.shape angle = np.random.uniform(low=-20.0, high=20.0) M = cv2.getRotationMatrix2D((cols/2,rows/2),angle,1) dst = cv2.warpAffine(image, M, (cols,rows)) return dst def Translate(image): rows,cols,channel = image.shape x_ = cols*0.15 y_ = rows*0.15 scale = np.random.uniform(0.80, 1.20) x = np.random.uniform(-x_, x_) y = np.random.uniform(-y_, y_) M = np.float32([[scale, 0, x], [0, scale, y]]) dst = cv2.warpAffine(image, M, (image.shape[1], image.shape[0])) return dst def Affine(image): img_info=image.shape image_height=img_info[0] image_weight=img_info[1] mat_src=np.float32([[0,0],[0,image_height-1],[image_weight-1,0]]) x1 = np.random.uniform(0, 50) y1 = np.random.uniform(0, 50) x2 = np.random.uniform(200, 400) y2 = np.random.uniform(300, 500) x3 = np.random.uniform(200, 400) y3 = np.random.uniform(300, 500) mat_dst=np.float32([[x1,y1],[x2,image_height-y2],[image_weight-x3,y3]]) mat_Affine=cv2.getAffineTransform(mat_src,mat_dst) dst=cv2.warpAffine(image,mat_Affine,(image_height,image_weight)) return dst def Crop(image): rows,cols,channel = image.shape L_delta = int(np.random.uniform(1, cols*0.15)) R_delta = int(np.random.uniform(1, cols*0.15)) U_delta = int(np.random.uniform(1, rows*0.15)) D_delta = int(np.random.uniform(1, rows*0.15)) TOP = 0 + L_delta DOWN = rows - R_delta LEFT = 0 + U_delta RIGHT = cols - D_delta crop_img = image[TOP:DOWN, LEFT:RIGHT] dst = cv2.copyMakeBorder(crop_img, L_delta, R_delta, U_delta , D_delta, cv2.BORDER_CONSTANT, value=(0, 0, 0, 0)) return dst def Hsv(image): hue_vari = 1 sat_vari = 0.5 val_vari = 0.5 hue_delta = np.random.randint(-hue_vari, hue_vari) sat_mult = 1 + np.random.uniform(-sat_vari, sat_vari) val_mult = 1 + np.random.uniform(-val_vari, val_vari) img_hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV).astype(np.float) img_hsv[:, :, 0] = (img_hsv[:, :, 0] + hue_delta) % 180 img_hsv[:, :, 1] *= sat_mult img_hsv[:, :, 2] *= val_mult img_hsv[img_hsv > 255] = 255 dst = cv2.cvtColor(np.round(img_hsv).astype(np.uint8), cv2.COLOR_HSV2BGR) return dst def Gamma(image): gamma_vari = 0.15 log_gamma_vari = np.log(gamma_vari) alpha = np.random.uniform(-log_gamma_vari, log_gamma_vari) gamma = np.exp(alpha) gamma_table = [np.power(x / 255.0, gamma) * 255.0 for x in range(256)] gamma_table = np.round(np.array(gamma_table)).astype(np.uint8) dst = cv2.LUT(image, gamma_table) return dst def Motion_blur(image): image =
np.array(image)
numpy.array
# This module has been generated automatically from space group information # obtained from the Computational Crystallography Toolbox # """ Space groups This module contains a list of all the 230 space groups that can occur in a crystal. The variable space_groups contains a dictionary that maps space group numbers and space group names to the corresponding space group objects. .. moduleauthor:: <NAME> <<EMAIL>> """ #----------------------------------------------------------------------------- # Copyright (C) 2013 The Mosaic Development Team # # Distributed under the terms of the BSD License. The full license is in # the file LICENSE.txt, distributed as part of this software. #----------------------------------------------------------------------------- import numpy as N class SpaceGroup(object): """ Space group All possible space group objects are created in this module. Other modules should access these objects through the dictionary space_groups rather than create their own space group objects. """ def __init__(self, number, symbol, transformations): """ :param number: the number assigned to the space group by international convention :type number: int :param symbol: the Hermann-Mauguin space-group symbol as used in PDB and mmCIF files :type symbol: str :param transformations: a list of space group transformations, each consisting of a tuple of three integer arrays (rot, tn, td), where rot is the rotation matrix and tn/td are the numerator and denominator of the translation vector. The transformations are defined in fractional coordinates. :type transformations: list """ self.number = number self.symbol = symbol self.transformations = transformations self.transposed_rotations = N.array([N.transpose(t[0]) for t in transformations]) self.phase_factors = N.exp(N.array([(-2j*N.pi*t[1])/t[2] for t in transformations])) def __repr__(self): return "SpaceGroup(%d, %s)" % (self.number, repr(self.symbol)) def __len__(self): """ :return: the number of space group transformations :rtype: int """ return len(self.transformations) def symmetryEquivalentMillerIndices(self, hkl): """ :param hkl: a set of Miller indices :type hkl: Scientific.N.array_type :return: a tuple (miller_indices, phase_factor) of two arrays of length equal to the number of space group transformations. miller_indices contains the Miller indices of each reflection equivalent by symmetry to the reflection hkl (including hkl itself as the first element). phase_factor contains the phase factors that must be applied to the structure factor of reflection hkl to obtain the structure factor of the symmetry equivalent reflection. :rtype: tuple """ hkls = N.dot(self.transposed_rotations, hkl) p = N.multiply.reduce(self.phase_factors**hkl, -1) return hkls, p space_groups = {} transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(1, 'P 1', transformations) space_groups[1] = sg space_groups['P 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(2, 'P -1', transformations) space_groups[2] = sg space_groups['P -1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(3, 'P 1 2 1', transformations) space_groups[3] = sg space_groups['P 1 2 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(4, 'P 1 21 1', transformations) space_groups[4] = sg space_groups['P 1 21 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(5, 'C 1 2 1', transformations) space_groups[5] = sg space_groups['C 1 2 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(6, 'P 1 m 1', transformations) space_groups[6] = sg space_groups['P 1 m 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(7, 'P 1 c 1', transformations) space_groups[7] = sg space_groups['P 1 c 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(8, 'C 1 m 1', transformations) space_groups[8] = sg space_groups['C 1 m 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(9, 'C 1 c 1', transformations) space_groups[9] = sg space_groups['C 1 c 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(10, 'P 1 2/m 1', transformations) space_groups[10] = sg space_groups['P 1 2/m 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(11, 'P 1 21/m 1', transformations) space_groups[11] = sg space_groups['P 1 21/m 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(12, 'C 1 2/m 1', transformations) space_groups[12] = sg space_groups['C 1 2/m 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(13, 'P 1 2/c 1', transformations) space_groups[13] = sg space_groups['P 1 2/c 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(14, 'P 1 21/c 1', transformations) space_groups[14] = sg space_groups['P 1 21/c 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(15, 'C 1 2/c 1', transformations) space_groups[15] = sg space_groups['C 1 2/c 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(16, 'P 2 2 2', transformations) space_groups[16] = sg space_groups['P 2 2 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(17, 'P 2 2 21', transformations) space_groups[17] = sg space_groups['P 2 2 21'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(18, 'P 21 21 2', transformations) space_groups[18] = sg space_groups['P 21 21 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(19, 'P 21 21 21', transformations) space_groups[19] = sg space_groups['P 21 21 21'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(20, 'C 2 2 21', transformations) space_groups[20] = sg space_groups['C 2 2 21'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(21, 'C 2 2 2', transformations) space_groups[21] = sg space_groups['C 2 2 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(22, 'F 2 2 2', transformations) space_groups[22] = sg space_groups['F 2 2 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(23, 'I 2 2 2', transformations) space_groups[23] = sg space_groups['I 2 2 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(24, 'I 21 21 21', transformations) space_groups[24] = sg space_groups['I 21 21 21'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(25, 'P m m 2', transformations) space_groups[25] = sg space_groups['P m m 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(26, 'P m c 21', transformations) space_groups[26] = sg space_groups['P m c 21'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(27, 'P c c 2', transformations) space_groups[27] = sg space_groups['P c c 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(28, 'P m a 2', transformations) space_groups[28] = sg space_groups['P m a 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(29, 'P c a 21', transformations) space_groups[29] = sg space_groups['P c a 21'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(30, 'P n c 2', transformations) space_groups[30] = sg space_groups['P n c 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(31, 'P m n 21', transformations) space_groups[31] = sg space_groups['P m n 21'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(32, 'P b a 2', transformations) space_groups[32] = sg space_groups['P b a 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(33, 'P n a 21', transformations) space_groups[33] = sg space_groups['P n a 21'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(34, 'P n n 2', transformations) space_groups[34] = sg space_groups['P n n 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(35, 'C m m 2', transformations) space_groups[35] = sg space_groups['C m m 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(36, 'C m c 21', transformations) space_groups[36] = sg space_groups['C m c 21'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(37, 'C c c 2', transformations) space_groups[37] = sg space_groups['C c c 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(38, 'A m m 2', transformations) space_groups[38] = sg space_groups['A m m 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(39, 'A b m 2', transformations) space_groups[39] = sg space_groups['A b m 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(40, 'A m a 2', transformations) space_groups[40] = sg space_groups['A m a 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(41, 'A b a 2', transformations) space_groups[41] = sg space_groups['A b a 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(42, 'F m m 2', transformations) space_groups[42] = sg space_groups['F m m 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,3,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,3,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([3,1,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([3,1,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([3,3,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([3,3,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(43, 'F d d 2', transformations) space_groups[43] = sg space_groups['F d d 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(44, 'I m m 2', transformations) space_groups[44] = sg space_groups['I m m 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(45, 'I b a 2', transformations) space_groups[45] = sg space_groups['I b a 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(46, 'I m a 2', transformations) space_groups[46] = sg space_groups['I m a 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(47, 'P m m m', transformations) space_groups[47] = sg space_groups['P m m m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(48, 'P n n n :2', transformations) space_groups[48] = sg space_groups['P n n n :2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(49, 'P c c m', transformations) space_groups[49] = sg space_groups['P c c m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(50, 'P b a n :2', transformations) space_groups[50] = sg space_groups['P b a n :2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(51, 'P m m a', transformations) space_groups[51] = sg space_groups['P m m a'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(52, 'P n n a', transformations) space_groups[52] = sg space_groups['P n n a'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(53, 'P m n a', transformations) space_groups[53] = sg space_groups['P m n a'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(54, 'P c c a', transformations) space_groups[54] = sg space_groups['P c c a'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(55, 'P b a m', transformations) space_groups[55] = sg space_groups['P b a m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(56, 'P c c n', transformations) space_groups[56] = sg space_groups['P c c n'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(57, 'P b c m', transformations) space_groups[57] = sg space_groups['P b c m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(58, 'P n n m', transformations) space_groups[58] = sg space_groups['P n n m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(59, 'P m m n :2', transformations) space_groups[59] = sg space_groups['P m m n :2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(60, 'P b c n', transformations) space_groups[60] = sg space_groups['P b c n'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(61, 'P b c a', transformations) space_groups[61] = sg space_groups['P b c a'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(62, 'P n m a', transformations) space_groups[62] = sg space_groups['P n m a'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(63, 'C m c m', transformations) space_groups[63] = sg space_groups['C m c m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(64, 'C m c a', transformations) space_groups[64] = sg space_groups['C m c a'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(65, 'C m m m', transformations) space_groups[65] = sg space_groups['C m m m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(66, 'C c c m', transformations) space_groups[66] = sg space_groups['C c c m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(67, 'C m m a', transformations) space_groups[67] = sg space_groups['C m m a'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(68, 'C c c a :2', transformations) space_groups[68] = sg space_groups['C c c a :2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(69, 'F m m m', transformations) space_groups[69] = sg space_groups['F m m m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([4,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([4,4,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([4,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([4,4,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,3,3]) trans_den = N.array([1,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,3]) trans_den = N.array([4,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,3,1]) trans_den = N.array([4,4,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,1,1]) trans_den = N.array([4,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,1,1]) trans_den = N.array([4,4,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,3]) trans_den = N.array([2,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([3,0,3]) trans_den = N.array([4,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([3,1,1]) trans_den = N.array([4,4,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,-1,1]) trans_den = N.array([2,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([4,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,-1,1]) trans_den = N.array([4,4,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,3,1]) trans_den = N.array([2,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([3,1,1]) trans_den = N.array([4,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([3,3,0]) trans_den = N.array([4,4,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,-1]) trans_den = N.array([2,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,-1]) trans_den = N.array([4,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([4,4,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(70, 'F d d d :2', transformations) space_groups[70] = sg space_groups['F d d d :2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(71, 'I m m m', transformations) space_groups[71] = sg space_groups['I m m m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(72, 'I b a m', transformations) space_groups[72] = sg space_groups['I b a m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(73, 'I b c a', transformations) space_groups[73] = sg space_groups['I b c a'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(74, 'I m m a', transformations) space_groups[74] = sg space_groups['I m m a'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(75, 'P 4', transformations) space_groups[75] = sg space_groups['P 4'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,3]) trans_den = N.array([1,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(76, 'P 41', transformations) space_groups[76] = sg space_groups['P 41'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(77, 'P 42', transformations) space_groups[77] = sg space_groups['P 42'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,3]) trans_den = N.array([1,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(78, 'P 43', transformations) space_groups[78] = sg space_groups['P 43'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(79, 'I 4', transformations) space_groups[79] = sg space_groups['I 4'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,3]) trans_den = N.array([2,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,3]) trans_den = N.array([2,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,5]) trans_den = N.array([1,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,5]) trans_den = N.array([1,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(80, 'I 41', transformations) space_groups[80] = sg space_groups['I 41'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(81, 'P -4', transformations) space_groups[81] = sg space_groups['P -4'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(82, 'I -4', transformations) space_groups[82] = sg space_groups['I -4'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(83, 'P 4/m', transformations) space_groups[83] = sg space_groups['P 4/m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(84, 'P 42/m', transformations) space_groups[84] = sg space_groups['P 42/m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(85, 'P 4/n :2', transformations) space_groups[85] = sg space_groups['P 4/n :2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(86, 'P 42/n :2', transformations) space_groups[86] = sg space_groups['P 42/n :2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(87, 'I 4/m', transformations) space_groups[87] = sg space_groups['I 4/m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,3,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-3,-3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([3,5,5]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([3,3,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,-1,-1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(88, 'I 41/a :2', transformations) space_groups[88] = sg space_groups['I 41/a :2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(89, 'P 4 2 2', transformations) space_groups[89] = sg space_groups['P 4 2 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(90, 'P 4 21 2', transformations) space_groups[90] = sg space_groups['P 4 21 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,3]) trans_den = N.array([1,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,3]) trans_den = N.array([1,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,4]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(91, 'P 41 2 2', transformations) space_groups[91] = sg space_groups['P 41 2 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,3]) trans_den = N.array([2,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,3]) trans_den = N.array([2,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(92, 'P 41 21 2', transformations) space_groups[92] = sg space_groups['P 41 21 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(93, 'P 42 2 2', transformations) space_groups[93] = sg space_groups['P 42 2 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(94, 'P 42 21 2', transformations) space_groups[94] = sg space_groups['P 42 21 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,3]) trans_den = N.array([1,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,3]) trans_den = N.array([1,1,4]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(95, 'P 43 2 2', transformations) space_groups[95] = sg space_groups['P 43 2 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,3]) trans_den = N.array([2,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,3]) trans_den = N.array([2,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(96, 'P 43 21 2', transformations) space_groups[96] = sg space_groups['P 43 21 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(97, 'I 4 2 2', transformations) space_groups[97] = sg space_groups['I 4 2 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,3]) trans_den = N.array([2,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,3]) trans_den = N.array([2,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,3]) trans_den = N.array([2,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,3]) trans_den = N.array([2,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,5]) trans_den = N.array([1,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,5]) trans_den = N.array([1,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,5]) trans_den = N.array([1,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,5]) trans_den = N.array([1,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(98, 'I 41 2 2', transformations) space_groups[98] = sg space_groups['I 41 2 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(99, 'P 4 m m', transformations) space_groups[99] = sg space_groups['P 4 m m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(100, 'P 4 b m', transformations) space_groups[100] = sg space_groups['P 4 b m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(101, 'P 42 c m', transformations) space_groups[101] = sg space_groups['P 42 c m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(102, 'P 42 n m', transformations) space_groups[102] = sg space_groups['P 42 n m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(103, 'P 4 c c', transformations) space_groups[103] = sg space_groups['P 4 c c'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(104, 'P 4 n c', transformations) space_groups[104] = sg space_groups['P 4 n c'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(105, 'P 42 m c', transformations) space_groups[105] = sg space_groups['P 42 m c'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(106, 'P 42 b c', transformations) space_groups[106] = sg space_groups['P 42 b c'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(107, 'I 4 m m', transformations) space_groups[107] = sg space_groups['I 4 m m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(108, 'I 4 c m', transformations) space_groups[108] = sg space_groups['I 4 c m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,3]) trans_den = N.array([2,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,3]) trans_den = N.array([2,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,3]) trans_den = N.array([2,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,3]) trans_den = N.array([2,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,5]) trans_den = N.array([1,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,5]) trans_den = N.array([1,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,5]) trans_den = N.array([1,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,5]) trans_den = N.array([1,2,4]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(109, 'I 41 m d', transformations) space_groups[109] = sg space_groups['I 41 m d'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,3]) trans_den = N.array([2,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,3]) trans_den = N.array([2,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,5]) trans_den = N.array([1,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,5]) trans_den = N.array([1,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,3]) trans_den = N.array([1,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,3]) trans_den = N.array([1,2,4]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(110, 'I 41 c d', transformations) space_groups[110] = sg space_groups['I 41 c d'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(111, 'P -4 2 m', transformations) space_groups[111] = sg space_groups['P -4 2 m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(112, 'P -4 2 c', transformations) space_groups[112] = sg space_groups['P -4 2 c'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(113, 'P -4 21 m', transformations) space_groups[113] = sg space_groups['P -4 21 m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(114, 'P -4 21 c', transformations) space_groups[114] = sg space_groups['P -4 21 c'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(115, 'P -4 m 2', transformations) space_groups[115] = sg space_groups['P -4 m 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(116, 'P -4 c 2', transformations) space_groups[116] = sg space_groups['P -4 c 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(117, 'P -4 b 2', transformations) space_groups[117] = sg space_groups['P -4 b 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(118, 'P -4 n 2', transformations) space_groups[118] = sg space_groups['P -4 n 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(119, 'I -4 m 2', transformations) space_groups[119] = sg space_groups['I -4 m 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(120, 'I -4 c 2', transformations) space_groups[120] = sg space_groups['I -4 c 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(121, 'I -4 2 m', transformations) space_groups[121] = sg space_groups['I -4 2 m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,3]) trans_den = N.array([2,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,3]) trans_den = N.array([2,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,3]) trans_den = N.array([2,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,3]) trans_den = N.array([2,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,5]) trans_den = N.array([1,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,5]) trans_den = N.array([1,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,5]) trans_den = N.array([1,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,5]) trans_den = N.array([1,2,4]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(122, 'I -4 2 d', transformations) space_groups[122] = sg space_groups['I -4 2 d'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(123, 'P 4/m m m', transformations) space_groups[123] = sg space_groups['P 4/m m m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(124, 'P 4/m c c', transformations) space_groups[124] = sg space_groups['P 4/m c c'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(125, 'P 4/n b m :2', transformations) space_groups[125] = sg space_groups['P 4/n b m :2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(126, 'P 4/n n c :2', transformations) space_groups[126] = sg space_groups['P 4/n n c :2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(127, 'P 4/m b m', transformations) space_groups[127] = sg space_groups['P 4/m b m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(128, 'P 4/m n c', transformations) space_groups[128] = sg space_groups['P 4/m n c'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(129, 'P 4/n m m :2', transformations) space_groups[129] = sg space_groups['P 4/n m m :2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(130, 'P 4/n c c :2', transformations) space_groups[130] = sg space_groups['P 4/n c c :2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(131, 'P 42/m m c', transformations) space_groups[131] = sg space_groups['P 42/m m c'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(132, 'P 42/m c m', transformations) space_groups[132] = sg space_groups['P 42/m c m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(133, 'P 42/n b c :2', transformations) space_groups[133] = sg space_groups['P 42/n b c :2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(134, 'P 42/n n m :2', transformations) space_groups[134] = sg space_groups['P 42/n n m :2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(135, 'P 42/m b c', transformations) space_groups[135] = sg space_groups['P 42/m b c'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(136, 'P 42/m n m', transformations) space_groups[136] = sg space_groups['P 42/m n m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(137, 'P 42/n m c :2', transformations) space_groups[137] = sg space_groups['P 42/n m c :2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(138, 'P 42/n c m :2', transformations) space_groups[138] = sg space_groups['P 42/n c m :2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(139, 'I 4/m m m', transformations) space_groups[139] = sg space_groups['I 4/m m m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(140, 'I 4/m c m', transformations) space_groups[140] = sg space_groups['I 4/m c m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,3,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,3,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-3,-1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-3,-1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([3,5,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([3,3,5]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([3,5,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([3,3,5]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,-1,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,-1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,-1,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,-1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(141, 'I 41/a m d :2', transformations) space_groups[141] = sg space_groups['I 41/a m d :2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,3,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,3,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-3,-1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-3,-3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([3,5,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([3,3,5]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([3,5,5]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([3,3,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,-1,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,-1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,-1,-1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(142, 'I 41/a c d :2', transformations) space_groups[142] = sg space_groups['I 41/a c d :2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(143, 'P 3', transformations) space_groups[143] = sg space_groups['P 3'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,2]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(144, 'P 31', transformations) space_groups[144] = sg space_groups['P 31'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,2]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(145, 'P 32', transformations) space_groups[145] = sg space_groups['P 32'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(146, 'R 3 :H', transformations) space_groups[146] = sg space_groups['R 3 :H'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(147, 'P -3', transformations) space_groups[147] = sg space_groups['P -3'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(148, 'R -3 :H', transformations) space_groups[148] = sg space_groups['R -3 :H'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(149, 'P 3 1 2', transformations) space_groups[149] = sg space_groups['P 3 1 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(150, 'P 3 2 1', transformations) space_groups[150] = sg space_groups['P 3 2 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,2]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,2]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(151, 'P 31 1 2', transformations) space_groups[151] = sg space_groups['P 31 1 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,2]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,2]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(152, 'P 31 2 1', transformations) space_groups[152] = sg space_groups['P 31 2 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,2]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,2]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(153, 'P 32 1 2', transformations) space_groups[153] = sg space_groups['P 32 1 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,2]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,2]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(154, 'P 32 2 1', transformations) space_groups[154] = sg space_groups['P 32 2 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(155, 'R 3 2 :H', transformations) space_groups[155] = sg space_groups['R 3 2 :H'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(156, 'P 3 m 1', transformations) space_groups[156] = sg space_groups['P 3 m 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(157, 'P 3 1 m', transformations) space_groups[157] = sg space_groups['P 3 1 m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(158, 'P 3 c 1', transformations) space_groups[158] = sg space_groups['P 3 c 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(159, 'P 3 1 c', transformations) space_groups[159] = sg space_groups['P 3 1 c'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(160, 'R 3 m :H', transformations) space_groups[160] = sg space_groups['R 3 m :H'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,7]) trans_den = N.array([3,3,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,7]) trans_den = N.array([3,3,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,7]) trans_den = N.array([3,3,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,5]) trans_den = N.array([3,3,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,5]) trans_den = N.array([3,3,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,5]) trans_den = N.array([3,3,6]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(161, 'R 3 c :H', transformations) space_groups[161] = sg space_groups['R 3 c :H'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(162, 'P -3 1 m', transformations) space_groups[162] = sg space_groups['P -3 1 m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(163, 'P -3 1 c', transformations) space_groups[163] = sg space_groups['P -3 1 c'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(164, 'P -3 m 1', transformations) space_groups[164] = sg space_groups['P -3 m 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(165, 'P -3 c 1', transformations) space_groups[165] = sg space_groups['P -3 c 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(166, 'R -3 m :H', transformations) space_groups[166] = sg space_groups['R -3 m :H'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,2,7]) trans_den = N.array([3,3,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,2,7]) trans_den = N.array([3,3,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,2,7]) trans_den = N.array([3,3,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,1]) trans_den = N.array([3,3,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,1]) trans_den = N.array([3,3,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,1]) trans_den = N.array([3,3,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([2,1,5]) trans_den = N.array([3,3,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([2,1,5]) trans_den = N.array([3,3,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([2,1,5]) trans_den = N.array([3,3,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,-1]) trans_den = N.array([3,3,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,-1]) trans_den = N.array([3,3,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,-1]) trans_den = N.array([3,3,6]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(167, 'R -3 c :H', transformations) space_groups[167] = sg space_groups['R -3 c :H'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(168, 'P 6', transformations) space_groups[168] = sg space_groups['P 6'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,5]) trans_den = N.array([1,1,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,2]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(169, 'P 61', transformations) space_groups[169] = sg space_groups['P 61'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,5]) trans_den = N.array([1,1,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,2]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(170, 'P 65', transformations) space_groups[170] = sg space_groups['P 65'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,2]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,2]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(171, 'P 62', transformations) space_groups[171] = sg space_groups['P 62'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,2]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,2]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(172, 'P 64', transformations) space_groups[172] = sg space_groups['P 64'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(173, 'P 63', transformations) space_groups[173] = sg space_groups['P 63'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(174, 'P -6', transformations) space_groups[174] = sg space_groups['P -6'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(175, 'P 6/m', transformations) space_groups[175] = sg space_groups['P 6/m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den =
N.array([1,1,2])
numpy.array
import sys def get_mitk_sphere(): """ Return MITK compliant dipy Sphere object. MITK stores ODFs as 252 values spherically sampled from the continuous ODF. The sampling directions are generate by a 5-fold subdivisions of an icosahedron. """ xyz = np.array([ 0.9756767549555488, 0.9977154378498742, 0.9738192119472443, 0.8915721200771204, 0.7646073555341725, 0.6231965669156312, 0.9817040172417226, 0.9870396762453547, 0.9325589150767597, 0.8173592116492303, 0.6708930871960926, 0.9399233672993689, 0.9144882783890762, 0.8267930935417315, 0.6931818659696647, 0.8407280774774689, 0.782394344826989, 0.6762337155773353, 0.7005607434301688, 0.6228579759074076, 0.5505632701289798, 0.4375940376503738, 0.3153040621970065, 0.1569517536476641, -0.01984099037382634, -0.1857690950088067, -0.3200730131503601, 0.5232435944036425, 0.3889403678268736, 0.2135250052622625, 0.02420694871807206, -0.1448539951504302, 0.5971534158422009, 0.4482053228282282, 0.2597018771197477, 0.06677517278138323, 0.6404616222418184, 0.4782876117785159, 0.2868761951248767, 0.6459894362878276, 0.4789651252338281, 0.3200724178002418, 0.4973180497018747, 0.6793811951363423, 0.8323587928990375, 0.9308933612987835, 0.4036036036586492, 0.5984781165037405, 0.7817280923310203, 0.9140795130247613, 0.4809905907165384, 0.6759621154318279, 0.8390728924802671, 0.5347729120192694, 0.7094340284155564, 0.5560356639783846, 0.2502538949373057, 0.3171352000240629, 0.3793963897789465, 0.4231100429674418, 0.4410301813437042, 0.4357529867703999, 0.5208717223808415, 0.5850086433327374, 0.611055499882272, 0.6009463532173235, 0.6305067000562991, 0.7188806066405239, 0.7654898954879897, 0.7616477696596397, 0.7997756996573342, 0.8700831379830764, 0.8872031228985237, 0.9155019734809123, 0.9568003701205341, -0.4375932291383153, -0.3153035222278598, -0.1569515927579475, 0.0198407706589918, 0.1857686171195431, -0.2644927501381796, -0.1064219080255857, 0.07849995612144045, 0.2583107784678281, -0.04938676750055992, 0.1358448755096817, 0.3243479900672576, 0.1811879481039926, 0.3692668145365748, 0.3890115016151001, -0.6231952788307174, -0.4943551945928708, -0.319458133528771, -0.1156489798772063, 0.08328895892415776, -0.4789641985801549, -0.3127252940830145, -0.1059392282183739, 0.1077444781964869, 0.2912280153186658, -0.2868758523956744, -0.08856892011805101, 0.1287405357080231, 0.3245517154572714, -0.06677541204276306, 0.1413542883070481, 0.3408430926744944, 0.1448534358763926, 0.3374016489097037, -0.2502532651867688, -0.3171345072414974, -0.3793956104585266, -0.4231091882680272, -0.4410293135613324, -0.09929959410007272, -0.1535127609134815, -0.2052877394623771, -0.2436963810571767, 0.08175409117371149, 0.04056025153798869, -0.006048944565669369, 0.2686152102237028, 0.2319923070602857, 0.430309819720559, -0.975676581463901, -0.9977153903038788, -0.9738191090293654, -0.8915716840571059, -0.7646064477130079, -0.9568001079664734, -0.9598482725023617, -0.9044523389503778, -0.7901672201648241, -0.6459882395962464, -0.8872027729137049, -0.8582754834679532, -0.7705800268610806, -0.6404605781008121, -0.7616472974254324, -0.7008201753656432, -0.5971525097007422, -0.6009457148226922, -0.5232427588825813, 0.4943566966479628, 0.3194596781650836, 0.1156503154178581, -0.0832879858164388, 0.5222841738261358, 0.3225497922064885, 0.1018140973507329, 0.5217885230992481, 0.3044789836562512, 0.4873191346491355, -0.4973183240635209, -0.6793811856410323, -0.8323586364840968, -0.9308931819742911, -0.3374020539278631, -0.5261951664998159, -0.7070125356849136, -0.8417962075837926, -0.9155017573317124, -0.3408433114184408, -0.5265312606271311, -0.6896418460594331, -0.7997755164970677, -0.3245517106425898, -0.4925847482169691, -0.6305065080228541, -0.2912277152063287, -0.4357526334612896, 0.7901679726328494, 0.9044526665335126, 0.9598484396937114, 0.7705806468939737, 0.858275831469383, 0.7008207681995118, -0.4036039458806759, -0.2583110138480089, -0.0784999126587471, 0.1064223584250461, 0.264493571710179, -0.4809907334514471, -0.3243480295764106, -0.1358446002697818, 0.04938746901646566, -0.5347730026038946, -0.3692667658371347, -0.1811875286592425, -0.5560358190148772, -0.3890114324926668, -0.5505634949474449, 0.8417963565884857, 0.7070125813068046, 0.5261950179989611, 0.6896418985458221, 0.5265311900255359, 0.4925848265160583, 0.2436972866599269, 0.2052886581368649, 0.153513629451971, 0.09930039009433847, 0.006049691633511915, -0.04055950638179381, -0.08175337578691833, -0.2319919155781195, -0.2686148310916902, -0.430309819678344, -0.02420720081803753, -0.2135248270679241, -0.3889397838050994, -0.2597016312374675, -0.4482046405142344, -0.4782867918076852, -0.1018130528605821, -0.322548598821141, -0.5222830294256716, -0.6708921376896406, -0.304478224282928, -0.5217878437313506, -0.6931813485878851, -0.4873188675145023, -0.6762335873429084, -0.6228580878699612, -0.6110548409057, -0.5850080622199078, -0.5208712693637837, -0.7654894328832393, -0.7188802647693375, -0.8700828159137221, -0.8173587433845655, -0.9325588839421305, -0.9870397834787261, -0.9817039872478999, -0.8267930492778305, -0.9144884914916022, -0.9399235077793813, -0.7823945479956939, -0.8407283372889187, -0.7005610213599369, -0.1077438933887955, 0.1059400956623477, 0.3127262866621893, -0.1287403742204129, 0.08856921814263634, -0.1413545191115968, -0.9140794058749131, -0.7817279594934516, -0.5984781448346268, -0.8390728949381593, -0.6759620794963979, -0.709434131000089, -0.1778161375899129, -0.06053925384414331, 0.07929679392711581, 0.222673458561735, 0.3458247516791153, 0.4366423972091846, 0.01030826616734189, 0.1591522280204451, 0.3173816763430465, 0.4549463955350546, 0.5521270265729551, 0.2292788658415479, 0.3973400932411465, 0.5502139834879405, 0.6594089221868847, 0.4476465561008348, 0.6096570464011057, 0.7343998566036512, 0.629214796874201, 0.7646693979379596, 0.7580253719184178, -0.5980610514568761, -0.5101530988159087, -0.382225667160838, -0.2244621267538426, -0.06301328229424107, 0.07805400320688782, -0.4311039309963852, -0.3079662136138592, -0.1501157132113724, 0.01750888497279251, 0.1650825345160538, -0.2148810450151756, -0.06090095222676627, 0.1073128739652992, 0.2584097661066967, 0.02655484252908358, 0.1901297170957776, 0.3420822257932489, 0.2531835106264871, 0.4022303494272352, -0.07805410188638827, -0.1080255529483224, -0.1376217050758367, -0.1609000070073124, -0.1740018618448228, 0.09827676798573926, 0.083291898217249, 0.06127443921955168, 0.03526739273256396, 0.2991139104294396, 0.2941068360088736, 0.2692865316145088, 0.4942032775296958, 0.4857723178878524, 0.6512069539966677, -0.9161616153729886, -0.9396953110011561, -0.9204280785344878, -0.8462030522374957, -0.7293237120999879, -0.8470541513588044, -0.8482966176587544, -0.7977006542517769, -0.6951661565374421, -0.566558592627622, -0.7243096319272092, -0.6931460376496088, -0.6140043047773551, -0.5016343691560573, -0.5520254073275178, -0.4928644880867128, -0.403575153350467, -0.3587591578566765, -0.2886351685087218, 0.5980613131647216, 0.5101532951859686, 0.382225843595672, 0.2244622808787926, 0.06301334452030186, 0.6944632949786616, 0.5955168212825119, 0.4473425940100297, 0.2700417838303327, 0.7724043956082883, 0.6553545192922715, 0.4871408620353512, 0.8097301284690857, 0.6725220182496192, 0.8002534097038426, -0.4366431953633789, -0.5869882376922511, -0.7332080507197046, -0.8450980113065225, -0.9041113586460733, -0.4022310083998925, -0.554596445154436, -0.6925605687496104, -0.7854318984598006, -0.8250621271173465, -0.3420827953668352, -0.4840440064641756, -0.6033456975789954, -0.6777531805937266, -0.2584102557043402, -0.3819753792546441, -0.4821906665520286, -0.1650828712784331, -0.270790845781693, 0.9161619708326184, 0.9396956424389374, 0.9204283182965946, 0.8462032095340455, 0.7293238793541417, 0.9749588444840027, 0.9879501207294071, 0.942053498973333, 0.8348196077814718, 0.9950795014807369, 0.9818515654328379, 0.9027098746674149, 0.9581801446138297, 0.9118246030313639, 0.8703772282258925, 0.1778171059718252, 0.06053992567271226, -0.07929659020903117, -0.2226737578340799, -0.345825401239635, 0.2886360377097776, 0.1672516508448342, 0.02000533874392893, -0.1285435155191929, -0.2531843553864728, 0.403575906447316, 0.2774342678683828, 0.1245598363284875, -0.02655554762561945, 0.5016349858535857, 0.3695530582277636, 0.2148806720954671, 0.5665590425344393, 0.431103930292903, 0.5869876102086139, 0.7332077514676827, 0.845098078457225, 0.9041116580482536, 0.7182616282077119, 0.8617334421407644, 0.9490975365686583, 0.8223898048944452, 0.9416915744235097, 0.8729720010540123, 0.1080256414522809, 0.1376220280275969, 0.1609005865750696, 0.1740026689030255, 0.2707904196202965, 0.3196768235430837, 0.3552546724685221, 0.3677018240803483, 0.3587598208776521, 0.4821901792282771, 0.5389508449256169, 0.5637713635689835, 0.5520258363563475, 0.6777529577987501, 0.7231337276202411, 0.724309982145211, 0.8250622687013296, 0.8470545173149734, 0.1285429999155006, -0.02000532948058562, -0.1672511147059996, -0.1245600244829796, -0.2774338902981233, -0.3695528631494325, -0.09827641615811868, -0.2700412859530667, -0.4473420975374328, -0.5955164071695848, -0.6944629164413806, -0.2991130971968019, -0.4871400501186961, -0.6553538941234454, -0.7724039524031648, -0.4942022299541438, -0.6725212074710563, -0.8097296395344389, -0.6512059956089504, -0.8002528392148971, -0.7580246814516085, -0.3677014077761052, -0.3552545716101517, -0.3196770257819652, -0.5637712030900536, -0.5389510214534028, -0.7231336172569296, -0.8348194119106425, -0.9420533966954356, -0.9879499956150448, -0.9749586635216289, -0.9027097279159257, -0.9818515951566739, -0.9950795477220543, -0.9118244750171576, -0.9581802235578871, -0.8703770126934449, -0.0175091339170676, 0.1501155140512474, 0.3079660822386824, -0.1073133727582037, 0.06090046334304851, -0.1901304002696938, -0.9490974969653682, -0.8617336589899791, -0.7182621005240754, -0.5521276321758419, -0.941691783045487, -0.8223901593137167, -0.6594093292610237, -0.872972144171723, -0.7343999908188845, -0.7646691446910742, 0.6951665021597787, 0.7977009700656229, 0.8482969664746548, 0.6140047811934269, 0.6931464276818936, 0.4928650597255946, -0.4549467775084718, -0.3173815862988101, -0.1591515620353438, -0.01030716362341688, -0.5502140363721867, -0.3973395475484636, -0.2292777334167206, -0.609656670182737, -0.4476455277450017, -0.6292139442700462, 0.7854319364049284, 0.6925603649758249, 0.5545959620739339, 0.6033453603619342, 0.4840435291285519, 0.3819748711371402, -0.03526641653115874, -0.06127364342066123, -0.0832913202753871, -0.2692854573778917, -0.2941058574917593, -0.4857712605383084, -0.1282040992012934, 0.02998172476739921, 0.2130449739264662, 0.394354771181159, 0.5438573645627299, 0.6488215902264565, -0.1901340637026595, -0.02057293935230464, 0.1720544722828635, 0.3534794142829396, 0.4950335464190314, -0.252933321812349, -0.07636778766011496, 0.1169519253626288, 0.2909961752861106, -0.304612640171253, -0.1271903099934383, 0.0580070042064605, -0.3366056805211806, -0.1653138037361849, -0.3496821715684524, 0.6714420577705413, 0.8002044514563711, 0.9106424580428781, 0.9742808059046055, 0.9805708386415104, 0.9441720387917811, 0.7350956003099328, 0.8682639008659977, 0.9653353535299492, 0.9995536316680411, 0.9755844796257857, 0.7728091190204586, 0.8918537226509272, 0.9597077065970592, 0.9637247890765801, 0.767530944505584, 0.857374860312736, 0.8948082473172733, 0.7201359303293944, 0.7802583897718675, -0.9441722324566724, -0.8608166107545396, -0.7207644955095487, -0.5303678229575245, -0.3211867088850157, -0.9096404828216634, -0.7967975927156801, -0.620601831095295, -0.4039985827676406, -0.8241231220089414, -0.6757043639889994, -0.4726959329165278, -0.6854057579633669, -0.5106159168102177, -0.5164821811548767, -0.3130828685601688, -0.128054626578418, 0.09418349997750548, 0.3239109228229815, 0.523048087763098, -0.3043330399192493, -0.09531787499064681, 0.146419102006115, 0.3786227553496849, 0.5638039035645359, -0.2789925774668332, -0.05252850546893189, 0.1924160430438771, 0.4101897544477446, -0.2358533016570041, -0.006318969895916147, 0.2236016867495729, -0.1820659309330632, 0.03496843200875603, -0.6714423515894649, -0.8002045390283683, -0.9106424117173109, -0.9742807748705438, -0.9805709251787237, -0.6691519386893557, -0.79626257796142, -0.8909109722488041, -0.9275521423149625, -0.6332080201962388, -0.7430051304270751, -0.8108589038018792, -0.5581290590099237, -0.6413705283620924, -0.4563600901355626, -0.648822290296783, -0.6411378559950974, -0.600293640880965, -0.5219527418637842, -0.4191009430775375, -0.7802586188950914, -0.7711197529973893, -0.713538182957094, -0.6094980396194888, -0.4842093859996422, -0.8948081394501657, -0.8705497953564927, -0.7870195954857328, -0.6597854273844109, -0.9637246412193355, -0.9132982945459158, -0.8070428410352181, -0.975584505681221, -0.9015722073987464, 0.3130823317650696, 0.1280539101236855, -0.09418429615654819, -0.3239116283455282, -0.523048586255087, 0.1989845274738189, -0.01970764286946627, -0.2653151882168217, -0.4936479477555078, 0.05597369301027853, -0.1852629737758222, -0.4302072668465533, -0.09867461327158224, -0.3387557568094476, -0.2393260112020272, 0.1282040764044601, -0.0299819504088954, -0.2130455201840074, -0.3943555879655132, -0.5438582278251758, -0.03496843048443223, -0.2252069693946209, -0.4261053308619027, -0.5992598174372795, -0.720136706807033, -0.2236017161594696, -0.4317330442416767, -0.6250530132529536, -0.7675317913865697, -0.4101898771205939, -0.6101488498350025, -0.7728099228904255, -0.5638041319099237, -0.7350961954485662, 0.6411372723067146, 0.6002931843810706, 0.5219523372221417, 0.4191004905746099, 0.4596949806286311, 0.3916338931244087, 0.2980734064957148, 0.226741584116328, 0.1432114770939381, -0.02097489882147943, 0.8608164411414747, 0.7207644427956729, 0.5303678926086439, 0.3211867913977836, 0.9015721838250796, 0.7879881821713033, 0.6114960278478284, 0.3951892122332402, 0.1820657113417612, 0.8070430398170311, 0.6574928275930984, 0.4544842943197335, 0.2358529185889448, 0.6597856586149884, 0.4841878538357612, 0.2789921022280572, 0.4842093252521232, 0.3043325272261384, 0.5992589358516202, 0.4261046359672609, 0.2252066549797059, 0.6250522113657903, 0.4317325950511361, 0.6101482870567641, 0.9096403689902206, 0.9275522217134882, 0.8909112253661301, 0.796262827475376, 0.6691520068054228, 0.8241233338640371, 0.810859375773786, 0.7430057321681839, 0.6332085061147845, 0.6854064426268304, 0.6413714065577412, 0.5581299045184589, 0.5164832226272315, 0.4563611494403301, 0.3496833143594963, -0.3951892821849063, -0.6114960336943951, -0.787988199289983, -0.4544844137443082, -0.657492739431111, -0.484187939006181, 0.4936478319326018, 0.2653148405479006, 0.01970714938077021, -0.1989850169013517, 0.4302075642722875, 0.1852629793843341, -0.0559739158243807, 0.3387563694841473, 0.09867487876932232, 0.2393267951217032, -0.999553621201999, -0.9653354239158236, -0.8682642090770526, -0.9597077173597477, -0.8918540989344099, -0.8573751662344773, -0.2980738893651726, -0.3916343988495664, -0.4596955428592778, -0.4950341577852201, -0.1432117197792371, -0.2267418620329016, -0.2909964852939082, 0.02097514873862574, -0.05800679989935065, 0.1653145532988453, -0.3786231842883476, -0.1464197032303796, 0.09531724619007391, -0.1924163631703616, 0.05252803743712917, 0.006318730357784829, -0.3534800054422614, -0.1720548071373146, 0.02057294660420643, 0.190134278339324, -0.1169519894866824, 0.07636807502743861, 0.2529338262925594, 0.1271908635410245, 0.3046134343217798, 0.3366066958443542, 0.6094980941008995, 0.7135382519498201, 0.7711196978950583, 0.7870198804193677, 0.8705500304441893, 0.9132984713369965, 0.403998910419839, 0.62060207699311, 0.7967976318501995, 0.4726965405256068, 0.6757048258462731, 0.5106167801856609]) n = int(xyz.shape[0] / 3) x = xyz[:n] y = xyz[n:2 * n] z = xyz[2 * n:] for i in range(n): v = np.array([x[i], y[i], z[i]]) norm =
np.linalg.norm(v)
numpy.linalg.norm
""" This module contains functions related to orbit calculations """ # Standard library imports from typing import Any,Dict,List,Tuple,Sequence #https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html # Third party imports import pandas as pd import numpy as np from numpy import rad2deg, deg2rad from numpy.linalg import norm import toolz as tz # Using Newton-Ramson method from scipy.integrate import solve_ivp from myastro import util as ut from myastro import data_catalog as dc from myastro import timeutil as tc from myastro import coord as co from myastro import orbit as ob from myastro.orbit import EphemrisInput from myastro.timeutil import PI_HALF, PI, TWOPI from myastro.keplerian import KeplerianOrbit from myastro.lagrange_coeff import rv_from_r0v0 from myastro.timeutil import epochformat2jd, jd2mjd, T, mjd2jd, jd2str_date, MDJ_J2000, JD_J2000 from myastro.planets import g_xyz_equat_sun_j2000, g_rlb_eclip_sun_eqxdate from myastro.util import mu_by_name, mu_Sun from myastro.orbit import calc_perturbed_accelaration from myastro.log import get_logger logger = get_logger(__file__.split('/')[-1]) def f1(vector): # Utility function return vector/pow(norm(vector),3) def calc_F(a, b ,c): # Function to compute the difference between nearly equal numbers # Appendix F of Orbital Mechanics q = a * (2*b-a)/pow(b,2) return (pow(q,2)- 3*q +3 / (1+pow(1-q,1.5)))*q def my_dfdt(t, y, r0, v0, t0): """ Computes the time derivative of the unknown function. Integrating this function, we obtain the unknown function. We know the velocity and acceleration that is basically what this function returns so integrating we obtain the position and velocity. Args: t : point in time (normally used in modified julian days) at which we want to calculate the derivative y : The vector with the variables to solve the differential equation system [0..3] delta_r [3..6] delta_v (not used in this case) r0 : Radio Vector of the object w.r.t. the Sun (AUs) at time t0 v0 : Velocity vector Elapsed time (AUs/days) at time t0 t0 : Initial point timme Returns : A vector vector of 6 positions with delta_v and delta_acc () """ delta_r = y[0:3] # The two-bodys orbit is calculated starting at r0,v0 and t-t0 as elapsed time r_osc, _ = rv_from_r0v0(mu_Sun, r0, v0, t-t0) # The radio vector perturbed is the two-bodys plus the delta_r r_pert = r_osc + delta_r F = 1 - pow(norm(r_osc)/norm(r_pert),3) #TODO Check if this works, to avoid compute the difference between nearly equal numbers #F = calc_F(norm(delta_r), norm(r_pert), norm(r_osc)) # The increment of accelration is calculated including the normal perturbed acceleartion delta_acc = (-mu_Sun/pow(norm(r_osc),3))*(delta_r- F*r_pert)+calc_perturbed_accelaration(t, r_pert) return np.concatenate((y[3:6],delta_acc)) def apply_enckes(eph, t_range, r0, v0): """ This is a utility function needed because the integration needs to be done in two intervals so this function is called for each of these intervals. It applies the enckles's approach, i.e. calcualate the dr and dv to modified the two bodys (osculating orbit) Args: eph : Ephemeris data (EphemrisInput) t_range : A numpy vector with the time samples where each time sample defines a time interval. The enckles method is applied in each one of this interval. The time samples are modified julian days. r0 : A numpy vector that indicates the initial radio vector (AUs) v0 : A numpy vector that indicates the initial velocity vector (AUs/days) r0 : Radio Vector of the object w.r.t. the Sun (AUs) at time t0 Returns : A dictionary where the key is a time reference in days (modified julian days) and the the value is the a tuple with two vectors, the radio vector r and the velocity vector at the time reference """ steps =
np.diff(t_range)
numpy.diff
import numpy as np def solve(A, x, min_sigma=1e-6): ''' Parameters ---------- min_sigma : float, `1e-6` by default Quality parameter of approximation. Lower `min_sigma` is better approximation. ''' L = 5 max_iter = 10 c = 0.75 mu = 2 A_inv = np.linalg.pinv(A) s_hat = np.dot(A_inv, x) sigma = 4.0*np.max(np.abs(s_hat), axis=1) sigma = sigma[:, np.newaxis] for i in range(max_iter): s = s_hat for l in range(L): delta = s * np.exp(-np.power(s, 2) / 2 / np.power(sigma, 2)) s = s - mu * delta rhs = np.dot(A, s) - x s = s - np.dot(A_inv, rhs) s_hat = s sigma *= c if
np.all(sigma < min_sigma)
numpy.all
#pyCGM # Copyright (c) 2015 <NAME> <<EMAIL>> # Core Developers: <NAME>, <NAME> # Contributors <NAME>, <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. #pyCGM import sys import os from math import * import math import numpy as np from .pycgmIO import * # Lowerbody Coordinate System def pelvisJointCenter(frame): """Make the Pelvis Axis function Takes in a dictionary of x,y,z positions and marker names, as well as an index Calculates the pelvis joint center and axis and returns both. Markers used: RASI,LASI,RPSI,LPSI Other landmarks used: origin, sacrum Pelvis X_axis: Computed with a Gram-Schmidt orthogonalization procedure(ref. Kadaba 1990) and then normalized. Pelvis Y_axis: LASI-RASI x,y,z positions, then normalized. Pelvis Z_axis: Cross product of x_axis and y_axis. Parameters ---------- frame : dict Dictionaries of marker lists. Returns ------- pelvis : array Returns an array that contains the pelvis origin in a 1x3 array of xyz values, which is then followed by a 4x1x3 array composed of the pelvis x, y, z axis components, and the sacrum x,y,z position. Examples -------- >>> import numpy as np >>> from .pyCGM import pelvisJointCenter >>> frame = {'RASI': np.array([ 395.36532593, 428.09790039, 1036.82763672]), ... 'LASI': np.array([ 183.18504333, 422.78927612, 1033.07299805]), ... 'RPSI': np.array([ 341.41815186, 246.72117615, 1055.99145508]), ... 'LPSI': np.array([ 255.79994202, 241.42199707, 1057.30065918]) } >>> pelvisJointCenter(frame) #doctest: +NORMALIZE_WHITESPACE [array([ 289.27518463, 425.44358826, 1034.95031739]), array([[ 289.25243803, 426.43632163, 1034.8321521 ], [ 288.27565385, 425.41858059, 1034.93263018], [ 289.25467091, 425.56129577, 1035.94315379]]), array([ 298.60904694, 244.07158661, 1056.64605713])] >>> frame = {'RASI': np.array([ 395.36532593, 428.09790039, 1036.82763672]), ... 'LASI': np.array([ 183.18504333, 422.78927612, 1033.07299805]), ... 'SACR': np.array([ 294.60904694, 242.07158661, 1049.64605713]) } >>> pelvisJointCenter(frame) #doctest: +NORMALIZE_WHITESPACE [array([ 289.27518463, 425.44358826, 1034.95031739]), array([[ 289.25166321, 426.44012508, 1034.87056085], [ 288.27565385, 425.41858059, 1034.93263018], [ 289.25556415, 425.52289134, 1035.94697483]]), array([ 294.60904694, 242.07158661, 1049.64605713])] """ # Get the Pelvis Joint Centre #REQUIRED MARKERS: # RASI # LASI # RPSI # LPSI RASI = frame['RASI'] LASI = frame['LASI'] try: RPSI = frame['RPSI'] LPSI = frame['LPSI'] # If no sacrum, mean of posterior markers is used as the sacrum sacrum = (RPSI+LPSI)/2.0 except: pass #going to use sacrum marker # If no sacrum, mean of posterior markers is used as the sacrum if 'SACR' in frame: sacrum = frame['SACR'] # REQUIRED LANDMARKS: # origin # sacrum # Origin is Midpoint between RASI and LASI origin = (RASI+LASI)/2.0 # This calculate the each axis # beta1,2,3 is arbitrary name to help calculate. beta1 = origin-sacrum beta2 = LASI-RASI # Y_axis is normalized beta2 y_axis = beta2/norm3d(beta2) # X_axis computed with a Gram-Schmidt orthogonalization procedure(ref. Kadaba 1990) # and then normalized. beta3_cal = np.dot(beta1,y_axis) beta3_cal2 = beta3_cal*y_axis beta3 = beta1-beta3_cal2 x_axis = beta3/norm3d(beta3) # Z-axis is cross product of x_axis and y_axis. z_axis = cross(x_axis,y_axis) # Add the origin back to the vector y_axis = y_axis+origin z_axis = z_axis+origin x_axis = x_axis+origin pelvis_axis = np.asarray([x_axis,y_axis,z_axis]) pelvis = [origin,pelvis_axis,sacrum] #probably don't need to return sacrum return pelvis def hipJointCenter(frame,pel_origin,pel_x,pel_y,pel_z,vsk=None): """Calculate the hip joint center function. Takes in a dictionary of x,y,z positions and marker names, as well as an index. Calculates the hip joint center and returns the hip joint center. Other landmarks used: origin, sacrum Subject Measurement values used: MeanLegLength, R_AsisToTrocanterMeasure, InterAsisDistance, L_AsisToTrocanterMeasure Hip Joint Center: Computed using Hip Joint Center Calculation (ref. Davis_1991) Parameters ---------- frame : dict Dictionaries of marker lists. pel_origin : array An array of pel_origin, pel_x, pel_y, pel_z each x,y,z position. [(),(),()] pel_x, pel_y, pel_z : int Respective axes of the pelvis. vsk : dict, optional A dictionary containing subject measurements from a VSK file. Returns ------- hip_JC : array Returns a 2x3 array that contains the left hip joint center, a 1x3 array containing the x,y,z components followed by the right hip joint center, another 1x3 array containing the x,y,z components. Examples -------- >>> import numpy as np >>> from .pyCGM import hipJointCenter >>> frame = None >>> vsk = {'MeanLegLength': 940.0, 'R_AsisToTrocanterMeasure': 72.512, ... 'L_AsisToTrocanterMeasure': 72.512, 'InterAsisDistance': 215.908996582031} >>> pel_origin = [ 251.60830688, 391.74131775, 1032.89349365] >>> pel_x = [251.74063624, 392.72694721, 1032.78850073] >>> pel_y = [250.61711554, 391.87232862, 1032.8741063] >>> pel_z = [251.60295336, 391.84795134, 1033.88777762] >>> hipJointCenter(frame,pel_origin,pel_x,pel_y,pel_z,vsk) array([[182.57097799, 339.43231799, 935.52900136], [308.38050352, 322.80342433, 937.98979092]]) """ #Get Global Values # Requires # pelvis axis pel_origin=np.asarray(pel_origin) pel_x=np.asarray(pel_x) pel_y=np.asarray(pel_y) pel_z=np.asarray(pel_z) # Model's eigen value # # LegLength # MeanLegLength # mm (marker radius) # interAsisMeasure #Set the variables needed to calculate the joint angle #Half of marker size mm = 7.0 MeanLegLength = vsk['MeanLegLength'] R_AsisToTrocanterMeasure = vsk['R_AsisToTrocanterMeasure'] L_AsisToTrocanterMeasure = vsk['L_AsisToTrocanterMeasure'] interAsisMeasure = vsk['InterAsisDistance'] C = ( MeanLegLength * 0.115 ) - 15.3 theta = 0.500000178813934 beta = 0.314000427722931 aa = interAsisMeasure/2.0 S = -1 # Hip Joint Center Calculation (ref. Davis_1991) # Left: Calculate the distance to translate along the pelvis axis L_Xh = (-L_AsisToTrocanterMeasure - mm) * cos(beta) + C * cos(theta) * sin(beta) L_Yh = S*(C*sin(theta)- aa) L_Zh = (-L_AsisToTrocanterMeasure - mm) * sin(beta) - C * cos(theta) * cos(beta) # Right: Calculate the distance to translate along the pelvis axis R_Xh = (-R_AsisToTrocanterMeasure - mm) * cos(beta) + C * cos(theta) * sin(beta) R_Yh = (C*sin(theta)- aa) R_Zh = (-R_AsisToTrocanterMeasure - mm) * sin(beta) - C * cos(theta) * cos(beta) # get the unit pelvis axis pelvis_xaxis = pel_x-pel_origin pelvis_yaxis = pel_y-pel_origin pelvis_zaxis = pel_z-pel_origin # multiply the distance to the unit pelvis axis L_hipJCx = pelvis_xaxis*L_Xh L_hipJCy = pelvis_yaxis*L_Yh L_hipJCz = pelvis_zaxis*L_Zh L_hipJC = np.asarray([ L_hipJCx[0]+L_hipJCy[0]+L_hipJCz[0], L_hipJCx[1]+L_hipJCy[1]+L_hipJCz[1], L_hipJCx[2]+L_hipJCy[2]+L_hipJCz[2]]) R_hipJCx = pelvis_xaxis*R_Xh R_hipJCy = pelvis_yaxis*R_Yh R_hipJCz = pelvis_zaxis*R_Zh R_hipJC = np.asarray([ R_hipJCx[0]+R_hipJCy[0]+R_hipJCz[0], R_hipJCx[1]+R_hipJCy[1]+R_hipJCz[1], R_hipJCx[2]+R_hipJCy[2]+R_hipJCz[2]]) L_hipJC = L_hipJC+pel_origin R_hipJC = R_hipJC+pel_origin hip_JC = np.asarray([L_hipJC,R_hipJC]) return hip_JC def hipAxisCenter(l_hip_jc,r_hip_jc,pelvis_axis): """Calculate the hip joint axis function. Takes in a hip joint center of x,y,z positions as well as an index. and takes the hip joint center and pelvis origin/axis from previous functions. Calculates the hip axis and returns hip joint origin and axis. Hip center axis: Computed by taking the mean at each x,y,z axis of the left and right hip joint center. Hip axis: Computed by getting the summation of the pelvis and hip center axes. Parameters ---------- l_hip_jc, r_hip_jc: array Array of R_hip_jc and L_hip_jc each x,y,z position. pelvis_axis : array An array of pelvis origin and axis. The axis is also composed of 3 arrays, each things are x axis, y axis, z axis. Returns ------- hipaxis_center, axis : array Returns an array that contains the hip axis center in a 1x3 array of xyz values, which is then followed by a 3x2x3 array composed of the hip axis center x, y, and z axis components. The xyz axis components are 2x3 arrays consisting of the axis center in the first dimension and the direction of the axis in the second dimension. Examples -------- >>> import numpy as np >>> from .pyCGM import hipAxisCenter >>> r_hip_jc = [182.57097863, 339.43231855, 935.529000126] >>> l_hip_jc = [308.38050472, 322.80342417, 937.98979061] >>> pelvis_axis = [np.array([251.60830688, 391.74131775, 1032.89349365]), ... np.array([[251.74063624, 392.72694721, 1032.78850073], ... [250.61711554, 391.87232862, 1032.8741063], ... [251.60295336, 391.84795134, 1033.88777762]]), ... np.array([231.57849121, 210.25262451, 1052.24969482])] >>> [np.around(arr,8) for arr in hipAxisCenter(l_hip_jc,r_hip_jc,pelvis_axis)] #doctest: +NORMALIZE_WHITESPACE [array([245.47574168, 331.11787136, 936.75939537]), array([[245.60807104, 332.10350082, 936.65440245], [244.48455034, 331.24888223, 936.74000802], [245.47038816, 331.22450495, 937.75367934]])] """ # Get shared hip axis, it is inbetween the two hip joint centers hipaxis_center = [(r_hip_jc[0]+l_hip_jc[0])/2.0,(r_hip_jc[1]+l_hip_jc[1])/2.0,(r_hip_jc[2]+l_hip_jc[2])/2.0] #convert pelvis_axis to x,y,z axis to use more easy pelvis_x_axis = np.subtract(pelvis_axis[1][0],pelvis_axis[0]) pelvis_y_axis = np.subtract(pelvis_axis[1][1],pelvis_axis[0]) pelvis_z_axis = np.subtract(pelvis_axis[1][2],pelvis_axis[0]) #Translate pelvis axis to shared hip centre # Add the origin back to the vector y_axis = [pelvis_y_axis[0]+hipaxis_center[0],pelvis_y_axis[1]+hipaxis_center[1],pelvis_y_axis[2]+hipaxis_center[2]] z_axis = [pelvis_z_axis[0]+hipaxis_center[0],pelvis_z_axis[1]+hipaxis_center[1],pelvis_z_axis[2]+hipaxis_center[2]] x_axis = [pelvis_x_axis[0]+hipaxis_center[0],pelvis_x_axis[1]+hipaxis_center[1],pelvis_x_axis[2]+hipaxis_center[2]] axis = [x_axis,y_axis,z_axis] return [hipaxis_center,axis] def kneeJointCenter(frame,hip_JC,delta,vsk=None): """Calculate the knee joint center and axis function. Takes in a dictionary of xyz positions and marker names, as well as an index. and takes the hip axis and pelvis axis. Calculates the knee joint axis and returns the knee origin and axis Markers used: RTHI, LTHI, RKNE, LKNE, hip_JC Subject Measurement values used: RightKneeWidth, LeftKneeWidth Knee joint center: Computed using Knee Axis Calculation(ref. Clinical Gait Analysis hand book, Baker2013) Parameters ---------- frame : dict dictionaries of marker lists. hip_JC : array An array of hip_JC containing the x,y,z axes marker positions of the hip joint center. delta : float The length from marker to joint center, retrieved from subject measurement file. vsk : dict, optional A dictionary containing subject measurements from a VSK file. Returns ------- R, L, axis : array Returns an array that contains the knee axis center in a 1x3 array of xyz values, which is then followed by a 2x3x3 array composed of the knee axis center x, y, and z axis components. The xyz axis components are 2x3 arrays consisting of the axis center in the first dimension and the direction of the axis in the second dimension. Modifies -------- delta is changed suitably to knee. Examples -------- >>> import numpy as np >>> from .pyCGM import kneeJointCenter >>> vsk = { 'RightKneeWidth' : 105.0, 'LeftKneeWidth' : 105.0 } >>> frame = { 'RTHI': np.array([426.50338745, 262.65310669, 673.66247559]), ... 'LTHI': np.array([51.93867874, 320.01849365, 723.03186035]), ... 'RKNE': np.array([416.98687744, 266.22558594, 524.04089355]), ... 'LKNE': np.array([84.62355804, 286.69122314, 529.39819336])} >>> hip_JC = [[182.57097863, 339.43231855, 935.52900126], ... [309.38050472, 32280342417, 937.98979061]] >>> delta = 0 >>> kneeJointCenter(frame,hip_JC,delta,vsk) #doctest: +NORMALIZE_WHITESPACE [array([413.21007973, 266.22558784, 464.66088466]), array([143.55478579, 279.90370346, 524.78408753]), array([[[414.20806312, 266.22558785, 464.59740907], [413.14660414, 266.22558786, 463.66290127], [413.21007973, 267.22558784, 464.66088468]], [[143.65611281, 280.88685896, 524.63197541], [142.56434499, 280.01777942, 524.86163553], [143.64837987, 280.0465038 , 525.76940383]]])] """ #Get Global Values mm = 7.0 R_kneeWidth = vsk['RightKneeWidth'] L_kneeWidth = vsk['LeftKneeWidth'] R_delta = (R_kneeWidth/2.0)+mm L_delta = (L_kneeWidth/2.0)+mm #REQUIRED MARKERS: # RTHI # LTHI # RKNE # LKNE # hip_JC RTHI = frame['RTHI'] LTHI = frame['LTHI'] RKNE = frame['RKNE'] LKNE = frame['LKNE'] R_hip_JC = hip_JC[1] L_hip_JC = hip_JC[0] # Determine the position of kneeJointCenter using findJointC function R = findJointC(RTHI,R_hip_JC,RKNE,R_delta) L = findJointC(LTHI,L_hip_JC,LKNE,L_delta) # Knee Axis Calculation(ref. Clinical Gait Analysis hand book, Baker2013) #Right axis calculation thi_kne_R = RTHI-RKNE # Z axis is Thigh bone calculated by the hipJC and kneeJC # the axis is then normalized axis_z = R_hip_JC-R # X axis is perpendicular to the points plane which is determined by KJC, HJC, KNE markers. # and calculated by each point's vector cross vector. # the axis is then normalized. # axis_x = cross(axis_z,thi_kne_R) axis_x = cross(axis_z,RKNE-R_hip_JC) # Y axis is determined by cross product of axis_z and axis_x. # the axis is then normalized. axis_y = cross(axis_z,axis_x) Raxis = np.asarray([axis_x,axis_y,axis_z]) #Left axis calculation thi_kne_L = LTHI-LKNE # Z axis is Thigh bone calculated by the hipJC and kneeJC # the axis is then normalized axis_z = L_hip_JC-L # X axis is perpendicular to the points plane which is determined by KJC, HJC, KNE markers. # and calculated by each point's vector cross vector. # the axis is then normalized. # axis_x = cross(thi_kne_L,axis_z) #using hipjc instead of thigh marker axis_x = cross(LKNE-L_hip_JC,axis_z) # Y axis is determined by cross product of axis_z and axis_x. # the axis is then normalized. axis_y = cross(axis_z,axis_x) Laxis = np.asarray([axis_x,axis_y,axis_z]) # Clear the name of axis and then nomalize it. R_knee_x_axis = Raxis[0] R_knee_x_axis = R_knee_x_axis/norm3d(R_knee_x_axis) R_knee_y_axis = Raxis[1] R_knee_y_axis = R_knee_y_axis/norm3d(R_knee_y_axis) R_knee_z_axis = Raxis[2] R_knee_z_axis = R_knee_z_axis/norm3d(R_knee_z_axis) L_knee_x_axis = Laxis[0] L_knee_x_axis = L_knee_x_axis/norm3d(L_knee_x_axis) L_knee_y_axis = Laxis[1] L_knee_y_axis = L_knee_y_axis/norm3d(L_knee_y_axis) L_knee_z_axis = Laxis[2] L_knee_z_axis = L_knee_z_axis/norm3d(L_knee_z_axis) #Put both axis in array # Add the origin back to the vector y_axis = R_knee_y_axis+R z_axis = R_knee_z_axis+R x_axis = R_knee_x_axis+R Raxis = np.asarray([x_axis,y_axis,z_axis]) # Add the origin back to the vector y_axis = L_knee_y_axis+L z_axis = L_knee_z_axis+L x_axis = L_knee_x_axis+L Laxis = np.asarray([x_axis,y_axis,z_axis]) axis = np.asarray([Raxis,Laxis]) return [R,L,axis] def ankleJointCenter(frame,knee_JC,delta,vsk=None): """Calculate the ankle joint center and axis function. Takes in a dictionary of xyz positions and marker names, as well as an index. and takes the knee axis. Calculates the ankle joint axis and returns the ankle origin and axis Markers used: tib_R, tib_L, ank_R, ank_L, knee_JC Subject Measurement values used: RightKneeWidth, LeftKneeWidth Ankle Axis: Computed using Ankle Axis Calculation(ref. Clinical Gait Analysis hand book, Baker2013). Parameters ---------- frame : dict dictionaries of marker lists. knee_JC : array An array of knee_JC each x,y,z position. delta : float The length from marker to joint center, retrieved from subject measurement file vsk : dict, optional A dictionary containing subject measurements from a VSK file. Returns ------- R, L, axis : array Returns an array that contains the ankle axis origin in a 1x3 array of xyz values, which is then followed by a 3x2x3 array composed of the ankle origin, x, y, and z axis components. The xyz axis components are 2x3 arrays consisting of the origin in the first dimension and the direction of the axis in the second dimension. Examples -------- >>> import numpy as np >>> from .pyCGM import ankleJointCenter >>> vsk = { 'RightAnkleWidth' : 70.0, 'LeftAnkleWidth' : 70.0, ... 'RightTibialTorsion': 0.0, 'LeftTibialTorsion' : 0.0} >>> frame = { 'RTIB': np.array([433.97537231, 211.93408203, 273.3008728]), ... 'LTIB': np.array([50.04016495, 235.90718079, 364.32226562]), ... 'RANK': np.array([422.77005005, 217.74053955, 92.86152649]), ... 'LANK': np.array([58.57380676, 208.54806519, 86.16953278]) } >>> knee_JC = [np.array([364.17774614, 292.17051722, 515.19181496]), ... np.array([143.55478579, 279.90370346, 524.78408753]), ... np.array([[[364.64959153, 293.06758353, 515.18513093], ... [363.29019771, 292.60656648, 515.04309095], ... [364.04724541, 292.24216264, 516.18067112]], ... [[143.65611282, 280.88685896, 524.63197541], ... [142.56434499, 280.01777943, 524.86163553], ... [143.64837987, 280.04650381, 525.76940383]]])] >>> delta = 0 >>> ankleJointCenter(frame,knee_JC,delta,vsk) #doctest: +NORMALIZE_WHITESPACE [array([393.76181609, 247.67829633, 87.73775041]), array([ 98.74901939, 219.46930221, 80.63068161]), [[array([394.48171575, 248.37201349, 87.715368 ]), array([393.07114385, 248.39110006, 87.61575574]), array([393.69314056, 247.78157916, 88.73002876])], [array([ 98.47494966, 220.42553804, 80.52821783]), array([ 97.79246671, 219.20927276, 80.76255902]), array([ 98.84848169, 219.60345781, 81.61663776])]]] """ #Get Global Values R_ankleWidth = vsk['RightAnkleWidth'] L_ankleWidth = vsk['LeftAnkleWidth'] R_torsion = vsk['RightTibialTorsion'] L_torsion = vsk['LeftTibialTorsion'] mm = 7.0 R_delta = ((R_ankleWidth)/2.0)+mm L_delta = ((L_ankleWidth)/2.0)+mm #REQUIRED MARKERS: # tib_R # tib_L # ank_R # ank_L # knee_JC tib_R = frame['RTIB'] tib_L = frame['LTIB'] ank_R = frame['RANK'] ank_L = frame['LANK'] knee_JC_R = knee_JC[0] knee_JC_L = knee_JC[1] # This is Torsioned Tibia and this describe the ankle angles # Tibial frontal plane being defined by ANK,TIB and KJC # Determine the position of ankleJointCenter using findJointC function R = findJointC(tib_R, knee_JC_R, ank_R, R_delta) L = findJointC(tib_L, knee_JC_L, ank_L, L_delta) # Ankle Axis Calculation(ref. Clinical Gait Analysis hand book, Baker2013) #Right axis calculation # Z axis is shank bone calculated by the ankleJC and kneeJC axis_z = knee_JC_R-R # X axis is perpendicular to the points plane which is determined by ANK,TIB and KJC markers. # and calculated by each point's vector cross vector. # tib_ank_R vector is making a tibia plane to be assumed as rigid segment. tib_ank_R = tib_R-ank_R axis_x = cross(axis_z,tib_ank_R) # Y axis is determined by cross product of axis_z and axis_x. axis_y = cross(axis_z,axis_x) Raxis = [axis_x,axis_y,axis_z] #Left axis calculation # Z axis is shank bone calculated by the ankleJC and kneeJC axis_z = knee_JC_L-L # X axis is perpendicular to the points plane which is determined by ANK,TIB and KJC markers. # and calculated by each point's vector cross vector. # tib_ank_L vector is making a tibia plane to be assumed as rigid segment. tib_ank_L = tib_L-ank_L axis_x = cross(tib_ank_L,axis_z) # Y axis is determined by cross product of axis_z and axis_x. axis_y = cross(axis_z,axis_x) Laxis = [axis_x,axis_y,axis_z] # Clear the name of axis and then normalize it. R_ankle_x_axis = Raxis[0] R_ankle_x_axis_div = norm2d(R_ankle_x_axis) R_ankle_x_axis = [R_ankle_x_axis[0]/R_ankle_x_axis_div,R_ankle_x_axis[1]/R_ankle_x_axis_div,R_ankle_x_axis[2]/R_ankle_x_axis_div] R_ankle_y_axis = Raxis[1] R_ankle_y_axis_div = norm2d(R_ankle_y_axis) R_ankle_y_axis = [R_ankle_y_axis[0]/R_ankle_y_axis_div,R_ankle_y_axis[1]/R_ankle_y_axis_div,R_ankle_y_axis[2]/R_ankle_y_axis_div] R_ankle_z_axis = Raxis[2] R_ankle_z_axis_div = norm2d(R_ankle_z_axis) R_ankle_z_axis = [R_ankle_z_axis[0]/R_ankle_z_axis_div,R_ankle_z_axis[1]/R_ankle_z_axis_div,R_ankle_z_axis[2]/R_ankle_z_axis_div] L_ankle_x_axis = Laxis[0] L_ankle_x_axis_div = norm2d(L_ankle_x_axis) L_ankle_x_axis = [L_ankle_x_axis[0]/L_ankle_x_axis_div,L_ankle_x_axis[1]/L_ankle_x_axis_div,L_ankle_x_axis[2]/L_ankle_x_axis_div] L_ankle_y_axis = Laxis[1] L_ankle_y_axis_div = norm2d(L_ankle_y_axis) L_ankle_y_axis = [L_ankle_y_axis[0]/L_ankle_y_axis_div,L_ankle_y_axis[1]/L_ankle_y_axis_div,L_ankle_y_axis[2]/L_ankle_y_axis_div] L_ankle_z_axis = Laxis[2] L_ankle_z_axis_div = norm2d(L_ankle_z_axis) L_ankle_z_axis = [L_ankle_z_axis[0]/L_ankle_z_axis_div,L_ankle_z_axis[1]/L_ankle_z_axis_div,L_ankle_z_axis[2]/L_ankle_z_axis_div] #Put both axis in array Raxis = [R_ankle_x_axis,R_ankle_y_axis,R_ankle_z_axis] Laxis = [L_ankle_x_axis,L_ankle_y_axis,L_ankle_z_axis] # Rotate the axes about the tibia torsion. R_torsion = np.radians(R_torsion) L_torsion = np.radians(L_torsion) Raxis = [[math.cos(R_torsion)*Raxis[0][0]-math.sin(R_torsion)*Raxis[1][0], math.cos(R_torsion)*Raxis[0][1]-math.sin(R_torsion)*Raxis[1][1], math.cos(R_torsion)*Raxis[0][2]-math.sin(R_torsion)*Raxis[1][2]], [math.sin(R_torsion)*Raxis[0][0]+math.cos(R_torsion)*Raxis[1][0], math.sin(R_torsion)*Raxis[0][1]+math.cos(R_torsion)*Raxis[1][1], math.sin(R_torsion)*Raxis[0][2]+math.cos(R_torsion)*Raxis[1][2]], [Raxis[2][0],Raxis[2][1],Raxis[2][2]]] Laxis = [[math.cos(L_torsion)*Laxis[0][0]-math.sin(L_torsion)*Laxis[1][0], math.cos(L_torsion)*Laxis[0][1]-math.sin(L_torsion)*Laxis[1][1], math.cos(L_torsion)*Laxis[0][2]-math.sin(L_torsion)*Laxis[1][2]], [math.sin(L_torsion)*Laxis[0][0]+math.cos(L_torsion)*Laxis[1][0], math.sin(L_torsion)*Laxis[0][1]+math.cos(L_torsion)*Laxis[1][1], math.sin(L_torsion)*Laxis[0][2]+math.cos(L_torsion)*Laxis[1][2]], [Laxis[2][0],Laxis[2][1],Laxis[2][2]]] # Add the origin back to the vector x_axis = Raxis[0]+R y_axis = Raxis[1]+R z_axis = Raxis[2]+R Raxis = [x_axis,y_axis,z_axis] x_axis = Laxis[0]+L y_axis = Laxis[1]+L z_axis = Laxis[2]+L Laxis = [x_axis,y_axis,z_axis] # Both of axis in array. axis = [Raxis,Laxis] return [R,L,axis] def footJointCenter(frame,vsk,ankle_JC,knee_JC,delta): """Calculate the foot joint center and axis function. Takes in a dictionary of xyz positions and marker names. and takes the ankle axis and knee axis. Calculate the foot joint axis by rotating incorrect foot joint axes about offset angle. Returns the foot axis origin and axis. In case of foot joint center, we've already make 2 kinds of axis for static offset angle. and then, Call this static offset angle as an input of this function for dynamic trial. Special Cases: (anatomical uncorrect foot axis) if foot flat is checked, make the reference markers instead of HEE marker which height is as same as TOE marker's height. elif foot flat is not checked, use the HEE marker for making Z axis. Markers used: RTOE, LTOE Other landmarks used: ANKLE_FLEXION_AXIS Subject Measurement values used: RightStaticRotOff, RightStaticPlantFlex, LeftStaticRotOff, LeftStaticPlantFlex Parameters ---------- frame : dict Dictionaries of marker lists. vsk : dict A dictionary containing subject measurements from a VSK file. ankle_JC : array An array of ankle_JC containing the x,y,z axes marker positions of the ankle joint center. knee_JC : array An array of knee_JC containing the x,y,z axes marker positions of the knee joint center. delta The length from marker to joint center, retrieved from subject measurement file. Returns ------- R, L, foot_axis : array Returns an array that contains the foot axis center in a 1x3 array of xyz values, which is then followed by a 2x3x3 array composed of the foot axis center x, y, and z axis components. The xyz axis components are 2x3 arrays consisting of the axis center in the first dimension and the direction of the axis in the second dimension. This function also saves the static offset angle in a global variable. Modifies -------- Axis changes following to the static info. you can set the static_info by the button. and this will calculate the offset angles the first setting, the foot axis show foot uncorrected anatomical reference axis(Z_axis point to the AJC from TOE) if press the static_info button so if static_info is not None, and then the static offsets angles are applied to the reference axis. the reference axis is Z axis point to HEE from TOE Examples -------- >>> import numpy as np >>> from .pyCGM import footJointCenter >>> vsk = { 'RightStaticRotOff' : 0.015683497632642047, 'LeftStaticRotOff': 0.009402910292403012, ... 'RightStaticPlantFlex' : 0.2702417907002758, 'LeftStaticPlantFlex': 0.20251085737834015} >>> frame = { 'RHEE': np.array([374.01257324, 181.57929993, 49.50960922]), ... 'LHEE': np.array([105.30126953, 180.2130127, 47.15660858]), ... 'RTOE': np.array([442.81997681, 381.62280273, 42.66047668]), ... 'LTOE': np.array([39.43652725, 382.44522095, 41.78911591])} >>> knee_JC = [np.array([364.17774614, 292.17051722, 515.19181496]), ... np.array([143.55478579, 279.90370346, 524.78408753]), ... np.array([[[364.64959153, 293.06758353, 515.18513093], ... [363.29019771, 292.60656648, 515.04309095], ... [364.04724541, 292.24216264, 516.18067112]], ... [[143.65611282, 280.88685896, 524.63197541], ... [142.56434499, 280.01777943, 524.86163553], ... [143.64837987, 280.04650381, 525.76940383]]])] >>> ankle_JC = [np.array([393.76181608, 247.67829633, 87.73775041]), ... np.array([98.74901939, 219.46930221, 80.6306816]), ... [[np.array([394.4817575, 248.37201348, 87.715368]), ... np.array([393.07114384, 248.39110006, 87.61575574]), ... np.array([393.69314056, 247.78157916, 88.73002876])], ... [np.array([98.47494966, 220.42553803, 80.52821783]), ... np.array([97.79246671, 219.20927275, 80.76255901]), ... np.array([98.84848169, 219.60345781, 81.61663775])]]] >>> delta = 0 >>> [np.around(arr,8) for arr in footJointCenter(frame,vsk,ankle_JC,knee_JC,delta)] #doctest: +NORMALIZE_WHITESPACE [array([442.81997681, 381.62280273, 42.66047668]), array([ 39.43652725, 382.44522095, 41.78911591]), array([[[442.84624127, 381.6513024 , 43.65972537], [441.87735057, 381.9563035 , 42.67574106], [442.48716163, 380.68048378, 42.69610043]], [[ 39.56652626, 382.50901001, 42.77857597], [ 38.49313328, 382.14606841, 41.93234851], [ 39.74166341, 381.4931502 , 41.81040459]]])] """ #REQUIRED MARKERS: # RTOE # LTOE TOE_R = frame["RTOE"] TOE_L = frame["LTOE"] #REQUIRE JOINT CENTER & AXIS #KNEE JOINT CENTER #ANKLE JOINT CENTER #ANKLE FLEXION AXIS ankle_JC_R = ankle_JC[0] ankle_JC_L = ankle_JC[1] ankle_flexion_R = ankle_JC[2][0][1] ankle_flexion_L = ankle_JC[2][1][1] # Toe axis's origin is marker position of TOE R = TOE_R L = TOE_L # HERE IS THE INCORRECT AXIS # the first setting, the foot axis show foot uncorrected anatomical axis and static_info is None ankle_JC_R = [ankle_JC_R[0],ankle_JC_R[1],ankle_JC_R[2]] ankle_JC_L = [ankle_JC_L[0],ankle_JC_L[1],ankle_JC_L[2]] # Right # z axis is from TOE marker to AJC. and normalized it. R_axis_z = [ankle_JC_R[0]-TOE_R[0],ankle_JC_R[1]-TOE_R[1],ankle_JC_R[2]-TOE_R[2]] R_axis_z_div = norm2d(R_axis_z) R_axis_z = [R_axis_z[0]/R_axis_z_div,R_axis_z[1]/R_axis_z_div,R_axis_z[2]/R_axis_z_div] # bring the flexion axis of ankle axes from AnkleJointCenter function. and normalized it. y_flex_R = [ankle_flexion_R[0]-ankle_JC_R[0],ankle_flexion_R[1]-ankle_JC_R[1],ankle_flexion_R[2]-ankle_JC_R[2]] y_flex_R_div = norm2d(y_flex_R) y_flex_R = [y_flex_R[0]/y_flex_R_div,y_flex_R[1]/y_flex_R_div,y_flex_R[2]/y_flex_R_div] # x axis is calculated as a cross product of z axis and ankle flexion axis. R_axis_x = cross(y_flex_R,R_axis_z) R_axis_x_div = norm2d(R_axis_x) R_axis_x = [R_axis_x[0]/R_axis_x_div,R_axis_x[1]/R_axis_x_div,R_axis_x[2]/R_axis_x_div] # y axis is then perpendicularly calculated from z axis and x axis. and normalized. R_axis_y = cross(R_axis_z,R_axis_x) R_axis_y_div = norm2d(R_axis_y) R_axis_y = [R_axis_y[0]/R_axis_y_div,R_axis_y[1]/R_axis_y_div,R_axis_y[2]/R_axis_y_div] R_foot_axis = [R_axis_x,R_axis_y,R_axis_z] # Left # z axis is from TOE marker to AJC. and normalized it. L_axis_z = [ankle_JC_L[0]-TOE_L[0],ankle_JC_L[1]-TOE_L[1],ankle_JC_L[2]-TOE_L[2]] L_axis_z_div = norm2d(L_axis_z) L_axis_z = [L_axis_z[0]/L_axis_z_div,L_axis_z[1]/L_axis_z_div,L_axis_z[2]/L_axis_z_div] # bring the flexion axis of ankle axes from AnkleJointCenter function. and normalized it. y_flex_L = [ankle_flexion_L[0]-ankle_JC_L[0],ankle_flexion_L[1]-ankle_JC_L[1],ankle_flexion_L[2]-ankle_JC_L[2]] y_flex_L_div = norm2d(y_flex_L) y_flex_L = [y_flex_L[0]/y_flex_L_div,y_flex_L[1]/y_flex_L_div,y_flex_L[2]/y_flex_L_div] # x axis is calculated as a cross product of z axis and ankle flexion axis. L_axis_x = cross(y_flex_L,L_axis_z) L_axis_x_div = norm2d(L_axis_x) L_axis_x = [L_axis_x[0]/L_axis_x_div,L_axis_x[1]/L_axis_x_div,L_axis_x[2]/L_axis_x_div] # y axis is then perpendicularly calculated from z axis and x axis. and normalized. L_axis_y = cross(L_axis_z,L_axis_x) L_axis_y_div = norm2d(L_axis_y) L_axis_y = [L_axis_y[0]/L_axis_y_div,L_axis_y[1]/L_axis_y_div,L_axis_y[2]/L_axis_y_div] L_foot_axis = [L_axis_x,L_axis_y,L_axis_z] foot_axis = [R_foot_axis,L_foot_axis] # Apply static offset angle to the incorrect foot axes # static offset angle are taken from static_info variable in radians. R_alpha = vsk['RightStaticRotOff'] R_beta = vsk['RightStaticPlantFlex'] #R_gamma = static_info[0][2] L_alpha = vsk['LeftStaticRotOff'] L_beta = vsk['LeftStaticPlantFlex'] #L_gamma = static_info[1][2] R_alpha = np.around(math.degrees(R_alpha),decimals=5) R_beta = np.around(math.degrees(R_beta),decimals=5) #R_gamma = np.around(math.degrees(static_info[0][2]),decimals=5) L_alpha = np.around(math.degrees(L_alpha),decimals=5) L_beta = np.around(math.degrees(L_beta),decimals=5) #L_gamma = np.around(math.degrees(static_info[1][2]),decimals=5) R_alpha = -math.radians(R_alpha) R_beta = math.radians(R_beta) #R_gamma = 0 L_alpha = math.radians(L_alpha) L_beta = math.radians(L_beta) #L_gamma = 0 R_axis = [[(R_foot_axis[0][0]),(R_foot_axis[0][1]),(R_foot_axis[0][2])], [(R_foot_axis[1][0]),(R_foot_axis[1][1]),(R_foot_axis[1][2])], [(R_foot_axis[2][0]),(R_foot_axis[2][1]),(R_foot_axis[2][2])]] L_axis = [[(L_foot_axis[0][0]),(L_foot_axis[0][1]),(L_foot_axis[0][2])], [(L_foot_axis[1][0]),(L_foot_axis[1][1]),(L_foot_axis[1][2])], [(L_foot_axis[2][0]),(L_foot_axis[2][1]),(L_foot_axis[2][2])]] # rotate incorrect foot axis around y axis first. # right R_rotmat = [[(math.cos(R_beta)*R_axis[0][0]+math.sin(R_beta)*R_axis[2][0]), (math.cos(R_beta)*R_axis[0][1]+math.sin(R_beta)*R_axis[2][1]), (math.cos(R_beta)*R_axis[0][2]+math.sin(R_beta)*R_axis[2][2])], [R_axis[1][0],R_axis[1][1],R_axis[1][2]], [(-1*math.sin(R_beta)*R_axis[0][0]+math.cos(R_beta)*R_axis[2][0]), (-1*math.sin(R_beta)*R_axis[0][1]+math.cos(R_beta)*R_axis[2][1]), (-1*math.sin(R_beta)*R_axis[0][2]+math.cos(R_beta)*R_axis[2][2])]] # left L_rotmat = [[(math.cos(L_beta)*L_axis[0][0]+math.sin(L_beta)*L_axis[2][0]), (math.cos(L_beta)*L_axis[0][1]+math.sin(L_beta)*L_axis[2][1]), (math.cos(L_beta)*L_axis[0][2]+math.sin(L_beta)*L_axis[2][2])], [L_axis[1][0],L_axis[1][1],L_axis[1][2]], [(-1*math.sin(L_beta)*L_axis[0][0]+math.cos(L_beta)*L_axis[2][0]), (-1*math.sin(L_beta)*L_axis[0][1]+math.cos(L_beta)*L_axis[2][1]), (-1*math.sin(L_beta)*L_axis[0][2]+math.cos(L_beta)*L_axis[2][2])]] # rotate incorrect foot axis around x axis next. # right R_rotmat = [[R_rotmat[0][0],R_rotmat[0][1],R_rotmat[0][2]], [(math.cos(R_alpha)*R_rotmat[1][0]-math.sin(R_alpha)*R_rotmat[2][0]), (math.cos(R_alpha)*R_rotmat[1][1]-math.sin(R_alpha)*R_rotmat[2][1]), (math.cos(R_alpha)*R_rotmat[1][2]-math.sin(R_alpha)*R_rotmat[2][2])], [(math.sin(R_alpha)*R_rotmat[1][0]+math.cos(R_alpha)*R_rotmat[2][0]), (math.sin(R_alpha)*R_rotmat[1][1]+math.cos(R_alpha)*R_rotmat[2][1]), (math.sin(R_alpha)*R_rotmat[1][2]+math.cos(R_alpha)*R_rotmat[2][2])]] # left L_rotmat = [[L_rotmat[0][0],L_rotmat[0][1],L_rotmat[0][2]], [(math.cos(L_alpha)*L_rotmat[1][0]-math.sin(L_alpha)*L_rotmat[2][0]), (math.cos(L_alpha)*L_rotmat[1][1]-math.sin(L_alpha)*L_rotmat[2][1]), (math.cos(L_alpha)*L_rotmat[1][2]-math.sin(L_alpha)*L_rotmat[2][2])], [(math.sin(L_alpha)*L_rotmat[1][0]+math.cos(L_alpha)*L_rotmat[2][0]), (math.sin(L_alpha)*L_rotmat[1][1]+math.cos(L_alpha)*L_rotmat[2][1]), (math.sin(L_alpha)*L_rotmat[1][2]+math.cos(L_alpha)*L_rotmat[2][2])]] # Bring each x,y,z axis from rotation axes R_axis_x = R_rotmat[0] R_axis_y = R_rotmat[1] R_axis_z = R_rotmat[2] L_axis_x = L_rotmat[0] L_axis_y = L_rotmat[1] L_axis_z = L_rotmat[2] # Attach each axis to the origin R_axis_x = [R_axis_x[0]+R[0],R_axis_x[1]+R[1],R_axis_x[2]+R[2]] R_axis_y = [R_axis_y[0]+R[0],R_axis_y[1]+R[1],R_axis_y[2]+R[2]] R_axis_z = [R_axis_z[0]+R[0],R_axis_z[1]+R[1],R_axis_z[2]+R[2]] R_foot_axis = [R_axis_x,R_axis_y,R_axis_z] L_axis_x = [L_axis_x[0]+L[0],L_axis_x[1]+L[1],L_axis_x[2]+L[2]] L_axis_y = [L_axis_y[0]+L[0],L_axis_y[1]+L[1],L_axis_y[2]+L[2]] L_axis_z = [L_axis_z[0]+L[0],L_axis_z[1]+L[1],L_axis_z[2]+L[2]] L_foot_axis = [L_axis_x,L_axis_y,L_axis_z] foot_axis = [R_foot_axis,L_foot_axis] return [R,L,foot_axis] # Upperbody Coordinate System def headJC(frame,vsk=None): """Calculate the head joint axis function. Takes in a dictionary of x,y,z positions and marker names. Calculates the head joint center and returns the head joint center and axis. Markers used: LFHD, RFHD, LBHD, RBHD Subject Measurement values used: HeadOffset Parameters ---------- frame : dict Dictionaries of marker lists. vsk : dict, optional A dictionary containing subject measurements from a VSK file. Returns ------- head_axis, origin : array Returns an array containing a 1x3x3 array containing the x, y, z axis components of the head joint center, and a 1x3 array containing the head origin x, y, z position. Examples -------- >>> import numpy as np >>> from .pyCGM import headJC >>> vsk = { 'HeadOffset': 0.2571990469310653 } >>> frame = {'RFHD': np.array([325.82983398, 402.55450439, 1722.49816895]), ... 'LFHD': np.array([184.55158997, 409.68713379, 1721.34289551]), ... 'RBHD': np.array([304.39898682, 242.91339111, 1694.97497559]), ... 'LBHD': np.array([197.8621521, 251.28889465, 1696.90197754])} >>> [np.around(arr,8) for arr in headJC(frame,vsk)] #doctest: +NORMALIZE_WHITESPACE [array([[ 255.21685583, 407.11593888, 1721.82538439], [ 254.19105385, 406.14680918, 1721.91767712], [ 255.1903437 , 406.21600904, 1722.91599129]]), array([ 255.19071198, 406.12081909, 1721.92053223])] """ #Get Global Values head_off = vsk['HeadOffset'] head_off = -1*head_off #Get the marker positions used for joint calculation LFHD = frame['LFHD'] RFHD = frame['RFHD'] LBHD = frame['LBHD'] RBHD = frame['RBHD'] #get the midpoints of the head to define the sides front = [(LFHD[0]+RFHD[0])/2.0, (LFHD[1]+RFHD[1])/2.0,(LFHD[2]+RFHD[2])/2.0] back = [(LBHD[0]+RBHD[0])/2.0, (LBHD[1]+RBHD[1])/2.0,(LBHD[2]+RBHD[2])/2.0] left = [(LFHD[0]+LBHD[0])/2.0, (LFHD[1]+LBHD[1])/2.0,(LFHD[2]+LBHD[2])/2.0] right = [(RFHD[0]+RBHD[0])/2.0, (RFHD[1]+RBHD[1])/2.0,(RFHD[2]+RBHD[2])/2.0] origin = front #Get the vectors from the sides with primary x axis facing front #First get the x direction x_vec = [front[0]-back[0],front[1]-back[1],front[2]-back[2]] x_vec_div = norm2d(x_vec) x_vec = [x_vec[0]/x_vec_div,x_vec[1]/x_vec_div,x_vec[2]/x_vec_div] #get the direction of the y axis y_vec = [left[0]-right[0],left[1]-right[1],left[2]-right[2]] y_vec_div = norm2d(y_vec) y_vec = [y_vec[0]/y_vec_div,y_vec[1]/y_vec_div,y_vec[2]/y_vec_div] # get z axis by cross-product of x axis and y axis. z_vec = cross(x_vec,y_vec) z_vec_div = norm2d(z_vec) z_vec = [z_vec[0]/z_vec_div,z_vec[1]/z_vec_div,z_vec[2]/z_vec_div] # make sure all x,y,z axis is orthogonal each other by cross-product y_vec = cross(z_vec,x_vec) y_vec_div = norm2d(y_vec) y_vec = [y_vec[0]/y_vec_div,y_vec[1]/y_vec_div,y_vec[2]/y_vec_div] x_vec = cross(y_vec,z_vec) x_vec_div = norm2d(x_vec) x_vec = [x_vec[0]/x_vec_div,x_vec[1]/x_vec_div,x_vec[2]/x_vec_div] # rotate the head axis around y axis about head offset angle. x_vec_rot = [x_vec[0]*math.cos(head_off)+z_vec[0]*math.sin(head_off), x_vec[1]*math.cos(head_off)+z_vec[1]*math.sin(head_off), x_vec[2]*math.cos(head_off)+z_vec[2]*math.sin(head_off)] y_vec_rot = [y_vec[0],y_vec[1],y_vec[2]] z_vec_rot = [x_vec[0]*-1*math.sin(head_off)+z_vec[0]*math.cos(head_off), x_vec[1]*-1*math.sin(head_off)+z_vec[1]*math.cos(head_off), x_vec[2]*-1*math.sin(head_off)+z_vec[2]*math.cos(head_off)] #Add the origin back to the vector to get it in the right position x_axis = [x_vec_rot[0]+origin[0],x_vec_rot[1]+origin[1],x_vec_rot[2]+origin[2]] y_axis = [y_vec_rot[0]+origin[0],y_vec_rot[1]+origin[1],y_vec_rot[2]+origin[2]] z_axis = [z_vec_rot[0]+origin[0],z_vec_rot[1]+origin[1],z_vec_rot[2]+origin[2]] head_axis =[x_axis,y_axis,z_axis] #Return the three axis and origin return [head_axis,origin] def thoraxJC(frame): """Calculate the thorax joint axis function. Takes in a dictionary of x,y,z positions and marker names. Calculates the thorax joint center and returns the thorax joint center and axis. Markers used: CLAV, C7, STRN, T10 Parameters ---------- frame : dict Dictionaries of marker lists. Returns ------- thorax_axis, origin : array Returns an array which contains a 2x3 array representing the right thorax joint center (1x3) and the left thorax joint center (1x3), which is then followed by a 6x3 array representing the right thorax x, y, z axis components (3x3) followed by the the left thorax x, y, z axis components (3x3). Examples -------- >>> import numpy as np >>> from .pyCGM import thoraxJC >>> frame = {'C7': np.array([256.78051758, 371.28042603, 1459.70300293]), ... 'T10': np.array([228.64323425, 192.32041931, 1279.6418457]), ... 'CLAV': np.array([256.78051758, 371.28042603, 1459.70300293]), ... 'STRN': np.array([251.67492676, 414.10391235, 1292.08508301])} >>> [np.around(arr,8) for arr in thoraxJC(frame)] #doctest: +NORMALIZE_WHITESPACE [array([[ 256.34546332, 365.72239585, 1461.92089119], [ 257.26637166, 364.696025 , 1462.23472346], [ 256.18427318, 364.43288984, 1461.36304534]]), array([ 256.27295428, 364.79605749, 1462.29053923])] """ #Set or get a marker size as mm marker_size = (14.0) /2.0 #Get the marker positions used for joint calculation CLAV = frame['CLAV'] C7 = frame['C7'] STRN = frame['STRN'] T10 = frame['T10'] #Temporary origin since the origin will be moved at the end origin = CLAV #Get the midpoints of the upper and lower sections, as well as the front and back sections upper = [(CLAV[0]+C7[0])/2.0,(CLAV[1]+C7[1])/2.0,(CLAV[2]+C7[2])/2.0] lower = [(STRN[0]+T10[0])/2.0,(STRN[1]+T10[1])/2.0,(STRN[2]+T10[2])/2.0] front = [(CLAV[0]+STRN[0])/2.0,(CLAV[1]+STRN[1])/2.0,(CLAV[2]+STRN[2])/2.0] back = [(T10[0]+C7[0])/2.0,(T10[1]+C7[1])/2.0,(T10[2]+C7[2])/2.0] C7_CLAV = [C7[0]-CLAV[0],C7[1]-CLAV[1],C7[2]-CLAV[2]] C7_CLAV = C7_CLAV/norm3d(C7_CLAV) #Get the direction of the primary axis Z (facing down) z_direc = [lower[0]-upper[0],lower[1]-upper[1],lower[2]-upper[2]] z_vec = z_direc/norm3d(z_direc) #The secondary axis X is from back to front x_direc = [front[0]-back[0],front[1]-back[1],front[2]-back[2]] x_vec = x_direc/norm3d(x_direc) # make sure all the axes are orthogonal each othe by cross-product y_direc = cross(z_vec,x_vec) y_vec = y_direc/norm3d(y_direc) x_direc = cross(y_vec,z_vec) x_vec = x_direc/norm3d(x_direc) z_direc = cross(x_vec,y_vec) z_vec = z_direc/norm3d(z_direc) # move the axes about offset along the x axis. offset = [x_vec[0]*marker_size,x_vec[1]*marker_size,x_vec[2]*marker_size] #Add the CLAV back to the vector to get it in the right position before translating it origin = [CLAV[0]-offset[0],CLAV[1]-offset[1],CLAV[2]-offset[2]] # Attach all the axes to the origin. x_axis = [x_vec[0]+origin[0],x_vec[1]+origin[1],x_vec[2]+origin[2]] y_axis = [y_vec[0]+origin[0],y_vec[1]+origin[1],y_vec[2]+origin[2]] z_axis = [z_vec[0]+origin[0],z_vec[1]+origin[1],z_vec[2]+origin[2]] thorax_axis = [x_axis,y_axis,z_axis] return [thorax_axis,origin] def findwandmarker(frame,thorax): """Calculate the wand marker function. Takes in a dictionary of x,y,z positions and marker names. and takes the thorax axis. Calculates the wand marker for calculating the clavicle. Markers used: RSHO, LSHO Parameters ---------- frame : dict Dictionaries of marker lists. thorax : array The x,y,z position of the thorax. Returns ------- wand : array Returns wand marker position for calculating knee joint center later. The wand marker position is returned as a 2x3 array containing the right wand marker x,y,z positions (1x3) followed by the left wand marker x,y,z positions (1x3). Examples -------- >>> import numpy as np >>> from .pyCGM import findwandmarker >>> frame = {'RSHO': np.array([428.88496562, 270.552948, 1500.73010254]), ... 'LSHO': np.array([68.24668121, 269.01049805, 1510.1072998])} >>> thorax = [[[256.23991128535846, 365.30496976939753, 1459.662169500559], ... [257.1435863244796, 364.21960599061947, 1459.5889787129829], ... [256.08430536580352, 354.32180498523223, 1458.6575930699294]], ... [256.14981023656401, 364.30906039339868, 1459.6553639290375]] >>> [np.around(arr,8) for arr in findwandmarker(frame,thorax)] [array([ 255.92550246, 364.32269503, 1460.6297869 ]), array([ 256.42380097, 364.27770361, 1460.61658494])] """ thorax_origin = thorax[1] tho_axis_x = thorax[0][0] #REQUIRED MARKERS: # RSHO # LSHO RSHO = frame['RSHO'] LSHO = frame['LSHO'] # Calculate for getting a wand marker # bring x axis from thorax axis axis_x_vec = [tho_axis_x[0]-thorax_origin[0],tho_axis_x[1]-thorax_origin[1],tho_axis_x[2]-thorax_origin[2]] axis_x_vec = axis_x_vec/norm3d(axis_x_vec) RSHO_vec = [RSHO[0]-thorax_origin[0],RSHO[1]-thorax_origin[1],RSHO[2]-thorax_origin[2]] LSHO_vec = [LSHO[0]-thorax_origin[0],LSHO[1]-thorax_origin[1],LSHO[2]-thorax_origin[2]] RSHO_vec = RSHO_vec/norm3d(RSHO_vec) LSHO_vec = LSHO_vec/norm3d(LSHO_vec) R_wand = cross(RSHO_vec,axis_x_vec) R_wand = R_wand/norm3d(R_wand) R_wand = [thorax_origin[0]+R_wand[0], thorax_origin[1]+R_wand[1], thorax_origin[2]+R_wand[2]] L_wand = cross(axis_x_vec,LSHO_vec) L_wand = L_wand/norm3d(L_wand) L_wand = [thorax_origin[0]+L_wand[0], thorax_origin[1]+L_wand[1], thorax_origin[2]+L_wand[2]] wand = [R_wand,L_wand] return wand def findshoulderJC(frame,thorax,wand,vsk=None): """Calculate the Shoulder joint center function. Takes in a dictionary of x,y,z positions and marker names. and takes the thorax axis and wand marker. Calculate each shoulder joint center and returns it. Markers used: RSHO, LSHO Subject Measurement values used: RightShoulderOffset, LeftShoulderOffset Parameters ---------- frame : dict Dictionaries of marker lists. thorax : array Array containing several x,y,z markers for the thorax. wand : array Array containing two x,y,z markers for wand. vsk : dict, optional A dictionary containing subject measurements from a VSK file. Returns ------- Sho_JC : array Returns a 2x3 array representing the right shoulder joint center x, y, z, marker positions (1x3) followed by the left shoulder joint center x, y, z, marker positions (1x3). Examples -------- >>> import numpy as np >>> from .pyCGM import findshoulderJC >>> vsk = { 'RightShoulderOffset' : 40.0, 'LeftShoulderOffset' : 40.0 } >>> frame = {'RSHO': np.array([428.88496562, 270.552948, 1500.73010254]), ... 'LSHO': np.array([68.24668121, 269.01049805, 1510.1072998])} >>> thorax = [[[256.23991128535846, 365.30496976939753, 1459.662169500559], ... [257.1435863244796, 364.21960599061947, 1459.5889787129829], ... [256.08430536580352, 354.32180498523223, 1458.6575930699294]], ... [256.14981023656401, 364.30906039339868, 1459.6553639290375]] >>> wand = [[255.92550222678443, 364.32269504976051, 1460.6297868417887], ... [256.42380097331767, 364.27770361353487, 1460.6165849382387]] >>> findshoulderJC(frame,thorax,wand,vsk) [array([ 429.66971693, 275.06718208, 1453.95397769]), array([ 64.51952733, 274.93442161, 1463.63133339])] """ thorax_origin = thorax[1] #Get Subject Measurement Values R_shoulderoffset = vsk['RightShoulderOffset'] L_shoulderoffset = vsk['LeftShoulderOffset'] mm = 7.0 R_delta =( R_shoulderoffset + mm ) L_delta =( L_shoulderoffset + mm ) #REQUIRED MARKERS: # RSHO # LSHO RSHO = frame['RSHO'] LSHO = frame['LSHO'] # Calculate the shoulder joint center first. R_wand = wand[0] L_wand = wand[1] R_Sho_JC = findJointC(R_wand,thorax_origin,RSHO,R_delta) L_Sho_JC = findJointC(L_wand,thorax_origin,LSHO,L_delta) Sho_JC = [R_Sho_JC,L_Sho_JC] return Sho_JC def shoulderAxisCalc(frame,thorax,shoulderJC,wand): """Calculate the Shoulder joint axis ( Clavicle) function. Takes in a dictionary of x,y,z positions and marker names, as well as an index. and takes the thorax axis and wand marker and then, shoulder joint center. Calculate each shoulder joint axis and returns it. Parameters ---------- frame : dict Dictionaries of marker lists. thorax : array The x,y,z position of the thorax. thorax = [[R_thorax joint center x,y,z position], [L_thorax_joint center x,y,z position], [[R_thorax x axis x,y,z position], [R_thorax,y axis x,y,z position], [R_thorax z axis x,y,z position]]] shoulderJC : array The x,y,z position of the shoulder joint center. shoulderJC = [[R shoulder joint center x,y,z position], [L shoulder joint center x,y,z position]] wand : array The x,y,z position of the wand. wand = [[R wand x,y,z, position], [L wand x,y,z position]] Returns ------- shoulderJC, axis : array Returns the Shoulder joint center and axis in three array shoulder_JC = [[[[R_shoulder x axis, x,y,z position], [R_shoulder y axis, x,y,z position], [R_shoulder z axis, x,y,z position]], [[L_shoulder x axis, x,y,z position], [L_shoulder y axis, x,y,z position], [L_shoulder z axis, x,y,z position]]], [R_shoulderJC_x, R_shoulderJC_y, R_shoulderJC_z], [L_shoulderJC_x,L_shoulderJC_y,L_shoulderJC_z]] Examples -------- >>> import numpy as np >>> from .pyCGM import shoulderAxisCalc >>> frame = None >>> thorax = [[[256.23991128535846, 365.30496976939753, 1459.662169500559], ... [257.1435863244796, 364.21960599061947, 1459.5889787129829], ... [256.08430536580352, 354.32180498523223, 1458.6575930699294]], ... [256.14981023656401, 364.30906039339868, 1459.6553639290375]] >>> shoulderJC = [np.array([429.66951995, 275.06718615, 1453.953978131]), ... np.array([64.51952734, 274.93442161, 1463.6313334])] >>> wand = [[255.92550222678443, 364.32269504976051, 1460.6297868417887], ... [256.42380097331767, 364.27770361353487, 1460.6165849382387]] >>> [np.around(arr,8) for arr in shoulderAxisCalc(frame,thorax,shoulderJC,wand)] #doctest: +NORMALIZE_WHITESPACE [array([[ 429.66951995, 275.06718615, 1453.95397813], [ 64.51952734, 274.93442161, 1463.6313334 ]]), array([[[ 430.12731331, 275.95136619, 1454.04698829], [ 429.68621685, 275.16323377, 1452.95874144], [ 428.78061813, 275.52435188, 1453.98318503]], [[ 64.10400325, 275.83192827, 1463.77905455], [ 64.59882849, 274.80838068, 1464.62018375], [ 65.42564602, 275.3570272 , 1463.61253313]]])] """ thorax_origin = thorax[1] R_shoulderJC = shoulderJC[0] L_shoulderJC = shoulderJC[1] R_wand = wand[0] L_wand = wand[1] R_wand_direc = [R_wand[0]-thorax_origin[0],R_wand[1]-thorax_origin[1],R_wand[2]-thorax_origin[2]] L_wand_direc = [L_wand[0]-thorax_origin[0],L_wand[1]-thorax_origin[1],L_wand[2]-thorax_origin[2]] R_wand_direc = R_wand_direc/norm3d(R_wand_direc) L_wand_direc = L_wand_direc/norm3d(L_wand_direc) # Right #Get the direction of the primary axis Z,X,Y z_direc = [(thorax_origin[0]-R_shoulderJC[0]), (thorax_origin[1]-R_shoulderJC[1]), (thorax_origin[2]-R_shoulderJC[2])] z_direc = z_direc/norm3d(z_direc) y_direc = [R_wand_direc[0]*-1,R_wand_direc[1]*-1,R_wand_direc[2]*-1] x_direc = cross(y_direc,z_direc) x_direc = x_direc/norm3d(x_direc) y_direc = cross(z_direc,x_direc) y_direc = y_direc/norm3d(y_direc) # backwards to account for marker size x_axis = [x_direc[0]+R_shoulderJC[0],x_direc[1]+R_shoulderJC[1],x_direc[2]+R_shoulderJC[2]] y_axis = [y_direc[0]+R_shoulderJC[0],y_direc[1]+R_shoulderJC[1],y_direc[2]+R_shoulderJC[2]] z_axis = [z_direc[0]+R_shoulderJC[0],z_direc[1]+R_shoulderJC[1],z_direc[2]+R_shoulderJC[2]] R_axis = [x_axis,y_axis,z_axis] # Left #Get the direction of the primary axis Z,X,Y z_direc = [(thorax_origin[0]-L_shoulderJC[0]), (thorax_origin[1]-L_shoulderJC[1]), (thorax_origin[2]-L_shoulderJC[2])] z_direc = z_direc/norm3d(z_direc) y_direc = L_wand_direc x_direc = cross(y_direc,z_direc) x_direc = x_direc/norm3d(x_direc) y_direc = cross(z_direc,x_direc) y_direc = y_direc/norm3d(y_direc) # backwards to account for marker size x_axis = [x_direc[0]+L_shoulderJC[0],x_direc[1]+L_shoulderJC[1],x_direc[2]+L_shoulderJC[2]] y_axis = [y_direc[0]+L_shoulderJC[0],y_direc[1]+L_shoulderJC[1],y_direc[2]+L_shoulderJC[2]] z_axis = [z_direc[0]+L_shoulderJC[0],z_direc[1]+L_shoulderJC[1],z_direc[2]+L_shoulderJC[2]] L_axis = [x_axis,y_axis,z_axis] axis = [R_axis,L_axis] return [shoulderJC,axis] def elbowJointCenter(frame,thorax,shoulderJC,wand,vsk=None): """Calculate the Elbow joint axis ( Humerus) function. Takes in a dictionary of x,y,z positions and marker names, as well as an index. and takes the thorax axis and wand marker and then, shoulder joint center. Calculate each elbow joint axis and returns it. Markers used: RSHO, LSHO, RELB, LELB, RWRA ,RWRB, LWRA, LWRB Subject Measurement values used: RightElbowWidth, LeftElbowWidth Parameters ---------- frame Dictionaries of marker lists. thorax : array The x,y,z position of the thorax. shoulderJC : array The x,y,z position of the shoulder joint center. wand : array The x,y,z position of the wand. vsk : dict, optional A dictionary containing subject measurements from a VSK file. Returns ------- origin, axis, wrist_O : array Returns an array containing a 2x3 array containing the right elbow x, y, z marker positions (1x3), and the left elbow x, y, z marker positions (1x3), which is followed by a 2x3x3 array containing right elbow x, y, z axis components (1x3x3) followed by the left x, y, z axis components (1x3x3) which is then followed by the right wrist joint center x, y, z marker positions (1x3), and the left wrist joint center x, y, z marker positions (1x3). Examples -------- >>> import numpy as np >>> from .pyCGM import elbowJointCenter >>> frame = {'RSHO': np.array([428.88496562, 270.552948, 1500.73010254]), ... 'LSHO': np.array([68.24668121, 269.01049805, 1510.1072998]), ... 'RELB': np.array([658.90338135, 326.07580566, 1285.28515625]), ... 'LELB': np.array([-156.32162476, 335.2593313, 1287.39916992]), ... 'RWRA': np.array([776.51898193,495.68103027, 1108.38464355]), ... 'RWRB': np.array([830.9072876, 436.75341797, 1119.11901855]), ... 'LWRA': np.array([-249.28146362, 525.32977295, 1117.09057617]), ... 'LWRB': np.array([-311.77532959, 477.22512817, 1125.1619873])} >>> thorax = [[[256.23991128535846, 365.30496976939753, 1459.662169500559], ... [257.1435863244796, 364.21960599061947, 1459.5889787129829], ... [256.08430536580352, 354.32180498523223, 1458.6575930699294]], ... [256.14981023656401, 364.30906039339868, 1459.6553639290375]] >>> shoulderJC = [np.array([429.66951995, 275.06718615, 1453.953978131]), ... np.array([64.51952734, 274.93442161, 1463.6313334])] >>> wand = [[255.92550222678443, 364.32269504976051, 1460.6297868417887], ... [256.42380097331767, 364.27770361353487, 1460.6165849382387]] >>> vsk = { 'RightElbowWidth': 74.0, 'LeftElbowWidth': 74.0, ... 'RightWristWidth': 55.0, 'LeftWristWidth': 55.0} >>> [np.around(arr,8) for arr in elbowJointCenter(frame,thorax,shoulderJC,wand,vsk)] #doctest: +NORMALIZE_WHITESPACE [array([[ 633.66707588, 304.95542115, 1256.07799541], [-129.16966701, 316.86794653, 1258.06440971]]), array([[[ 633.81070139, 303.96579005, 1256.07658507], [ 634.35247992, 305.05386589, 1256.79947301], [ 632.95321804, 304.8508319 , 1256.77043175]], [[-129.32406616, 315.88151182, 1258.00866516], [-128.45131692, 316.79460332, 1257.37260488], [-128.4913352 , 316.72108835, 1258.78433931]]]), array([[ 793.32814303, 451.29134788, 1084.4325513 ], [-272.45939135, 485.80149026, 1091.36664789]])] """ RSHO = frame['RSHO'] LSHO = frame['LSHO'] RELB = frame['RELB'] LELB = frame['LELB'] RWRA = frame['RWRA'] RWRB = frame['RWRB'] LWRA = frame['LWRA'] LWRB = frame['LWRB'] R_elbowwidth = vsk['RightElbowWidth'] L_elbowwidth = vsk['LeftElbowWidth'] R_elbowwidth = R_elbowwidth * -1 L_elbowwidth = L_elbowwidth mm = 7.0 R_delta =( (R_elbowwidth/2.0)-mm ) L_delta =( (L_elbowwidth/2.0)+mm ) RWRI = [(RWRA[0]+RWRB[0])/2.0,(RWRA[1]+RWRB[1])/2.0,(RWRA[2]+RWRB[2])/2.0] LWRI = [(LWRA[0]+LWRB[0])/2.0,(LWRA[1]+LWRB[1])/2.0,(LWRA[2]+LWRB[2])/2.0] # make humerus axis tho_y_axis = np.subtract(thorax[0][1],thorax[1]) R_sho_mod = [(RSHO[0]-R_delta*tho_y_axis[0]-RELB[0]), (RSHO[1]-R_delta*tho_y_axis[1]-RELB[1]), (RSHO[2]-R_delta*tho_y_axis[2]-RELB[2])] L_sho_mod = [(LSHO[0]+L_delta*tho_y_axis[0]-LELB[0]), (LSHO[1]+L_delta*tho_y_axis[1]-LELB[1]), (LSHO[2]+L_delta*tho_y_axis[2]-LELB[2])] # right axis z_axis = R_sho_mod z_axis_div = norm2d(z_axis) z_axis = [z_axis[0]/z_axis_div,z_axis[1]/z_axis_div,z_axis[2]/z_axis_div] # this is reference axis x_axis = np.subtract(RWRI,RELB) x_axis_div = norm2d(x_axis) x_axis = [x_axis[0]/x_axis_div,x_axis[1]/x_axis_div,x_axis[2]/x_axis_div] y_axis = cross(z_axis,x_axis) y_axis_div = norm2d(y_axis) y_axis = [y_axis[0]/y_axis_div,y_axis[1]/y_axis_div,y_axis[2]/y_axis_div] x_axis = cross(y_axis,z_axis) x_axis_div = norm2d(x_axis) x_axis = [x_axis[0]/x_axis_div,x_axis[1]/x_axis_div,x_axis[2]/x_axis_div] R_axis = [x_axis,y_axis,z_axis] # left axis z_axis = np.subtract(L_sho_mod,LELB) z_axis_div = norm2d(z_axis) z_axis = [z_axis[0]/z_axis_div,z_axis[1]/z_axis_div,z_axis[2]/z_axis_div] # this is reference axis x_axis = L_sho_mod x_axis_div = norm2d(x_axis) x_axis = [x_axis[0]/x_axis_div,x_axis[1]/x_axis_div,x_axis[2]/x_axis_div] y_axis = cross(z_axis,x_axis) y_axis_div = norm2d(y_axis) y_axis = [y_axis[0]/y_axis_div,y_axis[1]/y_axis_div,y_axis[2]/y_axis_div] x_axis = cross(y_axis,z_axis) x_axis_div = norm2d(x_axis) x_axis = [x_axis[0]/x_axis_div,x_axis[1]/x_axis_div,x_axis[2]/x_axis_div] L_axis = [x_axis,y_axis,z_axis] RSJC = shoulderJC[0] LSJC = shoulderJC[1] # make the construction vector for finding Elbow joint center R_con_1 = np.subtract(RSJC,RELB) R_con_1_div = norm2d(R_con_1) R_con_1 = [R_con_1[0]/R_con_1_div,R_con_1[1]/R_con_1_div,R_con_1[2]/R_con_1_div] R_con_2 = np.subtract(RWRI,RELB) R_con_2_div = norm2d(R_con_2) R_con_2 = [R_con_2[0]/R_con_2_div,R_con_2[1]/R_con_2_div,R_con_2[2]/R_con_2_div] R_cons_vec = cross(R_con_1,R_con_2) R_cons_vec_div = norm2d(R_cons_vec) R_cons_vec = [R_cons_vec[0]/R_cons_vec_div,R_cons_vec[1]/R_cons_vec_div,R_cons_vec[2]/R_cons_vec_div] R_cons_vec = [R_cons_vec[0]*500+RELB[0],R_cons_vec[1]*500+RELB[1],R_cons_vec[2]*500+RELB[2]] L_con_1 = np.subtract(LSJC,LELB) L_con_1_div = norm2d(L_con_1) L_con_1 = [L_con_1[0]/L_con_1_div,L_con_1[1]/L_con_1_div,L_con_1[2]/L_con_1_div] L_con_2 = np.subtract(LWRI,LELB) L_con_2_div = norm2d(L_con_2) L_con_2 = [L_con_2[0]/L_con_2_div,L_con_2[1]/L_con_2_div,L_con_2[2]/L_con_2_div] L_cons_vec = cross(L_con_1,L_con_2) L_cons_vec_div = norm2d(L_cons_vec) L_cons_vec = [L_cons_vec[0]/L_cons_vec_div,L_cons_vec[1]/L_cons_vec_div,L_cons_vec[2]/L_cons_vec_div] L_cons_vec = [L_cons_vec[0]*500+LELB[0],L_cons_vec[1]*500+LELB[1],L_cons_vec[2]*500+LELB[2]] REJC = findJointC(R_cons_vec,RSJC,RELB,R_delta) LEJC = findJointC(L_cons_vec,LSJC,LELB,L_delta) # this is radius axis for humerus # right x_axis = np.subtract(RWRA,RWRB) x_axis_div = norm2d(x_axis) x_axis = [x_axis[0]/x_axis_div,x_axis[1]/x_axis_div,x_axis[2]/x_axis_div] z_axis = np.subtract(REJC,RWRI) z_axis_div = norm2d(z_axis) z_axis = [z_axis[0]/z_axis_div,z_axis[1]/z_axis_div,z_axis[2]/z_axis_div] y_axis = cross(z_axis,x_axis) y_axis_div = norm2d(y_axis) y_axis = [y_axis[0]/y_axis_div,y_axis[1]/y_axis_div,y_axis[2]/y_axis_div] x_axis = cross(y_axis,z_axis) x_axis_div = norm2d(x_axis) x_axis = [x_axis[0]/x_axis_div,x_axis[1]/x_axis_div,x_axis[2]/x_axis_div] R_radius = [x_axis,y_axis,z_axis] # left x_axis = np.subtract(LWRA,LWRB) x_axis_div = norm2d(x_axis) x_axis = [x_axis[0]/x_axis_div,x_axis[1]/x_axis_div,x_axis[2]/x_axis_div] z_axis = np.subtract(LEJC,LWRI) z_axis_div = norm2d(z_axis) z_axis = [z_axis[0]/z_axis_div,z_axis[1]/z_axis_div,z_axis[2]/z_axis_div] y_axis = cross(z_axis,x_axis) y_axis_div = norm2d(y_axis) y_axis = [y_axis[0]/y_axis_div,y_axis[1]/y_axis_div,y_axis[2]/y_axis_div] x_axis = cross(y_axis,z_axis) x_axis_div = norm2d(x_axis) x_axis = [x_axis[0]/x_axis_div,x_axis[1]/x_axis_div,x_axis[2]/x_axis_div] L_radius = [x_axis,y_axis,z_axis] # calculate wrist joint center for humerus R_wristThickness = vsk['RightWristWidth'] L_wristThickness = vsk['LeftWristWidth'] R_wristThickness = (R_wristThickness / 2.0 + mm ) L_wristThickness = (L_wristThickness / 2.0 + mm ) RWJC = [RWRI[0]+R_wristThickness*R_radius[1][0],RWRI[1]+R_wristThickness*R_radius[1][1],RWRI[2]+R_wristThickness*R_radius[1][2]] LWJC = [LWRI[0]-L_wristThickness*L_radius[1][0],LWRI[1]-L_wristThickness*L_radius[1][1],LWRI[2]-L_wristThickness*L_radius[1][2]] # recombine the humerus axis #right z_axis = np.subtract(RSJC,REJC) z_axis_div = norm2d(z_axis) z_axis = [z_axis[0]/z_axis_div,z_axis[1]/z_axis_div,z_axis[2]/z_axis_div] x_axis = np.subtract(RWJC,REJC) x_axis_div = norm2d(x_axis) x_axis = [x_axis[0]/x_axis_div,x_axis[1]/x_axis_div,x_axis[2]/x_axis_div] y_axis = cross(x_axis,z_axis) y_axis_div = norm2d(y_axis) y_axis = [y_axis[0]/y_axis_div,y_axis[1]/y_axis_div,y_axis[2]/y_axis_div] x_axis = cross(y_axis,z_axis) x_axis_div = norm2d(x_axis) x_axis = [x_axis[0]/x_axis_div,x_axis[1]/x_axis_div,x_axis[2]/x_axis_div] # attach each calulcated elbow axis to elbow joint center. x_axis = [x_axis[0]+REJC[0],x_axis[1]+REJC[1],x_axis[2]+REJC[2]] y_axis = [y_axis[0]+REJC[0],y_axis[1]+REJC[1],y_axis[2]+REJC[2]] z_axis = [z_axis[0]+REJC[0],z_axis[1]+REJC[1],z_axis[2]+REJC[2]] R_axis = [x_axis,y_axis,z_axis] # left z_axis = np.subtract(LSJC,LEJC) z_axis_div = norm2d(z_axis) z_axis = [z_axis[0]/z_axis_div,z_axis[1]/z_axis_div,z_axis[2]/z_axis_div] x_axis = np.subtract(LWJC,LEJC) x_axis_div = norm2d(x_axis) x_axis = [x_axis[0]/x_axis_div,x_axis[1]/x_axis_div,x_axis[2]/x_axis_div] y_axis = cross(x_axis,z_axis) y_axis_div = norm2d(y_axis) y_axis = [y_axis[0]/y_axis_div,y_axis[1]/y_axis_div,y_axis[2]/y_axis_div] x_axis = cross(y_axis,z_axis) x_axis_div = norm2d(x_axis) x_axis = [x_axis[0]/x_axis_div,x_axis[1]/x_axis_div,x_axis[2]/x_axis_div] # attach each calulcated elbow axis to elbow joint center. x_axis = [x_axis[0]+LEJC[0],x_axis[1]+LEJC[1],x_axis[2]+LEJC[2]] y_axis = [y_axis[0]+LEJC[0],y_axis[1]+LEJC[1],y_axis[2]+LEJC[2]] z_axis = [z_axis[0]+LEJC[0],z_axis[1]+LEJC[1],z_axis[2]+LEJC[2]] L_axis = [x_axis,y_axis,z_axis] axis = [R_axis,L_axis] origin = [REJC,LEJC] wrist_O = [RWJC,LWJC] return [origin,axis,wrist_O] def wristJointCenter(frame,shoulderJC,wand,elbowJC): """Calculate the Wrist joint axis ( Radius) function. Takes in a dictionary of x,y,z positions and marker names, as well as an index. and takes the elbow axis and wand marker and then, shoulder joint center. Calculate each wrist joint axis and returns it. Markers used: RSHO, LSHO, RELB, LELB, RWRA ,RWRB, LWRA, LWRB Parameters ---------- frame : dict Dictionaries of marker lists. shoulderJC : array The x,y,z position of the shoulder joint center. elbowJC : array The x,y,z position of the elbow joint center. wand : array The x,y,z position of the wand. Returns -------- origin, axis : array Returns the Shoulder joint center and axis in three array return = [[R_wrist_JC_x, R_wrist_JC_y, R_wrist_JC_z], [L_wrist_JC_x,L_wrist_JC_y,L_wrist_JC_z], [[[R_wrist x axis, x,y,z position], [R_wrist y axis, x,y,z position], [R_wrist z axis, x,y,z position]], [[L_wrist x axis, x,y,z position], [L_wrist y axis, x,y,z position], [L_wrist z axis, x,y,z position]]]] Examples -------- >>> import numpy as np >>> from .pyCGM import wristJointCenter >>> frame = {'RSHO': np.array([428.88496562, 270.552948, 1500.73010254]), ... 'LSHO': np.array([68.24668121, 269.01049805, 1510.1072998]), ... 'RELB': np.array([658.90338135, 326.07580566, 1285.28515625]), ... 'LELB': np.array([-156.32162476, 335.2593313, 1287.39916992]), ... 'RWRA': np.array([776.51898193,495.68103027, 1108.38464355]), ... 'RWRB': np.array([830.9072876, 436.75341797, 1119.11901855]), ... 'LWRA': np.array([-249.28146362, 525.32977295, 1117.09057617]), ... 'LWRB': np.array([-311.77532959, 477.22512817, 1125.1619873])} >>> wand = [[255.92550222678443, 364.32269504976051, 1460.6297868417887], ... [256.42380097331767, 364.27770361353487, 1460.6165849382387]] >>> shoulderJC = [np.array([429.66951995, 275.06718615, 1453.953978131]), ... np.array([64.51952734, 274.93442161, 1463.6313334])] >>> elbowJC = [[np.array([633.66707587, 304.95542115, 1256.07799541]), ... np.array([-129.1695218, 316.8671644, 1258.06440717])], ... [[[633.81070138699954, 303.96579004975194, 1256.07658506845], ... [634.35247991784638, 305.05386589332528, 1256.7994730142241], ... [632.95321803901493, 304.85083190737765, 1256.7704317504911]], ... [[-129.32391792749493, 315.88072913249465, 1258.0086629318362], ... [-128.45117135279025, 316.79382333592832, 1257.37260287807], ... [-128.49119037560905, 316.7203088419364, 1258.783373067024]]], ... [[793.32814303250677, 451.29134788252043, 1084.4325513020426], ... [-272.4594189740742, 485.80152210947699, 1091.3666238350822]]] >>> [np.around(arr,8) for arr in wristJointCenter(frame,shoulderJC,wand,elbowJC)] #doctest: +NORMALIZE_WHITESPACE [array([[ 793.32814303, 451.29134788, 1084.4325513 ], [-272.45941897, 485.80152211, 1091.36662384]]), array([[[ 793.77133728, 450.44879187, 1084.12648231], [ 794.01354708, 451.38979263, 1085.1540289 ], [ 792.75038863, 450.76181223, 1085.05367274]], [[-272.92507295, 485.01202419, 1090.9667996 ], [-271.74106833, 485.72818103, 1090.67481935], [-271.94256432, 485.19216661, 1091.96791174]]])] """ # Bring Elbow joint center, axes and Wrist Joint Center for calculating Radius Axes REJC = elbowJC[0][0] LEJC = elbowJC[0][1] R_elbow_axis = elbowJC[1][0] L_elbow_axis = elbowJC[1][1] R_elbow_flex = [R_elbow_axis[1][0]-REJC[0],R_elbow_axis[1][1]-REJC[1],R_elbow_axis[1][2]-REJC[2]] L_elbow_flex = [L_elbow_axis[1][0]-LEJC[0],L_elbow_axis[1][1]-LEJC[1],L_elbow_axis[1][2]-LEJC[2]] RWJC = elbowJC[2][0] LWJC = elbowJC[2][1] # this is the axis of radius # right y_axis = R_elbow_flex y_axis = y_axis/ norm3d(y_axis) z_axis = np.subtract(REJC,RWJC) z_axis = z_axis/ norm3d(z_axis) x_axis = cross(y_axis,z_axis) x_axis = x_axis/ norm3d(x_axis) z_axis = cross(x_axis,y_axis) z_axis = z_axis/ norm3d(z_axis) # Attach all the axes to wrist joint center. x_axis = [x_axis[0]+RWJC[0],x_axis[1]+RWJC[1],x_axis[2]+RWJC[2]] y_axis = [y_axis[0]+RWJC[0],y_axis[1]+RWJC[1],y_axis[2]+RWJC[2]] z_axis = [z_axis[0]+RWJC[0],z_axis[1]+RWJC[1],z_axis[2]+RWJC[2]] R_axis = [x_axis,y_axis,z_axis] # left y_axis = L_elbow_flex y_axis = y_axis/ norm3d(y_axis) z_axis = np.subtract(LEJC,LWJC) z_axis = z_axis/ norm3d(z_axis) x_axis = cross(y_axis,z_axis) x_axis = x_axis/ norm3d(x_axis) z_axis = cross(x_axis,y_axis) z_axis = z_axis/ norm3d(z_axis) # Attach all the axes to wrist joint center. x_axis = [x_axis[0]+LWJC[0],x_axis[1]+LWJC[1],x_axis[2]+LWJC[2]] y_axis = [y_axis[0]+LWJC[0],y_axis[1]+LWJC[1],y_axis[2]+LWJC[2]] z_axis = [z_axis[0]+LWJC[0],z_axis[1]+LWJC[1],z_axis[2]+LWJC[2]] L_axis = [x_axis,y_axis,z_axis] origin = [RWJC,LWJC] axis = [R_axis,L_axis] return [origin,axis] def handJointCenter(frame,elbowJC,wristJC,vsk=None): """Calculate the Hand joint axis ( Hand) function. Takes in a dictionary of x,y,z positions and marker names. and takes the elbow axis and wrist axis. Calculate each Hand joint axis and returns it. Markers used: RWRA, RWRB, LWRA, LWRB, RFIN, LFIN Subject Measurement values used: RightHandThickness, LeftHandThickness Parameters ---------- frame Dictionaries of marker lists. elbowJC : array The x,y,z position of the elbow joint center. wristJC : array The x,y,z position of the wrist joint center. vsk : dict, optional A dictionary containing subject measurements from a VSK file. Returns ------- origin, axis : array Returns an array containing an array representing the right hand joint center x, y, z marker positions (1x3), followed by an array containing the left hand joint center x, y, z marker positions (1x3), followed by a 2x3x3 array containing the right hand joint center x, y, z axis components (1x3x3), followed by the left hand joint center x, y, z axis components (1x3x3). Examples -------- >>> import numpy as np >>> from .pyCGM import handJointCenter >>> frame = {'RWRA': np.array([776.51898193,495.68103027, 1108.38464355]), ... 'RWRB': np.array([830.9072876, 436.75341797, 1119.11901855]), ... 'LWRA': np.array([-249.28146362, 525.32977295, 1117.09057617]), ... 'LWRB': np.array([-311.77532959, 477.22512817, 1125.1619873]), ... 'RFIN': np.array([863.71374512, 524.4475708, 1074.54248047]), ... 'LFIN': np.array([-326.65890503, 558.34338379, 1091.04284668])} >>> elbowJC = [[np.array([633.66707587, 304.95542115, 1256.07799541]), ... np.array([-129.1695218, 316.8671644, 1258.06440717])], ... [[[633.81070138699954, 303.96579004975194, 1256.07658506845], ... [634.35247991784638, 305.05386589332528, 1256.7994730142241], ... [632.95321803901493, 304.85083190737765, 1256.7704317504911]], ... [[-129.32391792749493, 315.88072913249465, 1258.0086629318362], ... [-128.45117135279025, 316.79382333592832, 1257.37260287807], ... [-128.49119037560905, 316.7203088419364, 1258.783373067024]]], ... [[793.32814303250677, 451.29134788252043, 1084.4325513020426], ... [-272.4594189740742, 485.80152210947699, 1091.3666238350822]]] >>> wristJC = [[[793.32814303250677, 451.29134788252043, 1084.4325513020426], ... [-272.4594189740742, 485.80152210947699, 1091.3666238350822]], ... [[[793.77133727961598, 450.44879187190122, 1084.1264823093322], ... [794.01354707689597, 451.38979262469761, 1085.1540289034019], ... [792.7503886251119, 450761812234714, 1085.0536727414069]], ... [[-272.9250728167512, 485.01202418036871, 1090.9667994752267], ... [-271.74106814470946, 485.72818104689361, 1090.6748195459295], ... [-271.94256446383838, 485.1921666233502, 1091.967911874857]]]] >>> vsk = { 'RightHandThickness': 34.0, 'LeftHandThickness': 34.0} >>> [np.around(arr,8) for arr in handJointCenter(frame,elbowJC,wristJC,vsk)] #doctest: +NORMALIZE_WHITESPACE [array([[ 859.80614366, 517.28239823, 1051.97278945], [-324.53477798, 551.88744289, 1068.02526837]]), array([[[ 859.95675979, 517.59241232, 1052.9115152 ], [ 859.07975674, 517.96120459, 1051.86516062], [ 859.1355642 , 516.61673075, 1052.30021881]], [[-324.61994077, 552.15893309, 1068.9839343 ], [-325.33293185, 551.29292486, 1068.12272964], [-323.93837401, 551.13058004, 1068.29259013]]])] """ RWRA = frame['RWRA'] RWRB = frame['RWRB'] LWRA = frame['LWRA'] LWRB = frame['LWRB'] RFIN = frame['RFIN'] LFIN = frame['LFIN'] RWRI = [(RWRA[0]+RWRB[0])/2.0,(RWRA[1]+RWRB[1])/2.0,(RWRA[2]+RWRB[2])/2.0] LWRI = [(LWRA[0]+LWRB[0])/2.0,(LWRA[1]+LWRB[1])/2.0,(LWRA[2]+LWRB[2])/2.0] LWJC = wristJC[0][1] RWJC = wristJC[0][0] mm = 7.0 R_handThickness = vsk['RightHandThickness'] L_handThickness = vsk['LeftHandThickness'] R_delta =( R_handThickness/2.0 + mm ) L_delta =( L_handThickness/2.0 + mm ) LHND = findJointC(LWRI,LWJC,LFIN,L_delta) RHND = findJointC(RWRI,RWJC,RFIN,R_delta) # Left z_axis = [LWJC[0]-LHND[0],LWJC[1]-LHND[1],LWJC[2]-LHND[2]] z_axis_div = norm2d(z_axis) z_axis = [z_axis[0]/z_axis_div,z_axis[1]/z_axis_div,z_axis[2]/z_axis_div] y_axis = [LWRI[0]-LWRA[0],LWRI[1]-LWRA[1],LWRI[2]-LWRA[2]] y_axis_div = norm2d(y_axis) y_axis = [y_axis[0]/y_axis_div,y_axis[1]/y_axis_div,y_axis[2]/y_axis_div] x_axis = cross(y_axis,z_axis) x_axis_div = norm2d(x_axis) x_axis = [x_axis[0]/x_axis_div,x_axis[1]/x_axis_div,x_axis[2]/x_axis_div] y_axis = cross(z_axis,x_axis) y_axis_div = norm2d(y_axis) y_axis = [y_axis[0]/y_axis_div,y_axis[1]/y_axis_div,y_axis[2]/y_axis_div] L_axis = [x_axis,y_axis,z_axis] # Right z_axis = [RWJC[0]-RHND[0],RWJC[1]-RHND[1],RWJC[2]-RHND[2]] z_axis_div = norm2d(z_axis) z_axis = [z_axis[0]/z_axis_div,z_axis[1]/z_axis_div,z_axis[2]/z_axis_div] y_axis = [RWRA[0]-RWRI[0],RWRA[1]-RWRI[1],RWRA[2]-RWRI[2]] y_axis_div = norm2d(y_axis) y_axis = [y_axis[0]/y_axis_div,y_axis[1]/y_axis_div,y_axis[2]/y_axis_div] x_axis = cross(y_axis,z_axis) x_axis_div = norm2d(x_axis) x_axis = [x_axis[0]/x_axis_div,x_axis[1]/x_axis_div,x_axis[2]/x_axis_div] y_axis = cross(z_axis,x_axis) y_axis_div = norm2d(y_axis) y_axis = [y_axis[0]/y_axis_div,y_axis[1]/y_axis_div,y_axis[2]/y_axis_div] R_axis = [x_axis,y_axis,z_axis] R_origin = RHND L_origin = LHND # Attach it to the origin. L_axis = [[L_axis[0][0]+L_origin[0],L_axis[0][1]+L_origin[1],L_axis[0][2]+L_origin[2]], [L_axis[1][0]+L_origin[0],L_axis[1][1]+L_origin[1],L_axis[1][2]+L_origin[2]], [L_axis[2][0]+L_origin[0],L_axis[2][1]+L_origin[1],L_axis[2][2]+L_origin[2]]] R_axis = [[R_axis[0][0]+R_origin[0],R_axis[0][1]+R_origin[1],R_axis[0][2]+R_origin[2]], [R_axis[1][0]+R_origin[0],R_axis[1][1]+R_origin[1],R_axis[1][2]+R_origin[2]], [R_axis[2][0]+R_origin[0],R_axis[2][1]+R_origin[1],R_axis[2][2]+R_origin[2]]] origin = [R_origin, L_origin] axis = [R_axis, L_axis] return [origin,axis] def findJointC(a, b, c, delta): """Calculate the Joint Center function. This function is based on physical markers, a,b,c and joint center which will be calulcated in this function are all in the same plane. Parameters ---------- a,b,c : list Three markers x,y,z position of a, b, c. delta : float The length from marker to joint center, retrieved from subject measurement file. Returns ------- mr : array Returns the Joint C x, y, z positions in a 1x3 array. Examples -------- >>> import numpy as np >>> from .pyCGM import findJointC >>> a = [468.14532471, 325.09780884, 673.12591553] >>> b = [355.90861996, 365.38260964, 940.6974861] >>> c = [452.35180664, 329.0609436, 524.77893066] >>> delta = 59.5 >>> findJointC(a,b,c,delta) array([396.25286248, 347.91367254, 518.63620527]) """ # make the two vector using 3 markers, which is on the same plane. v1 = (a[0]-c[0],a[1]-c[1],a[2]-c[2]) v2 = (b[0]-c[0],b[1]-c[1],b[2]-c[2]) # v3 is cross vector of v1, v2 # and then it normalized. # v3 = cross(v1,v2) v3 = [v1[1]*v2[2] - v1[2]*v2[1],v1[2]*v2[0] - v1[0]*v2[2],v1[0]*v2[1] - v1[1]*v2[0]] v3_div = norm2d(v3) v3 = [v3[0]/v3_div,v3[1]/v3_div,v3[2]/v3_div] m = [(b[0]+c[0])/2.0,(b[1]+c[1])/2.0,(b[2]+c[2])/2.0] length = np.subtract(b,m) length = norm2d(length) theta = math.acos(delta/norm2d(v2)) cs = math.cos(theta*2) sn = math.sin(theta*2) ux = v3[0] uy = v3[1] uz = v3[2] # this rotation matrix is called Rodriques' rotation formula. # In order to make a plane, at least 3 number of markers is required which means three physical markers on the segment can make a plane. # then the orthogonal vector of the plane will be rotating axis. # joint center is determined by rotating the one vector of plane around rotating axis. rot = np.matrix([[cs+ux**2.0*(1.0-cs),ux*uy*(1.0-cs)-uz*sn,ux*uz*(1.0-cs)+uy*sn], [uy*ux*(1.0-cs)+uz*sn,cs+uy**2.0*(1.0-cs),uy*uz*(1.0-cs)-ux*sn], [uz*ux*(1.0-cs)-uy*sn,uz*uy*(1.0-cs)+ux*sn,cs+uz**2.0*(1.0-cs)]]) r = rot*(np.matrix(v2).transpose()) r = r* length/np.linalg.norm(r) r = [r[0,0],r[1,0],r[2,0]] mr = np.array([r[0]+m[0],r[1]+m[1],r[2]+m[2]]) return mr def cross(a, b): """Cross Product function Given vectors a and b, calculate the cross product. Parameters ---------- a : list First 3D vector. b : list Second 3D vector. Returns ------- c : list The cross product of vector a and vector b. Examples -------- >>> import numpy as np >>> from .pyCGM import cross >>> a = [6.25286248, 7.91367254, 18.63620527] >>> b = [3.49290439, 4.42038315, 19.23948238] >>> np.around(cross(a, b),8) array([ 6.98757956e+01, -5.52073543e+01, -1.65361000e-03]) """ c = [a[1]*b[2] - a[2]*b[1], a[2]*b[0] - a[0]*b[2], a[0]*b[1] - a[1]*b[0]] return c def getPelangle(axisP,axisD): """Pelvis angle calculation function. This function takes in two axis and returns three angles. and It uses the inverse Euler rotation matrix in YXZ order. the output shows the angle in degrees. Parameters ---------- axisP : list Shows the unit vector of axisP, the position of the proximal axis. axisD : list Shows the unit vector of axisD, the position of the distal axis. Returns ------- angle : list Returns the gamma, beta, alpha angles in degrees in a 1x3 corresponding list. Examples ------- >>> import numpy as np >>> from .pyCGM import getPelangle >>> axisP = [[ 0.0464229, 0.99648672, 0.06970743], ... [ 0.99734011, -0.04231089, -0.05935067], ... [-0.05619277, 0.07227725, -0.99580037]] >>> axisD = [[-0.18067218, -0.98329158, -0.02225371], ... [ 0.71383942, -0.1155303, -0.69071415], ... [ 0.67660243, -0.1406784, 0.7227854 ]] >>> np.around(getPelangle(axisP,axisD),8) array([-175.65183483, 39.63221918, -10.2668477 ]) """ # this is the angle calculation which order is Y-X-Z # alpha is abdcution angle. # beta is flextion angle # gamma is rotation angle beta = np.arctan2(((axisD[2][0]*axisP[1][0])+(axisD[2][1]*axisP[1][1])+(axisD[2][2]*axisP[1][2])), np.sqrt(pow(axisD[2][0]*axisP[0][0]+axisD[2][1]*axisP[0][1]+axisD[2][2]*axisP[0][2],2)+pow((axisD[2][0]*axisP[2][0]+axisD[2][1]*axisP[2][1]+axisD[2][2]*axisP[2][2]),2))) alpha = np.arctan2(((axisD[2][0]*axisP[0][0])+(axisD[2][1]*axisP[0][1])+(axisD[2][2]*axisP[0][2])),((axisD[2][0]*axisP[2][0])+(axisD[2][1]*axisP[2][1])+(axisD[2][2]*axisP[2][2]))) gamma = np.arctan2(((axisD[0][0]*axisP[1][0])+(axisD[0][1]*axisP[1][1])+(axisD[0][2]*axisP[1][2])),((axisD[1][0]*axisP[1][0])+(axisD[1][1]*axisP[1][1])+(axisD[1][2]*axisP[1][2]))) alpha = 180.0 * alpha/ pi beta = 180.0 * beta/ pi gamma = 180.0 * gamma/ pi angle = [alpha, beta, gamma] return angle def getHeadangle(axisP,axisD): """Head angle calculation function. This function takes in two axis and returns three angles. and It uses the inverse Euler rotation matrix in YXZ order. the output shows the angle in degrees. Parameters ---------- axisP : list Shows the unit vector of axisP, the position of the proximal axis. axisD : list Shows the unit vector of axisD, the position of the distal axis. Returns ------- angle : list Returns the gamma, beta, alpha angles in degrees in a 1x3 corresponding list. Examples -------- >>> import numpy as np >>> from .pyCGM import getHeadangle >>> axisP = [[ 0.0464229, 0.99648672, 0.06970743], ... [ 0.99734011, -0.04231089, -0.05935067], ... [-0.05619277, 0.07227725, -0.99580037]] >>> axisD = [[-0.18067218, -0.98329158, -0.02225371], ... [ 0.71383942, -0.1155303, -0.69071415], ... [ 0.67660243, -0.1406784, 0.7227854 ]] >>> np.around(getHeadangle(axisP,axisD),8) array([ 184.34816517, -39.63221894, -190.2668477 ]) """ # this is the angle calculation which order is Y-X-Z # alpha is abdcution angle. ang=((-1*axisD[2][0]*axisP[1][0])+(-1*axisD[2][1]*axisP[1][1])+(-1*axisD[2][2]*axisP[1][2])) alpha = np.nan if -1<=ang<=1: alpha = np.arcsin(ang) # check the abduction angle is in the area between -pi/2 and pi/2 # beta is flextion angle # gamma is rotation angle beta = np.arctan2(((axisD[2][0]*axisP[1][0])+(axisD[2][1]*axisP[1][1])+(axisD[2][2]*axisP[1][2])), np.sqrt(pow(axisD[0][0]*axisP[1][0]+axisD[0][1]*axisP[1][1]+axisD[0][2]*axisP[1][2],2)+pow((axisD[1][0]*axisP[1][0]+axisD[1][1]*axisP[1][1]+axisD[1][2]*axisP[1][2]),2))) alpha = np.arctan2(-1*((axisD[2][0]*axisP[0][0])+(axisD[2][1]*axisP[0][1])+(axisD[2][2]*axisP[0][2])),((axisD[2][0]*axisP[2][0])+(axisD[2][1]*axisP[2][1])+(axisD[2][2]*axisP[2][2]))) gamma = np.arctan2(-1*((axisD[0][0]*axisP[1][0])+(axisD[0][1]*axisP[1][1])+(axisD[0][2]*axisP[1][2])),((axisD[1][0]*axisP[1][0])+(axisD[1][1]*axisP[1][1])+(axisD[1][2]*axisP[1][2]))) alpha = 180.0 * alpha/ pi beta = 180.0 * beta/ pi gamma = 180.0 * gamma/ pi beta = -1*beta if alpha <0: alpha = alpha *-1 else: if 0<alpha < 180: alpha = 180+(180-alpha) if gamma > 90.0: if gamma >120: gamma = (gamma - 180)*-1 else: gamma = (gamma + 180)*-1 else: if gamma <0: gamma = (gamma + 180)*-1 else: gamma = (gamma*-1)-180.0 angle = [alpha, beta, gamma] return angle def getangle_sho(axisP,axisD): """Shoulder angle calculation function. This function takes in two axis and returns three angles. and It use inverse Euler rotation matrix in XYZ order. the output shows the angle in degrees. Parameters ---------- axisP : list Shows the unit vector of axisP, the position of the proximal axis. axisD : list Shows the unit vector of axisD, the position of the distal axis. Returns ------- angle : list Returns the gamma, beta, alpha angles in degrees in a 1x3 corresponding list. Examples -------- >>> import numpy as np >>> from .pyCGM import getangle_sho >>> axisP = [[ 0.0464229, 0.99648672, 0.06970743], ... [ 0.99734011, -0.04231089, -0.05935067], ... [-0.05619277, 0.07227725, -0.99580037]] >>> axisD = [[-0.18067218, -0.98329158, -0.02225371], ... [ 0.71383942, -0.1155303, -0.69071415], ... [ 0.67660243, -0.1406784, 0.7227854 ]] >>> np.around(getangle_sho(axisP,axisD),8) array([ -3.3474503 , -140.28662977, 172.50982168]) """ # beta is flexion /extension # gamma is adduction / abduction # alpha is internal / external rotation # this is shoulder angle calculation alpha = np.arcsin(((axisD[2][0]*axisP[0][0])+(axisD[2][1]*axisP[0][1])+(axisD[2][2]*axisP[0][2]))) beta = np.arctan2(-1*((axisD[2][0]*axisP[1][0])+(axisD[2][1]*axisP[1][1])+(axisD[2][2]*axisP[1][2])) , ((axisD[2][0]*axisP[2][0])+(axisD[2][1]*axisP[2][1])+(axisD[2][2]*axisP[2][2]))) gamma = np.arctan2(-1*((axisD[1][0]*axisP[0][0])+(axisD[1][1]*axisP[0][1])+(axisD[1][2]*axisP[0][2])) , ((axisD[0][0]*axisP[0][0])+(axisD[0][1]*axisP[0][1])+(axisD[0][2]*axisP[0][2]))) angle = [180.0 * alpha/ pi, 180.0 *beta/ pi, 180.0 * gamma/ pi] return angle def getangle_spi(axisP,axisD): """Spine angle calculation function. This function takes in two axis and returns three angles. and It use inverse Euler rotation matrix in XZX order. the output shows the angle in degrees. Parameters ---------- axisP : list Shows the unit vector of axisP, the position of the proximal axis. axisD : list Shows the unit vector of axisD, the position of the distal axis. Returns ------- angle : list Returns the gamma, beta, alpha angles in degrees in a 1x3 corresponding list. Examples -------- >>> import numpy as np >>> from .pyCGM import getangle_spi >>> axisP = [[ 0.0464229, 0.99648672, 0.06970743], ... [ 0.99734011, -0.04231089, -0.05935067], ... [-0.05619277, 0.07227725, -0.99580037]] >>> axisD = [[-0.18067218, -0.98329158,-0.02225371], ... [ 0.71383942, -0.1155303, -0.69071415], ... [ 0.67660243, -0.1406784, 0.7227854 ]] >>> np.around(getangle_spi(axisP,axisD),8) array([ 2.8891964 , 9.7438295 , 39.74341087]) """ # this angle calculation is for spine angle. alpha = np.arcsin(((axisD[1][0]*axisP[2][0])+(axisD[1][1]*axisP[2][1])+(axisD[1][2]*axisP[2][2]))) gamma = np.arcsin(((-1*axisD[1][0]*axisP[0][0])+(-1*axisD[1][1]*axisP[0][1])+(-1*axisD[1][2]*axisP[0][2])) / np.cos(alpha)) beta = np.arcsin(((-1*axisD[0][0]*axisP[2][0])+(-1*axisD[0][1]*axisP[2][1])+(-1*axisD[0][2]*axisP[2][2])) / np.cos(alpha)) angle = [180.0 * beta/ pi, 180.0 *gamma/ pi, 180.0 * alpha/ pi] return angle def getangle(axisP,axisD): """Normal angle calculation function. This function takes in two axis and returns three angles. and It use inverse Euler rotation matrix in YXZ order. the output shows the angle in degrees. As we use arc sin we have to care about if the angle is in area between -pi/2 to pi/2 Parameters ---------- axisP : list Shows the unit vector of axisP, the position of the proximal axis. axisD : list Shows the unit vector of axisD, the position of the distal axis. Returns ------- angle : list Returns the gamma, beta, alpha angles in degrees in a 1x3 corresponding list. Examples -------- >>> import numpy as np >>> from .pyCGM import getangle >>> axisP = [[ 0.0464229, 0.99648672, 0.06970743], ... [ 0.99734011, -0.04231089, -0.05935067], ... [-0.05619277, 0.07227725, -0.99580037]] >>> axisD = [[-0.18067218, -0.98329158, -0.02225371], ... [ 0.71383942, -0.1155303, -0.69071415], ... [ 0.67660243, -0.1406784, 0.7227854 ]] >>> np.around(getangle(axisP,axisD),8) array([-175.65183483, -39.6322192 , 100.2668477 ]) """ # this is the angle calculation which order is Y-X-Z # alpha is abdcution angle. ang=((-1*axisD[2][0]*axisP[1][0])+(-1*axisD[2][1]*axisP[1][1])+(-1*axisD[2][2]*axisP[1][2])) alpha = np.nan if -1<=ang<=1: # alpha = np.arcsin(ang) alpha = np.arcsin(ang) # check the abduction angle is in the area between -pi/2 and pi/2 # beta is flextion angle # gamma is rotation angle if -1.57079633<alpha<1.57079633: beta = np.arctan2(((axisD[2][0]*axisP[0][0])+(axisD[2][1]*axisP[0][1])+(axisD[2][2]*axisP[0][2])) , ((axisD[2][0]*axisP[2][0])+(axisD[2][1]*axisP[2][1])+(axisD[2][2]*axisP[2][2]))) gamma = np.arctan2(((axisD[1][0]*axisP[1][0])+(axisD[1][1]*axisP[1][1])+(axisD[1][2]*axisP[1][2])) , ((axisD[0][0]*axisP[1][0])+(axisD[0][1]*axisP[1][1])+(axisD[0][2]*axisP[1][2]))) else: beta = np.arctan2(-1*((axisD[2][0]*axisP[0][0])+(axisD[2][1]*axisP[0][1])+(axisD[2][2]*axisP[0][2])) , ((axisD[2][0]*axisP[2][0])+(axisD[2][1]*axisP[2][1])+(axisD[2][2]*axisP[2][2]))) gamma = np.arctan2(-1*((axisD[1][0]*axisP[1][0])+(axisD[1][1]*axisP[1][1])+(axisD[1][2]*axisP[1][2])) , ((axisD[0][0]*axisP[1][0])+(axisD[0][1]*axisP[1][1])+(axisD[0][2]*axisP[1][2]))) angle = [180.0 * beta/ pi, 180.0 *alpha/ pi, 180.0 * gamma / pi ] return angle def norm2d(v): """2D Vector normalization function This function calculates the normalization of a 3-dimensional vector. Parameters ---------- v : list A 3D vector. Returns ------- float The normalization of the vector as a float. Examples -------- >>> import numpy as np >>> from .pyCGM import norm2d >>> v = [105.141121037153, 101.890788777524, 326.7710280245359] >>> np.around(norm2d(v),8) 358.07218955 """ try: return sqrt((v[0]*v[0]+v[1]*v[1]+v[2]*v[2])) except: return np.nan def norm3d(v): """3D Vector normalization function This function calculates the normalization of a 3-dimensional vector. Parameters ---------- v : list A 3D vector. Returns ------- list The normalization of the vector returned as a float in an array. Examples -------- >>> from .pyCGM import norm3d >>> v = [125.44928201, 143.94301493, 213.49204956] >>> norm3d(v) array(286.4192192) """ try: return np.asarray(sqrt((v[0]*v[0]+v[1]*v[1]+v[2]*v[2]))) except: return np.nan def normDiv(v): """Normalized divison function This function calculates the normalization division of a 3-dimensional vector. Parameters ---------- v : list A 3D vector. Returns ------- array The divison normalization of the vector returned as a float in an array. Examples -------- >>> import numpy as np >>> from .pyCGM import normDiv >>> v = [1.44928201, 1.94301493, 2.49204956] >>> np.around(normDiv(v),8) array([0.11991376, 0.16076527, 0.20619246]) """ try: vec = sqrt((v[0]*v[0]+v[1]*v[1]+v[2]*v[2])) v = [v[0]/vec,v[1]/vec,v[2]/vec] except: vec = np.nan return [v[0]/vec,v[1]/vec,v[2]/vec] def matrixmult (A, B): """Matrix multiplication function This function returns the product of a matrix multiplication given two matrices. Let the dimension of the matrix A be: m by n, let the dimension of the matrix B be: p by q, multiplication will only possible if n = p, creating a matrix of m by q size. Parameters ---------- A : list First matrix, in a 2D array format. B : list Second matrix, in a 2D array format. Returns ------- C : list The product of the matrix multiplication. Examples -------- >>> from .pyCGM import matrixmult >>> A = [[11,12,13],[14,15,16]] >>> B = [[1,2],[3,4],[5,6]] >>> matrixmult(A, B) [[112, 148], [139, 184]] """ C = [[0 for row in range(len(A))] for col in range(len(B[0]))] for i in range(len(A)): for j in range(len(B[0])): for k in range(len(B)): C[i][j] += A[i][k]*B[k][j] return C def rotmat(x=0,y=0,z=0): """Rotation Matrix function This function creates and returns a rotation matrix. Parameters ---------- x,y,z : float, optional Angle, which will be converted to radians, in each respective axis to describe the rotations. The default is 0 for each unspecified angle. Returns ------- Rxyz : list The product of the matrix multiplication. Examples -------- >>> import numpy as np >>> from .pyCGM import rotmat >>> x = 0.5 >>> y = 0.3 >>> z = 0.8 >>> np.around(rotmat(x,y,z),8) array([[ 0.99988882, -0.01396199, 0.00523596], [ 0.01400734, 0.99986381, -0.00872642], [-0.00511341, 0.00879879, 0.99994822]]) >>> x = 0.5 >>> np.around(rotmat(x),8) array([[ 1. , 0. , 0. ], [ 0. , 0.99996192, -0.00872654], [ 0. , 0.00872654, 0.99996192]]) >>> x = 1 >>> y = 1 >>> np.around(rotmat(x,y),8) array([[ 9.9984770e-01, 0.0000000e+00, 1.7452410e-02], [ 3.0459000e-04, 9.9984770e-01, -1.7449750e-02], [-1.7449750e-02, 1.7452410e-02, 9.9969541e-01]]) """ x = math.radians(x) y = math.radians(y) z = math.radians(z) Rx = [ [1,0,0],[0,math.cos(x),math.sin(x)*-1],[0,math.sin(x),math.cos(x)] ] Ry = [ [math.cos(y),0,math.sin(y)],[0,1,0],[math.sin(y)*-1,0,math.cos(y)] ] Rz = [ [math.cos(z),math.sin(z)*-1,0],[math.sin(z),math.cos(z),0],[0,0,1] ] Rxy = matrixmult(Rx,Ry) Rxyz = matrixmult(Rxy,Rz) Ryx = matrixmult(Ry,Rx) Ryxz = matrixmult(Ryx,Rz) return Rxyz def JointAngleCalc(frame,vsk): """ Joint Angle Calculation function Calculates the Joint angles of plugingait and stores the data in array Stores RPel_angle = [] LPel_angle = [] RHip_angle = [] LHip_angle = [] RKnee_angle = [] LKnee_angle = [] RAnkle_angle = [] LAnkle_angle = [] Joint Axis store like below form Basically, the axis form is like [[origin],[axis]] So, there's origin which define the position of axis and there's Unit vector of each axis which is attach to the origin. If it is just single one (Pelvis, Hip, Head, Thorax) Axis = [[origin_x, origin_y, origin_z],[[Xaxis_x,Xaxis_y,Xaxis_z], [Yaxis_x,Yaxis_y,Yaxis_z], [Zaxis_x,Zaxis_y,Zaxis_z]]] If it has both of Right and Left ( knee, angle, foot, clavicle, humerus, radius, hand) Axis = [[[R_origin_x,R_origin_y,R_origin_z], [L_origin_x,L_origin_y,L_origin_z]],[[[R_Xaxis_x,R_Xaxis_y,R_Xaxis_z], [R_Yaxis_x,R_Yaxis_y,R_Yaxis_z], [R_Zaxis_x,R_Zaxis_y,R_Zaxis_z]], [[L_Xaxis_x,L_Xaxis_y,L_Xaxis_z], [L_Yaxis_x,L_Yaxis_y,L_Yaxis_z], [L_Zaxis_x,L_Zaxis_y,L_Zaxis_z]]]] Parameters ---------- frame : dict Dictionaries of marker lists. vsk : dict, optional A dictionary containing subject measurements from a VSK file. Returns ------- r, jc : tuple Returns a tuple containing an array that holds the result of all the joint calculations, followed by a dictionary for joint center marker positions. Examples -------- >>> import numpy as np >>> from .pyCGM import JointAngleCalc >>> from .pycgmIO import loadC3D, loadVSK >>> from .pycgmStatic import getStatic >>> from .pyCGM_Helpers import getfilenames >>> import os >>> fileNames=getfilenames(2) >>> c3dFile = fileNames[1] >>> vskFile = fileNames[2] >>> result = loadC3D(c3dFile) >>> data = result[0] >>> frame = result[0][0] >>> vskData = loadVSK(vskFile, False) >>> vsk = getStatic(data,vskData,flat_foot=False) >>> results = JointAngleCalc(frame, vsk)[1] >>> np.around(results['Pelvis'],8) array([ 246.152565 , 353.26243591, 1031.71362305]) >>> np.around(results['Thorax'],8) array([ 250.56159618, 303.23273922, 1461.17230698]) >>> np.around(results['Head'],8) array([ 244.89547729, 325.05789185, 1730.1619873 ]) >>> np.around(results['RHand'],8) array([ 770.93339376, 591.04557736, 1079.04817118]) """ # THIS IS FOOT PROGRESS ANGLE rfoot_prox,rfoot_proy,rfoot_proz,lfoot_prox,lfoot_proy,lfoot_proz = [None]*6 #First Calculate Pelvis pelvis_axis = pelvisJointCenter(frame) kin_Pelvis_axis = pelvis_axis kin_Pelvis_JC = pelvis_axis[0] #quick fix for storing JC #change to same format Pelvis_vectors = pelvis_axis[1] Pelvis_origin = pelvis_axis[0] #need to update this based on the file global_Axis = vsk['GCS'] #make the array which will be the input of findangle function pelvis_Axis_mod = np.vstack([np.subtract(Pelvis_vectors[0],Pelvis_origin), np.subtract(Pelvis_vectors[1],Pelvis_origin), np.subtract(Pelvis_vectors[2],Pelvis_origin)]) global_pelvis_angle = getangle(global_Axis,pelvis_Axis_mod) pelx=global_pelvis_angle[0] pely=global_pelvis_angle[1] pelz=global_pelvis_angle[2] # and then find hip JC hip_JC = hipJointCenter(frame,pelvis_axis[0],pelvis_axis[1][0],pelvis_axis[1][1],pelvis_axis[1][2],vsk=vsk) kin_L_Hip_JC = hip_JC[0] #quick fix for storing JC kin_R_Hip_JC = hip_JC[1] #quick fix for storing JC hip_axis = hipAxisCenter(hip_JC[0],hip_JC[1],pelvis_axis) knee_JC = kneeJointCenter(frame,hip_JC,0,vsk=vsk) kin_R_Knee_JC = knee_JC[0] #quick fix for storing JC kin_L_Knee_JC = knee_JC[1] #quick fix for storing JC #change to same format Hip_axis_form = hip_axis[1] Hip_center_form = hip_axis[0] R_Knee_axis_form = knee_JC[2][0] R_Knee_center_form = knee_JC[0] L_Knee_axis_form = knee_JC[2][1] L_Knee_center_form = knee_JC[1] #make the array which will be the input of findangle function hip_Axis = np.vstack([np.subtract(Hip_axis_form[0],Hip_center_form), np.subtract(Hip_axis_form[1],Hip_center_form), np.subtract(Hip_axis_form[2],Hip_center_form)]) R_knee_Axis = np.vstack([np.subtract(R_Knee_axis_form[0],R_Knee_center_form), np.subtract(R_Knee_axis_form[1],R_Knee_center_form), np.subtract(R_Knee_axis_form[2],R_Knee_center_form)]) L_knee_Axis = np.vstack([np.subtract(L_Knee_axis_form[0],L_Knee_center_form), np.subtract(L_Knee_axis_form[1],L_Knee_center_form), np.subtract(L_Knee_axis_form[2],L_Knee_center_form)]) R_pelvis_knee_angle = getangle(hip_Axis,R_knee_Axis) L_pelvis_knee_angle = getangle(hip_Axis,L_knee_Axis) rhipx=R_pelvis_knee_angle[0]*-1 rhipy=R_pelvis_knee_angle[1] rhipz=R_pelvis_knee_angle[2]*-1+90 lhipx=L_pelvis_knee_angle[0]*-1 lhipy=L_pelvis_knee_angle[1]*-1 lhipz=L_pelvis_knee_angle[2]-90 ankle_JC = ankleJointCenter(frame,knee_JC,0,vsk=vsk) kin_R_Ankle_JC = ankle_JC[0] #quick fix for storing JC kin_L_Ankle_JC = ankle_JC[1] #quick fix for storing JC #change to same format R_Ankle_axis_form = ankle_JC[2][0] R_Ankle_center_form = ankle_JC[0] L_Ankle_axis_form = ankle_JC[2][1] L_Ankle_center_form = ankle_JC[1] #make the array which will be the input of findangle function # In case of knee axis I mentioned it before as R_knee_Axis and L_knee_Axis R_ankle_Axis = np.vstack([np.subtract(R_Ankle_axis_form[0],R_Ankle_center_form), np.subtract(R_Ankle_axis_form[1],R_Ankle_center_form), np.subtract(R_Ankle_axis_form[2],R_Ankle_center_form)]) L_ankle_Axis = np.vstack([np.subtract(L_Ankle_axis_form[0],L_Ankle_center_form), np.subtract(L_Ankle_axis_form[1],L_Ankle_center_form), np.subtract(L_Ankle_axis_form[2],L_Ankle_center_form)]) R_knee_ankle_angle = getangle(R_knee_Axis,R_ankle_Axis) L_knee_ankle_angle = getangle(L_knee_Axis,L_ankle_Axis) rkneex=R_knee_ankle_angle[0] rkneey=R_knee_ankle_angle[1] rkneez=R_knee_ankle_angle[2]*-1+90 lkneex=L_knee_ankle_angle[0] lkneey=L_knee_ankle_angle[1]*-1 lkneez=L_knee_ankle_angle[2] - 90 # ANKLE ANGLE offset = 0 foot_JC = footJointCenter(frame,vsk,ankle_JC,knee_JC,offset) kin_R_Foot_JC = foot_JC[0] #quick fix for storing JC kin_L_Foot_JC = foot_JC[1] #quick fix for storing JC kin_RHEE = frame['RHEE'] kin_LHEE = frame['LHEE'] # Change to same format R_Foot_axis_form = foot_JC[2][0] R_Foot_center_form = foot_JC[0] L_Foot_axis_form = foot_JC[2][1] L_Foot_center_form = foot_JC[1] R_foot_Axis = np.vstack([np.subtract(R_Foot_axis_form[0],R_Foot_center_form), np.subtract(R_Foot_axis_form[1],R_Foot_center_form), np.subtract(R_Foot_axis_form[2],R_Foot_center_form)]) L_foot_Axis = np.vstack([np.subtract(L_Foot_axis_form[0],L_Foot_center_form), np.subtract(L_Foot_axis_form[1],L_Foot_center_form), np.subtract(L_Foot_axis_form[2],L_Foot_center_form)]) R_ankle_foot_angle = getangle(R_ankle_Axis,R_foot_Axis) L_ankle_foot_angle = getangle(L_ankle_Axis,L_foot_Axis) ranklex=R_ankle_foot_angle[0]*(-1)-90 rankley=R_ankle_foot_angle[2]*(-1)+90 ranklez=R_ankle_foot_angle[1] lanklex=L_ankle_foot_angle[0]*(-1)-90 lankley=L_ankle_foot_angle[2]-90 lanklez=L_ankle_foot_angle[1]*(-1) # ABSOLUTE FOOT ANGLE R_global_foot_angle = getangle(global_Axis,R_foot_Axis) L_global_foot_angle = getangle(global_Axis,L_foot_Axis) rfootx=R_global_foot_angle[0] rfooty=R_global_foot_angle[2]-90 rfootz=R_global_foot_angle[1] lfootx=L_global_foot_angle[0] lfooty=(L_global_foot_angle[2]-90)*-1 lfootz=L_global_foot_angle[1]*-1 #First Calculate HEAD head_axis = headJC(frame,vsk=vsk) kin_Head_JC = head_axis[1] #quick fix for storing JC LFHD = frame['LFHD'] #as above RFHD = frame['RFHD'] LBHD = frame['LBHD'] RBHD = frame['RBHD'] kin_Head_Front = np.array((LFHD+RFHD)/2) kin_Head_Back = np.array((LBHD+RBHD)/2) #change to same format Head_axis_form = head_axis[0] Head_center_form = head_axis[1] #Global_axis_form = [[0,1,0],[-1,0,0],[0,0,1]] Global_center_form = [0,0,0] #*********************************************************** Global_axis_form = vsk['GCS'] #Global_axis_form = rotmat(x=0,y=0,z=180) #this is some weird fix to global axis #make the array which will be the input of findangle function head_Axis_mod = np.vstack([np.subtract(Head_axis_form[0],Head_center_form), np.subtract(Head_axis_form[1],Head_center_form), np.subtract(Head_axis_form[2],Head_center_form)]) global_Axis = np.vstack([np.subtract(Global_axis_form[0],Global_center_form),
np.subtract(Global_axis_form[1],Global_center_form)
numpy.subtract
import logging import numpy as np import matplotlib.pyplot as plt from numpy import imag, real, where from scipy import linalg from .dmd import get_dmd, get_amplitude_spectrum, find_possible_ranks logger = logging.getLogger(__name__) class Postprocessor: """Postprocessor of the simulation results. Parameters ---------- t : ndarray Values of time. d : ndarray Values of the perturbation of detonation velocity. growth_rate_tol : float, optional Tolerance for the growth rate (default is 1e-3). When the growth rate is within the tolerance in absolute value, then the corresponding mode is considered neutrally stable. plot : bool, optional If True, then plotting will be done for spectrum, etc. Default is False. """ def __init__(self, t, d, growth_rate_tol=1e-3, plot=False): self.t = t.copy() self.d = d.copy() self._plot = plot self._plot_sigma = plot self._re_lower = growth_rate_tol # Number of rows in Hankel matrix of inputs. self._L = 1000 self._dt = (self.t[-1] - self.t[0]) / (len(self.t) - 1.0) self.d_tmp = np.copy(self.d) logger.info('Mean of time series: {:.1e}'.format(self.d_tmp.mean())) if t[-1] <= 10.0: t_cutoff = 1.0 else: t_cutoff = 10.0 logger.info('t_cutoff: {}'.format(t_cutoff)) self.t_tmp = self.t[(t >= t_cutoff)] self.d_tmp = self.d_tmp[(t >= t_cutoff)] self.tol_rank = 1e-10 def extract_stability_info(self): # Handle situation when time series is short. if self._L >= len(self.d_tmp): msg = 'Cannot construct input Hankel matrix' logger.error(msg) raise CannotConstructHankelMatrix(msg) X, Y = build_input_matrices(self.d_tmp, self._L, noise_amp=0.0) ranks = find_possible_ranks(X, threshold=self.tol_rank) U2, s2, Vh2 = linalg.svd(X, full_matrices=False) svd_result = (U2, s2, Vh2) lamdas_list, Phi_list, Psi_list, b_list = [], [], [], [] res_list, fit_list = [], [] for r in ranks: phys_lamdas, Phi, Psi, b, error_res, error_fit = \ get_lamdas_amps_errors( self.t_tmp, self.d_tmp, X, Y, svd_result, L=self._L, target_rank=r, tol_rank=self.tol_rank, plot=self._plot, plot_sigma=self._plot_sigma) logger.info('r={:3d}, err_res={:8.2e}, err_fit={:8.2e}'.format( r, error_res, error_fit)) lamdas_list.append(phys_lamdas) Phi_list.append(Phi) Psi_list.append(Psi) b_list.append(b) res_list.append(error_res) fit_list.append(error_fit) # Finding minimum error_fit error_fit_array = np.array(fit_list) idx = np.argsort(error_fit_array) if len(idx) == 1: min_idx = idx[0] else: candidate_1 = idx[0] candidate_2 = idx[1] error_1 = error_fit_array[candidate_1] error_2 = error_fit_array[candidate_2] if 0.5 <= error_1 / error_2 <= 1: if res_list[candidate_1] < res_list[candidate_2]: min_idx = candidate_1 else: min_idx = candidate_2 else: min_idx = candidate_1 logger.info('Minimum error_fit with rank={}'.format(ranks[min_idx])) phys_lamdas = lamdas_list[min_idx] Phi = Phi_list[min_idx] Psi = Psi_list[min_idx] b = b_list[min_idx] error_res = res_list[min_idx] error_fit = fit_list[min_idx] if error_fit > 1e-2: msg = 'Fit error is too large' logger.info(msg) raise PostprocessingError(msg) idx_pos_freqs = [] for i, im_part in enumerate(np.imag(phys_lamdas)): if im_part > 0.0: idx_pos_freqs.append(i) idx_neg_freqs = [] for i, im_part in enumerate(imag(phys_lamdas)): if im_part < 0.0: idx_neg_freqs.append(i) total_amps = [] for i in range(Psi.shape[0]): total_amps.append(linalg.norm(Psi[i, :])) total_amps = np.array(total_amps) total_amps[idx_pos_freqs] = 2*total_amps[idx_pos_freqs] total_amps[idx_neg_freqs] = 2*total_amps[idx_neg_freqs] max_total_amp = total_amps.max() total_amps = total_amps / max_total_amp # Plot amplitude spectrum. if self._plot: plt.figure() plt.plot(real(phys_lamdas), imag(phys_lamdas), 'p', markersize=12, markeredgecolor='k') plt.xlabel('Real part of eigenvalue') plt.ylabel('Imag part of eigenvalue') plt.tight_layout(pad=0.1) plt.show() idx = np.where(real(phys_lamdas) > -self._re_lower)[0] freq, amps = get_amplitude_spectrum(phys_lamdas, b, self._L) plt.figure() plt.semilogy(freq, total_amps, 'o') plt.semilogy(freq[idx], total_amps[idx], 'ro') plt.xlabel('Linear frequency (like in FFT)') plt.ylabel('Amplitude, scaled by eigenvalue') plt.tight_layout(pad=0.1) plt.show() # Plot DMD modes. plt.figure() for i in range(Phi.shape[1]): plt.plot(self.t_tmp, Psi[i, :], label=str(i)) logger.info('{0:3d} {1:20f} {2:6.2e}'.format( i, phys_lamdas[i], total_amps[i])) plt.xlabel('Time') plt.ylabel('DMD modes') plt.legend(loc='best') plt.tight_layout(pad=0.1) plt.show() # Removal of spurious modes. unstable_eigvals_idx = where(real(phys_lamdas) >= -self._re_lower)[0] stable_eigvals_idx = where(real(phys_lamdas) < -self._re_lower)[0] spurious_idx = [] for i in unstable_eigvals_idx: cond_1 = np.any(total_amps[i] < total_amps[stable_eigvals_idx]) cond_2 = total_amps[i] < 1e-4 if cond_1 and cond_2: spurious_idx.append(i) phys_lamdas_new = [] total_amps_new = [] b_new = [] for i in range(len(phys_lamdas)): if i in spurious_idx: logger.info('Remove spurious unstable mode {}'.format(i)) continue phys_lamdas_new.append(phys_lamdas[i]) total_amps_new.append(total_amps[i]) b_new.append(b[i]) phys_lamdas = np.array(phys_lamdas_new) total_amps = np.array(total_amps_new) b = np.array(b_new) # Check for false unstable mode (see Exp. 44): pos_idx = where(real(phys_lamdas) > 0)[0] if len(pos_idx) == 1: d_ = self.d_tmp mid = len(d_) // 2 norm_1, norm_2 = linalg.norm(d_[:mid], 2), linalg.norm(d_[mid:], 2) # If norm_1 is larger than norm_2 than it's stable detonation, # and unstable mode is false. if norm_1 > norm_2: logger.info('Remove spurious unstable eigenvalue') idx = np.where(np.real(phys_lamdas) <= 0)[0] phys_lamdas = phys_lamdas[idx] b = b[idx] total_amps = total_amps[idx] assert len(phys_lamdas) >= 1 lamdas, amps = get_discrete_physical_eigenvalues_and_amplitudes( phys_lamdas, total_amps, re_lower=self._re_lower) assert len(lamdas) >= 1 # TODO: stop returning results here. # Client should read the below properties instead. self.modes = np.array(lamdas) self.error_res = error_res self.error_fit = error_fit return lamdas, error_res, error_fit def get_lamdas_amps_errors(t, d, X, Y, svd_result, L=1000, target_rank=None, tol_rank=None, plot=False, plot_sigma=False, alg='exact'): lamda, Phi, Psi, amplitudes, d_hat, error_res = get_dmd( t, X, Y, svd_result, target_rank=target_rank, tol=tol_rank, plot_sigma=plot_sigma, alg=alg) # Compute fit error error_fit = np.linalg.norm(d_hat - d, 2) / np.linalg.norm(d, 2) if plot: plt.figure() plt.plot(t, d, '-') plt.plot(t, d_hat, '--') plt.show() return lamda, Phi, Psi, amplitudes, error_res, error_fit def build_input_matrices(z, L, noise_amp=0.0): A = linalg.hankel(c=z[0:L], r=z[L-1:]) if noise_amp != 0.0: m, n = A.shape A = A + noise_amp*np.random.randn(m, n) return A[:, :-1], A[:, 1:] def get_physical_eigenvalues(lamdas, tol=None): """Find only physical eigenvalues. Parameters ---------- lamdas : ndarray Array of eigenvalues from which physical ones will be chosen. tol : float Tolerance of eigenvalues. printed to the screen. Returns ------- x : ndarray Array of physical eigenvalues. """ assert len(lamdas) == 2, \ 'Two sets of eigenvalues are required to find physical eigenvalues.' default_tol = 1 if tol is None: # print('Using default tol={}.'.format(default_tol)) tol = default_tol phys_lamdas = [] for i, lam_root in enumerate(lamdas[1]): min_dist = np.min(np.abs(lam_root - lamdas[0])) / np.abs(lam_root) if min_dist <= tol: phys_lamdas.append(lam_root) if len(phys_lamdas) == 0: msg = ('Cannot find physical eigenvalues that shifted with distance ' 'less than {}'.format(tol)) logger.info(msg) raise CannotFindPhysicalEigenvalues(msg) return
np.asarray(phys_lamdas)
numpy.asarray
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import sys import numpy as np import tensorflow as tf from scipy import misc app_path = os.environ['APP_PATH'] for p in app_path.split(';'): sys.path.append(p) import os import copy import facenet import align.detect_face from common import config_fetcher from kafka import KafkaConsumer from kafka import KafkaProducer import json from bean import event servers = config_fetcher.bootstrap_hosts group_id = config_fetcher.group_id compare_topic = config_fetcher.compare_topic aggregate_topic = config_fetcher.aggregate_topic model = config_fetcher.model # To consume latest messages and auto-commit offsets consumer = KafkaConsumer(compare_topic, group_id = group_id, bootstrap_servers = servers, value_deserializer=lambda m: json.loads(m.decode('ascii'))) producer = KafkaProducer(value_serializer=lambda v:json.dumps(v).encode('utf-8'), bootstrap_servers = servers) def execute(): # images = load_and_align_data(image_files, image_size, margin, gpu_memory_fraction) with tf.Graph().as_default(): with tf.Session() as sess: # Load the model facenet.load_model(model) ######################################################################################################### ############################################# Split Line ################################################ ######################################################################################################### print('load model done...') for message in consumer: try: request = message.value image_files = request['face_extract_path'] target_extract_path = request['target_extract_path'] image_files.insert(0, target_extract_path) print("get a request") images = load_and_align_data(image_files, config_fetcher.compare_is, config_fetcher.compare_margin, config_fetcher.compare_gmf) # Get input and output tensors images_placeholder = tf.get_default_graph().get_tensor_by_name("input:0") embeddings = tf.get_default_graph().get_tensor_by_name("embeddings:0") phase_train_placeholder = tf.get_default_graph().get_tensor_by_name("phase_train:0") # Run forward pass to calculate embeddings feed_dict = {images_placeholder: images, phase_train_placeholder: False} emb = sess.run(embeddings, feed_dict=feed_dict) nrof_images = len(image_files) print_target_images(nrof_images, image_files) print_result_matrix(np, nrof_images, emb) fr = extract_final_result(np, nrof_images, emb) result = False for r in fr: if r < 1: result = True break next_request = build_next_request(request, result, '') print('-----------------------------------') print(event.convert_to_dict(next_request)) producer.send(aggregate_topic, next_request) print('-----------------------------------') print("process one request done...") except Exception as e: print(e) def extract_final_result(np, nrof_images, emb): final_result = [] for j in range(1, nrof_images): dist = np.sqrt(np.sum(np.square(np.subtract(emb[0, :], emb[j, :])))) final_result.append(dist) return final_result def print_target_images(nrof_images, image_files): print('Images:') for i in range(nrof_images): print('%1d: %s' % (i, image_files[i])) print('') def print_result_matrix(np, nrof_images, emb): # Print distance matrix print('Distance matrix') print(' ', end='') for i in range(nrof_images): print(' %1d ' % i, end='') print('') for i in range(nrof_images): print('%1d ' % i, end='') for j in range(nrof_images): dist = np.sqrt(np.sum(np.square(np.subtract(emb[i, :], emb[j, :])))) print(' %1.4f ' % dist, end='') print('') def load_and_align_data(image_paths, image_size, margin, gpu_memory_fraction): minsize = 20 # minimum size of face threshold = [0.6, 0.7, 0.7] # three steps's threshold factor = 0.709 # scale factor print('Creating networks and loading parameters') with tf.Graph().as_default(): gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_memory_fraction) sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False)) with sess.as_default(): pnet, rnet, onet = align.detect_face.create_mtcnn(sess, None) tmp_image_paths = copy.copy(image_paths) img_list = [] for image in tmp_image_paths: img = misc.imread(os.path.expanduser(image), mode='RGB') img_size = np.asarray(img.shape)[0:2] bounding_boxes, _ = align.detect_face.detect_face(img, minsize, pnet, rnet, onet, threshold, factor) if len(bounding_boxes) < 1: image_paths.remove(image) print("can't detect face, remove ", image) continue det = np.squeeze(bounding_boxes[0, 0:4]) bb = np.zeros(4, dtype=np.int32) bb[0] = np.maximum(det[0] - margin / 2, 0) bb[1] =
np.maximum(det[1] - margin / 2, 0)
numpy.maximum
""" Various low-dimensional dynamical systems in Python. For flows that occur on unbounded intervals (eg non-autonomous systems), coordinates are transformed to a basis where the domain remains bounded Requirements: + numpy + scipy + sdeint (for integration with noise) + numba (optional, for faster integration) """ import numpy as np from .base import DynSys, DynSysDelay, staticjit class Lorenz(DynSys): @staticjit def _rhs(x, y, z, t, beta, rho, sigma): xdot = sigma * (y - x) ydot = x * (rho - z) - y zdot = x * y - beta * z return xdot, ydot, zdot @staticjit def _jac(x, y, z, t, beta, rho, sigma): row1 = [-sigma, sigma, 0] row2 = [rho - z, -1, -x] row3 = [y, x, -beta] return [row1, row2, row3] class LorenzBounded(DynSys): @staticjit def _rhs(x, y, z, t, beta, r, rho, sigma): f = 1 - (x ** 2 + y ** 2 + z ** 2) / r ** 2 xdot = sigma * (y - x) * f ydot = (x * (rho - z) - y) * f zdot = (x * y - beta * z) * f return xdot, ydot, zdot class LorenzCoupled(DynSys): @staticjit def _rhs(x1, y1, z1, x2, y2, z2, t, beta, eps, rho, rho1, rho2, sigma): x1dot = sigma * (y1 - x1) y1dot = x1 * (rho1 - z1) - y1 z1dot = x1 * y1 - beta * z1 x2dot = sigma * (y2 - x2) + eps * (x1 - x2) y2dot = x2 * (rho2 - z2) - y2 z2dot = x2 * y2 - beta * z2 return x1dot, y1dot, z1dot, x2dot, y2dot, z2dot class Lorenz96(DynSys): def rhs(self, X, t): Xdot = np.zeros_like(X) Xdot[0] = (X[1] - X[-2]) * X[-1] - X[0] + self.f Xdot[1] = (X[2] - X[-1]) * X[0] - X[1] + self.f Xdot[-1] = (X[0] - X[-3]) * X[-2] - X[-1] + self.f Xdot[2:-1] = (X[3:] - X[:-3]) * X[1:-2] - X[2:-1] + self.f return Xdot class Lorenz84(DynSys): @staticjit def _rhs(x, y, z, t, a, b, f, g): xdot = -a * x - y ** 2 - z ** 2 + a * f ydot = -y + x * y - b * x * z + g zdot = -z + b * x * y + x * z return xdot, ydot, zdot class Rossler(DynSys): @staticjit def _rhs(x, y, z, t, a, b, c): xdot = -y - z ydot = x + a * y zdot = b + z * (x - c) return xdot, ydot, zdot class Thomas(DynSys): @staticjit def _rhs(x, y, z, t, a, b): xdot = -a * x + b * np.sin(y) ydot = -a * y + b * np.sin(z) zdot = -a * z + b * np.sin(x) return xdot, ydot, zdot class ThomasLabyrinth(Thomas): pass class DoublePendulum(DynSys): @staticjit def _rhs(th1, th2, p1, p2, t, d, m): g = 9.82 pre = 6 / (m * d ** 2) denom = 16 - 9 * np.cos(th1 - th2) ** 2 th1_dot = pre * (2 * p1 - 3 * np.cos(th1 - th2) * p2) / denom th2_dot = pre * (8 * p2 - 3 * np.cos(th1 - th2) * p1) / denom p1_dot = ( -0.5 * (m * d ** 2) * (th1_dot * th2_dot * np.sin(th1 - th2) + 3 * (g / d) * np.sin(th1)) ) p2_dot = ( -0.5 * (m * d ** 2) * (-th1_dot * th2_dot * np.sin(th1 - th2) + 3 * (g / d) * np.sin(th2)) ) return th1_dot, th2_dot, p1_dot, p2_dot @staticjit def _postprocessing(th1, th2, p1, p2): return np.sin(th1), np.sin(th2), p1, p2 class SwingingAtwood(DynSys): @staticjit def _rhs(r, th, pr, pth, t, m1, m2): g = 9.82 rdot = pr / (m1 + m2) thdot = pth / (m1 * r ** 2) prdot = pth ** 2 / (m1 * r ** 3) - m2 * g + m1 * g * np.cos(th) pthdot = -m1 * g * r * np.sin(th) return rdot, thdot, prdot, pthdot @staticjit def _postprocessing(r, th, pr, pth): return r, np.sin(th), pr, pth class GuckenheimerHolmes(DynSys): @staticjit def _rhs(x, y, z, t, a, b, c, d, e, f): xdot = a * x - b * y + c * z * x + d * z * (x ** 2 + y ** 2) ydot = a * y + b * x + c * z * y zdot = e - z ** 2 - f * (x ** 2 + y ** 2) - a * z ** 3 return xdot, ydot, zdot class HenonHeiles(DynSys): @staticjit def _rhs(x, y, px, py, t, lam): xdot = px ydot = py pxdot = -x - 2 * lam * x * y pydot = -y - lam * (x ** 2 - y ** 2) return xdot, ydot, pxdot, pydot class Halvorsen(DynSys): @staticjit def _rhs(x, y, z, t, a, b): xdot = -a * x - b * (y + z) - y ** 2 ydot = -a * y - b * (z + x) - z ** 2 zdot = -a * z - b * (x + y) - x ** 2 return xdot, ydot, zdot class Chua(DynSys): @staticjit def _rhs(x, y, z, t, alpha, beta, m0, m1): ramp_x = m1 * x + 0.5 * (m0 - m1) * (np.abs(x + 1) - np.abs(x - 1)) xdot = alpha * (y - x - ramp_x) ydot = x - y + z zdot = -beta * y return xdot, ydot, zdot class MultiChua(DynSys): def diode(self, x): m, c = self.m, self.c total = m[-1] * x for i in range(1, 6): total += 0.5 * (m[i - 1] - m[i]) * (np.abs(x + c[i]) - np.abs(x - c[i])) return total def rhs(self, X, t): x, y, z = X xdot = self.a * (y - self.diode(x)) ydot = x - y + z zdot = -self.b * y return (xdot, ydot, zdot) class Duffing(DynSys): @staticjit def _rhs(x, y, z, t, alpha, beta, delta, gamma, omega): xdot = y ydot = -delta * y - beta * x - alpha * x ** 3 + gamma * np.cos(z) zdot = omega return xdot, ydot, zdot @staticjit def _postprocessing(x, y, z): return x, y, np.cos(z) class MackeyGlass(DynSysDelay): @staticjit def _rhs(x, xt, t, beta, gamma, n, tau): xdot = beta * (xt / (1 + xt ** n)) - gamma * x return xdot class IkedaDelay(DynSysDelay): @staticjit def _rhs(x, xt, t, c, mu, tau, x0): xdot = mu * np.sin(xt - x0) - c * x return xdot class SprottDelay(IkedaDelay): pass class VossDelay(DynSysDelay): @staticjit def _rhs(x, xt, t, alpha, tau): f = -10.44 * xt ** 3 - 13.95 * xt ** 2 - 3.63 * xt + 0.85 xdot = -alpha * x + f return xdot class ScrollDelay(DynSysDelay): @staticjit def _rhs(x, xt, t, alpha, beta, tau): f = np.tanh(10 * xt) xdot = -alpha * xt + beta * f return xdot class PiecewiseCircuit(DynSysDelay): @staticjit def _rhs(x, xt, t, alpha, beta, c, tau): f = -((xt / c) ** 3) + 3 * xt / c xdot = -alpha * xt + beta * f return xdot # ## this was not chaotic # class ENSODelay(DynSysDelay): # @staticjit # def _rhs(x, xt, t, alpha, beta, tau): # xdot = x - x**3 - alpha * xt + beta # return xdot class DoubleGyre(DynSys): @staticjit def _rhs(x, y, z, t, alpha, eps, omega): a = eps * np.sin(z) b = 1 - 2 * eps * np.sin(z) f = a * x ** 2 + b * x dx = -alpha * np.pi * np.sin(np.pi * f) * np.cos(np.pi * y) dy = alpha * np.pi * np.cos(np.pi * f) * np.sin(np.pi * y) * (2 * a * x + b) dz = omega return dx, dy, dz @staticjit def _postprocessing(x, y, z): return x, y, np.sin(z) class BlinkingRotlet(DynSys): @staticjit def _rotlet(r, theta, a, b, bc): """A rotlet velocity field""" kappa = a ** 2 + (b ** 2 * r ** 2) / a ** 2 - 2 * b * r * np.cos(theta) gamma = (1 - r ** 2 / a ** 2) * (a ** 2 - (b ** 2 * r ** 2) / a ** 2) iota = (b ** 2 * r) / a ** 2 - b * np.cos(theta) zeta = b ** 2 + r ** 2 - 2 * b * r * np.cos(theta) nu = a ** 2 + b ** 2 - (2 * b ** 2 * r ** 2) / a ** 2 vr = b * np.sin(theta) * (-bc * (gamma / kappa ** 2) - 1 / kappa + 1 / zeta) vth = ( bc * (gamma * iota) / kappa ** 2 + bc * r * nu / (a ** 2 * kappa) + iota / kappa - (r - b * np.cos(theta)) / zeta ) return vr, vth @staticjit def _protocol(t, tau, stiffness=20): return 0.5 + 0.5 * np.tanh(tau * stiffness * np.sin(2 * np.pi * t / tau)) def rhs(self, X, t): r, theta, tt = X weight = self._protocol(tt, self.tau) dr1, dth1 = self._rotlet(r, theta, self.a, self.b, self.bc) dr2, dth2 = self._rotlet(r, theta, self.a, -self.b, self.bc) dr = weight * dr1 + (1 - weight) * dr2 dth = (weight * dth1 + (1 - weight) * dth2) / r dtt = 1 return self.sigma * dr, self.sigma * dth, dtt def _postprocessing(self, r, th, tt): return r * np.cos(th), r * np.sin(th), np.sin(2 * np.pi * tt / self.tau) class BlinkingVortex(BlinkingRotlet): pass class OscillatingFlow(DynSys): @staticjit def _rhs(x, y, z, t, b, k, omega, u): f = x + b * np.sin(z) dx = u * np.cos(k * y) * np.sin(k * f) dy = -u * np.sin(k * y) * np.cos(k * f) dz = omega return dx, dy, dz def _postprocessing(self, x, y, z): return np.cos(self.k * x), y, np.sin(z) class BickleyJet(DynSys): @staticjit def _rhs(y, x, z, t, ell, eps, k, omega, sigma, u): sechy = 1 / np.cosh(y / ell) inds = np.arange(3) un = k[inds] * (x - z * sigma[inds]) dx = u * sechy ** 2 * (-1 - 2 * np.dot(np.cos(un), eps) * np.tanh(y / ell)) dy = ell * u * sechy ** 2 * np.dot(eps * k, np.sin(un)) dz = omega return dy, dx, dz def _postprocessing(self, x, y, z): km = np.min(self.k) sm = np.min(self.sigma) return x, np.sin(km * y), np.sin(self.omega * z * km * sm) class ArnoldBeltramiChildress(DynSys): @staticjit def _rhs(x, y, z, t, a, b, c): dx = a * np.sin(z) + c * np.cos(y) dy = b * np.sin(x) + a * np.cos(z) dz = c * np.sin(y) + b * np.cos(x) return dx, dy, dz @staticjit def _postprocessing(x, y, z): return np.sin(x), np.cos(y), np.sin(z) class JerkCircuit(DynSys): @staticjit def _rhs(x, y, z, t, eps, y0): xdot = y ydot = z zdot = -z - x - eps * (np.exp(y / y0) - 1) return xdot, ydot, zdot class ForcedBrusselator(DynSys): @staticjit def _rhs(x, y, z, t, a, b, f, w): xdot = a + x ** 2 * y - (b + 1) * x + f * np.cos(z) ydot = b * x - x ** 2 * y zdot = w return xdot, ydot, zdot @staticjit def _postprocessing(x, y, z): return x, y, np.sin(z) class WindmiReduced(DynSys): @staticjit def _rhs(i, v, p, t, a1, b1, b2, b3, d1, vsw): idot = a1 * (vsw - v) vdot = b1 * i - b2 * p ** 1 / 2 - b3 * v pdot = ( vsw ** 2 - p ** (5 / 4) * vsw ** (1 / 2) * (1 + np.tanh(d1 * (i - 1))) / 2 ) return idot, vdot, pdot class MooreSpiegel(DynSys): @staticjit def _rhs(x, y, z, t, a, b, eps): xdot = y ydot = a * z zdot = -z + eps * y - y * x ** 2 - b * x return xdot, ydot, zdot class CoevolvingPredatorPrey(DynSys): @staticjit def _rhs(x, y, alpha, t, a1, a2, a3, b1, b2, d1, d2, delta, k1, k2, k4, vv): xdot = x * ( -((a3 * y) / (1 + b2 * x)) + (a1 * alpha * (1 - k1 * x * (-alpha + alpha * delta))) / (1 + b1 * alpha) - d1 * ( 1 - k2 * (-(alpha ** 2) + (alpha * delta) ** 2) + k4 * (-(alpha ** 4) + (alpha * delta) ** 4) ) ) ydot = (-d2 + (a2 * x) / (1 + b2 * x)) * y alphadot = vv * ( -((a1 * k1 * x * alpha * delta) / (1 + b1 * alpha)) - d1 * (-2 * k2 * alpha * delta ** 2 + 4 * k4 * alpha ** 3 * delta ** 4) ) return xdot, ydot, alphadot class KawczynskiStrizhak(DynSys): @staticjit def _rhs(x, y, z, t, beta, gamma, kappa, mu): xdot = gamma * (y - x ** 3 + 3 * mu * x) ydot = -2 * mu * x - y - z + beta zdot = kappa * (x - z) return xdot, ydot, zdot class BelousovZhabotinsky(DynSys): @staticjit def _rhs( x, z, v, t, c1, c10, c11, c12, c13, c2, c3, c4, c5, c6, c7, c8, c9, ci, kf, t0, y0, yb1, yb2, yb3, z0, ): ybar = (1 / y0) * yb1 * z * v / (yb2 * x + yb3 + kf) if x < 0.0: x = 0 rf = (ci - z0 * z) * np.sqrt(x) xdot = c1 * x * ybar + c2 * ybar + c3 * x ** 2 + c4 * rf + c5 * x * z - kf * x zdot = (c6 / z0) * rf + c7 * x * z + c8 * z * v + c9 * z - kf * z vdot = c10 * x * ybar + c11 * ybar + c12 * x ** 2 + c13 * z * v - kf * v return xdot * t0, zdot * t0, vdot * t0 class IsothermalChemical(DynSys): @staticmethod def _rhs(alpha, beta, gamma, t, delta, kappa, mu, sigma): alphadot = mu * (kappa + gamma) - alpha * beta ** 2 - alpha betadot = (alpha * beta ** 2 + alpha - beta) / sigma gammadot = (beta - gamma) / delta return alphadot, betadot, gammadot class VallisElNino(DynSys): @staticmethod def _rhs(x, y, z, t, b, c, p): xdot = b * y - c * (x + p) ydot = -y + x * z zdot = -z - x * y + 1 return xdot, ydot, zdot class RabinovichFabrikant(DynSys): @staticjit def _rhs(x, y, z, t, a, g): xdot = y * (z - 1 + x ** 2) + g * x ydot = x * (3 * z + 1 - x ** 2) + g * y zdot = -2 * z * (a + x * y) return (xdot, ydot, zdot) class NoseHoover(DynSys): @staticjit def _rhs(x, y, z, t, a): xdot = y ydot = -x + y * z zdot = a - y ** 2 return xdot, ydot, zdot class Dadras(DynSys): @staticjit def _rhs(x, y, z, t, c, e, o, p, r): xdot = y - p * x + o * y * z ydot = r * y - x * z + z zdot = c * x * y - e * z return xdot, ydot, zdot class RikitakeDynamo(DynSys): @staticjit def _rhs(x, y, z, t, a, mu): xdot = -mu * x + y * z ydot = -mu * y + x * (z - a) zdot = 1 - x * y return xdot, ydot, zdot class NuclearQuadrupole(DynSys): @staticjit def _rhs(q1, q2, p1, p2, t, a, b, d): q1dot = a * p1 q2dot = a * p2 p1dot = ( -(a * q1) + (3 * b * (q1 ** 2 - q2 ** 2)) / np.sqrt(2) - d * q1 * (q1 ** 2 + q2 ** 2) ) p2dot = -(q2 * (a + 3 * np.sqrt(2) * b * q1 + d * (q1 ** 2 + q2 ** 2))) return q1dot, q2dot, p1dot, p2dot class PehlivanWei(DynSys): @staticjit def _rhs(x, y, z, t): xdot = y - y * z ydot = y + y * z - 2 * x zdot = 2 - x * y - y ** 2 return xdot, ydot, zdot class SprottTorus(DynSys): @staticjit def _rhs(x, y, z, t): xdot = y + 2 * x * y + x * z ydot = 1 - 2 * x ** 2 + y * z zdot = x - x ** 2 - y ** 2 return xdot, ydot, zdot class SprottJerk(DynSys): @staticjit def _rhs(x, y, z, t, mu): xdot = y ydot = z zdot = -x + y ** 2 - mu * z return xdot, ydot, zdot ## Not chaotic # class JerkCircuit(DynSys): # def rhs(self, X, t): # x, y, z = X # xdot = y # ydot = z # zdot = -z - x - self.eps*(np.exp(y/self.y0) - 1) # return (xdot, ydot, zdot) class SprottA(DynSys): @staticjit def _rhs(x, y, z, t): xdot = y ydot = -x + y * z zdot = 1 - y ** 2 return xdot, ydot, zdot class SprottB(DynSys): @staticjit def _rhs(x, y, z, t): xdot = y * z ydot = x - y zdot = 1 - x * y return xdot, ydot, zdot class SprottC(DynSys): @staticjit def _rhs(x, y, z, t): xdot = y * z ydot = x - y zdot = 1 - x ** 2 return xdot, ydot, zdot class SprottD(DynSys): @staticjit def _rhs(x, y, z, t): xdot = -y ydot = x + z zdot = x * z + 3 * y ** 2 return xdot, ydot, zdot class SprottE(DynSys): @staticjit def _rhs(x, y, z, t): xdot = y * z ydot = x ** 2 - y zdot = 1 - 4 * x return xdot, ydot, zdot class SprottF(DynSys): @staticjit def _rhs(x, y, z, t, a): xdot = y + z ydot = -x + a * y zdot = x ** 2 - z return xdot, ydot, zdot class SprottG(DynSys): @staticjit def _rhs(x, y, z, t, a): xdot = a * x + z ydot = x * z - y zdot = -x + y return xdot, ydot, zdot class SprottH(DynSys): @staticjit def _rhs(x, y, z, t, a): xdot = -y + z ** 2 ydot = x + a * y zdot = x - z return xdot, ydot, zdot class SprottI(DynSys): @staticjit def _rhs(x, y, z, t, a): xdot = -a * y ydot = x + z zdot = x + y ** 2 - z return xdot, ydot, zdot class SprottJ(DynSys): @staticjit def _rhs(x, y, z, t): xdot = 2 * z ydot = -2 * y + z zdot = -x + y + y ** 2 return (xdot, ydot, zdot) class SprottK(DynSys): @staticjit def _rhs(x, y, z, t, a): xdot = x * y - z ydot = x - y zdot = x + a * z return xdot, ydot, zdot class SprottL(DynSys): @staticjit def _rhs(x, y, z, t, a, b): xdot = y + b * z ydot = a * x ** 2 - y zdot = 1 - x return xdot, ydot, zdot class SprottM(DynSys): @staticjit def _rhs(x, y, z, t, a): xdot = -z ydot = -(x ** 2) - y zdot = a * (1 + x) + y return xdot, ydot, zdot class SprottN(DynSys): @staticjit def _rhs(x, y, z, t): xdot = -2 * y ydot = x + z ** 2 zdot = 1 + y - 2 * z return xdot, ydot, zdot class SprottO(DynSys): @staticjit def _rhs(x, y, z, t, a): xdot = y ydot = x - z zdot = x + x * z + a * y return xdot, ydot, zdot class SprottP(DynSys): @staticjit def _rhs(x, y, z, t, a): xdot = a * y + z ydot = -x + y ** 2 zdot = x + y return xdot, ydot, zdot class SprottQ(DynSys): @staticjit def _rhs(x, y, z, t, a, b): xdot = -z ydot = x - y zdot = a * x + y ** 2 + b * z return (xdot, ydot, zdot) class SprottR(DynSys): @staticjit def _rhs(x, y, z, t, a, b): xdot = a - y ydot = b + z zdot = x * y - z return xdot, ydot, zdot class SprottS(DynSys): @staticjit def _rhs(x, y, z, t): xdot = -x - 4 * y ydot = x + z ** 2 zdot = 1 + x return xdot, ydot, zdot class SprottMore(DynSys): @staticjit def _rhs(x, y, z, t): xdot = y ydot = -x - np.sign(z) * y zdot = y ** 2 - np.exp(-(x ** 2)) return xdot, ydot, zdot class Arneodo(DynSys): @staticjit def _rhs(x, y, z, t, a, b, c, d): xdot = y ydot = z zdot = -a * x - b * y - c * z + d * x ** 3 return xdot, ydot, zdot class Coullet(Arneodo): pass class Rucklidge(DynSys): @staticjit def _rhs(x, y, z, t, a, b): xdot = -a * x + b * y - y * z ydot = x zdot = -z + y ** 2 return xdot, ydot, zdot class Sakarya(DynSys): @staticjit def _rhs(x, y, z, t, a, b, c, h, p, q, r, s): xdot = a * x + h * y + s * y * z ydot = -b * y - p * x + q * x * z zdot = c * z - r * x * y return xdot, ydot, zdot class LiuChen(Sakarya): pass class RayleighBenard(DynSys): @staticjit def _rhs(x, y, z, t, a, b, r): xdot = a * (y - x) ydot = r * y - x * z zdot = x * y - b * z return xdot, ydot, zdot class Finance(DynSys): @staticjit def _rhs(x, y, z, t, a, b, c): xdot = (1 / b - a) * x + z + x * y ydot = -b * y - x ** 2 zdot = -x - c * z return xdot, ydot, zdot class Bouali2(DynSys): @staticjit def _rhs(x, y, z, t, a, b, bb, c, g, m, y0): xdot = a * x * (y0 - y) - b * z ydot = -g * y * (1 - x ** 2) zdot = -m * x * (1.5 - bb * z) - c * z return xdot, ydot, zdot class Bouali(Bouali2): pass class LuChenCheng(DynSys): @staticjit def _rhs(x, y, z, t, a, b, c): xdot = -(a * b) / (a + b) * x - y * z + c ydot = a * y + x * z zdot = b * z + x * y return xdot, ydot, zdot class LuChen(DynSys): @staticjit def _rhs(x, y, z, t, a, b, c): xdot = a * (y - x) ydot = -x * z + c * y zdot = x * y - b * z return xdot, ydot, zdot class QiChen(DynSys): @staticjit def _rhs(x, y, z, t, a, b, c): xdot = a * (y - x) + y * z ydot = c * x + y - x * z zdot = x * y - b * z return xdot, ydot, zdot class ZhouChen(DynSys): @staticjit def _rhs(x, y, z, t, a, b, c, d, e): xdot = a * x + b * y + y * z ydot = c * y - x * z + d * y * z zdot = e * z - x * y return xdot, ydot, zdot class BurkeShaw(DynSys): @staticjit def _rhs(x, y, z, t, e, n): xdot = -n * (x + y) ydot = y - n * x * z zdot = n * x * y + e return xdot, ydot, zdot class Chen(DynSys): @staticjit def _rhs(x, y, z, t, a, b, c): xdot = a * (y - x) ydot = (c - a) * x - x * z + c * y zdot = x * y - b * z return xdot, ydot, zdot class ChenLee(DynSys): @staticjit def _rhs(x, y, z, t, a, b, c): xdot = a * x - y * z ydot = b * y + x * z zdot = c * z + x * y / 3 return xdot, ydot, zdot class WangSun(DynSys): @staticjit def _rhs(x, y, z, t, a, b, d, e, f, q): xdot = a * x + q * y * z ydot = b * x + d * y - x * z zdot = e * z + f * x * y return xdot, ydot, zdot class YuWang(DynSys): @staticjit def _rhs(x, y, z, t, a, b, c, d): xdot = a * (y - x) ydot = b * x - c * x * z zdot = np.exp(x * y) - d * z return xdot, ydot, zdot class YuWang2(DynSys): @staticjit def _rhs(x, y, z, t, a, b, c, d): xdot = a * (y - x) ydot = b * x - c * x * z zdot = np.cosh(x * y) - d * z return xdot, ydot, zdot class SanUmSrisuchinwong(DynSys): @staticjit def _rhs(x, y, z, t, a): xdot = y - x ydot = -z * np.tanh(x) zdot = -a + x * y + np.abs(y) return xdot, ydot, zdot class DequanLi(DynSys): @staticjit def _rhs(x, y, z, t, a, c, d, eps, f, k): xdot = a * (y - x) + d * x * z ydot = k * x + f * y - x * z zdot = c * z + x * y - eps * x ** 2 return xdot, ydot, zdot class PanXuZhou(DequanLi): pass class Tsucs2(DequanLi): pass class ArnoldWeb(DynSys): @staticjit def _rhs(p1, p2, x1, x2, z, t, mu, w): denom = 4 + np.cos(z) + np.cos(x1) + np.cos(x2) p1dot = -mu * np.sin(x1) / denom ** 2 p2dot = -mu * np.sin(x2) / denom ** 2 x1dot = p1 x2dot = p2 zdot = w return p1dot, p2dot, x1dot, x2dot, zdot @staticjit def _postprocessing(p1, p2, x1, x2, z): return p1, p2, np.sin(x1), np.sin(x2), np.cos(z) class NewtonLiepnik(DynSys): @staticjit def _rhs(x, y, z, t, a, b): xdot = -a * x + y + 10 * y * z ydot = -x - 0.4 * y + 5 * x * z zdot = b * z - 5 * x * y return xdot, ydot, zdot class HyperRossler(DynSys): @staticjit def _rhs(x, y, z, w, t, a, b, c, d): xdot = -y - z ydot = x + a * y + w zdot = b + x * z wdot = -c * z + d * w return xdot, ydot, zdot, wdot class HyperLorenz(DynSys): @staticjit def _rhs(x, y, z, w, t, a, b, c, d): xdot = a * (y - x) + w ydot = -x * z + c * x - y zdot = -b * z + x * y wdot = d * w - x * z return xdot, ydot, zdot, wdot class HyperCai(DynSys): @staticjit def _rhs(x, y, z, w, t, a, b, c, d, e): xdot = a * (y - x) ydot = b * x + c * y - x * z + w zdot = -d * z + y ** 2 wdot = -e * x return xdot, ydot, zdot, wdot class HyperBao(DynSys): @staticjit def _rhs(x, y, z, w, t, a, b, c, d, e): xdot = a * (y - x) + w ydot = c * y - x * z zdot = x * y - b * z wdot = e * x + d * y * z return xdot, ydot, zdot, wdot class HyperJha(DynSys): @staticjit def _rhs(x, y, z, w, t, a, b, c, d): xdot = a * (y - x) + w ydot = -x * z + b * x - y zdot = x * y - c * z wdot = -x * z + d * w return xdot, ydot, zdot, wdot class HyperQi(DynSys): @staticjit def _rhs(x, y, z, w, t, a, b, c, d, e, f): xdot = a * (y - x) + y * z ydot = b * (x + y) - x * z zdot = -c * z - e * w + x * y wdot = -d * w + f * z + x * y return xdot, ydot, zdot, wdot class Qi(DynSys): @staticjit def _rhs(x, y, z, w, t, a, b, c, d): xdot = a * (y - x) + y * z * w ydot = b * (x + y) - x * z * w zdot = -c * z + x * y * w wdot = -d * w + x * y * z return xdot, ydot, zdot, wdot class LorenzStenflo(DynSys): @staticjit def _rhs(x, y, z, w, t, a, b, c, d): xdot = a * (y - x) + d * w ydot = x * (c - z) - y zdot = x * y - b * z wdot = -x - a * w return xdot, ydot, zdot, wdot class HyperYangChen(DynSys): @staticjit def _rhs(x, y, z, w, t, a=30, b=3, c=35, d=8): xdot = a * (y - x) ydot = c * x - x * z + w zdot = -b * z + x * y wdot = -d * x return xdot, ydot, zdot, wdot class HyperYan(DynSys): @staticjit def _rhs(x, y, z, w, t, a=37, b=3, c=26, d=38): xdot = a * (y - x) ydot = (c - a) * x - x * z + c * y zdot = -b * z + x * y - y * z + x * z - w wdot = -d * w + y * z - x * z return xdot, ydot, zdot, wdot class HyperXu(DynSys): @staticjit def _rhs(x, y, z, w, t, a=10, b=40, c=2.5, d=2, e=16): xdot = a * (y - x) + w ydot = b * x + e * x * z zdot = -c * z - x * y wdot = x * z - d * y return xdot, ydot, zdot, wdot class HyperWang(DynSys): @staticjit def _rhs(x, y, z, w, t, a=10, b=40, c=2.5, d=10.6, e=4): xdot = a * (y - x) ydot = -x * z + b * x + w zdot = -c * z + e * x ** 2 wdot = -d * x return xdot, ydot, zdot, wdot class HyperPang(DynSys): @staticjit def _rhs(x, y, z, w, t, a=36, b=3, c=20, d=2): xdot = a * (y - x) ydot = -x * z + c * y + w zdot = x * y - b * z wdot = -d * (x + y) return xdot, ydot, zdot, wdot class HyperLu(DynSys): @staticjit def _rhs(x, y, z, w, t, a=36, b=3, c=20, d=1.3): xdot = a * (y - x) + w ydot = -x * z + c * y zdot = x * y - b * z wdot = d * w + x * z return xdot, ydot, zdot, wdot class SaltonSea(DynSys): @staticjit def _rhs(x, y, z, t, a, d, k, lam, m, mu, r, th): xdot = r * x * (1 - (x + y) / k) - lam * x * y ydot = lam * x * y - m * y * z / (y + a) - mu * y zdot = th * y * z / (y + a) - d * z return xdot, ydot, zdot class ExcitableCell(DynSys): def rhs(self, X, t): v, n, c = X alpham = 0.1 * (25 + v) / (1 - np.exp(-0.1 * v - 2.5)) betam = 4 * np.exp(-(v + 50) / 18) minf = alpham / (alpham + betam) alphah = 0.07 * np.exp(-0.05 * v - 2.5) betah = 1 / (1 + np.exp(-0.1 * v - 2)) hinf = alphah / (alphah + betah) alphan = 0.01 * (20 + v) / (1 - np.exp(-0.1 * v - 2)) betan = 0.125 * np.exp(-(v + 30) / 80) ninf = alphan / (alphan + betan) tau = 1 / (230 * (alphan + betan)) ca = c / (1 + c) vdot = ( self.gi * minf ** 3 * hinf * (self.vi - v) + self.gkv * n ** 4 * (self.vk - v) + self.gkc * ca * (self.vk - v) + self.gl * (self.vl - v) ) ndot = (ninf - n) / tau cdot = self.rho * (minf ** 3 * hinf * (self.vc - v) - self.kc * c) return vdot, ndot, cdot class CaTwoPlus(DynSys): def rhs(self, X, t): z, y, a = X Vin = self.V0 + self.V1 * self.beta V2 = self.Vm2 * (z ** 2) / (self.K2 ** 2 + z ** 2) V3 = ( (self.Vm3 * (z ** self.m) / (self.Kz ** self.m + z ** self.m)) * (y ** 2 / (self.Ky ** 2 + y ** 2)) * (a ** 4 / (self.Ka ** 4 + a ** 4)) ) V5 = ( self.Vm5 * (a ** self.p / (self.K5 ** self.p + a ** self.p)) * (z ** self.n / (self.Kd ** self.n + z ** self.n)) ) zdot = Vin - V2 + V3 + self.kf * y - self.k * z ydot = V2 - V3 - self.kf * y adot = self.beta * self.V4 - V5 - self.eps * a return (zdot, ydot, adot) class CellCycle(DynSys): def rhs(self, X, t): c1, m1, x1, c2, m2, x2 = X Vm1, Um1 = 2 * [self.Vm1] vi1, vi2 = 2 * [self.vi] H1, H2, H3, H4 = 4 * [self.K] K1, K2, K3, K4 = 4 * [self.K] V2, U2 = 2 * [self.V2] Vm3, Um3 = 2 * [self.Vm3] V4, U4 = 2 * [self.V4] Kc1, Kc2 = 2 * [self.Kc] vd1, vd2 = 2 * [self.vd] Kd1, Kd2 = 2 * [self.Kd1] kd1, kd2 = 2 * [self.kd1] Kim1, Kim2 = 2 * [self.Kim] V1 = Vm1 * c1 / (Kc1 + c1) U1 = Um1 * c2 / (Kc2 + c2) V3 = m1 * Vm3 U3 = m2 * Um3 c1dot = vi1 * Kim1 / (Kim1 + m2) - vd1 * x1 * c1 / (Kd1 + c1) - kd1 * c1 c2dot = vi2 * Kim2 / (Kim2 + m1) - vd2 * x2 * c2 / (Kd2 + c2) - kd2 * c2 m1dot = V1 * (1 - m1) / (K1 + (1 - m1)) - V2 * m1 / (K2 + m1) m2dot = U1 * (1 - m2) / (H1 + (1 - m2)) - U2 * m2 / (H2 + m2) x1dot = V3 * (1 - x1) / (K3 + (1 - x1)) - V4 * x1 / (K4 + x1) x2dot = U3 * (1 - x2) / (H3 + (1 - x2)) - U4 * x2 / (H4 + x2) return c1dot, m1dot, x1dot, c2dot, m2dot, x2dot class CircadianRhythm(DynSys): @staticjit def _rhs( m, fc, fs, fn, th, t, Ki, k, k1, k2, kd, kdn, km, ks, n, vd, vdn, vm, vmax, vmin, v, ): vs = 2.5 * ((0.5 + 0.5 * np.cos(th)) + vmin) * (vmax - vmin) mdot = vs * (Ki ** n) / (Ki ** n + fn ** n) - vm * m / (km + m) fcdot = ks * m - k1 * fc + k2 * fn - k * fc fsdot = k * fc - vd * fs / (kd + fs) fndot = k1 * fc - k2 * fn - vdn * fn / (kdn + fn) thdot = 2 * np.pi / 24 return mdot, fcdot, fsdot, fndot, thdot @staticjit def _postprocessing(m, fc, fs, fn, th): return m, fc, fs, fn, np.cos(th) class FluidTrampoline(DynSys): @staticmethod def _rhs(x, y, th, t, gamma, psi, w): xdot = y ydot = -1 - np.heaviside(-x, 0) * (x + psi * y * np.abs(y)) + gamma * np.cos(th) thdot = w return (xdot, ydot, thdot) @staticjit def _postprocessing(x, y, th): return x, y, np.cos(th) class Aizawa(DynSys): @staticjit def _rhs(x, y, z, t, a, b, c, d, e, f): xdot = (z - b) * x - d * y ydot = d * x + (z - b) * y zdot = c + a * z - z ** 3 / 3 - (x ** 2 + y ** 2) * (1 + e * z) + f * z * x ** 3 return xdot, ydot, zdot class AnishchenkoAstakhov(DynSys): def rhs(self, X, t): x, y, z = X mu, eta = self.mu, self.eta xdot = mu * x + y - x * z ydot = -x zdot = -eta * z + eta * np.heaviside(x, 0) * x ** 2 return (xdot, ydot, zdot) class ShimizuMorioka(DynSys): @staticjit def _rhs(x, y, z, t, a, b): xdot = y ydot = x - a * y - x * z zdot = -b * z + x ** 2 return xdot, ydot, zdot class GenesioTesi(DynSys): @staticjit def _rhs(x, y, z, t, a, b, c): xdot = y ydot = z zdot = -c * x - b * y - a * z + x ** 2 return xdot, ydot, zdot class AtmosphericRegime(DynSys): @staticjit def _rhs( x, y, z, t, alpha, beta, mu1, mu2, omega, sigma ): xdot = mu1 * x + sigma * x * y ydot = mu2 * y + (omega + alpha * y + beta * z) * z - sigma * x ** 2 zdot = mu2 * z - (omega + alpha * y + beta * z) * y return xdot, ydot, zdot class Hadley(DynSys): @staticjit def _rhs(x, y, z, t, a, b, f, g): xdot = -(y ** 2) - z ** 2 - a * x + a * f ydot = x * y - b * x * z - y + g zdot = b * x * y + x * z - z return xdot, ydot, zdot class ForcedVanDerPol(DynSys): @staticjit def _rhs(x, y, z, t, a, mu, w): ydot = mu * (1 - x ** 2) * y - x + a * np.sin(z) xdot = y zdot = w return xdot, ydot, zdot @staticjit def _postprocessing(x, y, z): return x, y, np.sin(z) class ForcedFitzHughNagumo(DynSys): @staticjit def _rhs(v, w, z, t, a, b, curr, f, gamma, omega): vdot = v - v ** 3 / 3 - w + curr + f * np.sin(z) wdot = gamma * (v + a - b * w) zdot = omega return vdot, wdot, zdot @staticjit def _postprocessing(x, y, z): return x, y, np.sin(z) class HindmarshRose(DynSys): @staticjit def _rhs(x, y, z, t, a, b, c, d, s, tx, tz): xdot = -tx * x + y - a * x ** 3 + b * x ** 2 + z ydot = -a * x ** 3 - (d - b) * x ** 2 + z zdot = -s * x - z + c return xdot / tx, ydot, zdot / tz class Colpitts(DynSys): def rhs(self, X, t): x, y, z = X u = z - (self.e - 1) fz = -u * (1 - np.heaviside(u, 0)) xdot = y - self.a * fz ydot = self.c - x - self.b * y - z zdot = y - self.d * z return (xdot, ydot, zdot) class Laser(DynSys): @staticjit def _rhs(x, y, z, t, a, b, c, d, h, k): xdot = a * (y - x) + b * y * z ** 2 ydot = c * x + d * x * z ** 2 zdot = h * z + k * x ** 2 return xdot, ydot, zdot class Blasius(DynSys): @staticjit def _rhs(x, y, z, t, a, alpha1, alpha2, b, c, k1, k2, zs): xdot = a * x - alpha1 * x * y / (1 + k1 * x) ydot = -b * y + alpha1 * x * y / (1 + k1 * x) - alpha2 * y * z / (1 + k2 * y) zdot = -c * (z - zs) + alpha2 * y * z / (1 + k2 * y) return xdot, ydot, zdot class TurchinHanski(DynSys): @staticjit def _rhs(n, p, z, t, a, d, e, g, h, r, s): ndot = ( r * (1 - e * np.sin(z)) * n - r * (n ** 2) - g * (n ** 2) / (n ** 2 + h ** 2) - a * n * p / (n + d) ) pdot = s * (1 - e * np.sin(z)) * p - s * (p ** 2) / n zdot = 2 * np.pi return ndot, pdot, zdot @staticjit def _postprocessing(x, y, z): return x, y, np.sin(z) class StickSlipOscillator(DynSys): def _t(self, v): return self.t0 * np.sign(v) - self.alpha * v + self.beta * v ** 3 @staticjit def _rhs(x, v, th, t, a, alpha, b, beta, eps, gamma, t0, vs, w): tq = t0 * np.sign(v - vs) - alpha * v + beta * (v - vs) ** 3 xdot = v vdot = eps * (gamma * np.cos(th) - tq) + a * x - b * x ** 3 thdot = w return xdot, vdot, thdot @staticjit def _postprocessing(x, v, th): return x, v, np.cos(th) class HastingsPowell(DynSys): @staticjit def _rhs(x, y, z, t, a1, a2, b1, b2, d1, d2): xdot = x * (1 - x) - y * a1 * x / (1 + b1 * x) ydot = y * a1 * x / (1 + b1 * x) - z * a2 * y / (1 + b2 * y) - d1 * y zdot = z * a2 * y / (1 + b2 * y) - d2 * z return xdot, ydot, zdot class CellularNeuralNetwork(DynSys): @staticjit def f(x): return 0.5 * (np.abs(x + 1) - np.abs(x - 1)) def rhs(self, X, t): x, y, z = X xdot = -x + self.d * self.f(x) - self.b * self.f(y) - self.b * self.f(z) ydot = -y - self.b * self.f(x) + self.c * self.f(y) - self.a * self.f(z) zdot = -z - self.b * self.f(x) + self.a * self.f(y) + self.f(z) return (xdot, ydot, zdot) class BeerRNN(DynSys): @staticjit def _sig(x): return 1.0 / (1.0 +
np.exp(-x)
numpy.exp
import json import numpy as np from scipy import sparse from io import BytesIO from nilearn._utils import rename_parameters, check_niimg_4d, check_niimg_3d from nilearn._utils.niimg import _safe_get_data from nilearn.image.resampling import coord_transform from .. import datasets from . import cm from .html_stat_map import _bytesIO_to_base64 from .js_plotting_utils import (add_js_lib, mesh_to_plotly, encode, colorscale, get_html_template, to_color_strings) from nilearn.reporting import HTMLDocument class ConnectomeView(HTMLDocument): pass def _prepare_line(edges, nodes): path_edges = np.zeros(len(edges) * 3, dtype=int) path_edges[::3] = edges path_edges[1::3] = edges path_nodes = np.zeros(len(nodes) * 3, dtype=int) path_nodes[::3] = nodes[:, 0] path_nodes[1::3] = nodes[:, 1] return path_edges, path_nodes def _get_connectome(adjacency_matrix, coords, threshold=None, marker_size=None, cmap=cm.blue_red, symmetric_cmap=True): connectome = {} coords = np.asarray(coords, dtype='<f4') adjacency_matrix = np.nan_to_num(adjacency_matrix, copy=True) colors = colorscale( cmap, adjacency_matrix.ravel(), threshold=threshold, symmetric_cmap=symmetric_cmap) connectome['colorscale'] = colors['colors'] connectome['cmin'] = float(colors['vmin']) connectome['cmax'] = float(colors['vmax']) if threshold is not None: adjacency_matrix[ np.abs(adjacency_matrix) <= colors['abs_threshold']] = 0 s = sparse.coo_matrix(adjacency_matrix) nodes = np.asarray([s.row, s.col], dtype=int).T edges = np.arange(len(nodes)) path_edges, path_nodes = _prepare_line(edges, nodes) connectome["_con_w"] = encode(np.asarray(s.data, dtype='<f4')[path_edges]) c = coords[path_nodes] if np.ndim(marker_size) > 0: marker_size = np.asarray(marker_size) marker_size = marker_size[path_nodes] x, y, z = c.T for coord, cname in [(x, "x"), (y, "y"), (z, "z")]: connectome["_con_{}".format(cname)] = encode( np.asarray(coord, dtype='<f4')) connectome["markers_only"] = False if hasattr(marker_size, 'tolist'): marker_size = marker_size.tolist() connectome['marker_size'] = marker_size return connectome def _get_volume(img, threshold=0, atlas=None, stride=1, t_start=0, t_end=-1, n_t=50, t_r=None, marker_size=3, cmap=cm.cold_hot, symmetric_cmap=True, vmax=None, vmin=None): connectome = {} img = check_niimg_4d(img) t_unit = "" if not t_r else " s" if not t_r: t_r = 1 if t_end < 0: t_end = img.shape[3] + t_end if not n_t: n_t = t_end-t_start t_idx = np.round(np.linspace(t_start, t_end, n_t)).astype(int) t_labels = [str(t_r*t)+t_unit for t in t_idx] data = _safe_get_data(img)[::stride,::stride,::stride,t_idx] mask = np.abs(data[:,:,:,0]) > threshold i, j, k = mask.nonzero() x, y, z = coord_transform(i*stride, j*stride, k*stride, img.affine) for coord, cname in [(x, "x"), (y, "y"), (z, "z")]: connectome["_con_{}".format(cname)] = encode( np.asarray(coord, dtype='<f4')) colors = colorscale(cmap, data.ravel(), symmetric_cmap=symmetric_cmap, vmax=vmax, vmin=vmin) if atlas: atlas = check_niimg_3d(atlas) atlas_data = _safe_get_data(atlas)[::stride,::stride,::stride] connectome['atlas'] = encode(np.asarray(atlas_data[i,j,k], dtype='<f4')) connectome['atlas_nb'] = int(np.max(atlas_data)) connectome['colorscale'] = colors['colors'] connectome['cmin'] = float(colors['vmin']) connectome['cmax'] = float(colors['vmax']) connectome['n_time'] = n_t connectome['t_labels'] = t_labels values = [encode(np.asarray(data[i,j,k,t], dtype='<f4')) for t in range(data.shape[3])] connectome['values'] = values return connectome def _get_markers(coords, colors): connectome = {} coords = np.asarray(coords, dtype='<f4') x, y, z = coords.T for coord, cname in [(x, "x"), (y, "y"), (z, "z")]: connectome["_con_{}".format(cname)] = encode(
np.asarray(coord, dtype='<f4')
numpy.asarray
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Mar 8 20:03:35 2019 @author: siddhesh """ from torch.utils.data.dataset import Dataset from torch.utils.data import DataLoader import numpy as np import pandas as pd import os import torch from albumentations import ( RandomBrightnessContrast, HueSaturationValue, RandomGamma, GaussNoise, GaussianBlur, HorizontalFlip, VerticalFlip, Compose, Normalize, ) import time from openslide import OpenSlide from tqdm import tqdm class GenClassDataset(Dataset): def __init__(self, csv_file, ref_file, params, valid=False): self.csv_file = csv_file self.ref_file = ref_file self.df = pd.read_csv(csv_file) self.params = params self.valid = valid self.openslide_obs = {} self.train_transforms = Compose( [ RandomBrightnessContrast(brightness_limit=0.4, contrast_limit=0.4), HueSaturationValue( hue_shift_limit=30, sat_shift_limit=45, val_shift_limit=30 ), RandomGamma(gamma_limit=(80, 120)), GaussNoise(var_limit=(10, 200)), GaussianBlur(blur_limit=11), VerticalFlip(p=0.5), HorizontalFlip(p=0.5), Normalize( mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5), always_apply=True, p=1.0 ), ] ) self.validation_transforms = Compose( [ Normalize( mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5), always_apply=True, p=1.0 ) ] ) self.reset_slideobjects() def reset_slideobjects(self): print("Resetting") temp_df = pd.read_csv(self.ref_file) for i in tqdm(range(temp_df.shape[0])): pid = temp_df.iloc[i, 0] path = temp_df.iloc[i, 1] self.openslide_obs[pid] = OpenSlide(path) def __len__(self): return len(self.df) def __getitem__(self, patient_id): pid = self.df.loc[patient_id, "PID"] x = int(self.df.loc[patient_id, "x_loc"]) y = int(self.df.loc[patient_id, "y_loc"]) slide_ob = self.openslide_obs[pid] patch = np.array(slide_ob.read_region((x, y), 0, (1024, 1024)).convert("RGB")) label = self.df.loc[patient_id, "label"] if self.valid: image = self.train_transforms(image=patch) else: image = self.validation_transforms(image=patch) patch = image["image"] patch =
np.transpose(patch, (2, 0, 1))
numpy.transpose
import numpy as np import torch from torch.utils.data import Dataset def sigmoid(x): return 1. / (1 + np.exp(-x)) def gen_synth_causal_dat(nObs=100, causalFunc='nueralnet_l1', noise_dist='laplace'): """ generate causal data where one variable causes another Inputs: - nObs: number of observations - causalFunc: specify causal function """ causalFuncDict = {'linear': lambda x, n: 1 * x + n, 'hoyer2009': lambda x, n: x + (.5) * x * x * x + (n), 'nueralnet_l1': lambda x, n: sigmoid(sigmoid(np.random.normal(loc=1) * x) + n), 'mnm': lambda x, n: sigmoid(np.random.normal(loc=1) * x) + .5 * x ** 2 + sigmoid(np.random.normal(loc=1) * x) * n } # scale divided by np.sqrt(2) to ensure std of 1 if noise_dist == 'laplace': N = np.random.laplace(loc=0, scale=1. / np.sqrt(2), size=(nObs, 2)) elif noise_dist == 'gaussian': N = np.random.normal(loc=0, scale=1., size=(nObs, 2)) elif noise_dist == 'cauchy': N = np.random.standard_cauchy(size=(nObs, 2)) elif noise_dist == 'student': N = np.random.standard_t(df=5, size=(nObs, 2)) else: raise ValueError(noise_dist) X = np.zeros((nObs, 2)) X[:, 0] = N[:, 0] X[:, 1] = causalFuncDict[causalFunc](X[:, 0], N[:, 1]) if np.random.uniform() < .5: mod_dir = 'y->x' X = X[:, [1, 0]] else: mod_dir = 'x->y' return X, mod_dir def intervention_sem(n_obs, dim=4, seed=0, noise_dist='laplace', random=True, shuffle=False, nonlin='poly', multiplicative=False, iidx=None, value=0): np.random.seed(seed) if dim == 3: if noise_dist == 'laplace': X_1, U_2, U_3 = np.random.laplace(loc=0, scale=1. / np.sqrt(2), size=(n_obs, dim)).T elif noise_dist == 'gaussian': X_1, U_2, U_3 = np.random.normal(loc=0, scale=1., size=(n_obs, dim)).T elif noise_dist == 'cauchy': X_1, U_2, U_3 = np.random.standard_cauchy(size=(n_obs, dim)).T elif noise_dist == 'student': X_1, U_2, U_3 = np.random.standard_t(df=5, size=(n_obs, dim)).T else: raise ValueError(noise_dist) # effects if nonlin == 'lin': # np.random.uniform(low, high, size) # coeffs = np.random.uniform(.1, .9, 3) if random else [-1, 0.05, 0.25] coeffs = [-1, 2, 0.25] if iidx is not None: if iidx == 0: X_1 = np.ones_like(X_1)*value X_2 = coeffs[0] * X_1 + U_2 X_3 = coeffs[1] * X_1 + coeffs[2] * X_2 + U_3 elif iidx == 1: X_2 = np.ones_like(U_2)*value X_3 = coeffs[1] * X_1 + coeffs[2] * X_2 + U_3 elif iidx ==2: X_2 = coeffs[0] * X_1 + U_2 X_3 = np.ones_like(U_3)*value else: X_2 = coeffs[0] * X_1 + U_2 X_3 = coeffs[1] * X_1 + coeffs[2] * X_2 + U_3 elif nonlin == 'poly': # np.random.uniform(low, high, size) coeffs = np.random.uniform(.1, .9, 2) if random else [.5, .5] X_3 = X_1 + coeffs[0] * (X_2 * X_2 * X_2) X_4 = -X_2 + coeffs[1] * (X_1 * X_1) if multiplicative: X_3 *= np.random.laplace(0, 1 / np.sqrt(2), size=n_obs) X_4 *= np.random.laplace(0, 1 / np.sqrt(2), size=n_obs) else: X_3 += np.random.laplace(0, 1 / np.sqrt(2), size=n_obs) X_4 += np.random.laplace(0, 1 / np.sqrt(2), size=n_obs) elif nonlin == 'sigmoid': N_3 = np.random.laplace(0, 1 / np.sqrt(2), size=n_obs) N_4 = np.random.laplace(0, 1 /
np.sqrt(2)
numpy.sqrt
from typing import Tuple import cv2 import numpy as np from torchvision.models import squeezenet1_1 from .psroi_pooling.psroi_pool import PsRoIPool2D as Pool from utils import image as imagelib from utils.network import * class Classifier(nn.Module): def __init__(self): super(Classifier, self).__init__() self.epoch, self.lr = 0, .01 self.scale = 1. self.score = None self.stride = 4 self.shape = [64, 128, 256, 512] # Network squeeze = squeezenet1_1(pretrained=True) self.conv1 = nn.Sequential( squeeze.features[0], squeeze.features[1], ) self.conv2 = nn.Sequential( nn.MaxPool2d(kernel_size=3, stride=2, padding=1), squeeze.features[3], squeeze.features[4], ) self.conv3 = nn.Sequential( nn.MaxPool2d(kernel_size=3, stride=2, padding=1), squeeze.features[6], squeeze.features[7], ) self.conv4 = nn.Sequential( nn.MaxPool2d(kernel_size=3, stride=2, padding=1), squeeze.features[9], squeeze.features[10], squeeze.features[11], squeeze.features[12], ) self.conv1[0].padding = (1, 1) self.stage_0 = nn.Sequential( nn.Dropout2d(inplace=True), nn.Conv2d(in_channels=self.shape[-1], out_channels=256, kernel_size=3, padding=1), nn.ReLU(inplace=True), ) feature_size = self.shape[1:] in_channels = 256 out_shape = [128, 256] for i in range(1, len(feature_size)): out_channels = out_shape[-i] setattr(self, 'upconv_{}'.format(i), nn.Sequential( nn.Conv2d(in_channels, out_channels, 3, padding=1, bias=True), nn.BatchNorm2d(out_channels), nn.ReLU(inplace=True), Interpolate(scale_factor=2, mode='bilinear', align_corners=False), )) feat_channels = feature_size[-1-i] setattr(self, 'proj_{}'.format(i), nn.Sequential( ConcatTable( DilationLayer(feat_channels, out_channels // 2, 3, dilation=1), DilationLayer(feat_channels, out_channels // 2, 5, dilation=1), ), nn.Conv2d(out_channels // 2, out_channels // 2, 1), nn.BatchNorm2d(out_channels // 2), nn.ReLU(inplace=True) )) in_channels = out_channels + out_channels // 2 roi_size = 7 self.cls_conv = nn.Sequential( nn.Conv2d(in_channels, in_channels, 3, padding=1), nn.BatchNorm2d(in_channels), nn.ReLU(inplace=True), nn.Conv2d(in_channels, roi_size * roi_size, 1, padding=1) ) self.roi_pool = Pool(roi_size, roi_size, 1. / self.stride) self.avg_pool = nn.AvgPool2d(roi_size, roi_size) # TODO: Check CUDA available self.cuda() self.eval() @staticmethod def transform(image: np.ndarray) \ -> Tuple[np.ndarray, np.ndarray, tuple, float]: size = 640 if min(image.shape[0:2]) > 720 else 368 padded, scale, shape = imagelib.factor_crop(image, size, factor=16, padding=0, based='min') cropped = cv2.cvtColor(padded, cv2.COLOR_BGR2RGB) cropped = cropped.astype(np.float32) / 255. - .5 return cropped, padded, shape, scale def forward(self, x: torch.Tensor): x2 = self.conv1(x) x4 = self.conv2(x2) x8 = self.conv3(x4) x16 = self.conv4(x8) features = [x2, x4, x8, x16] inputs = self.stage_0(features[-1]) for i in range(1, len(self.shape[1:])): inputs = torch.cat(( getattr(self, 'upconv_{}'.format(i))(inputs), # depth getattr(self, 'proj_{}'.format(i))(features[-1 - i]), # project ), 1) return self.cls_conv(inputs) def update(self, image: np.ndarray): cropped, padded, shape, scale = self.transform(image) self.scale = scale with torch.no_grad(): self.score = self( torch.autograd.Variable( torch.from_numpy(cropped.astype(np.float32)).permute(2, 0, 1).unsqueeze(0) ).cuda() ) return shape, scale def predict(self, rois: np.ndarray): rois = rois * self.scale size =
np.size(rois, 0)
numpy.size
import numpy as np import scipy.constants as const import json import os from matplotlib import pyplot as plt import ckvpy.tools.photon_yield as photon_yield import ckvpy.tools.effective as effective class dataAnalysis(object): """Class to handle wavelength cuts, sorting, angle finding etc.""" def __init__(self, data): self.data_dict = data self._get_num_bands() self._rm_nan() def _get_num_bands(self): self.num_bands = {} for root in self.data_dict: i = 0 for bands in self.data_dict[root]: i += 1 self.num_bands[root] = i def _rm_nan(self): """Remove NaNs in data using a mask""" for root in self.data_dict: for band in self.data_dict[root]: final_mask = None for param in self.data_dict[root][band]: data = self.data_dict[root][band][param] band_len = len(self.data_dict[root][band]['band']) if type(data) is list and len(data) == band_len: nan_array = np.isnan(data) # print(nan_array[-1]) # nan_list = [val is not 'nan' for val in data] if final_mask is None: final_mask = nan_array final_mask = np.logical_or(final_mask, nan_array) final_mask = np.logical_not(final_mask) for param in self.data_dict[root][band]: # do elementwise pop() instead of this strange conversion? band_len = len(self.data_dict[root][band]['band']) data = self.data_dict[root][band][param] if type(data) is list and len(data) == band_len: data = np.array(data)[final_mask].tolist() def save(self, name): with open(name, 'w') as f: json.dump(self.data_dict, f) def find_angle(self, wl_range=[250.0e-9, 500.0e-9], filename=None): """Get Cherenkov angles/chromatic error for wavelength range wl_range Params: wl_range list[float]: wavelength range that Cherenkov angle and chromatic error is calculated over Returns: tuple(float): Cherenkov angle average and range """ for a in self.data_dict: for band in self.data_dict[a]: print("Finding angle for a =", a, "band", band) wl1, wl2, average, rnge = self.calc_err(wl_range, a=a, band=band) try: a_ = float(a) except ValueError: a_ = 0. array = np.array([wl1, wl2, average, rnge, float(a_)]) self.data_dict[a][band]['cherenkov'] = array.tolist() # json friendly # self.data_dict[a][band][str(wl1)+'-'] # print(average, rnge) return average, rnge # dont return average and range if computed # for multiple values of 'a', these are stored in file. def calculate_n_eff(self, method='gradient'): """method is 'gradient' or 'angle', TODO: may remove, redundant""" for root in self.data_dict: for band in self.data_dict[root]: data = self.data_dict[root][band] if 'n' in data: print('refractive index already in data') continue if 'kx' in data and 'ky' in data and 'ky' in data: kx = np.array(data['kx']) ky = np.array(data['ky']) kz = np.array(data['kz']) kabs = np.sqrt(kx*kx+ky*ky+kz*kz) th_in = np.arctan(kz/np.sqrt(kx*kx+ky*ky)) elif 'kz' in data and 'k_rho' in data: # 3D kz = np.array(data['kz']) k_rho = np.array(data['k_rho']) kabs = np.sqrt(k_rho*k_rho+kz*kz) d_rho, dz = self.data_dict['default'][band]['direction'] if dz == 1: k_parallel = k_rho k_perp = kz elif d_rho == 1: k_parallel = kz k_perp = k_rho th_in = np.arctan(k_parallel/(k_perp+1e-20)) else: raise ValueError("No kx, ky and kz in dataset") f = np.array(data['frequency']) k0 = 2*np.pi*f/const.c # omega/c neff = kabs/k0 wl_in = 2*np.pi/kabs wl_nan = np.isnan(wl_in) # deal with NaNs th_nan = np.isnan(th_in) neff_nan = np.isnan(neff) nan_mask =
np.logical_or(wl_nan, th_nan, neff_nan)
numpy.logical_or
from functools import partial import numpy as np from scipy.stats import boxcox from sklearn.datasets import make_blobs from sklearn.preprocessing import minmax_scale from clustermatch.cluster import run_quantile_clustering def blobs_data_generator01(): """ Blobs. n_samples=100, n_features=20, centers=3, cluster_std=0.10, center_box=(-1.0, 1.0) """ return make_blobs( n_samples=100, centers=3, n_features=20, cluster_std=0.10, shuffle=True, center_box=(-1.0, 1.0) ) def blobs_data_generator02(seed=None, n_samples=100, n_features=1000): """ Blobs. n_samples=100, n_features=1000, centers=3, cluster_std=0.10, center_box=(-1.0, 1.0) """ return make_blobs( n_samples=n_samples, centers=3, n_features=n_features, cluster_std=0.10, shuffle=True, center_box=(-1.0, 1.0), random_state=seed, ) def _get_array_chunks(data, chunk_size): """Yield successive n-sized chunks from l.""" for i in range(0, len(data), chunk_size): sl = slice(i, i + chunk_size) yield sl, data[sl] def _apply_noise(data, data_noise): data_n_objects = data.shape[1] data_n_measures = data.shape[0] if len(data_noise) == 0: return data percentage_objects = data_noise.get('percentage_objects', 0.1) percentage_measures = data_noise.get('percentage_measures', 0.0) magnitude = data_noise.get('magnitude', 0.0) selected_rows = np.random.choice( data_n_measures, size=int(data_n_measures * percentage_measures), replace=False ) selected_cols = np.random.choice( data_n_objects, size=int(data_n_objects * percentage_objects), replace=False ) noisy_data = data.copy() if np.issubdtype(data.dtype, np.number) or all([np.isreal(x) for row in data for x in row]): if not np.issubdtype(data.dtype, np.number): data = data.astype(float) if len(selected_rows) > 0: noisy_points = np.random.rand(len(selected_rows), data_n_objects) noisy_points = minmax_scale(noisy_points, axis=1, feature_range=(data.min(), data.max())) noisy_points = noisy_points * magnitude noisy_data[selected_rows, :] += noisy_points if len(selected_cols) > 0: noisy_points = np.random.rand(data_n_measures, len(selected_cols)) noisy_points = minmax_scale(noisy_points, axis=1, feature_range=(data.min(), data.max())) noisy_data[:, selected_cols] = noisy_points else: assert all([not np.isreal(x) for row in data for x in row]) unique_cat = np.unique(data) if len(selected_cols) > 0: # noisy_points = np.random.rand(data_n_measures, len(selected_cols)) noisy_points = np.random.choice(unique_cat, (data_n_measures, len(selected_cols))) # noisy_points = minmax_scale(noisy_points, axis=1, feature_range=(data.min(), data.max())) noisy_data[:, selected_cols] = noisy_points # for i in range(data.shape[0]): # for j in range(data.shape[1]): # if np.random.rand() < magnitude: # noisy_data[i, j] = np.random.choice(unique_cat) return noisy_data def _generic_data_transformation(data, sources_transformers, dtype=None, **kwargs): if len(sources_transformers) == 0: return data n_data = data.shape[0] n_sim_sources = len(sources_transformers) data_step = int(n_data / n_sim_sources) t_data = np.empty(data.shape, dtype=data.dtype if dtype is None else dtype) i = 0 for sl, data_chunk in _get_array_chunks(data, data_step): transformer = sources_transformers[i % n_sim_sources] # transform if callable(transformer): t_data_chunk = transformer(data_chunk) else: t_data_chunk = data_chunk * transformer t_data[sl] = t_data_chunk # if not np.issubdtype(t_data_chunk.dtype, np.number): # is_data_object = True # data noise if 'data_noise' in kwargs: data_noise = kwargs['data_noise'] t_data[sl] = _apply_noise(t_data[sl], data_noise) i += 1 return t_data def _create_categorical(data, cats): n_cats = len(cats) t_data = np.empty(data.shape, dtype=object) for data_row_idx, data_row in enumerate(data): data_row_part = run_quantile_clustering(data_row, n_cats) t_data[data_row_idx] = np.array([cats[int(x)] for x in data_row_part]) return t_data def transform_rows_nonlinear_and_categorical01(data, **kwargs): """ Nonlinear and categorical row transformation 01. 7 numerical data sources (x^4, log, exp2, 100, x^5, 10000, 0.0001) and 3 categorical (10, 4 and 2 categories). """ sources_transformers = [ lambda x: np.power(x, 4), lambda x: np.log(np.abs(x)), lambda x: np.exp2(x), 100.0, lambda x: _create_categorical(x, cats=[ 'cat01', 'cat02', 'cat03', 'cat04', 'cat05', 'cat06', 'cat07', 'cat08', 'cat09', 'cat10', ]), lambda x: np.power(x, 5), 10000.0, lambda x: _create_categorical(x, cats=['cat01', 'cat02', 'cat03', 'cat04']), 0.0001, lambda x: _create_categorical(x, cats=['cat01', 'cat02']), ] return _generic_data_transformation(data, sources_transformers, dtype=object, **kwargs) def transform_rows_nonlinear_and_categorical02(data, **kwargs): """ Nonlinear and categorical row transformation 02. 7 numerical data sources (x^4, log, exp2, log1p, x^5, log10, log2) and 3 categorical (8, 4 and 2 categories). """ sources_transformers = [ lambda x: np.power(x, 4), lambda x: np.log(np.abs(x)), lambda x: np.exp2(x), lambda x: _create_categorical(x, cats=[ 'cat01', 'cat02', 'cat03', 'cat04', 'cat05', 'cat06', 'cat07', 'cat08', 'cat09', 'cat10', ]), lambda x: np.log1p(np.abs(x)), lambda x: np.power(x, 5), lambda x: _create_categorical(x, cats=['cat01', 'cat02', 'cat03', 'cat04']), lambda x: np.log10(np.abs(x)), lambda x: _create_categorical(x, cats=['cat01', 'cat02']), lambda x: np.log2(np.abs(x)), ] return _generic_data_transformation(data, sources_transformers, dtype=object, **kwargs) def transform_rows_full_scaled01(data): """ Full row scale. 5 simulated data sources; values: 0.01, 0.1, 10, 100, 1000 """ sources_transformers = [0.01, 0.1, 10.0, 100.0, 1000.0] return _generic_data_transformation(data, sources_transformers) def transform_rows_nonlinear01(data, **kwargs): """ Nonlinear row transformation 01. 5 simulated data sources; Functions: exp, x^2, log, expm1, log10 """ sources_transformers = [ np.exp, lambda x: np.power(x, 2), lambda x: np.log(np.abs(x)), np.expm1, lambda x: np.log10(np.abs(x)), ] return _generic_data_transformation(data, sources_transformers, **kwargs) def transform_rows_nonlinear02(data, **kwargs): """ Nonlinear row transformation 02. 4 simulated data sources; Functions: x^3, log, log1p, exp2 """ sources_transformers = [ lambda x: np.power(x, 3), lambda x: np.log(np.abs(x)), lambda x: np.log1p(np.abs(x)), np.exp2, ] return _generic_data_transformation(data, sources_transformers, **kwargs) def transform_rows_nonlinear03(data, **kwargs): """ Nonlinear row transformation 03. 10 simulated data sources; Functions: x^4, log, exp2, 100, log1p, x^5, 10000, log10, 0.0001, log2 """ sources_transformers = [ lambda x: np.power(x, 4), lambda x: np.log(np.abs(x)), lambda x: np.exp2(x), 100.0, lambda x: np.log1p(np.abs(x)), lambda x: np.power(x, 5), 10000.0, lambda x: np.log10(np.abs(x)), 0.0001, lambda x: np.log2(np.abs(x)), ] return _generic_data_transformation(data, sources_transformers, **kwargs) def transform_rows_nonlinear03_01(data, **kwargs): """ Nonlinear row transformation 03_01. 10 simulated data sources; Functions: x^2, log, exp2, 100, log1p, x^3, 10000, log10, 0.0001, log2 """ sources_transformers = [ lambda x: np.power(x, 2), lambda x: np.log(np.abs(x)), lambda x: np.exp2(x), 100.0, lambda x: np.log1p(np.abs(x)), lambda x: np.power(x, 3), 10000.0, lambda x: np.log10(np.abs(x)), 0.0001, lambda x: np.log2(np.abs(x)), ] return _generic_data_transformation(data, sources_transformers, **kwargs) def transform_rows_nonlinear04(data, **kwargs): """ Nonlinear row transformation 04. 10 simulated data sources; Functions: 1.0, 0.5*(x+1)^2, sin(pi*x), cos(pi*x), x^5, exp2, log10, boxcox(2), boxcox(4), boxcox(6). """ sources_transformers = [ 1.0, lambda x: 0.5 * np.power((x+1), 2), lambda x: np.sin(np.pi * x), lambda x: np.cos(np.pi * x), lambda x: np.power(x, 5), lambda x: np.exp2(x), lambda x: np.log10(np.abs(x)), lambda x: boxcox(x + (-1.0 * x.min()) + 0.01, 2.00), lambda x: boxcox(x + (-1.0 * x.min()) + 0.01, 4.00), lambda x: boxcox(x + (-1.0 * x.min()) + 0.01, 6.00), ] return _generic_data_transformation(data, sources_transformers, **kwargs) def transform_rows_nonlinear05(data, **kwargs): """ Nonlinear row transformation 05. 10 simulated data sources; Functions: 1.0, 0.5*(x+1)^2, sin(pi*x), cos(pi*x), x^5, exp2, log10(x-x.min()), boxcox(2), boxcox(4), boxcox(6). """ sources_transformers = [ 1.0, lambda x: 0.5 * np.power((x+1), 2), lambda x: np.sin(np.pi * x), lambda x: np.cos(np.pi * x), lambda x: np.power(x, 5), lambda x: np.exp2(x), lambda x: np.log10(x + (-1.0 * x.min()) + 0.01), lambda x: boxcox(x + (-1.0 * x.min()) + 0.01, 2.00), lambda x: boxcox(x + (-1.0 * x.min()) + 0.01, 4.00), lambda x: boxcox(x + (-1.0 * x.min()) + 0.01, 6.00), ] return _generic_data_transformation(data, sources_transformers, **kwargs) def transform_rows_nonlinear06(data, **kwargs): """ Nonlinear row transformation 06. 12 simulated data sources; Functions: 1.0, 0.5*(x+1)^2, sin(pi*x), sin(2*pi*x), cos(pi*x), cos(2*pi*x), x^5, exp2, log10(x-x.min()), boxcox(2), boxcox(4), boxcox(6). """ sources_transformers = [ 1.0, lambda x: 0.5 * np.power((x+1), 2), lambda x: np.sin(np.pi * x), lambda x: np.sin(2.0 * np.pi * x), lambda x: np.cos(np.pi * x), lambda x: np.cos(2.0 * np.pi * x), lambda x: np.power(x, 5), lambda x: np.exp2(x), lambda x: np.log10(x + (-1.0 * x.min()) + 0.01), lambda x: boxcox(x + (-1.0 * x.min()) + 0.01, 2.00), lambda x: boxcox(x + (-1.0 * x.min()) + 0.01, 4.00), lambda x: boxcox(x + (-1.0 * x.min()) + 0.01, 6.00), ] return _generic_data_transformation(data, sources_transformers, **kwargs) def transform_rows_nonlinear07(data, **kwargs): """ Nonlinear row transformation 07. 12 simulated data sources; Functions: 1.0, 0.5*(x+1)^2, sin(pi*x), -100, cos(pi*x), 0.0001, x^5, exp2, log10(x-x.min()), boxcox(2), boxcox(4), boxcox(6). """ sources_transformers = [ 1.0, lambda x: 0.5 * np.power((x+1), 2), lambda x:
np.sin(np.pi * x)
numpy.sin
import math import numpy as np from PIL import Image from skimage import io from skimage.color import rgb2gray, rgb2lab, rgb2hsv def load(image_path): """Loads an image from a file path. HINT: Look up `skimage.io.imread()` function. Args: image_path: file path to the image. Returns: out: numpy array of shape(image_height, image_width, 3). """ # YOUR CODE HERE # Use skimage io.imread out = io.imread(image_path) print(out) # END YOUR CODE # Let's convert the image to be between the correct range. out = out.astype(np.float64) / 255 return out def dim_image(image): """Change the value of every pixel by following x_n = 0.5*x_p^2 where x_n is the new value and x_p is the original value. Args: image: numpy array of shape(image_height, image_width, 3). Returns: out: numpy array of shape(image_height, image_width, 3). """ out = None # YOUR CODE HERE out = 0.5 * np.square(image) # END YOUR CODE return out def convert_to_grey_scale(image): """Change image to gray scale. HINT: Look at `skimage.color` library to see if there is a function there you can use. Args: image: numpy array of shape(image_height, image_width, 3). Returns: out: numpy array of shape(image_height, image_width). """ # YOUR CODE HERE out = rgb2gray(image) # END YOUR CODE return out def rgb_exclusion(image, channel): """Return image **excluding** the rgb channel specified Args: image: numpy array of shape(image_height, image_width, 3). channel: str specifying the channel. Can be either "R", "G" or "B". Returns: out: numpy array of shape(image_height, image_width, 3). """ # YOUR CODE HERE RGB = ['R', 'G', 'B'] out = image.copy() out[..., RGB.index(channel)] = 0 # END YOUR CODE return out def lab_decomposition(image, channel): """Decomposes the image into LAB and only returns the channel specified. Args: image: numpy array of shape(image_height, image_width, 3). channel: str specifying the channel. Can be either "L", "A" or "B". Returns: out: numpy array of shape(image_height, image_width). """ lab = rgb2lab(image) # YOUR CODE HERE LAB = ['L', 'A', 'B'] out = lab[..., LAB.index(channel)] # END YOUR CODE return out def hsv_decomposition(image, channel): """Decomposes the image into HSV and only returns the channel specified. Args: image: numpy array of shape(image_height, image_width, 3). channel: str specifying the channel. Can be either "H", "S" or "V". Returns: out: numpy array of shape(image_height, image_width). """ hsv = rgb2hsv(image) # YOUR CODE HERE HSV = ['H', 'S', 'V'] out = hsv[..., HSV.index(channel)] # END YOUR CODE return out def mix_images(image1, image2, channel1, channel2): """Combines image1 and image2 by taking the left half of image1 and the right half of image2. The final combination also excludes channel1 from image1 and channel2 from image2 for each image. HINTS: Use `rgb_exclusion()` you implemented earlier as a helper function. Also look up `np.concatenate()` to help you combine images. Args: image1: numpy array of shape(image_height, image_width, 3). image2: numpy array of shape(image_height, image_width, 3). channel1: str specifying channel used for image1. channel2: str specifying channel used for image2. Returns: out: numpy array of shape(image_height, image_width, 3). """ # YOUR CODE HERE image1 = rgb_exclusion(image1, channel1) image2 = rgb_exclusion(image2, channel2) height, width, _ = image1.shape cut = width // 2 s1 = image1[:, :cut] s2 = image2[:, cut:] out =
np.concatenate((s1, s2), axis=1)
numpy.concatenate
# Coded by Marafi # To Do List: # Add Concrete Wall Weight # Add Basement Floors # Add Using 2.5' Deep by 6' Coupling Beams # Distribute Forces using MRSA, include 0.85 factor for 2008 designs #################################################################################### #region Defining Classes #################################################################################### from __future__ import absolute_import import numpy as np import ATCWallArchetypeHelpers as ATCWallHelper from ATCWallArchetypeObjects import ArchetypeData from ATCWallArchetypeObjects import CouplingBeam from ATCWallArchetypeObjects import PlanarWallSection from ATCWallArchetypeObjects import TWallSection from ATCWallArchetypeObjects import IWallSection from six.moves import filter class Basement: def __init__(self, FloorStiffnesses, WallStiffnesses, BasementMass, **kwargs): self.FloorStiffnesses = list(FloorStiffnesses) self.WallStiffnesses = list(WallStiffnesses) self.BasementMass = list(BasementMass) self.__dict__.update(kwargs) #################################################################################### # endregion #################################################################################### #################################################################################### #region Defining Functions #################################################################################### #################################################################################### # endregion #################################################################################### def GetSeattle2008Hazard(Height, R=6, Period = None, IgnoreMinBaseShear = False, Overstrength=1.0): Sds = 0.91 * Overstrength S1 = 0.529 * Overstrength Sd1 = 0.458 * Overstrength TL = 6 I = 1.0 Cd = 5 if Period == None: CuTa = 1.4 * ASCEHelper.ComputeCuTa((Height / 12.), 0.02, 0.75) else: CuTa = Period Periods = [0.01 ,0.1 ,0.2 ,0.3 ,0.4 ,0.5 ,0.6 ,0.75 ,1 ,2 ,3 ,4 ,5 ,7 ,8 ,9 ,10] BasinFactors = [1.235, 1.231, 1.249, 1.340, 1.351, 1.428, 1.477, 1.551, 1.557, 1.583, 1.541, 1.576, 1.581, 1.728, 1.744, 1.703, 1.662] # if Height / 12. > 240: # FactorS = np.exp(np.interp(np.log(0.2), np.log(Periods), np.log(BasinFactors))) # Add basin effects # Factor1 = np.exp(np.interp(np.log(1.0), np.log(Periods), np.log(BasinFactors))) # Add basin effects # else: # FactorS = 1.0 # Factor1 = 1.0 FactorS = 1.0 Factor1 = 1.0 SaDesign = ASCEHelper.GetDesignSa(CuTa, S1 * Factor1, Sds * FactorS, Sd1 * Factor1, TL, R, I, IgnoreMinBaseShear) return SaDesign, Sds, CuTa def GetSeattle2014Hazard(Height, R=6, Period = None, IgnoreMinBaseShear = False, Overstrength=1.0): Sds = 1.12 * Overstrength S1 = 0.488 * Overstrength Sd1 = 0.488 * Overstrength TL = 6 I = 1.0 Cd = 5 if Period == None: CuTa = 1.4 * ASCEHelper.ComputeCuTa((Height / 12.), 0.02, 0.75) else: CuTa = Period Periods = [0.01 ,0.1 ,0.2 ,0.3 ,0.4 ,0.5 ,0.6 ,0.75 ,1 ,2 ,3 ,4 ,5 ,7 ,8 ,9 ,10] BasinFactors = [1.235, 1.231, 1.249, 1.340, 1.351, 1.428, 1.477, 1.551, 1.557, 1.583, 1.541, 1.576, 1.581, 1.728, 1.744, 1.703, 1.662] # if Height / 12. > 240: # FactorS = np.exp(np.interp(np.log(0.2), np.log(Periods), np.log(BasinFactors))) # Add basin effects # Factor1 = np.exp(np.interp(np.log(1.0), np.log(Periods), np.log(BasinFactors))) # Add basin effects # else: # FactorS = 1.0 # Factor1 = 1.0 FactorS = 1.0 Factor1 = 1.0 SaDesign = ASCEHelper.GetDesignSa(CuTa, S1 * Factor1, Sds * FactorS, Sd1 * Factor1, TL, R, I, IgnoreMinBaseShear) return SaDesign, Sds, CuTa # Global Variables # Loading # DL 150psf Floors #### All Floors have the same load # LL 65psf Floors and 20psf Roof DL_Basements = [155, 155, 155, 230] # Include Basement Wall Loads LL_Basements = [40, 40, 40, 100] # Check LL DL = 130 # psf LL = 50 # psf DL_Roof = 200 # psf LL_Roof = 20 # psf BasementFloorArea = 160. * 160. / 2. FloorArea = 100. * 100. / 2. PercentageFloorAreaResistedByWall = 0.5 FirstFloorHeight = 10 * 12. FloorHeights = 10 * 12. BasementFloorHeights = 10 * 12. # Pick Out Prelim. Section Size using Shear fy = 60.; fu = 105. fpc_core = 8. fpc_slabs = 5. ConcreteDensity = 150. def CreateArchetype(Basement=None, Use2008Maps = True, Overstrength = 1.0): # Defining Story Levels YGrids = [0] + np.array(np.arange(0, (NoOfStories) * FloorHeights, FloorHeights) + FloorHeights).tolist() # Defining Gravity Loads DeadLoads = np.ones(NoOfStories) * DL / 1000. DeadLoads[-1] = DeadLoads[-1] * DL_Roof / DL LiveLoads = np.ones(NoOfStories) * LL / 1000. LiveLoads[-1] = LiveLoads[-1] * LL_Roof / LL # Computing Mass of Wall WallSelfWeight = [] i = -1 for section in Sections: i += 1 if isinstance(section, IWallSection): CoreVolume = (section.b_w * section.t_w * 2. + (section.l_w - section.t_w * 2.) * section.t_w) * ( YGrids[i + 1] - YGrids[i]) / 12. ** 3. EquivalentDL = CoreVolume * ConcreteDensity / 1000. WallSelfWeight.append(EquivalentDL) elif isinstance(section, PlanarWallSection): CoreVolume = section.l_w * section.t_w * ( YGrids[i + 1] - YGrids[i]) / 12. ** 3. EquivalentDL = CoreVolume * ConcreteDensity / 1000. WallSelfWeight.append(EquivalentDL) # Defining Mass Mass = ( DeadLoads + 0.5 * LiveLoads ) * FloorArea # Compute Mass = Mass + np.array(WallSelfWeight) # Adding Wall Self Weight WallTribArea = FloorArea * PercentageFloorAreaResistedByWall WallGravityLoad = WallTribArea * DeadLoads + np.array(WallSelfWeight) WallDeadLoads = DeadLoads * FloorArea + np.array(WallSelfWeight) WallLiveLoads = LiveLoads * FloorArea PDeltaGravityLoad = Mass - WallGravityLoad if Basement is not None: Height = YGrids[-1] - YGrids[len(Basement.FloorStiffnesses)] else: Height = YGrids[-1] # Seismic Hazard R = 6; Cd = 5 if Use2008Maps: SaDesign, Sds, CuTa = GetSeattle2008Hazard(Height, R=R, Overstrength = Overstrength) else: SaDesign, Sds, CuTa = GetSeattle2014Hazard(Height, R=R, Overstrength = Overstrength) if Basement is not None: archetypename = ArchetypeData(Name, YGrids, R, CuTa, Length, Thickness, None, None, None, fpc_core, fy, fu, PDeltaGravityLoad, Mass, WallGravityLoad, None, None, None, Sections, CuTa=CuTa, SaDesign=SaDesign, Cd=Cd, BasementProperties=Basement, WallDeadLoads = list(WallDeadLoads), WallLiveLoads = list(WallLiveLoads), Sds = Sds) else: archetypename = ArchetypeData(Name, YGrids, R, CuTa, Length, Thickness, None, None, None, fpc_core, fy, fu, PDeltaGravityLoad, Mass, WallGravityLoad, None, None, None, Sections, CuTa=CuTa, SaDesign=SaDesign, Cd=Cd, WallDeadLoads = list(WallDeadLoads), WallLiveLoads = list(WallLiveLoads), Sds = Sds) return archetypename BasementFloorStiffnesses = np.array([8200, 8200, 8200, 10100]) * 0.5 BasementWallStiffnesses = np.array([0.0496e9, 0.0496e9, 0.0496e9, 0.0496e9, ]) * 0.5 BasementMass = (np.array(DL_Basements) + 0.5 * np.array(LL_Basements)) * ( BasementFloorArea - FloorArea ) / 1000. Basements = Basement(BasementFloorStiffnesses, BasementWallStiffnesses, BasementMass) BasementFloorStiffnesses = np.array([8200, 8200, 10100]) * 0.5 BasementWallStiffnesses = np.array([0.0496e9, 0.0496e9, 0.0496e9, ]) * 0.5 BasementMass = (np.array(DL_Basements[1:]) + 0.5 * np.array(LL_Basements[1:])) * ( BasementFloorArea - FloorArea ) / 1000. Basements3Levels = Basement(BasementFloorStiffnesses, BasementWallStiffnesses, BasementMass) BasementFloorStiffnesses = np.array([8200, 10100]) * 0.5 BasementWallStiffnesses = np.array([0.0496e9, 0.0496e9 ]) * 0.5 BasementMass = (np.array(DL_Basements[2:]) + 0.5 * np.array(LL_Basements[2:])) * ( BasementFloorArea - FloorArea ) / 1000. Basements2Levels = Basement(BasementFloorStiffnesses, BasementWallStiffnesses, BasementMass) #################################################################################### #region Defining Archetype #################################################################################### Archetypes = [] import ASCEHelper ############################### Performance Group #1 ############################### # 2008 Maps #region Archetype S4H08SEA and S4H08SEAWB Name = 'S4H08SEA' # print 'Importing Archetype: ' + Name # Compute Seismic Weight NoOfStories = 4 YGrids = [0] + np.array(np.arange(0,(NoOfStories)*13*12, 13*12)+15*12).tolist() DeadLoads = np.ones(NoOfStories) * DL / 1000. DeadLoads[-1] = DeadLoads[-1] * DL_Roof / DL LiveLoads = np.ones(NoOfStories) * LL / 1000. LiveLoads[-1] = LiveLoads[-1] * LL_Roof / LL MassPerSqFt = DL / 1000. Mass = np.ones(NoOfStories) * MassPerSqFt * FloorArea Mass[-1] = FloorArea * DL_Roof / 1000. # Adjust for Roof Weight WallTribArea = FloorArea * 0.5 WeightPerSqFt = DL BuildingWeight = np.ones(NoOfStories) * WeightPerSqFt * FloorArea BuildingWeight[-1] = 152. / 1000. * FloorArea # Adjust for Roof Weight # Seismic Hazard R = 6; Cd = 5 SaDesign, Sds, CuTa = GetSeattle2008Hazard(YGrids[-1], R=R) Thickness = 14. Length = 14. * 12. Long_Spacing = 4 NoOfCols = 10 BarSize = 8. Ag = ( (NoOfCols - 1) * Long_Spacing + 6 ) * Thickness Rho = ( NoOfCols * 2 + 2 ) * np.pi * ( BarSize / 2. / 8.) ** 2. / Ag # print Rho Section1 = PlanarWallSection(Length, Thickness, (NoOfCols - 1) * Long_Spacing + 6, (NoOfCols - 1) * Long_Spacing + 6, BarSize, [3] + (np.ones(NoOfCols - 2) * 2.).tolist() + [3], [3] + (np.ones(NoOfCols - 2) * 2.).tolist() + [3], 0.255, 4.037, fpc_core, fy, fu, 3, 4., NoOfCols, 3) NoOfCols = 6 BarSize = 8.0 Ag = ( (NoOfCols - 1) * Long_Spacing + 6 ) * Thickness Rho = ( NoOfCols * 2 + 2 ) * np.pi * ( BarSize / 2. / 8.) ** 2. / Ag # print Rho Section2 = PlanarWallSection(Length, Thickness, (NoOfCols - 1) * Long_Spacing + 6, (NoOfCols - 1) * Long_Spacing + 6, BarSize, [3] + (np.ones(NoOfCols - 2) * 2.).tolist() + [3], [3] + (np.ones(NoOfCols - 2) * 2.).tolist() + [3], 0.255, 4.037, fpc_core, fy, fu, 3, 4., 8, 3) Section3 = PlanarWallSection(Length, Thickness, 0, 0, 10.173, [], [], 0.255, 4.037, fpc_core, fy, fu, None, None, None, None) Sections = [Section1, Section1, Section2, Section2] S4H08SEA = CreateArchetype() Archetypes.append(S4H08SEA) Name = 'S4H08SEAWB' NoOfStories = 6 Sections = [ Section1, Section1, Section1, Section1, Section2, Section2 ] S4H08SEAWB = CreateArchetype(Basements2Levels) Archetypes.append(S4H08SEAWB) #endregion #region Archetype S8H08SEA and S8H08SEAWB Name = 'S8H08SEA' # print 'Importing Archetype: ' + Name #### Input Variables NoOfStories = 8 Thickness = 14. Length = 16. * 12. Flange_Thickness = 8*12. # Assume 6' Long Core Long_Spacing = 4 BarSize = 7.0 Rho = 0.9 #In Fraction Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section1 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing, Thickness - 3.5) BarSize = 5.0 Rho = 0.55 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section2 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section3 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) Sections = [Section1, Section1, Section1, Section2, Section2, Section2, Section3, Section3, ] S8H08SEA = CreateArchetype() Archetypes.append(S8H08SEA) Name = 'S8H08SEAWB' NoOfStories = 11 Sections = [ Section1, Section1, Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section3, Section3, ] S8H08SEAWB = CreateArchetype(Basements3Levels) Archetypes.append(S8H08SEAWB) #endregion #region Archetype S12H08SEA and S12H08SEAWB Name = 'S12H08SEA' # print 'Importing Archetype: ' + Name #### Input Variables NoOfStories = 12 Thickness = 14. Length = 20. * 12. Flange_Thickness = 10.0*12. # Assume 6' Long Core Long_Spacing = 4 BarSize = 5.0 Rho = 0.50 #In Fraction Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section1 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing, Thickness - 3.5) BarSize = 5.0 Rho = 0.50 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section2 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 14. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 4.0 Rho = 0.35 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section3 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section4 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) Sections = [Section1, Section1, Section1, Section2, Section2, Section2, Section3, Section3, Section3, Section4, Section4, Section4, ] S12H08SEA = CreateArchetype() Archetypes.append(S12H08SEA) Name = 'S12H08SEAWB' NoOfStories = 16 Sections = [ Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section3, Section3, Section3, Section4, Section4, Section4, ] S12H08SEAWB = CreateArchetype(Basements) Archetypes.append(S12H08SEAWB) #endregion #region Archetype S16H08SEA and S16H08SEAWB Name = 'S16H08SEA' #### Input Variables NoOfStories = 16 Thickness = 14. Length = 22. * 12. Flange_Thickness = 11.*12. # Assume 6' Long Core Long_Spacing = 4 BarSize = 6.0 Rho = 0.5 #In Fraction Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section1 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing, Thickness - 3.5) BarSize = 5.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section2 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 14. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section3 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section4 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) Sections = [Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, ] S16H08SEA = CreateArchetype() Archetypes.append(S16H08SEA) Name = 'S16H08SEAWB' NoOfStories = 20 # Include Basement Floors Here Sections = [Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, ] S16H08SEAWB = CreateArchetype(Basements) Archetypes.append(S16H08SEAWB) #endregion #region Archetype S20H08SEA and S20H08SEAWB Name = 'S20H08SEA' # print 'Importing Archetype: ' + Name #### Input Variables NoOfStories = 20 Thickness = 14. Length = 24. * 12. Flange_Thickness = 12*12. # Assume 6' Long Core Long_Spacing = 4 BarSize = 6.0 Rho = 0.5 #In Fraction Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section1 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing, Thickness - 3.5) BarSize = 5.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section2 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 14. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 4.0 Rho =0.35 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section3 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section4 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) ThicknessBelow = float(Thickness) Thickness = 14. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section5 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) Sections = [Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, Section5, Section5, Section5, Section5, ] S20H08SEA = CreateArchetype() Archetypes.append(S20H08SEA) Name = 'S20H08SEAWB' NoOfStories = 24 # Include Basement Floors Here Sections = [Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, Section5, Section5, Section5, Section5, ] S20H08SEAWB = CreateArchetype(Basements) Archetypes.append(S20H08SEAWB) #endregion #region Archetype S24H08SEA and S24H08SEAWB Name = 'S24H08SEA' # print 'Importing Archetype: ' + Name #### Input Variables NoOfStories = 24 Thickness = 18 Length = 26. * 12. Flange_Thickness = 13.*12. # Assume 6' Long Core Long_Spacing = 4 BarSize = 7.0 Rho = 1.0 #In Fraction Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section1 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing, Thickness - 3.5) BarSize = 6.0 Rho = 0.75 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section2 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2., Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 18. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 6.0 Rho = 0.60 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section3 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2., Thickness - 3.5) BarSize = 5.0 Rho = 0.50 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section4 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2., Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 14. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 5.0 Rho = 0.50 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section5 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2., Thickness - 3.5) BarSize = 5.0 Rho = 0.50 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section6 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) Sections = [Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, Section5, Section5, Section5, Section5, Section6, Section6, Section6, Section6, ] S24H08SEA = CreateArchetype() Archetypes.append(S24H08SEA) Name = 'S24H08SEAWB' NoOfStories = 28 Sections = [Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, Section5, Section5, Section5, Section5, Section6, Section6, Section6, Section6, ] S24H08SEAWB = CreateArchetype(Basements) Archetypes.append(S24H08SEAWB) #endregion #region Archetype S28H08SEA and S28H08SEAWB Name = 'S28H08SEA' # print 'Importing Archetype: ' + Name #### Input Variables NoOfStories = 28 Thickness = 18. Length = 28. * 12. Flange_Thickness = 14*12. # Assume 6' Long Core Long_Spacing = 4 BarSize = 7.0 Rho = 0.85 #In Fraction Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section1 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing, Thickness - 3.5) BarSize = 6.0 Rho = 0.6 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section2 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 18. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 6.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section3 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 6.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section4 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 16. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 6.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section5 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 6.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section6 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 16. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 6.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section7 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) Sections = [ Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, Section5, Section5, Section5, Section5, Section6, Section6, Section6, Section6, Section7, Section7, Section7, Section7, ] S28H08SEA = CreateArchetype() Archetypes.append(S28H08SEA) Name = 'S28H08SEAWB' NoOfStories = 32 Sections = [ Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, Section5, Section5, Section5, Section5, Section6, Section6, Section6, Section6, Section7, Section7, Section7, Section7, ] S28H08SEAWB = CreateArchetype(Basements) Archetypes.append(S28H08SEAWB) #endregion #region Archetype S32H08SEA and S32H08SEAWB Name = 'S32H08SEA' # print 'Importing Archetype: ' + Name #### Input Variables NoOfStories = 32 Thickness = 20. Length = 30. * 12. Flange_Thickness = 15*12. # Assume 6' Long Core Long_Spacing = 4 BarSize = 6.0 Rho = 0.75 #In Fraction Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section1 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing, Thickness - 3.5) BarSize = 5.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section2 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2., Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 20. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 5.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section3 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 5.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section4 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 18. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 5.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section5 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 5.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section6 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 18. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 5.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section7 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 5.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section8 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) Sections = [ Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, Section5, Section5, Section5, Section5, Section6, Section6, Section6, Section6, Section7, Section7, Section7, Section7, Section8, Section8, Section8, Section8, ] S32H08SEA = CreateArchetype() Archetypes.append(S32H08SEA) Name = 'S32H08SEAWB' NoOfStories = 36 Sections = [ Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, Section5, Section5, Section5, Section5, Section6, Section6, Section6, Section6, Section7, Section7, Section7, Section7, Section8, Section8, Section8, Section8, ] S32H08SEAWB = CreateArchetype(Basements) Archetypes.append(S32H08SEAWB) #endregion #region Archetype S36H08SEA and S36H08SEAWB Name = 'S36H08SEA' # print 'Importing Archetype: ' + Name #### Input Variables NoOfStories = 36 Thickness = 22. Length = 32. * 12. Flange_Thickness = 16*12. # Assume 6' Long Core Long_Spacing = 4 BarSize = 6.0 Rho = 0.6 #In Fraction Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section1 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing, Thickness - 3.5) BarSize = 6.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section2 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 22. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 6.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section3 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 6.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section4 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 16. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 6.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section5 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 6.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section6 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 16. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 6.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section7 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 6.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section8 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 16. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 6.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section9 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) Sections = [ Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, Section5, Section5, Section5, Section5, Section6, Section6, Section6, Section6, Section7, Section7, Section7, Section7, Section8, Section8, Section8, Section8, Section9, Section9, Section9, Section9, ] S36H08SEA = CreateArchetype() Archetypes.append(S36H08SEA) Name = 'S36H08SEAWB' NoOfStories = 40 Sections = [ Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, Section5, Section5, Section5, Section5, Section6, Section6, Section6, Section6, Section7, Section7, Section7, Section7, Section8, Section8, Section8, Section8, Section9, Section9, Section9, Section9, ] S36H08SEAWB = CreateArchetype(Basements) Archetypes.append(S36H08SEAWB) #endregion #region Archetype S40H08SEA and S40H08SEAWB Name = 'S40H08SEA' # print 'Importing Archetype: ' + Name #### Input Variables NoOfStories = 40 Thickness = 24. Length = 34. * 12. Flange_Thickness = 17.*12. # Assume 6' Long Core Long_Spacing = 4 BarSize = 6.0 Rho = 0.6 #In Fraction Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section1 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing, Thickness - 3.5) BarSize = 6.0 Rho = 0.6 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section2 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 24. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 6.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section3 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 6.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section4 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 18. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 6.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section5 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 6.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section6 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 18. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 6.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section7 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 6.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section8 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 16. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 6.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section9 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 6.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section10 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) Sections = [ Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, Section5, Section5, Section5, Section5, Section6, Section6, Section6, Section6, Section7, Section7, Section7, Section7, Section8, Section8, Section8, Section8, Section9, Section9, Section9, Section9, Section10, Section10, Section10, Section10, ] S40H08SEA = CreateArchetype() Archetypes.append(S40H08SEA) Name = 'S40H08SEAWB' NoOfStories = 44 Sections = [ Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, Section5, Section5, Section5, Section5, Section6, Section6, Section6, Section6, Section7, Section7, Section7, Section7, Section8, Section8, Section8, Section8, Section9, Section9, Section9, Section9, Section10, Section10, Section10, Section10, ] S40H08SEAWB = CreateArchetype(Basements) Archetypes.append(S40H08SEAWB) #endregion # 2014 Maps #region Archetype S4H14SEA and S4H14SEAWB Name = 'S4H14SEA' # print 'Importing Archetype: ' + Name # Compute Seismic Weight NoOfStories = 4 YGrids = [0] + np.array(np.arange(0,(NoOfStories)*13*12, 13*12)+15*12).tolist() DeadLoads = np.ones(NoOfStories) * DL / 1000. DeadLoads[-1] = DeadLoads[-1] * DL_Roof / DL LiveLoads = np.ones(NoOfStories) * LL / 1000. LiveLoads[-1] = LiveLoads[-1] * LL_Roof / LL MassPerSqFt = DL / 1000. Mass = np.ones(NoOfStories) * MassPerSqFt * FloorArea Mass[-1] = FloorArea * DL_Roof / 1000. # Adjust for Roof Weight WallTribArea = FloorArea * 0.5 WeightPerSqFt = DL BuildingWeight = np.ones(NoOfStories) * WeightPerSqFt * FloorArea BuildingWeight[-1] = 152. / 1000. * FloorArea # Adjust for Roof Weight # Seismic Hazard R = 6; Cd = 5 SaDesign, Sds, CuTa = GetSeattle2008Hazard(YGrids[-1], R=R) Thickness = 18. Length = 16. * 12. Long_Spacing = 4 NoOfCols = 13 BarSize = 8. Ag = ( (NoOfCols - 1) * Long_Spacing + 6 ) * Thickness Rho = ( NoOfCols * 2 + 2 ) * np.pi * ( BarSize / 2. / 8.) ** 2. / Ag # print Rho Section1 = PlanarWallSection(Length, Thickness, (NoOfCols - 1) * Long_Spacing + 6, (NoOfCols - 1) * Long_Spacing + 6, BarSize, [3] + (np.ones(NoOfCols - 2) * 2.).tolist() + [3], [3] + (np.ones(NoOfCols - 2) * 2.).tolist() + [3], 0.255, 4.037, fpc_core, fy, fu, 3, 4., NoOfCols, 3) NoOfCols = 8 BarSize = 8.0 Ag = ( (NoOfCols - 1) * Long_Spacing + 6 ) * Thickness Rho = ( NoOfCols * 2 + 2 ) * np.pi * ( BarSize / 2. / 8.) ** 2. / Ag # print Rho Section2 = PlanarWallSection(Length, Thickness, (NoOfCols - 1) * Long_Spacing + 6, (NoOfCols - 1) * Long_Spacing + 6, BarSize, [3] + (np.ones(NoOfCols - 2) * 2.).tolist() + [3], [3] + (np.ones(NoOfCols - 2) * 2.).tolist() + [3], 0.255, 4.037, fpc_core, fy, fu, 3, 4., 8, 3) Section3 = PlanarWallSection(Length, Thickness, 0, 0, 10.173, [], [], 0.255, 4.037, fpc_core, fy, fu, None, None, None, None) Sections = [Section1, Section1, Section2, Section2] S4H14SEA = CreateArchetype(Use2008Maps = False) Archetypes.append(S4H14SEA) Name = 'S4H14SEAWB' NoOfStories = 6 Sections = [ Section1, Section1, Section1, Section1, Section2, Section2 ] S4H14SEAWB = CreateArchetype(Basements2Levels, Use2008Maps = False) Archetypes.append(S4H14SEAWB) #endregion #region Archetype S8H14SEA and S8H14SEAWB Name = 'S8H14SEA' # print 'Importing Archetype: ' + Name #### Input Variables NoOfStories = 8 Thickness = 16. Length = 18. * 12. Flange_Thickness = 9.*12. # Assume 6' Long Core Long_Spacing = 4 BarSize = 7.0 Rho = 0.95 #In Fraction Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section1 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing, Thickness - 3.5) BarSize = 5.0 Rho = 0.70 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section2 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section3 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) Sections = [Section1, Section1, Section1, Section2, Section2, Section2, Section3, Section3, ] S8H14SEA = CreateArchetype(Use2008Maps = False) Archetypes.append(S8H14SEA) Name = 'S8H14SEAWB' NoOfStories = 11 Sections = [ Section1, Section1, Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section3, Section3, ] S8H14SEAWB = CreateArchetype(Basements3Levels, Use2008Maps = False) Archetypes.append(S8H14SEAWB) #endregion #region Archetype S12H14SEA and S12H14SEAWB Name = 'S12H14SEA' # print 'Importing Archetype: ' + Name #### Input Variables NoOfStories = 12 Thickness = 18. Length = 20. * 12. Flange_Thickness = 10.*12. # Assume 6' Long Core Long_Spacing = 4 BarSize = 6.0 Rho = 0.85 #In Fraction Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section1 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing, Thickness - 3.5) BarSize = 6.0 Rho = 0.6 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section2 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 18. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 4.0 Rho = 0.40 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section3 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section4 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) Sections = [Section1, Section1, Section1, Section2, Section2, Section2, Section3, Section3, Section3, Section4, Section4, Section4, ] S12H14SEA = CreateArchetype(Use2008Maps = False) Archetypes.append(S12H14SEA) Name = 'S12H14SEAWB' NoOfStories = 16 Sections = [ Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section3, Section3, Section3, Section4, Section4, Section4, ] S12H14SEAWB = CreateArchetype(Basements, Use2008Maps = False) Archetypes.append(S12H14SEAWB) #endregion #region Archetype S16H14SEA and S16H14SEAWB Name = 'S16H14SEA' #### Input Variables NoOfStories = 16 Thickness = 22. Length = 24. * 12. Flange_Thickness = 12.*12. # Assume 6' Long Core Long_Spacing = 4 BarSize = 7.0 Rho = 0.6 #In Fraction Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section1 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing, Thickness - 3.5) BarSize = 6.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section2 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 22. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 5.0 Rho = 0.40 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section3 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section4 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) Sections = [Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, ] S16H14SEA = CreateArchetype(Use2008Maps = False) Archetypes.append(S16H14SEA) Name = 'S16H14SEAWB' NoOfStories = 20 # Include Basement Floors Here Sections = [Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, ] S16H14SEAWB = CreateArchetype(Basements, False) Archetypes.append(S16H14SEAWB) #endregion #region Archetype S20H14SEA and S20H14SEAWB Name = 'S20H14SEA' # print 'Importing Archetype: ' + Name #### Input Variables NoOfStories = 20 Thickness = 24. Length = 26. * 12. Flange_Thickness = 13*12. # Assume 6' Long Core Long_Spacing = 4 BarSize = 7.0 Rho = 0.55 #In Fraction Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section1 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing, Thickness - 3.5) BarSize = 5.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section2 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 24. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 5.0 Rho =0.45 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section3 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section4 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) ThicknessBelow = float(Thickness) Thickness = 20. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section5 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) Sections = [Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, Section5, Section5, Section5, Section5, ] S20H14SEA = CreateArchetype(Use2008Maps = False) Archetypes.append(S20H14SEA) Name = 'S20H14SEAWB' NoOfStories = 24 # Include Basement Floors Here Sections = [Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, Section5, Section5, Section5, Section5, ] S20H14SEAWB = CreateArchetype(Basements, False) Archetypes.append(S20H14SEAWB) #endregion #region Archetype S24H14SEA and S24H14SEAWB Name = 'S24H14SEA' # print 'Importing Archetype: ' + Name #### Input Variables NoOfStories = 24 Thickness = 26. Length = 28. * 12. Flange_Thickness = 14.*12. # Assume 6' Long Core Long_Spacing = 4 BarSize = 8.0 Rho = 1.1 #In Fraction Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section1 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing, Thickness - 3.5) BarSize = 7.0 Rho = 0.75 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section2 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 26. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 6.0 Rho = 0.6 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section3 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 6.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section4 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 22. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 6.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section5 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 6.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section6 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) Sections = [Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, Section5, Section5, Section5, Section5, Section6, Section6, Section6, Section6, ] S24H14SEA = CreateArchetype(Use2008Maps = False) Archetypes.append(S24H14SEA) Name = 'S24H14SEAWB' NoOfStories = 28 Sections = [Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, Section5, Section5, Section5, Section5, Section6, Section6, Section6, Section6, ] S24H14SEAWB = CreateArchetype(Basements, False) Archetypes.append(S24H14SEAWB) #endregion #region Archetype S28H14SEA and S28H14SEAWB Name = 'S28H14SEA' # print 'Importing Archetype: ' + Name #### Input Variables NoOfStories = 28 Thickness = 28. Length = 30. * 12. Flange_Thickness = 15*12. # Assume 6' Long Core Long_Spacing = 4 BarSize = 7.0 Rho = 0.95 #In Fraction Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section1 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing, Thickness - 3.5) BarSize = 7.0 Rho = 0.7 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section2 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 28. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 6.0 Rho = 0.6 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section3 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 6.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section4 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 24. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 6.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section5 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 6.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section6 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 6.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section7 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) Sections = [ Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, Section5, Section5, Section5, Section5, Section6, Section6, Section6, Section6, Section7, Section7, Section7, Section7, ] S28H14SEA = CreateArchetype(Use2008Maps = False) Archetypes.append(S28H14SEA) Name = 'S28H14SEAWB' NoOfStories = 32 Sections = [ Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, Section5, Section5, Section5, Section5, Section6, Section6, Section6, Section6, Section7, Section7, Section7, Section7, ] S28H14SEAWB = CreateArchetype(Basements, False) Archetypes.append(S28H14SEAWB) #endregion #region Archetype S32H14SEA and S32H14SEAWB Name = 'S32H14SEA' # print 'Importing Archetype: ' + Name #### Input Variables NoOfStories = 32 Thickness = 30. Length = 32. * 12. Flange_Thickness = 16.*12. # Assume 6' Long Core Long_Spacing = 4 BarSize = 7.0 Rho = 0.95 #In Fraction Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section1 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing, Thickness - 3.5) BarSize = 7.0 Rho = 0.8 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section2 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 30. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 7.0 Rho = 0.7 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section3 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 5.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section4 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 26. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 6.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section5 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 6.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section6 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 26. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 6.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section7 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 6.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section8 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) Sections = [ Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, Section5, Section5, Section5, Section5, Section6, Section6, Section6, Section6, Section7, Section7, Section7, Section7, Section8, Section8, Section8, Section8, ] S32H14SEA = CreateArchetype(Use2008Maps = False) Archetypes.append(S32H14SEA) Name = 'S32H14SEAWB' NoOfStories = 36 Sections = [ Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, Section5, Section5, Section5, Section5, Section6, Section6, Section6, Section6, Section7, Section7, Section7, Section7, Section8, Section8, Section8, Section8, ] S32H14SEAWB = CreateArchetype(Basements, False) Archetypes.append(S32H14SEAWB) #endregion #region Archetype S36H14SEA and S36H14SEAWB Name = 'S36H14SEA' # print 'Importing Archetype: ' + Name #### Input Variables NoOfStories = 36 Thickness = 32. Length = 34. * 12. Flange_Thickness = 17.*12. # Assume 6' Long Core Long_Spacing = 4 BarSize = 8.0 Rho = 1.1 #In Fraction Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section1 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing, Thickness - 3.5) BarSize = 8.0 Rho = 0.8 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section2 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 32. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 7.0 Rho = 0.7 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section3 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 7.0 Rho = 0.6 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section4 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 28. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 6.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section5 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 6.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section6 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 28. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 6.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section7 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 6.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section8 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 6.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section9 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) Sections = [ Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, Section5, Section5, Section5, Section5, Section6, Section6, Section6, Section6, Section7, Section7, Section7, Section7, Section8, Section8, Section8, Section8, Section9, Section9, Section9, Section9, ] S36H14SEA = CreateArchetype(Use2008Maps = False) Archetypes.append(S36H14SEA) Name = 'S36H14SEAWB' NoOfStories = 40 Sections = [ Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, Section5, Section5, Section5, Section5, Section6, Section6, Section6, Section6, Section7, Section7, Section7, Section7, Section8, Section8, Section8, Section8, Section9, Section9, Section9, Section9, ] S36H14SEAWB = CreateArchetype(Basements, False) Archetypes.append(S36H14SEAWB) #endregion #region Archetype S40H14SEA and S40H14SEAWB Name = 'S40H14SEA' # print 'Importing Archetype: ' + Name #### Input Variables NoOfStories = 40 Thickness = 34. Length = 36. * 12. Flange_Thickness = 18.*12. # Assume 6' Long Core Long_Spacing = 4 BarSize = 8.0 Rho = 1.2 #In Fraction Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section1 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing, Thickness - 3.5) BarSize = 8.0 Rho = 1.0 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section2 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 34. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 7.0 Rho = 0.8 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section3 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 6.0 Rho = 0.8 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section4 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 28. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 5.0 Rho = 0.7 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section5 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 6.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section6 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 28. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 6.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section7 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 6.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section8 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 24. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 6.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section9 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 6.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section10 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) Sections = [ Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, Section5, Section5, Section5, Section5, Section6, Section6, Section6, Section6, Section7, Section7, Section7, Section7, Section8, Section8, Section8, Section8, Section9, Section9, Section9, Section9, Section10, Section10, Section10, Section10, ] S40H14SEA = CreateArchetype(Use2008Maps = False) Archetypes.append(S40H14SEA) Name = 'S40H14SEAWB' NoOfStories = 44 Sections = [ Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, Section5, Section5, Section5, Section5, Section6, Section6, Section6, Section6, Section7, Section7, Section7, Section7, Section8, Section8, Section8, Section8, Section9, Section9, Section9, Section9, Section10, Section10, Section10, Section10, ] S40H14SEAWB = CreateArchetype(Basements, False) Archetypes.append(S40H14SEAWB) #endregion ############################### Performance Group #2 ############################### ##### 2008 Maps ###### #region Archetype S4H08SEAPG2 and S4H08SEAWBPG2 Name = 'S4H08SEAPG2' # print 'Importing Archetype: ' + Name # Compute Seismic Weight NoOfStories = 4 YGrids = [0] + np.array(np.arange(0,(NoOfStories)*13*12, 13*12)+15*12).tolist() DeadLoads = np.ones(NoOfStories) * DL / 1000. DeadLoads[-1] = DeadLoads[-1] * DL_Roof / DL LiveLoads = np.ones(NoOfStories) * LL / 1000. LiveLoads[-1] = LiveLoads[-1] * LL_Roof / LL MassPerSqFt = DL / 1000. Mass = np.ones(NoOfStories) * MassPerSqFt * FloorArea Mass[-1] = FloorArea * DL_Roof / 1000. # Adjust for Roof Weight WallTribArea = FloorArea * 0.5 WeightPerSqFt = DL BuildingWeight = np.ones(NoOfStories) * WeightPerSqFt * FloorArea BuildingWeight[-1] = 152. / 1000. * FloorArea # Adjust for Roof Weight # Seismic Hazard R = 6; Cd = 5 SaDesign, Sds, CuTa = GetSeattle2008Hazard(YGrids[-1], R=R) Thickness = 14. Length = 10. * 12. Long_Spacing = 4 NoOfCols = 14 BarSize = 8. Ag = ( (NoOfCols - 1) * Long_Spacing + 6 ) * Thickness Rho = ( NoOfCols * 2 + 2 ) * np.pi * ( BarSize / 2. / 8.) ** 2. / Ag # print Rho Section1 = PlanarWallSection(Length, Thickness, (NoOfCols - 1) * Long_Spacing + 6, (NoOfCols - 1) * Long_Spacing + 6, BarSize, [3] + (np.ones(NoOfCols - 2) * 2.).tolist() + [3], [3] + (np.ones(NoOfCols - 2) * 2.).tolist() + [3], 0.255, 4.037, fpc_core, fy, fu, 3, 4., NoOfCols, 3) NoOfCols = 6 BarSize = 8.0 Ag = ( (NoOfCols - 1) * Long_Spacing + 6 ) * Thickness Rho = ( NoOfCols * 2 + 2 ) * np.pi * ( BarSize / 2. / 8.) ** 2. / Ag # print Rho Section2 = PlanarWallSection(Length, Thickness, (NoOfCols - 1) * Long_Spacing + 6, (NoOfCols - 1) * Long_Spacing + 6, BarSize, [3] + (np.ones(NoOfCols - 2) * 2.).tolist() + [3], [3] + (np.ones(NoOfCols - 2) * 2.).tolist() + [3], 0.255, 4.037, fpc_core, fy, fu, 3, 4., 8, 3) Section3 = PlanarWallSection(Length, Thickness, 0, 0, 10.173, [], [], 0.255, 4.037, fpc_core, fy, fu, None, None, None, None) Sections = [Section1, Section1, Section2, Section2] S4H08SEAPG2 = CreateArchetype() Archetypes.append(S4H08SEAPG2) Name = 'S4H08SEAWBPG2' NoOfStories = 6 Sections = [ Section1, Section1, Section1, Section1, Section2, Section2 ] S4H08SEAWBPG2 = CreateArchetype(Basements2Levels) Archetypes.append(S4H08SEAWBPG2) #endregion #region Archetype S8H08SEAPG2 and S8H08SEAWBPG2 Name = 'S8H08SEAPG2' # print 'Importing Archetype: ' + Name #### Input Variables NoOfStories = 8 Thickness = 20. Length = 11. * 12. Flange_Thickness = 5.5*12. # Assume 6' Long Core Long_Spacing = 4 BarSize = 8.0 Rho = 2.0 #In Fraction Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section1 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing, Thickness - 3.5) BarSize = 8.0 Rho = 1.1 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section2 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section3 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) Sections = [Section1, Section1, Section1, Section2, Section2, Section2, Section3, Section3, ] S8H08SEAPG2 = CreateArchetype() Archetypes.append(S8H08SEAPG2) Name = 'S8H08SEAWBPG2' NoOfStories = 11 Sections = [ Section1, Section1, Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section3, Section3, ] S8H08SEAWBPG2 = CreateArchetype(Basements3Levels) Archetypes.append(S8H08SEAWBPG2) #endregion #region Archetype S12H08SEAPG2 and S12H08SEAWBPG2 Name = 'S12H08SEAPG2' # print 'Importing Archetype: ' + Name #### Input Variables NoOfStories = 12 Thickness = 20. Length = 14. * 12. Flange_Thickness = 7*12. # Assume 6' Long Core Long_Spacing = 4 BarSize = 8.0 Rho = 1.6 #In Fraction Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section1 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing, Thickness - 3.5) BarSize = 8.0 Rho = 1.0 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section2 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 16. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 4.0 Rho = 0.45 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section3 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section4 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) Sections = [Section1, Section1, Section1, Section2, Section2, Section2, Section3, Section3, Section3, Section4, Section4, Section4, ] S12H08SEAPG2 = CreateArchetype() Archetypes.append(S12H08SEAPG2) Name = 'S12H08SEAWBPG2' NoOfStories = 16 Sections = [ Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section3, Section3, Section3, Section4, Section4, Section4, ] S12H08SEAWBPG2 = CreateArchetype(Basements) Archetypes.append(S12H08SEAWBPG2) #endregion #region Archetype S16H08SEAPG2 and S16H08SEAWBPG2 Name = 'S16H08SEAPG2' #### Input Variables NoOfStories = 16 Thickness = 22. Length = 16. * 12. Flange_Thickness = 8.*12. # Assume 6' Long Core Long_Spacing = 4 BarSize = 8.0 Rho = 1.4 #In Fraction Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section1 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing, Thickness - 3.5) BarSize = 8.0 Rho = 1.0 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section2 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 16. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 4.0 Rho = 0.35 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section3 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section4 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) Sections = [Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, ] S16H08SEAPG2 = CreateArchetype() Archetypes.append(S16H08SEAPG2) Name = 'S16H08SEAWBPG2' NoOfStories = 20 # Include Basement Floors Here Sections = [Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, ] S16H08SEAWBPG2 = CreateArchetype(Basements) Archetypes.append(S16H08SEAWBPG2) #endregion #region Archetype S20H08SEAPG2 and S20H08SEAWBPG2 Name = 'S20H08SEAPG2' # print 'Importing Archetype: ' + Name #### Input Variables NoOfStories = 20 Thickness = 24. Length = 18. * 12. Flange_Thickness = 9*12. # Assume 6' Long Core Long_Spacing = 4 BarSize = 8.0 Rho = 1.2 #In Fraction Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section1 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing, Thickness - 3.5) BarSize = 8.0 Rho = 0.9 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section2 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 18. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 4.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section3 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section4 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) ThicknessBelow = float(Thickness) Thickness = 18. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section5 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) Sections = [Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, Section5, Section5, Section5, Section5, ] S20H08SEA = CreateArchetype() Archetypes.append(S20H08SEA) Name = 'S20H08SEAWBPG2' NoOfStories = 24 # Include Basement Floors Here Sections = [Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, Section5, Section5, Section5, Section5, ] S20H08SEAWBPG2 = CreateArchetype(Basements) Archetypes.append(S20H08SEAWBPG2) #endregion #region Archetype S24H08SEAPG2 and S24H08SEAWBPG2 Name = 'S24H08SEAPG2' # print 'Importing Archetype: ' + Name #### Input Variables NoOfStories = 24 Thickness = 28 Length = 21. * 12. Flange_Thickness = 10.5*12. # Assume 6' Long Core Long_Spacing = 4 BarSize = 5.0 Rho = 0.7 #In Fraction Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section1 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing, Thickness - 3.5) BarSize = 5.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section2 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2., Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 18. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 4.0 Rho = 0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section3 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2., Thickness - 3.5) BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section4 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) ThicknessBelow = float(Thickness) Thickness = 18. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section5 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section6 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) Sections = [Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, Section5, Section5, Section5, Section5, Section6, Section6, Section6, Section6, ] S24H08SEAPG2 = CreateArchetype() Archetypes.append(S24H08SEAPG2) Name = 'S24H08SEAWBPG2' NoOfStories = 28 Sections = [Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, Section5, Section5, Section5, Section5, Section6, Section6, Section6, Section6, ] S24H08SEAWBPG2 = CreateArchetype(Basements) Archetypes.append(S24H08SEAWBPG2) #endregion ##### 2014 Maps ###### #region Archetype S4H14SEAPG2 and S4H14SEAWBPG2 Name = 'S4H14SEAPG2' # print 'Importing Archetype: ' + Name # Compute Seismic Weight NoOfStories = 4 YGrids = [0] + np.array(np.arange(0,(NoOfStories)*13*12, 13*12)+15*12).tolist() DeadLoads = np.ones(NoOfStories) * DL / 1000. DeadLoads[-1] = DeadLoads[-1] * DL_Roof / DL LiveLoads = np.ones(NoOfStories) * LL / 1000. LiveLoads[-1] = LiveLoads[-1] * LL_Roof / LL MassPerSqFt = DL / 1000. Mass = np.ones(NoOfStories) * MassPerSqFt * FloorArea Mass[-1] = FloorArea * DL_Roof / 1000. # Adjust for Roof Weight WallTribArea = FloorArea * 0.5 WeightPerSqFt = DL BuildingWeight = np.ones(NoOfStories) * WeightPerSqFt * FloorArea BuildingWeight[-1] = 152. / 1000. * FloorArea # Adjust for Roof Weight # Seismic Hazard R = 6; Cd = 5 SaDesign, Sds, CuTa = GetSeattle2008Hazard(YGrids[-1], R=R) Thickness = 18. Length = 12. * 12. Long_Spacing = 4 NoOfCols = 12 BarSize = 10. Ag = ( (NoOfCols - 1) * Long_Spacing + 6 ) * Thickness Rho = ( NoOfCols * 2 + 2 ) * np.pi * ( BarSize / 2. / 8.) ** 2. / Ag # print Rho Section1 = PlanarWallSection(Length, Thickness, (NoOfCols - 1) * Long_Spacing + 6, (NoOfCols - 1) * Long_Spacing + 6, BarSize, [3] + (np.ones(NoOfCols - 2) * 2.).tolist() + [3], [3] + (np.ones(NoOfCols - 2) * 2.).tolist() + [3], 0.255, 4.037, fpc_core, fy, fu, 3, 4., NoOfCols, 3) NoOfCols = 10 BarSize = 8.0 Ag = ( (NoOfCols - 1) * Long_Spacing + 6 ) * Thickness Rho = ( NoOfCols * 2 + 2 ) * np.pi * ( BarSize / 2. / 8.) ** 2. / Ag # print Rho Section2 = PlanarWallSection(Length, Thickness, (NoOfCols - 1) * Long_Spacing + 6, (NoOfCols - 1) * Long_Spacing + 6, BarSize, [3] + (np.ones(NoOfCols - 2) * 2.).tolist() + [3], [3] + (np.ones(NoOfCols - 2) * 2.).tolist() + [3], 0.255, 4.037, fpc_core, fy, fu, 3, 4., 8, 3) Section3 = PlanarWallSection(Length, Thickness, 0, 0, 10.173, [], [], 0.255, 4.037, fpc_core, fy, fu, None, None, None, None) Sections = [Section1, Section1, Section2, Section2] S4H14SEAPG2 = CreateArchetype(Use2008Maps = False) Archetypes.append(S4H14SEAPG2) Name = 'S4H14SEAWBPG2' NoOfStories = 6 Sections = [ Section1, Section1, Section1, Section1, Section2, Section2 ] S4H14SEAWBPG2 = CreateArchetype(Basements2Levels, Use2008Maps = False) Archetypes.append(S4H14SEAWBPG2) #endregion #region Archetype S8H14SEAPG2 and S8H14SEAWBPG2 Name = 'S8H14SEAPG2' # print 'Importing Archetype: ' + Name #### Input Variables NoOfStories = 8 Thickness = 24. Length = 12. * 12. Flange_Thickness = 6*12. # Assume 6' Long Core Long_Spacing = 4 BarSize = 8.0 Rho = 2.0 #In Fraction Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section1 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing, Thickness - 3.5) BarSize = 8.0 Rho = 1.0 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section2 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section3 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) Sections = [Section1, Section1, Section1, Section2, Section2, Section2, Section3, Section3, ] S8H14SEAPG2 = CreateArchetype(Use2008Maps = False) Archetypes.append(S8H14SEAPG2) Name = 'S8H14SEAWBPG2' NoOfStories = 11 Sections = [ Section1, Section1, Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section3, Section3, ] S8H14SEAWBPG2 = CreateArchetype(Basements3Levels, Use2008Maps = False) Archetypes.append(S8H14SEAWBPG2) #endregion #region Archetype S12H14SEAPG2 and S12H14SEAWBPG2 Name = 'S12H14SEAPG2' # print 'Importing Archetype: ' + Name #### Input Variables NoOfStories = 12 Thickness = 24. Length = 15. * 12. Flange_Thickness = 7.5*12. # Assume 6' Long Core Long_Spacing = 4 BarSize = 8.0 Rho = 1.6 #In Fraction Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section1 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing, Thickness - 3.5) BarSize = 8.0 Rho = 1.2 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section2 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 18. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 4.0 Rho = 0.7 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section3 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section4 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) Sections = [Section1, Section1, Section1, Section2, Section2, Section2, Section3, Section3, Section3, Section4, Section4, Section4, ] S12H14SEAPG2 = CreateArchetype(Use2008Maps = False) Archetypes.append(S12H14SEAPG2) Name = 'S12H14SEAWBPG2' NoOfStories = 16 Sections = [ Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section3, Section3, Section3, Section4, Section4, Section4, ] S12H14SEAWBPG2 = CreateArchetype(Basements, Use2008Maps = False) Archetypes.append(S12H14SEAWBPG2) #endregion #region Archetype S16H14SEAPG2 and S16H14SEAWBPG2 Name = 'S16H14SEAPG2' #### Input Variables NoOfStories = 16 Thickness = 28. Length = 17. * 12. Flange_Thickness = 8.5*12. # Assume 6' Long Core Long_Spacing = 4 BarSize = 8.0 Rho = 1.5 #In Fraction Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section1 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing, Thickness - 3.5) BarSize = 8.0 Rho = 1.0 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section2 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 20. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 5.0 Rho = 0.60 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section3 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section4 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) Sections = [Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, ] S16H14SEAPG2 = CreateArchetype(Use2008Maps = False) Archetypes.append(S16H14SEAPG2) Name = 'S16H14SEAWBPG2' NoOfStories = 20 # Include Basement Floors Here Sections = [Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, ] S16H14SEAWBPG2 = CreateArchetype(Basements, False) Archetypes.append(S16H14SEAWBPG2) #endregion #region Archetype S20H14SEAPG2 and S20H14SEAWBPG2 Name = 'S20H14SEAPG2' # print 'Importing Archetype: ' + Name #### Input Variables NoOfStories = 20 Thickness = 30. Length = 19. * 12. Flange_Thickness = 9.5*12. # Assume 6' Long Core Long_Spacing = 4 BarSize = 9.0 Rho = 1.4 #In Fraction Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section1 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing, Thickness - 3.5) BarSize = 8.0 Rho = 0.95 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section2 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 22. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 6.0 Rho =0.7 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section3 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section4 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) ThicknessBelow = float(Thickness) Thickness = 22. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section5 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) Sections = [Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, Section5, Section5, Section5, Section5, ] S20H14SEAPG2 = CreateArchetype(Use2008Maps = False) Archetypes.append(S20H14SEAPG2) Name = 'S20H14SEAWBPG2' NoOfStories = 24 # Include Basement Floors Here Sections = [Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, Section5, Section5, Section5, Section5, ] S20H14SEAWBPG2 = CreateArchetype(Basements, False) Archetypes.append(S20H14SEAWBPG2) #endregion #region Archetype S24H14SEAPG2 and S24H14SEAWBPG2 Name = 'S24H14SEAPG2' # print 'Importing Archetype: ' + Name #### Input Variables NoOfStories = 24 Thickness = 32. Length = 21. * 12. Flange_Thickness = 10.5*12. # Assume 6' Long Core Long_Spacing = 4 BarSize = 9.0 Rho = 1.3 #In Fraction Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section1 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing, Thickness - 3.5) BarSize = 8.0 Rho = 1.1 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section2 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2., Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 26. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 7.0 Rho = 0.8 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section3 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2., Thickness - 3.5) BarSize = 4.0 Rho = 0.35 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section4 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) ThicknessBelow = float(Thickness) Thickness = 26. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section5 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section6 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) Sections = [Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, Section5, Section5, Section5, Section5, Section6, Section6, Section6, Section6, ] S24H14SEAPG2 = CreateArchetype(Use2008Maps = False) Archetypes.append(S24H14SEAPG2) Name = 'S24H14SEAWBPG2' NoOfStories = 28 Sections = [Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, Section5, Section5, Section5, Section5, Section6, Section6, Section6, Section6, ] S24H14SEAWBPG2 = CreateArchetype(Basements, False) Archetypes.append(S24H14SEAWBPG2) #endregion #region Archetype S24H14SEAPG2 and S24H14SEAWBPG2 Name = 'S24H14SEAPG2TEST' # print 'Importing Archetype: ' + Name #### Input Variables NoOfStories = 24 Thickness = 32. Length = 21. * 12. Flange_Thickness = 10.5*12. # Assume 6' Long Core Long_Spacing = 4 BarSize = 9.0 Rho = 1.3 #In Fraction Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section1 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing, Thickness - 3.5) BarSize = 8.0 Rho = 1.1 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section2 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2., Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 26. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 7.0 Rho = 0.8 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section3 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2., Thickness - 3.5) BarSize = 4.0 Rho = 0.35 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section4 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) ThicknessBelow = float(Thickness) Thickness = 26. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section5 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section6 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) Sections = [Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, ] S24H14SEAPG2TEST = CreateArchetype(Use2008Maps = False) Archetypes.append(S24H14SEAPG2TEST) Name = 'S24H14SEAWBPG2TEST' NoOfStories = 28 Sections = [Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, ] S24H14SEAWBPG2TEST = CreateArchetype(Basements, False) Archetypes.append(S24H14SEAWBPG2TEST) #endregion ##### 2014 Maps ###### # PG3 : 25% Over-strength on ASCE 7 loads #region Archetype S4H14SEAPG3 and S4H14SEAWBPG3 Name = 'S4H14SEAPG3' # print 'Importing Archetype: ' + Name # Compute Seismic Weight NoOfStories = 4 YGrids = [0] + np.array(np.arange(0,(NoOfStories)*13*12, 13*12)+15*12).tolist() DeadLoads = np.ones(NoOfStories) * DL / 1000. DeadLoads[-1] = DeadLoads[-1] * DL_Roof / DL LiveLoads = np.ones(NoOfStories) * LL / 1000. LiveLoads[-1] = LiveLoads[-1] * LL_Roof / LL MassPerSqFt = DL / 1000. Mass = np.ones(NoOfStories) * MassPerSqFt * FloorArea Mass[-1] = FloorArea * DL_Roof / 1000. # Adjust for Roof Weight WallTribArea = FloorArea * 0.5 WeightPerSqFt = DL BuildingWeight = np.ones(NoOfStories) * WeightPerSqFt * FloorArea BuildingWeight[-1] = 152. / 1000. * FloorArea # Adjust for Roof Weight # Seismic Hazard R = 6; Cd = 5 SaDesign, Sds, CuTa = GetSeattle2014Hazard(YGrids[-1], R=R, Overstrength = 1.25) Thickness = 20. Length = 13. * 12. Long_Spacing = 4 NoOfCols = 16 BarSize = 10. Ag = ( (NoOfCols - 1) * Long_Spacing + 6 ) * Thickness Rho = ( NoOfCols * 2 + 2 ) * np.pi * ( BarSize / 2. / 8.) ** 2. / Ag # print Rho Section1 = PlanarWallSection(Length, Thickness, (NoOfCols - 1) * Long_Spacing + 6, (NoOfCols - 1) * Long_Spacing + 6, BarSize, [3] + (np.ones(NoOfCols - 2) * 2.).tolist() + [3], [3] + (np.ones(NoOfCols - 2) * 2.).tolist() + [3], 0.255, 4.037, fpc_core, fy, fu, 3, 4., NoOfCols, 3) NoOfCols = 16 BarSize = 8.0 Ag = ( (NoOfCols - 1) * Long_Spacing + 6 ) * Thickness Rho = ( NoOfCols * 2 + 2 ) * np.pi * ( BarSize / 2. / 8.) ** 2. / Ag # print Rho Section2 = PlanarWallSection(Length, Thickness, (NoOfCols - 1) * Long_Spacing + 6, (NoOfCols - 1) * Long_Spacing + 6, BarSize, [3] + (np.ones(NoOfCols - 2) * 2.).tolist() + [3], [3] + (np.ones(NoOfCols - 2) * 2.).tolist() + [3], 0.255, 4.037, fpc_core, fy, fu, 3, 4., 8, 3) Section3 = PlanarWallSection(Length, Thickness, 0, 0, 10.173, [], [], 0.255, 4.037, fpc_core, fy, fu, None, None, None, None) Sections = [Section1, Section1, Section2, Section2] S4H14SEAPG3 = CreateArchetype(Use2008Maps = False, Overstrength = 1.25) Archetypes.append(S4H14SEAPG3) Name = 'S4H14SEAWBPG3' NoOfStories = 6 Sections = [ Section1, Section1, Section1, Section1, Section2, Section2 ] S4H14SEAWBPG3 = CreateArchetype(Basements2Levels, Use2008Maps = False, Overstrength = 1.25) Archetypes.append(S4H14SEAWBPG3) #endregion #region Archetype S8H14SEAPG3 and S8H14SEAWBPG3 Name = 'S8H14SEAPG3' # print 'Importing Archetype: ' + Name #### Input Variables NoOfStories = 8 Thickness = 24. Length = 14. * 12. Flange_Thickness = 7*12. # Assume 6' Long Core Long_Spacing = 4 BarSize = 8.0 Rho = 2.0 #In Fraction Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section1 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing, Thickness - 3.5) BarSize = 8.0 Rho = 1.1 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section2 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 4.0 Rho = 0.30 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section3 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) Sections = [Section1, Section1, Section1, Section2, Section2, Section2, Section3, Section3, ] S8H14SEAPG3 = CreateArchetype(Use2008Maps = False, Overstrength = 1.25) Archetypes.append(S8H14SEAPG3) Name = 'S8H14SEAWBPG3' NoOfStories = 11 Sections = [ Section1, Section1, Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section3, Section3, ] S8H14SEAWBPG3 = CreateArchetype(Basements3Levels, Use2008Maps = False, Overstrength = 1.25) Archetypes.append(S8H14SEAWBPG3) #endregion #region Archetype S12H14SEAPG3 and S12H14SEAWBPG3 Name = 'S12H14SEAPG3' # print 'Importing Archetype: ' + Name #### Input Variables NoOfStories = 12 Thickness = 24. Length = 18. * 12. Flange_Thickness = 9*12. # Assume 6' Long Core Long_Spacing = 4 BarSize = 8.0 Rho = 1.55 #In Fraction Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section1 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing, Thickness - 3.5) BarSize = 8.0 Rho = 1.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section2 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 18. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 4.0 Rho = 0.75 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section3 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section4 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) Sections = [Section1, Section1, Section1, Section2, Section2, Section2, Section3, Section3, Section3, Section4, Section4, Section4, ] S12H14SEAPG3 = CreateArchetype(Use2008Maps = False, Overstrength = 1.25) Archetypes.append(S12H14SEAPG3) Name = 'S12H14SEAWBPG3' NoOfStories = 16 Sections = [ Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section3, Section3, Section3, Section4, Section4, Section4, ] S12H14SEAWBPG3 = CreateArchetype(Basements, Use2008Maps = False, Overstrength = 1.25) Archetypes.append(S12H14SEAWBPG3) #endregion #region Archetype S16H14SEAPG3 and S16H14SEAWBPG3 Name = 'S16H14SEAPG3' #### Input Variables NoOfStories = 16 Thickness = 34. Length = 22. * 12. Flange_Thickness = 11*12. # Assume 6' Long Core Long_Spacing = 4 BarSize = 8.0 Rho = 0.9 #In Fraction Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section1 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing, Thickness - 3.5) BarSize = 7.0 Rho = 0.8 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section2 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 24. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 5.0 Rho = 0.60 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section3 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section4 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) Sections = [Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, ] S16H14SEAPG3 = CreateArchetype(Use2008Maps = False, Overstrength = 1.25) Archetypes.append(S16H14SEAPG3) Name = 'S16H14SEAWBPG3' NoOfStories = 20 # Include Basement Floors Here Sections = [Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, ] S16H14SEAWBPG3 = CreateArchetype(Basements, False, Overstrength = 1.25) Archetypes.append(S16H14SEAWBPG3) #endregion #region Archetype S20H14SEAPG3 and S20H14SEAWBPG3 Name = 'S20H14SEAPG3' # print 'Importing Archetype: ' + Name #### Input Variables NoOfStories = 20 Thickness = 40. Length = 26. * 12. Flange_Thickness = 13.*12. # Assume 6' Long Core Long_Spacing = 4 BarSize = 8.0 Rho = 0.675 #In Fraction Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section1 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing, Thickness - 3.5) BarSize = 7.0 Rho = 0.6 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section2 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 26. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 6.0 Rho =0.6 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section3 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section4 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) ThicknessBelow = float(Thickness) Thickness = 22. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section5 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) Sections = [Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, Section5, Section5, Section5, Section5, ] S20H14SEAPG3 = CreateArchetype(Use2008Maps = False, Overstrength = 1.25) Archetypes.append(S20H14SEAPG3) Name = 'S20H14SEAWBPG3' NoOfStories = 24 # Include Basement Floors Here Sections = [Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, Section5, Section5, Section5, Section5, ] S20H14SEAWBPG3 = CreateArchetype(Basements, False, Overstrength = 1.25) Archetypes.append(S20H14SEAWBPG3) #endregion #region Archetype S24H14SEAPG3 and S24H14SEAWBPG3 Name = 'S24H14SEAPG3' # print 'Importing Archetype: ' + Name #### Input Variables NoOfStories = 24 Thickness = 44. Length = 30. * 12. Flange_Thickness = 15*12. # Assume 6' Long Core Long_Spacing = 4 BarSize = 7.0 Rho = 0.525 #In Fraction Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section1 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing, Thickness - 3.5) BarSize = 7.0 Rho = 0.525 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section2 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2., Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 30. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 6.0 Rho = 0.55 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section3 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2., Thickness - 3.5) BarSize = 4.0 Rho = 0.30 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section4 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) ThicknessBelow = float(Thickness) Thickness = 24. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section5 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section6 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) Sections = [Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, Section5, Section5, Section5, Section5, Section6, Section6, Section6, Section6, ] S24H14SEAPG3 = CreateArchetype(Use2008Maps = False, Overstrength = 1.25) Archetypes.append(S24H14SEAPG3) Name = 'S24H14SEAWBPG3' NoOfStories = 28 Sections = [Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, Section5, Section5, Section5, Section5, Section6, Section6, Section6, Section6, ] S24H14SEAWBPG3 = CreateArchetype(Basements, False, Overstrength = 1.25) Archetypes.append(S24H14SEAWBPG3) #endregion # PG4 : 50% Over-strength on ASCE 7 loads #region Archetype S4H14SEAPG4 and S4H14SEAWBPG4 Name = 'S4H14SEAPG4' # print 'Importing Archetype: ' + Name # Compute Seismic Weight NoOfStories = 4 YGrids = [0] + np.array(np.arange(0,(NoOfStories)*13*12, 13*12)+15*12).tolist() DeadLoads = np.ones(NoOfStories) * DL / 1000. DeadLoads[-1] = DeadLoads[-1] * DL_Roof / DL LiveLoads = np.ones(NoOfStories) * LL / 1000. LiveLoads[-1] = LiveLoads[-1] * LL_Roof / LL MassPerSqFt = DL / 1000. Mass = np.ones(NoOfStories) * MassPerSqFt * FloorArea Mass[-1] = FloorArea * DL_Roof / 1000. # Adjust for Roof Weight WallTribArea = FloorArea * 0.5 WeightPerSqFt = DL BuildingWeight = np.ones(NoOfStories) * WeightPerSqFt * FloorArea BuildingWeight[-1] = 152. / 1000. * FloorArea # Adjust for Roof Weight # Seismic Hazard R = 6; Cd = 5 SaDesign, Sds, CuTa = GetSeattle2014Hazard(YGrids[-1], R=R, Overstrength = 1.50) Thickness = 22. Length = 15. * 12. Long_Spacing = 4 NoOfCols = 18 BarSize = 10. Ag = ( (NoOfCols - 1) * Long_Spacing + 6 ) * Thickness Rho = ( NoOfCols * 2 + 2 ) * np.pi * ( BarSize / 2. / 8.) ** 2. / Ag # print Rho Section1 = PlanarWallSection(Length, Thickness, (NoOfCols - 1) * Long_Spacing + 6, (NoOfCols - 1) * Long_Spacing + 6, BarSize, [3] + (np.ones(NoOfCols - 2) * 2.).tolist() + [3], [3] + (np.ones(NoOfCols - 2) * 2.).tolist() + [3], 0.255, 4.037, fpc_core, fy, fu, 3, 4., NoOfCols, 3) NoOfCols = 18 BarSize = 8.0 Ag = ( (NoOfCols - 1) * Long_Spacing + 6 ) * Thickness Rho = ( NoOfCols * 2 + 2 ) * np.pi * ( BarSize / 2. / 8.) ** 2. / Ag # print Rho Section2 = PlanarWallSection(Length, Thickness, (NoOfCols - 1) * Long_Spacing + 6, (NoOfCols - 1) * Long_Spacing + 6, BarSize, [3] + (np.ones(NoOfCols - 2) * 2.).tolist() + [3], [3] + (np.ones(NoOfCols - 2) * 2.).tolist() + [3], 0.255, 4.037, fpc_core, fy, fu, 3, 4., 8, 3) Section3 = PlanarWallSection(Length, Thickness, 0, 0, 10.173, [], [], 0.255, 4.037, fpc_core, fy, fu, None, None, None, None) Sections = [Section1, Section1, Section2, Section2] S4H14SEAPG4 = CreateArchetype(Use2008Maps = False, Overstrength = 1.50) Archetypes.append(S4H14SEAPG4) Name = 'S4H14SEAWBPG4' NoOfStories = 6 Sections = [ Section1, Section1, Section1, Section1, Section2, Section2 ] S4H14SEAWBPG4 = CreateArchetype(Basements2Levels, Use2008Maps = False, Overstrength = 1.50) Archetypes.append(S4H14SEAWBPG4) #endregion #region Archetype S8H14SEAPG4 and S8H14SEAWBPG4 Name = 'S8H14SEAPG4' # print 'Importing Archetype: ' + Name #### Input Variables NoOfStories = 8 Thickness = 26. Length = 15. * 12. Flange_Thickness = 7.5*12. # Assume 6' Long Core Long_Spacing = 4 BarSize = 10.0 Rho = 2.0 #In Fraction Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section1 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing, Thickness - 3.5) BarSize = 9.0 Rho = 1.3 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section2 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 5.0 Rho = 0.40 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section3 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) Sections = [Section1, Section1, Section1, Section2, Section2, Section2, Section3, Section3, ] S8H14SEAPG4 = CreateArchetype(Use2008Maps = False, Overstrength = 1.50) Archetypes.append(S8H14SEAPG4) Name = 'S8H14SEAWBPG4' NoOfStories = 11 Sections = [ Section1, Section1, Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section3, Section3, ] S8H14SEAWBPG4 = CreateArchetype(Basements3Levels, Use2008Maps = False, Overstrength = 1.50) Archetypes.append(S8H14SEAWBPG4) #endregion #region Archetype S12H14SEAPG4 and S12H14SEAWBPG4 Name = 'S12H14SEAPG4' # print 'Importing Archetype: ' + Name #### Input Variables NoOfStories = 12 Thickness = 30. Length = 18. * 12. Flange_Thickness = 9.0*12. # Assume 6' Long Core Long_Spacing = 4 BarSize = 9.0 Rho = 1.70 #In Fraction Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section1 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing, Thickness - 3.5) BarSize = 8.0 Rho = 1.35 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section2 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 22. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 6.0 Rho = 0.9 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section3 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 4.0 Rho = 0.35 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section4 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) Sections = [Section1, Section1, Section1, Section2, Section2, Section2, Section3, Section3, Section3, Section4, Section4, Section4, ] S12H14SEAPG4 = CreateArchetype(Use2008Maps = False, Overstrength = 1.50) Archetypes.append(S12H14SEAPG4) Name = 'S12H14SEAWBPG4' NoOfStories = 16 Sections = [ Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section3, Section3, Section3, Section4, Section4, Section4, ] S12H14SEAWBPG4 = CreateArchetype(Basements, Use2008Maps = False, Overstrength = 1.50) Archetypes.append(S12H14SEAWBPG4) #endregion #region Archetype S16H14SEAPG4 and S16H14SEAWBPG4 Name = 'S16H14SEAPG4' #### Input Variables NoOfStories = 16 Thickness = 34. Length = 23. * 12. Flange_Thickness = 11.5*12. # Assume 6' Long Core Long_Spacing = 4 BarSize = 9.0 Rho = 1.2 #In Fraction Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section1 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing, Thickness - 3.5) BarSize = 8.0 Rho = 0.9 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section2 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 26. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 5.0 Rho = 0.65 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section3 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section4 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) Sections = [Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, ] S16H14SEAPG4 = CreateArchetype(Use2008Maps = False, Overstrength = 1.50) Archetypes.append(S16H14SEAPG4) Name = 'S16H14SEAWBPG4' NoOfStories = 20 # Include Basement Floors Here Sections = [Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, ] S16H14SEAWBPG4 = CreateArchetype(Basements, False, Overstrength = 1.50) Archetypes.append(S16H14SEAWBPG4) #endregion #region Archetype S20H14SEAPG4 and S20H14SEAWBPG4 Name = 'S20H14SEAPG4' # print 'Importing Archetype: ' + Name #### Input Variables NoOfStories = 20 Thickness = 44. Length = 27. * 12. Flange_Thickness = 13.5*12. # Assume 6' Long Core Long_Spacing = 4 BarSize = 8.0 Rho = 0.825 #In Fraction Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section1 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing, Thickness - 3.5) BarSize = 8.0 Rho = 0.7 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section2 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 30. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 8.0 Rho =0.70 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section3 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 5.0 Rho = 0.4 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section4 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) ThicknessBelow = float(Thickness) Thickness = 22. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section5 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) Sections = [Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, Section5, Section5, Section5, Section5, ] S20H14SEAPG4 = CreateArchetype(Use2008Maps = False, Overstrength = 1.50) Archetypes.append(S20H14SEAPG4) Name = 'S20H14SEAWBPG4' NoOfStories = 24 # Include Basement Floors Here Sections = [Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, Section5, Section5, Section5, Section5, ] S20H14SEAWBPG4 = CreateArchetype(Basements, False, Overstrength = 1.50) Archetypes.append(S20H14SEAWBPG4) #endregion #region Archetype S24H14SEAPG4 and S24H14SEAWBPG4 Name = 'S24H14SEAPG4' # print 'Importing Archetype: ' + Name #### Input Variables NoOfStories = 24 Thickness = 50. Length = 31. * 12. Flange_Thickness = 15.5*12. # Assume 6' Long Core Long_Spacing = 4 BarSize = 8.0 Rho = 0.7 #In Fraction Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section1 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing, Thickness - 3.5) BarSize = 8.0 Rho = 0.6 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section2 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2., Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 36. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 7.0 Rho = 0.65 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section3 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2., Thickness - 3.5) BarSize = 5.0 Rho = 0.40 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section4 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) ThicknessBelow = float(Thickness) Thickness = 26. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section5 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section6 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) Sections = [Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, Section5, Section5, Section5, Section5, Section6, Section6, Section6, Section6, ] S24H14SEAPG4 = CreateArchetype(Use2008Maps = False, Overstrength = 1.50) Archetypes.append(S24H14SEAPG4) Name = 'S24H14SEAWBPG4' NoOfStories = 28 Sections = [Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, Section5, Section5, Section5, Section5, Section6, Section6, Section6, Section6, ] S24H14SEAWBPG4 = CreateArchetype(Basements, False, Overstrength = 1.50) Archetypes.append(S24H14SEAWBPG4) #endregion # PG5: 1.5% Drift Limit #region Archetype S4H14SEAPG5 and S4H14SEAWBPG5 Name = 'S4H14SEAPG5' # print 'Importing Archetype: ' + Name # Compute Seismic Weight NoOfStories = 4 YGrids = [0] + np.array(np.arange(0,(NoOfStories)*13*12, 13*12)+15*12).tolist() DeadLoads = np.ones(NoOfStories) * DL / 1000. DeadLoads[-1] = DeadLoads[-1] * DL_Roof / DL LiveLoads = np.ones(NoOfStories) * LL / 1000. LiveLoads[-1] = LiveLoads[-1] * LL_Roof / LL MassPerSqFt = DL / 1000. Mass = np.ones(NoOfStories) * MassPerSqFt * FloorArea Mass[-1] = FloorArea * DL_Roof / 1000. # Adjust for Roof Weight WallTribArea = FloorArea * 0.5 WeightPerSqFt = DL BuildingWeight = np.ones(NoOfStories) * WeightPerSqFt * FloorArea BuildingWeight[-1] = 152. / 1000. * FloorArea # Adjust for Roof Weight # Seismic Hazard R = 6; Cd = 5 SaDesign, Sds, CuTa = GetSeattle2008Hazard(YGrids[-1], R=R) Thickness = 24. Length = 13. * 12. Long_Spacing = 4 NoOfCols = 9 BarSize = 10. Ag = ( (NoOfCols - 1) * Long_Spacing + 6 ) * Thickness Rho = ( NoOfCols * 2 + 2 ) * np.pi * ( BarSize / 2. / 8.) ** 2. / Ag # print Rho Section1 = PlanarWallSection(Length, Thickness, (NoOfCols - 1) * Long_Spacing + 6, (NoOfCols - 1) * Long_Spacing + 6, BarSize, [3] + (np.ones(NoOfCols - 2) * 2.).tolist() + [3], [3] + (np.ones(NoOfCols - 2) * 2.).tolist() + [3], 0.255, 4.037, fpc_core, fy, fu, 3, 4., NoOfCols, 3) NoOfCols = 9 BarSize = 8.0 Ag = ( (NoOfCols - 1) * Long_Spacing + 6 ) * Thickness Rho = ( NoOfCols * 2 + 2 ) * np.pi * ( BarSize / 2. / 8.) ** 2. / Ag # print Rho Section2 = PlanarWallSection(Length, Thickness, (NoOfCols - 1) * Long_Spacing + 6, (NoOfCols - 1) * Long_Spacing + 6, BarSize, [3] + (np.ones(NoOfCols - 2) * 2.).tolist() + [3], [3] + (np.ones(NoOfCols - 2) * 2.).tolist() + [3], 0.255, 4.037, fpc_core, fy, fu, 3, 4., 8, 3) Section3 = PlanarWallSection(Length, Thickness, 0, 0, 10.173, [], [], 0.255, 4.037, fpc_core, fy, fu, None, None, None, None) Sections = [Section1, Section1, Section2, Section2] S4H14SEAPG5 = CreateArchetype(Use2008Maps = False) Archetypes.append(S4H14SEAPG5) Name = 'S4H14SEAWBPG5' NoOfStories = 6 Sections = [ Section1, Section1, Section1, Section1, Section2, Section2 ] S4H14SEAWBPG5 = CreateArchetype(Basements2Levels, Use2008Maps = False) Archetypes.append(S4H14SEAWBPG5) #endregion #region Archetype S8H14SEAPG5 and S8H14SEAWBPG5 Name = 'S8H14SEAPG5' # print 'Importing Archetype: ' + Name #### Input Variables NoOfStories = 8 Thickness = 24. Length = 14. * 12. Flange_Thickness = 7*12. # Assume 6' Long Core Long_Spacing = 4 BarSize = 8.0 Rho = 1.25 #In Fraction Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section1 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing, Thickness - 3.5) BarSize = 8.0 Rho = 0.8 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section2 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section3 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) Sections = [Section1, Section1, Section1, Section2, Section2, Section2, Section3, Section3, ] S8H14SEAPG5 = CreateArchetype(Use2008Maps = False) Archetypes.append(S8H14SEAPG5) Name = 'S8H14SEAWBPG5' NoOfStories = 11 Sections = [ Section1, Section1, Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section3, Section3, ] S8H14SEAWBPG5 = CreateArchetype(Basements3Levels, Use2008Maps = False) Archetypes.append(S8H14SEAWBPG5) #endregion #region Archetype S12H14SEAPG5 and S12H14SEAWBPG5 Name = 'S12H14SEAPG5' # print 'Importing Archetype: ' + Name #### Input Variables NoOfStories = 12 Thickness = 26. Length = 17. * 12. Flange_Thickness = 8.5*12. # Assume 6' Long Core Long_Spacing = 4 BarSize = 8.0 Rho = 1.025 #In Fraction Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section1 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing, Thickness - 3.5) BarSize = 7.0 Rho = 0.80 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section2 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 18. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 5.0 Rho = 0.60 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section3 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section4 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) Sections = [Section1, Section1, Section1, Section2, Section2, Section2, Section3, Section3, Section3, Section4, Section4, Section4, ] S12H14SEAPG5 = CreateArchetype(Use2008Maps = False) Archetypes.append(S12H14SEAPG5) Name = 'S12H14SEAWBPG5' NoOfStories = 16 Sections = [ Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section3, Section3, Section3, Section4, Section4, Section4, ] S12H14SEAWBPG5 = CreateArchetype(Basements, Use2008Maps = False) Archetypes.append(S12H14SEAWBPG5) #endregion #region Archetype S16H14SEAPG5 and S16H14SEAWBPG5 Name = 'S16H14SEAPG5' #### Input Variables NoOfStories = 16 Thickness = 32. Length = 20. * 12. Flange_Thickness = 10*12. # Assume 6' Long Core Long_Spacing = 4 BarSize = 8.0 Rho = 0.725 #In Fraction Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section1 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing, Thickness - 3.5) BarSize = 8.0 Rho = 0.6 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section2 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 18. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 5.0 Rho = 0.50 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section3 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section4 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) Sections = [Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, ] S16H14SEAPG5 = CreateArchetype(Use2008Maps = False) Archetypes.append(S16H14SEAPG5) Name = 'S16H14SEAWBPG5' NoOfStories = 20 # Include Basement Floors Here Sections = [Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, ] S16H14SEAWBPG5 = CreateArchetype(Basements, False) Archetypes.append(S16H14SEAWBPG5) #endregion #region Archetype S20H14SEAPG5 and S20H14SEAWBPG5 Name = 'S20H14SEAPG5' # print 'Importing Archetype: ' + Name #### Input Variables NoOfStories = 20 Thickness = 36. Length = 23. * 12. Flange_Thickness = 11.5*12. # Assume 6' Long Core Long_Spacing = 4 BarSize = 7.0 Rho = 0.525 #In Fraction Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section1 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing, Thickness - 3.5) BarSize = 7.0 Rho = 0.525 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section2 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 20. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 6.0 Rho =0.5 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section3 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2, Thickness - 3.5) BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section4 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) ThicknessBelow = float(Thickness) Thickness = 22. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section5 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) Sections = [Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, Section5, Section5, Section5, Section5, ] S20H14SEAPG5 = CreateArchetype(Use2008Maps = False) Archetypes.append(S20H14SEAPG5) Name = 'S20H14SEAWBPG5' NoOfStories = 24 # Include Basement Floors Here Sections = [Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, Section5, Section5, Section5, Section5, ] S20H14SEAWBPG5 = CreateArchetype(Basements, False) Archetypes.append(S20H14SEAWBPG5) #endregion #region Archetype S24H14SEAPG5 and S24H14SEAWBPG5 Name = 'S24H14SEAPG5' # print 'Importing Archetype: ' + Name #### Input Variables NoOfStories = 24 Thickness = 40. Length = 25. * 12. Flange_Thickness = 12.5*12. # Assume 6' Long Core Long_Spacing = 4 BarSize = 7.0 Rho = 0.50 #In Fraction Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section1 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing, Thickness - 3.5) BarSize = 7.0 Rho = 0.501 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section2 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2., Thickness - 3.5) ThicknessBelow = float(Thickness) Thickness = 26. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 7.0 Rho = 0.55 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section3 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, 3., 4., Spacing*2., Thickness - 3.5) BarSize = 4.0 Rho = 0.35 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section4 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) ThicknessBelow = float(Thickness) Thickness = 20. Length = Length - (ThicknessBelow - Thickness) * 2. BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section5 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) BarSize = 4.0 Rho = 0.25 #In percentages Abar = np.pi*(BarSize / 8. / 2.)**2. Spacing = Abar * 2. / Thickness / Rho * 100 Section6 = IWallSection(Length, Flange_Thickness, Thickness, Rho, BarSize, fpc_core, fy, fu, None, None, None, None) Sections = [Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, Section5, Section5, Section5, Section5, Section6, Section6, Section6, Section6, ] S24H14SEAPG5 = CreateArchetype(Use2008Maps = False) Archetypes.append(S24H14SEAPG5) Name = 'S24H14SEAWBPG5' NoOfStories = 28 Sections = [Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section1, Section2, Section2, Section2, Section2, Section3, Section3, Section3, Section3, Section4, Section4, Section4, Section4, Section5, Section5, Section5, Section5, Section6, Section6, Section6, Section6, ] S24H14SEAWBPG5 = CreateArchetype(Basements, False) Archetypes.append(S24H14SEAWBPG5) #endregion # PG6: 1.25% Drift Limit #region Archetype S4H14SEAPG6 and S4H14SEAWBPG6 Name = 'S4H14SEAPG6' # print 'Importing Archetype: ' + Name # Compute Seismic Weight NoOfStories = 4 YGrids = [0] + np.array(np.arange(0,(NoOfStories)*13*12, 13*12)+15*12).tolist() DeadLoads = np.ones(NoOfStories) * DL / 1000. DeadLoads[-1] = DeadLoads[-1] * DL_Roof / DL LiveLoads = np.ones(NoOfStories) * LL / 1000. LiveLoads[-1] = LiveLoads[-1] * LL_Roof / LL MassPerSqFt = DL / 1000. Mass = np.ones(NoOfStories) * MassPerSqFt * FloorArea Mass[-1] = FloorArea * DL_Roof / 1000. # Adjust for Roof Weight WallTribArea = FloorArea * 0.5 WeightPerSqFt = DL BuildingWeight = np.ones(NoOfStories) * WeightPerSqFt * FloorArea BuildingWeight[-1] = 152. / 1000. * FloorArea # Adjust for Roof Weight # Seismic Hazard R = 6; Cd = 5 SaDesign, Sds, CuTa = GetSeattle2008Hazard(YGrids[-1], R=R) Thickness = 28. Length = 14. * 12. Long_Spacing = 4 NoOfCols = 10 BarSize = 9. Ag = ( (NoOfCols - 1) * Long_Spacing + 6 ) * Thickness Rho = ( NoOfCols * 2 + 2 ) * np.pi * ( BarSize / 2. / 8.) ** 2. / Ag # print Rho Section1 = PlanarWallSection(Length, Thickness, (NoOfCols - 1) * Long_Spacing + 6, (NoOfCols - 1) * Long_Spacing + 6, BarSize, [3] + (np.ones(NoOfCols - 2) * 2.).tolist() + [3], [3] + (np.ones(NoOfCols - 2) * 2.).tolist() + [3], 0.255, 4.037, fpc_core, fy, fu, 3, 4., NoOfCols, 3) NoOfCols = 8 BarSize = 8.0 Ag = ( (NoOfCols - 1) * Long_Spacing + 6 ) * Thickness Rho = ( NoOfCols * 2 + 2 ) * np.pi * ( BarSize / 2. / 8.) ** 2. / Ag # print Rho Section2 = PlanarWallSection(Length, Thickness, (NoOfCols - 1) * Long_Spacing + 6, (NoOfCols - 1) * Long_Spacing + 6, BarSize, [3] + (
np.ones(NoOfCols - 2)
numpy.ones
import numpy as np from datetime import timedelta import pandas as pd import matplotlib.pyplot as plt import matplotlib.ticker as ticker import matplotlib.colors as colors from pyadlml.dataset import DEVICE from pyadlml.dataset.stats.devices import duration_correlation, \ trigger_time_diff, device_tcorr, device_triggers_one_day, \ devices_trigger_count, devices_on_off_stats from pyadlml.dataset.plot.util import heatmap_square, func_formatter_seconds2time,\ heatmap, annotate_heatmap, savefig, _num_bars_2_figsize, \ _num_items_2_heatmap_square_figsize, _num_boxes_2_figsize, \ _num_items_2_heatmap_one_day_figsize, _num_items_2_heatmap_square_figsize_ver2 from pyadlml.dataset.devices import _is_dev_rep2, device_rep1_2_rep2 from pyadlml.util import get_sequential_color, get_secondary_color, get_primary_color, get_diverging_color def hist_trigger_time_diff(df_devs=None, x=None, n_bins=50, figsize=(10, 6), color=None, file_path=None): """ Plot a histogram of the differences between succeeding device triggers. Parameters ---------- df_devs : pd.DataFrame, optional Recorded devices from a dataset. Fore more information refer to the :ref:`user guide<device_dataframe>`. x : ndarray, optional Array of time deltas used to plot the histogram n_bins : int, default=50 the number of bins for the histogram. color : str, optional sets the color of the plot. When not set, the primary theming color is used. Learn more about theming in the :ref:`user guide <theming>` figsize : (float, float), default: None width, height in inches. If not provided, the figsize is inferred by automatically. file_path : str, optional If set, saves the plot under the given file path and return *None* instead of returning the figure. Examples -------- >>> from pyadlml.plot import plot_trigger_time_dev >>> plot_trigger_time_dev_todo(data.df_devs) .. image:: ../_static/images/plots/dev_hist_trigger_td.png :height: 300px :width: 500 px :scale: 100 % :alt: alternate text :align: center Returns ------- res : fig or None Either a figure if file_path is not specified or nothing. """ assert not (df_devs is None and x is None) title='Time difference between succeeding device' log_sec_col = 'total_log_secs' sec_col = 'total_secs' ylabel='count' ax2label = 'cummulative percentage' ax1label = 'timedeltas count ' xlabel = 'log seconds' color = (get_primary_color() if color is None else color) color2 = get_secondary_color() if x is None: X = trigger_time_diff(df_devs.copy()) else: X = x # make equal bin size from max to min bins = np.logspace(min(np.log10(X)), max(np.log10(X)), n_bins) # make data ready for hist hist, _ = np.histogram(X, bins=bins) cum_percentage = hist.cumsum()/hist.sum() cum_percentage =
np.concatenate(([0], cum_percentage))
numpy.concatenate
# -*- coding: utf-8 -*- # ====================================================================================================================== # Copyright (©) 2015-2021 LCS - Laboratoire Catalyse et Spectrochimie, Caen, France. # = # CeCILL-B FREE SOFTWARE LICENSE AGREEMENT - See full LICENSE agreement in the root directory # = # ====================================================================================================================== """ This module implements the `BaselineCorrection` class for baseline corrections. """ __all__ = ['BaselineCorrection', 'ab', 'abc', 'dc', 'basc'] __dataset_methods__ = ['ab', 'abc', 'dc', 'basc'] import numpy as np import scipy.interpolate from traitlets import Int, Instance, HasTraits, Float, Unicode, Tuple, List from matplotlib.widgets import SpanSelector import matplotlib.pyplot as plt from ..dataset.coordrange import trim_ranges from ..plotters.multiplot import multiplot from ..dataset.nddataset import NDDataset from ...utils import TYPE_INTEGER, TYPE_FLOAT from .smooth import smooth from .. import debug_, warning_ from spectrochempy.core.processors.utils import _units_agnostic_method class BaselineCorrection(HasTraits): """ Baseline Correction processor. 2 methods are proposed : * ``sequential`` (default) = classical polynom fit or spline interpolation with separate fitting of each row (spectrum) * ``multivariate`` = SVD modeling of baseline, polynomial fit of PC's and calculation of the modelled baseline spectra. Interactive mode is proposed using the interactive function : :meth:`run`. Parameters ---------- dataset : |NDDataset| The dataset to be transformed. See Also -------- abc : Automatic baseline correction. Examples -------- .. plot:: :include-source: from spectrochempy import * nd = NDDataset.read_omnic(os.path.join('irdata', 'nh4y-activation.spg')) ndp = nd[:, 1291.0:5999.0] bc = BaselineCorrection(ndp) ranges=[[5996., 5998.], [1290., 1300.], [2205., 2301.], [5380., 5979.], [3736., 5125.]] span = bc.compute(*ranges,method='multivariate', interpolation='pchip', npc=8) _ = bc.corrected.plot_stack() show() """ dataset = Instance(NDDataset) corrected = Instance(NDDataset) method = Unicode('sequential') interpolation = Unicode('pchip') axis = Int(-1) dim = Unicode('') order = Int(6, min=1, allow_none=True) npc = Int(5, min=1, allow_none=True) zoompreview = Float(1.) figsize = Tuple((7, 5)) sps = List() # .................................................................................................................. def __init__(self, dataset, *args, **kwargs): self.dataset = dataset self.corrected = self.dataset.copy() if args or kwargs: warning_("DEPRECATION WARNING: Pass all arguments such range, and method definition in the " "``compute`` method, not during the initialisation of the BaselineCorrection instance.\n" "Here they are ignored.") # .................................................................................................................. def _extendranges(self, *ranges, **kwargs): if not ranges: # look in the kwargs ranges = kwargs.pop('ranges', ()) if isinstance(ranges, tuple) and len(ranges) == 1: ranges = ranges[0] # probably passed with no start to the compute function if not isinstance(ranges, (list, tuple)): ranges = list(ranges) if not ranges: return if len(ranges) == 2: if (isinstance(ranges[0], TYPE_INTEGER + TYPE_FLOAT) and isinstance(ranges[1], TYPE_INTEGER + TYPE_FLOAT)): # a pair a values, we intepret this as a single range ranges = [[ranges[0], ranges[1]]] # find the single values for item in ranges: if isinstance(item, TYPE_INTEGER + TYPE_FLOAT): # a single numerical value: intepret this as a single range item = [item, item] self.ranges.append(item) # .................................................................................................................. def _setup(self, **kwargs): self.method = kwargs.get('method', self.method) self.interpolation = kwargs.get('interpolation', self.interpolation) if self.interpolation == 'polynomial': self.order = int(kwargs.get('order', self.order)) if self.method == 'multivariate': self.npc = int(kwargs.get('npc', self.npc)) self.zoompreview = kwargs.get('zoompreview', self.zoompreview) self.figsize = kwargs.get('figsize', self.figsize) # .................................................................................................................. def __call__(self, *ranges, **kwargs): return self.compute(*ranges, **kwargs) # .................................................................................................................. def compute(self, *ranges, **kwargs): """ Base function for dataset baseline correction. Parameters ---------- *ranges : a variable number of pair-tuples The regions taken into account for the manual baseline correction. **kwargs : dict See other parameters. Other Parameters ---------------- dim : str or int, keyword parameter, optional, default='x'. Specify on which dimension to apply the apodization method. If `dim` is specified as an integer it is equivalent to the usual `axis` numpy parameter. method : str, keyword parameter, optional, default='sequential' Correction method among ['multivariate','sequential'] interpolation : string, keyword parameter, optional, default='polynomial' Interpolation method for the computation of the baseline, among ['polynomial','pchip'] order : int, keyword parameter, optional, default=6 If the correction method polynomial, this give the polynomial order to use. npc : int, keyword parameter, optional, default=5 Number of components to keep for the ``multivariate`` method zoompreview : float, keyword parameter, optional, default=1.0 The zoom factor for the preview in interactive mode figsize : tuple, keyword parameter, optional, default=(8, 6) Size of the figure to display in inch """ self._setup(**kwargs) # output dataset new = self.corrected # we assume that the last dimension if always the dimension to which we want to subtract the baseline. # Swap the axes to be sure to be in this situation axis, dim = new.get_axis(**kwargs, negative_axis=True) swaped = False if axis != -1: new.swapdims(axis, -1, inplace=True) swaped = True lastcoord = new.coordset[dim] # most of the time we need sorted axis, so let's do it now is_descendant = False if lastcoord.descendant: new.sort(dim=dim, inplace=True, descend=False) is_descendant = True lastcoord = new.coordset[dim] x = lastcoord.data self.ranges = [[x[0], x[2]], [x[-3], x[-1]]] self._extendranges(*ranges, **kwargs) self.ranges = ranges = trim_ranges(*self.ranges) baseline = np.zeros_like(new) # Extract: Sbase: the matrix of data corresponding to ranges # xbase: the xaxis values corresponding to ranges s = [] for pair in ranges: # determine the slices sl = slice(*pair) sect = new[..., sl] if sect is None: continue s.append(sect) sbase = NDDataset.concatenate(s, axis=-1) # TODO: probably we could use masked data instead of concatenating - could be faster xbase = sbase.coordset(dim) if self.method == 'sequential': if self.interpolation == 'polynomial': # # bad fit when NaN values => are replaced by 0 # NO reason we have Nan -> suppressed # if np.any(np.isnan(sbase)): # sbase[np.isnan(sbase)] = 0 polycoef = np.polynomial.polynomial.polyfit(xbase.data, sbase.data.T, deg=self.order, rcond=None, full=False) baseline = np.polynomial.polynomial.polyval(x, polycoef) elif self.interpolation == 'pchip': for i in range(new.shape[0]): interp = scipy.interpolate.PchipInterpolator(xbase.data, sbase.data[i]) baseline[i] = interp(x) elif self.method == 'multivariate': # SVD of Sbase U, s, Vt = np.linalg.svd(sbase.data, full_matrices=False, compute_uv=True) # npc cannot be higher than the size of s npc = min(self.npc, s.shape[0]) # select npc loadings & compute scores Pt = (Vt[0:npc]) T = np.dot(U[:, 0:npc], np.diag(s)[0:npc, 0:npc]) baseline_loadings = np.zeros((npc, new.shape[-1])) if self.interpolation == 'pchip': for i in range(npc): interp = scipy.interpolate.PchipInterpolator(xbase.data, Pt[i]) baseline_loadings[i] = interp(x) elif self.interpolation == 'polynomial': polycoef = np.polynomial.polynomial.polyfit(xbase.data, Pt.T, deg=self.order, rcond=None, full=False) baseline_loadings = np.polynomial.polynomial.polyval(x, polycoef) baseline = np.dot(T, baseline_loadings) new.data = new.data - baseline # eventually sort back to the original order if is_descendant: new.sort(axis=-1, inplace=True, descend=True) new.history = str(new.modified) + ': ' + 'Baseline correction.' + ' Method: ' if self.method == 'Multivariate': new.history = 'Multivariate (' + str(self.npc) + ' PCs).' else: new.history = 'Sequential.' if self.interpolation == 'polynomial': new.history = 'Interpolation: Polynomial, order=' + str(self.order) + '.\n' else: new.history = 'Interpolation: Pchip. \n' if swaped: new = new.swapdims(axis, -1) self.corrected = new return new # .................................................................................................................. def show_regions(self, ax): if self.sps: for sp in self.sps: sp.remove() self.sps = [] self.ranges = list(trim_ranges(*self.ranges)) for x in self.ranges: x.sort() sp = ax.axvspan(x[0], x[1], facecolor='#2ca02c', alpha=0.5) self.sps.append(sp) # .................................................................................................................. def run(self, *ranges, **kwargs): """ Interactive version of the baseline correction. Parameters ---------- *ranges : a variable number of pair-tuples The regions taken into account for the manual baseline correction. **kwargs : dict See other parameter of method compute. """ self._setup(**kwargs) self.sps = [] # output dataset new = self.corrected origin = self.dataset.copy() # we assume that the last dimension if always the dimension to which we want to subtract the baseline. # Swap the axes to be sure to be in this situation axis, dim = new.get_axis(**kwargs, negative_axis=True) # swaped = False if axis != -1: new.swapdims(axis, -1, inplace=True) origin.swapdims(axis, -1, inplace=True) # swaped = True lastcoord = new.coordset[dim] # most of the time we need sorted axis, so let's do it now if lastcoord.reversed: new.sort(dim=dim, inplace=True, descend=False) lastcoord = new.coordset[dim] x = lastcoord.data self.ranges = [[x[0], x[2]], [x[-3], x[-1]]] self._extendranges(*ranges, **kwargs) self.ranges = ranges = trim_ranges(*self.ranges) new = self.compute(*ranges, **kwargs) # display datasets = [origin, new] labels = ['Click on left button & Span to set regions. Click on right button on a region to remove it.', 'Baseline corrected dataset preview'] axes = multiplot(datasets, labels, method='stack', sharex=True, nrow=2, ncol=1, figsize=self.figsize, suptitle='INTERACTIVE BASELINE CORRECTION') fig = plt.gcf() fig.canvas.draw() ax1 = axes['axe11'] ax2 = axes['axe21'] self.show_regions(ax1) def show_basecor(ax2): corrected = self.compute(*ranges, **kwargs) ax2.clear() ax2.set_title('Baseline corrected dataset preview', fontweight='bold', fontsize=8) if self.zoompreview > 1: zb = 1. # self.zoompreview zlim = [corrected.data.min() / zb, corrected.data.max() / zb] _ = corrected.plot_stack(ax=ax2, colorbar=False, zlim=zlim, clear=False) else: _ = corrected.plot_stack(ax=ax2, colorbar=False, clear=False) show_basecor(ax2) def onselect(xmin, xmax): self.ranges.append([xmin, xmax]) self.show_regions(ax1) show_basecor(ax2) fig.canvas.draw() def onclick(event): if event.button == 3: for i, r in enumerate(self.ranges): if r[0] > event.xdata or r[1] < event.xdata: continue else: self.ranges.remove(r) self.show_regions(ax1) show_basecor(ax2) fig.canvas.draw() # _idle _ = fig.canvas.mpl_connect('button_press_event', onclick) _ = SpanSelector(ax1, onselect, 'horizontal', minspan=5, button=[1], useblit=True, rectprops=dict(alpha=0.5, facecolor='blue')) fig.canvas.draw() return # ...................................................................................................................... def basc(dataset, *ranges, **kwargs): """ Compute a baseline correction using the BaselineCorrection processor. 2 methods are proposed : * ``sequential`` (default) = classical polynom fit or spline interpolation with separate fitting of each row (spectrum) * ``multivariate`` = SVD modeling of baseline, polynomial fit of PC's and calculation of the modelled baseline spectra. Parameters ---------- dataset : a [NDDataset| instance The dataset where to calculate the baseline. *ranges : a variable number of pair-tuples The regions taken into account for the manual baseline correction. **kwargs : dict See other parameters. Other Parameters ---------------- dim : str or int, keyword parameter, optional, default='x'. Specify on which dimension to apply the apodization method. If `dim` is specified as an integer it is equivalent to the usual `axis` numpy parameter. method : str, keyword parameter, optional, default='sequential' Correction method among ['multivariate','sequential'] interpolation : string, keyword parameter, optional, default='polynomial' Interpolation method for the computation of the baseline, among ['polynomial','pchip'] order : int, keyword parameter, optional, default=6 If the correction method polynomial, this give the polynomial order to use. npc : int, keyword parameter, optional, default=5 Number of components to keep for the ``multivariate`` method See Also -------- BaselineCorrection : Manual baseline corrections. abc : Automatic baseline correction. Notes ----- For more flexibility and functionality, it is advised to use the BaselineCorrection processor instead. Examples -------- .. plot:: :include-source: import spectrochempy as scp nd = scp.read('irdata/nh4y-activation.spg') ndp = nd[:, 1291.0:5999.0] ranges=[[5996., 5998.], [1290., 1300.], [2205., 2301.], [5380., 5979.], [3736., 5125.]] ndcorr = spc.basc(ndp, *ranges,method='multivariate', interpolation='pchip', npc=8) ndcorr.plot() spc.show() """ blc = BaselineCorrection(dataset) if not ranges and dataset.meta.regions is not None: # use the range stored in metadata ranges = dataset.meta.regions['baseline'] return blc.compute(*ranges, **kwargs) # ====================================================================================================================== # abc # TODO: some work to perform on this # ====================================================================================================================== def abc(dataset, dim=-1, **kwargs): """ Automatic baseline correction. Various algorithms are provided to calculate the baseline automatically. Parameters ---------- dataset : a [NDDataset| instance The dataset where to calculate the baseline. dim : str or int, optional The dataset dimentsion where to calculate the baseline. Default is -1. **kwargs : dict See other parameters. Returns ------- baseline_corrected A baseline corrected dataset. baseline_only Only the baseline (apply must be set to False). baseline_points Points where the baseline is calculated (return_points must be set to True). Other Parameters ---------------- basetype : string, optional, default: 'linear' See notes - available = linear, basf, ... window : float/int, optional, default is 0.05 If float <1 then the corresponding percentage ot the axis size is taken as window. nbzone : int, optional, default is 32 Number of zones. We will divide the size of the last axis by this number to determine the number of points in each zone (nw). mult : int A multiplicator. determine the number of point for the database calculation (nw*mult<n base points). nstd : int, optional, default is 2 times the standard error Another multiplicator. Multiply the standard error to determine the region in which points are from the baseline. polynom : bool, optional, default is True If True a polynom is computed for the base line, else an interpolation is achieved betwwen points. porder : int, default is 6 Order of the polynom to fit on the baseline points return_points : bool, optional, default is False If True, the points abscissa used to determine the baseline are returned. apply : bool, optional, default is True If apply is False, the data are not modified only the baseline is returned. return_pts : bool, optional, default is False If True, the baseline reference points are returned. See Also -------- BaselineCorrection : Manual baseline corrections. basc : Manual baseline correction. Notes ----- #TODO: description of these algorithms * linear - * basf - Examples -------- To be done """ # # options evaluation # parser = argparse.ArgumentParser(description='BC processing.', usage=""" # ab [-h] [--mode {linear,poly, svd}] [--dryrun] # [--window WINDOW] [--step STEP] [--nbzone NBZONE] # [--mult MULT] [--order ORDER] [--verbose] # """) # # positional arguments # parser.add_argument('--mode', '-mo', default='linear', # choices=['linear', 'poly', 'svd'], help="mode of correction") # parser.add_argument('--dryrun', action='store_true', help='dry flag') # # parser.add_argument('--window', '-wi', default=0.05, type=float, help='selected window for linear and svd bc') # parser.add_argument('--step', '-st', default=5, type=int, help='step for svd bc') # parser.add_argument('--nbzone', '-nz', default=32, type=int, help='number of zone for poly') # parser.add_argument('--mult', '-mt', default=4, type=int, help='multiplicator of zone for poly') # parser.add_argument('--order', '-or', default=5, type=int, help='polynom order for poly') # # parser.add_argument('--verbose', action='store_true', help='verbose flag') # args = parser.parse_args(options.split()) # # source.history.append('baseline correction mode:%s' % args.mode) inplace = kwargs.pop('inplace', False) dryrun = kwargs.pop('dryrun', False) # output dataset inplace or not if not inplace or dryrun: # default new = dataset.copy() else: new = dataset axis, dim = new.get_axis(dim, negative_axis=True) swaped = False if axis != -1: new.swapdims(axis, -1, inplace=True) # must be done in place swaped = True base = _basecor(new.data.real, **kwargs) if not dryrun: new.data -= base # return the corrected spectra else: new.data = base # return the baseline # restore original data order if it was swaped if swaped: new.swapdims(axis, -1, inplace=True) # must be done inplace new.history = '`abc` Baseline correction applied.' return new # ...................................................................................................................... def ab(dataset, dim=-1, **kwargs): """ Alias of `abc` """ return abs(dataset, dim, **kwargs) # ...................................................................................................................... @_units_agnostic_method def dc(dataset, **kwargs): """ Time domain baseline correction Parameters ---------- dataset : nddataset The time domain daatset to be corrected. kwargs : dict, optional additional parameters. Returns ------- dc DC corrected array. Other Parameters ---------------- len : float, optional Proportion in percent of the data at the end of the dataset to take into account. By default, 25%. """ len = int(kwargs.pop('len', .25) * dataset.shape[-1]) dc = np.mean(np.atleast_2d(dataset)[..., -len:]) dataset -= dc return dataset # ======================================================================================================================= # private functions # ======================================================================================================================= def _basecor(data, **kwargs): mode = kwargs.pop('mode', 'linear') if mode == 'linear': return _linearbase(data, **kwargs) if mode == 'svd': return _svdbase(data, **kwargs) if mode == 'poly': return _polybase(data, **kwargs) else: raise ValueError(f'`ab` mode = `{mode}` not known') # # _linear mode # def _linearbase(data, **kwargs): # Apply a linear baseline correction # Very simple and naive procedure that compute a straight baseline from side to the other # (averging on a window given by the window parameters : 5% of the total width on each side by default) window = kwargs.pop('window', 0.05) if window <= 1.0: # percent window = int(data.shape[-1] * window) if len(data.shape) == 1: npts = float(data.shape[-1]) a = (data[-window:].mean() - data[:window].mean()) / (npts - 1.) b = data[:window].mean() baseline = a * np.arange(npts) + b else: npts = float(data.shape[-1]) a = (data[:, -window:].mean(axis=-1) - data[:, :window].mean(axis=-1)) / (npts - 1.) b = data[:, :window].mean(axis=-1) baseline = (((
np.ones_like(data)
numpy.ones_like
"""Deviation preserving reduction""" import numpy as np from gameanalysis import paygame from gameanalysis import restrict from gameanalysis import rsgame from gameanalysis import utils from gameanalysis.reduction import _common from gameanalysis.reduction import hierarchical def _devs(game, num_profs): """Return an array of the player counts after deviation""" return np.tile( np.repeat( game.num_role_players - np.eye(game.num_roles, dtype=int), game.num_role_strats, 0, ), (num_profs, 1), ) def reduce_game(full_game, red_players): # pylint: disable=too-many-locals """Reduce a game using deviation preserving reduction Parameters ---------- full_game : Game The game to reduce. red_players : ndarray-like The reduced number of players for each role. This will be coerced into the proper shape if necessary. """ red_game = rsgame.empty_names( full_game.role_names, red_players, full_game.strat_names ) utils.check( np.all((red_game.num_role_players > 1) | (full_game.num_role_players == 1)), "all reduced players must be greater than zero", ) utils.check( np.all(full_game.num_role_players >= red_game.num_role_players), "all full counts must not be less than reduced counts", ) if full_game.is_empty(): return red_game elif full_game.num_profiles < red_game.num_all_dpr_profiles: full_profiles = full_game.profiles() full_payoffs = full_game.payoffs() else: full_profiles = expand_profiles(full_game, red_game.all_profiles()) full_payoffs = full_game.get_payoffs(full_profiles) valid = ~np.all(np.isnan(full_payoffs) | (full_profiles == 0), 1) full_profiles = full_profiles[valid] full_payoffs = full_payoffs[valid] # Reduce red_profiles, red_inds, full_inds, strat_inds = _reduce_profiles( red_game, full_profiles, True ) if red_profiles.size == 0: # Empty reduction return red_game # Build mapping from payoffs to reduced profiles, and use bincount # to count the number of payoffs mapped to a specific location, and # sum the number of payoffs mapped to a specific location cum_inds = red_inds * full_game.num_strats + strat_inds payoff_vals = full_payoffs[full_inds, strat_inds] red_payoffs = np.bincount(cum_inds, payoff_vals, red_profiles.size).reshape( red_profiles.shape ) red_payoff_counts = np.bincount(cum_inds, minlength=red_profiles.size).reshape( red_profiles.shape ) mask = red_payoff_counts > 1 red_payoffs[mask] /= red_payoff_counts[mask] unknown = (red_profiles > 0) & (red_payoff_counts == 0) red_payoffs[unknown] = np.nan valid = ~np.all((red_profiles == 0) | np.isnan(red_payoffs), 1) return paygame.game_replace(red_game, red_profiles[valid], red_payoffs[valid]) def expand_profiles(full_game, profiles): # pylint: disable=too-many-locals """Expand profiles using dpr Parameters ---------- full_game : Game Game that expanded profiles will be valid for. profiles : ndarray-like The profiles to expand return_contributions : bool, optional If specified, returns a boolean array matching the shape is returned indicating the payoffs that are needed for the initial profiles. """ profiles = np.asarray(profiles, int) utils.check( profiles.shape[-1] == full_game.num_strats, "profiles not a valid shape" ) if not profiles.size: return np.empty((0, full_game.num_strats), int) profiles = profiles.reshape((-1, full_game.num_strats)) all_red_players = np.add.reduceat(profiles, full_game.role_starts, 1) red_players = all_red_players[0] utils.check(np.all(all_red_players == red_players), "profiles must be valid") num_profs = profiles.shape[0] dev_profs = profiles[:, None] -
np.eye(full_game.num_strats, dtype=int)
numpy.eye
import numpy as np import quaternion from shapes import * def test_pentatope_centered(): for vertices in [pentatope(), pentatope_v2()]: assert (np.isclose(0, abs(sum(vertices)))) def test_pentatope_equidistance(): for vertices in [pentatope(), pentatope_v2()]: for v1 in vertices: for v2 in vertices: d = abs(v1 - v2) assert (d == 0 or np.isclose(d, np.sqrt(2.5))) def test_pentatope_symmetry(): symmetry = pentatope_rotors() assert (len(symmetry) == 120) vertices = pentatope() for v in vertices: for left, right in symmetry: assert (contains(vertices, left*v*right)) def test_orthoplex_closed(): vertices = orthoplex(False) for v1 in vertices: for v2 in vertices: assert (contains(vertices, v1*v2)) def test_tesseract_symmetry(): vertices = tesseract(False) symmetry = orthoplex(False) twist = [1,
np.quaternion(0.5**0.5, 0.5**0.5, 0, 0)
numpy.quaternion
import numpy as np import pytest from sklearn.datasets import load_iris from libifbtsvm import iFBTSVM from libifbtsvm.models.ifbtsvm import ( FuzzyMembership, Hyperparameters, Hyperplane, ) def test_generate_sub_samples(dataset_3_classes): parameters = Hyperparameters() model = iFBTSVM(parameters=parameters) sub_data_sets = model._generate_sub_sets(X=dataset_3_classes.X, y=dataset_3_classes.y) dag_1 = next(sub_data_sets) truth_1 = [np.array([0.9, 1.0, 1.1]), np.array(['1', '1', '1']), np.array([10.9, 11.0, 11.1]), np.array(['2', '2', '2'])] for i in range(len(truth_1)): assert np.array_equal(dag_1[i], truth_1[i]) dag_2 = next(sub_data_sets) truth_2 = [np.array([0.9, 1.0, 1.1]), np.array(['1', '1', '1']), np.array([110.9, 111.0, 111.1]), np.array(['3', '3', '3'])] for i in range(len(truth_2)): assert np.array_equal(dag_2[i], truth_2[i]) dag_3 = next(sub_data_sets) truth_3 = [np.array([10.9, 11.0, 11.1]), np.array(['2', '2', '2']), np.array([110.9, 111.0, 111.1]),
np.array(['3', '3', '3'])
numpy.array
import logging log = logging.getLogger(__name__) from fractions import math from math import gcd import numpy as np import pandas as pd from scipy import signal def as_numeric(x): if not isinstance(x, (np.ndarray, pd.DataFrame, pd.Series)): x = np.asanyarray(x) return x def db(target, reference=1): target = as_numeric(target) reference = as_numeric(reference) return 20*np.log10(target/reference) def dbi(db, reference=1): db = as_numeric(db) return (10**(db/20))*reference def dbtopa(db): ''' Convert dB SPL to Pascal .. math:: 10^{dB/20.0}/(20\cdot10^{-6}) >>> round(dbtopa(94), 4) 1.0024 >>> dbtopa(100) 2.0 >>> dbtopa(120) 20.0 >>> patodb(dbtopa(94.0)) 94.0 Will also take sequences: >>> print(dbtopa([80, 100, 120])) [ 0.2 2. 20. ] ''' return dbi(db, 20e-6) def patodb(pa): ''' Convert Pascal to dB SPL .. math:: 20*log10(pa/20e-6) >>> round(patodb(1)) 94 >>> patodb(2) 100.0 >>> patodb(0.2) 80.0 Will also take sequences: >>> print(patodb([0.2, 2.0, 20.0])) [ 80. 100. 120.] ''' return db(pa, 20e-6) def normalize_rms(waveform, out=None): ''' Normalize RMS power to 1 (typically used when generating a noise waveform that will be scaled by a calibration factor) waveform : array_like Input array. out : array_like An array to store the output. Must be the same shape as `waveform`. ''' return np.divide(waveform, rms(waveform), out) def csd(s, window=None, waveform_averages=None, detrend='linear'): if waveform_averages is not None and waveform_averages != 1: new_shape = (waveform_averages, -1) + s.shape[1:] s = s.reshape(new_shape).mean(axis=0) if detrend is not None: s = signal.detrend(s, type=detrend, axis=-1) n = s.shape[-1] if window is not None: w = signal.get_window(window, n) s = w/w.mean()*s scale = 2 / n / np.sqrt(2) return np.fft.rfft(s, axis=-1) * scale def csd_to_signal(csd): n = 2 * (len(csd) - 1) scale = 2 / n / np.sqrt(2) return np.fft.irfft(csd, axis=-1) / scale def _phase(csd, unwrap=True): p = np.angle(csd) if unwrap: p = np.unwrap(p) if isinstance(csd, pd.DataFrame): p = pd.DataFrame(p, index=csd.index, columns=csd.columns) elif isinstance(csd, pd.Series): p = pd.Series(p, index=csd.index) return p def phase(s, fs, window=None, waveform_averages=None, unwrap=True): c = csd(s, window, waveform_averages) return _phase(c, unwrap) def psd(s, fs, window=None, waveform_averages=None, trim_samples=True): if waveform_averages is None: waveform_averages = 1 if trim_samples: n = (s.shape[-1] // waveform_averages) * waveform_averages s = s[..., :n] new_shape = (waveform_averages, -1) + s.shape[1:] s = s.reshape(new_shape) c = csd(s, window) return np.abs(c).mean(axis=0) def psd_freq(s, fs): return np.fft.rfftfreq(s.shape[-1], 1.0/fs) def csd_df(s, fs, *args, **kw): c = csd(s, *args, **kw) freqs = pd.Index(psd_freq(s, fs), name='frequency') if c.ndim == 1: name = s.name if isinstance(s, pd.Series) else 'psd' return pd.Series(c, index=freqs, name=name) else: index = s.index if isinstance(s, pd.DataFrame) else None return pd.DataFrame(c, columns=freqs, index=index) def psd_df(s, fs, *args, waveform_averages=None, **kw): p = psd(s, fs, *args, waveform_averages=waveform_averages, **kw) n = s.shape[-1] if waveform_averages is not None: n = n // waveform_averages freqs = pd.Index(np.fft.rfftfreq(n, 1/fs), name='frequency') if p.ndim == 1: name = s.name if isinstance(s, pd.Series) else 'psd' return pd.Series(p, index=freqs, name=name) else: index = s.index if isinstance(s, pd.DataFrame) else None return pd.DataFrame(p, columns=freqs, index=index) def tone_conv(s, fs, frequency, window=None): frequency_shape = tuple([Ellipsis] + [np.newaxis]*s.ndim) frequency = np.asarray(frequency)[frequency_shape] s = signal.detrend(s, type='linear', axis=-1) n = s.shape[-1] if window is not None: w = signal.get_window(window, n) s = w/w.mean()*s t = np.arange(n)/fs r = 2.0*s*np.exp(-1.0j*(2.0*np.pi*t*frequency)) return np.mean(r, axis=-1) def tone_power_conv(s, fs, frequency, window=None): r = tone_conv(s, fs, frequency, window) return np.abs(r)/np.sqrt(2.0) def tone_phase_conv(s, fs, frequency, window=None): r = tone_conv(s, fs, frequency, window) return np.angle(r) def tone_power_fft(s, fs, frequency, window=None): power = psd(s, fs, window) freqs = psd_freq(s, fs) flb, fub = freqs*0.9, freqs*1.1 mask = (freqs >= flb) & (freqs < fub) return power[..., mask].max(axis=-1) def tone_phase_fft(s, fs, frequency, window=None): p = phase(s, fs, window, unwrap=False) freqs = psd_freq(s, fs) flb, fub = freqs*0.9, freqs*1.1 mask = (freqs >= flb) & (freqs < fub) return p[..., mask].max(axis=-1) def tone_power_conv_nf(s, fs, frequency, window=None): samples = s.shape[-1] resolution = fs/samples frequencies = frequency+np.arange(-2, 3)*resolution magnitude = tone_power_conv(s, fs, frequencies, window) nf_rms = magnitude[(0, 1, 3, 4), ...].mean(axis=0) tone_rms = magnitude[2] return nf_rms, tone_rms def analyze_mic_sens(ref_waveforms, exp_waveforms, vrms, ref_mic_gain, exp_mic_gain, output_gain, ref_mic_sens, **kwargs): ref_data = analyze_tone(ref_waveforms, mic_gain=ref_mic_gain, **kwargs) exp_data = analyze_tone(exp_waveforms, mic_gain=exp_mic_gain, **kwargs) # Actual output SPL output_spl = ref_data['mic_rms']-ref_mic_sens-db(20e-6) # Output SPL assuming 0 dB gain and 1 VRMS norm_output_spl = output_spl-output_gain-db(vrms) # Exp mic sensitivity in dB(V/Pa) exp_mic_sens = exp_data['mic_rms']+ref_mic_sens-ref_data['mic_rms'] result = { 'output_spl': output_spl, 'norm_output_spl': norm_output_spl, 'exp_mic_sens': exp_mic_sens, 'output_gain': output_gain, } shared = ('time', 'frequency') result.update({k: ref_data[k] for k in shared}) t = {'ref_'+k: ref_data[k] for k, v in ref_data.items() if k not in shared} result.update(t) t = {'exp_'+k: exp_data[k] for k, v in exp_data.items() if k not in shared} result.update(t) return result def thd(s, fs, frequency, harmonics=3, window=None): ph = np.array([tone_power_conv(s, fs, frequency*(i+1), window)[np.newaxis] \ for i in range(harmonics)]) ph = np.concatenate(ph, axis=0) return (np.sum(ph[1:]**2, axis=0)**0.5)/ph[0] def analyze_tone(waveforms, frequency, fs, mic_gain, trim=0, thd_harmonics=3): trim_n = int(trim*fs) waveforms = waveforms[:, trim_n:-trim_n] # Get average tone power across channels power = tone_power_conv(waveforms, fs, frequency, window='flattop') power = db(power).mean(axis=0) average_waveform = waveforms.mean(axis=0) time = np.arange(len(average_waveform))/fs # Correct for gains (i.e. we want to know the *actual* Vrms at 0 dB input # and 0 dB output gain). power -= mic_gain #max_harmonic = np.min(int(np.floor((fs/2.0)/frequency)), thd_harmonics) harmonics = [] for i in range(thd_harmonics): f_harmonic = frequency*(i+1) p = tone_power_conv(waveforms, fs, f_harmonic, window='flattop') p_harmonic = db(p).mean(axis=0) harmonics.append({ 'harmonic': i+1, 'frequency': f_harmonic, 'mic_rms': p_harmonic, }) harmonic_v = [] for h_info in harmonics: harmonic_v.append(dbi(h_info['mic_rms'])) harmonic_v = np.asarray(harmonic_v)[:thd_harmonics] thd = (np.sum(harmonic_v[1:]**2)**0.5)/harmonic_v[0] return { 'frequency': frequency, 'time': time, 'mic_rms': power, 'thd': thd, 'mic_waveform': average_waveform, 'harmonics': harmonics, } def spectrum_to_band_level(spectrum_db, flb, fub): ''' Convert overall band level to spectrum level ''' return spectrum_db + 10 * np.log10(fub - flb) def band_to_spectrum_level(band_db, flb, fub): ''' Convert overall band level to spectrum level ''' return band_db - 10 * np.log10(fub - flb) def rms(s, detrend=False): if detrend: s = signal.detrend(s, axis=-1) return np.mean(s**2, axis=-1)**0.5 def rms_rfft(x): return np.sqrt(np.sum(np.abs(x) ** 2)) def golay_pair(n=15): ''' Generate pair of Golay sequences ''' a0 = np.array([1, 1]) b0 = np.array([1, -1]) for i in range(n): a = np.concatenate([a0, b0]) b = np.concatenate([a0, -b0]) a0, b0 = a, b return a.astype(np.float32), b.astype(np.float32) def transfer_function(stimulus, response, fs): response = response[:len(stimulus)] h_response = np.fft.rfft(response, axis=-1) h_stimulus = np.fft.rfft(stimulus, axis=-1) freq = psd_freq(response, fs) return freq, 2*np.abs(h_response*np.conj(h_stimulus)) def golay_tf(a, b, a_signal, b_signal, fs): ''' Estimate system transfer function from Golay sequence Implements algorithm as described in Zhou et al. 1992. ''' a_signal = a_signal[..., :len(a)] b_signal = b_signal[..., :len(b)] ah_psd = np.fft.rfft(a_signal, axis=-1) bh_psd = np.fft.rfft(b_signal, axis=-1) a_psd = np.fft.rfft(a) b_psd = np.fft.rfft(b) h_omega = (ah_psd*np.conj(a_psd) + bh_psd*np.conj(b_psd))/(2*len(a)) freq = psd_freq(a, fs) h_psd = np.abs(h_omega) h_phase = np.unwrap(np.angle(h_omega)) return freq, h_psd, h_phase def golay_ir(n, a, b, a_signal, b_signal): ''' Estimate system impulse response from Golay sequence Implements algorithm described in Zhou et al. 1992 ''' a_signal = a_signal.mean(axis=0) b_signal = b_signal.mean(axis=0) a_conv = np.apply_along_axis(np.convolve, 1, a_signal, a[::-1], 'full') b_conv = np.apply_along_axis(np.convolve, 1, b_signal, b[::-1], 'full') return 1.0/(2.0*n)*(a_conv+b_conv)[..., -len(a):] def summarize_golay(fs, a, b, a_response, b_response, waveform_averages=None): if waveform_averages is not None: n_epochs, n_time = a_response.shape new_shape = (waveform_averages, -1, n_time) a_response = a_response.reshape(new_shape).mean(axis=0) b_response = b_response.reshape(new_shape).mean(axis=0) time = np.arange(a_response.shape[-1])/fs freq, tf_psd, tf_phase = golay_tf(a, b, a_response, b_response, fs) tf_psd = tf_psd.mean(axis=0) tf_phase = tf_phase.mean(axis=0) return { 'psd': tf_psd, 'phase': tf_phase, 'frequency': freq, } def freq_smooth(frequency, power, bandwidth=20): ''' Uses Konno & Ohmachi (1998) algorithm ''' smoothed = [] old = np.seterr(all='ignore') for f in frequency: if f == 0: # Special case for divide by 0 k = np.zeros_like(frequency) else: r = bandwidth*np.log10(frequency/f) k = (np.sin(r)/r)**4 # Special case for np.log10(0/frequency) k[0] = 0 # Special case where ratio is 1 (log of ratio is set to 0) k[frequency == f] = 1 # Equalize weights k /= k.sum(axis=0) smoothed.append(np.sum(power*k))
np.seterr(**old)
numpy.seterr
""" Most of codes are "COPIED" from saliconeval.auc, etc. just because, the salicon interfaces sucks :-( and https://github.com/herrlich10/saliency/blob/master/benchmark/metrics.py """ import numpy as np from skimage.transform import resize import numpy.random as random from functools import partial import scipy.sparse def normalize_range(x): res = (x - np.min(x)) / (np.max(x) - np.min(x)) return res def resize_onehot_tensor_sparse(x, target_shape): assert len(target_shape) == 2 H1, W1 = x.shape[-2:] H2, W2 = target_shape if len(x.shape) == 2: ret = np.zeros((H2, W2), dtype=np.bool) for y, x in zip(*np.where(x > 0)): y_ = y * (H2 - 1.0) / (H1 - 1.0) x_ = x * (W2 - 1.0) / (W1 - 1.0) y_ = int(np.round(y_) + 1e-9) x_ = int(np.round(x_) + 1e-9) #print t, y, x, '=>', y_, x_ ret[y_, x_] = 1 else: raise ValueError('x.shape : %s' % x.shape) return ret def AUC_Judd(fixation_map, saliency_map, jitter=True): ''' AUC stands for Area Under ROC Curve. This measures how well the saliency map of an image predicts the ground truth human fixations on the image. ROC curve is created by sweeping through threshold values determined by range of saliency map values at fixation locations. True positive (tp) rate correspond to the ratio of saliency map values above threshold at fixation locations to the total number of fixation locations. False positive (fp) rate correspond to the ratio of saliency map values above threshold at all other locations to the total number of possible other locations (non-fixated image pixels). AUC=0.5 is chance level. Parameters ---------- saliency_map : real-valued matrix fixation_map : binary matrix Human fixation map. jitter : boolean, optional If True (default), a small random number would be added to each pixel of the saliency map. Jitter saliency maps that come from saliency models that have a lot of zero values. If the saliency map is made with a Gaussian then it does not need to be jittered as the values vary and there is not a large patch of the same value. In fact, jittering breaks the ordering in the small values! Returns ------- AUC : float, between [0,1] ''' saliency_map = np.array(saliency_map, copy=False) fixation_map = np.array(fixation_map, copy=False) > 0.5 # If there are no fixation to predict, return NaN if not np.any(fixation_map): print('no fixation to predict') return np.nan # Make the saliency_map the size of the fixation_map if saliency_map.shape != fixation_map.shape: saliency_map = resize(saliency_map, fixation_map.shape, order=3, mode='nearest') # Jitter the saliency map slightly to disrupt ties of the same saliency value if jitter: saliency_map += random.rand(*saliency_map.shape) * 1e-7 # Normalize saliency map to have values between [0,1] saliency_map = normalize_range(saliency_map) S = saliency_map.ravel() F = fixation_map.ravel() S_fix = S[F] # Saliency map values at fixation locations n_fix = len(S_fix) n_pixels = len(S) # Calculate AUC thresholds = sorted(S_fix, reverse=True) tp = np.zeros(len(thresholds)+2) fp = np.zeros(len(thresholds)+2) tp[0] = 0; tp[-1] = 1 fp[0] = 0; fp[-1] = 1 for k, thresh in enumerate(thresholds): above_th = np.sum(S >= thresh) # Total number of saliency map values above threshold tp[k+1] = (k + 1) / float(n_fix) # Ratio saliency map values at fixation locations above threshold fp[k+1] = (above_th - k - 1) / float(n_pixels - n_fix) # Ratio other saliency map values above threshold return np.trapz(tp, fp) # y, x def AUC_Borji(fixation_map, saliency_map, n_rep=100, step_size=0.1, rand_sampler=None): ''' This measures how well the saliency map of an image predicts the ground truth human fixations on the image. ROC curve created by sweeping through threshold values at fixed step size until the maximum saliency map value. True positive (tp) rate correspond to the ratio of saliency map values above threshold at fixation locations to the total number of fixation locations. False positive (fp) rate correspond to the ratio of saliency map values above threshold at random locations to the total number of random locations (as many random locations as fixations, sampled uniformly from fixation_map ALL IMAGE PIXELS), averaging over n_rep number of selections of random locations. Parameters ---------- saliency_map : real-valued matrix fixation_map : binary matrix Human fixation map. n_rep : int, optional Number of repeats for random sampling of non-fixated locations. step_size : int, optional Step size for sweeping through saliency map. rand_sampler : callable S_rand = rand_sampler(S, F, n_rep, n_fix) Sample the saliency map at random locations to estimate false positive. Return the sampled saliency values, S_rand.shape=(n_fix,n_rep) Returns ------- AUC : float, between [0,1] ''' saliency_map = np.array(saliency_map, copy=False) fixation_map = np.array(fixation_map, copy=False) > 0.5 # If there are no fixation to predict, return NaN if not np.any(fixation_map): print('no fixation to predict') return np.nan # Make the saliency_map the size of the fixation_map if saliency_map.shape != fixation_map.shape: saliency_map = resize(saliency_map, fixation_map.shape, order=3, mode='nearest') # Normalize saliency map to have values between [0,1] saliency_map = normalize_range(saliency_map) S = saliency_map.ravel() F = fixation_map.ravel() S_fix = S[F] # Saliency map values at fixation locations n_fix = len(S_fix) n_pixels = len(S) # For each fixation, sample n_rep values from anywhere on the saliency map if rand_sampler is None: r = random.randint(0, n_pixels, [n_fix, n_rep]) S_rand = S[r] # Saliency map values at random locations (including fixated locations!? underestimated) else: S_rand = rand_sampler(S, F, n_rep, n_fix) # Calculate AUC per random split (set of random locations) auc = np.zeros(n_rep) * np.nan for rep in range(n_rep): thresholds = np.r_[0:np.max(np.r_[S_fix, S_rand[:,rep]]):step_size][::-1] tp = np.zeros(len(thresholds)+2) fp = np.zeros(len(thresholds)+2) tp[0] = 0; tp[-1] = 1 fp[0] = 0; fp[-1] = 1 for k, thresh in enumerate(thresholds): tp[k+1] = np.sum(S_fix >= thresh) / float(n_fix) fp[k+1] = np.sum(S_rand[:,rep] >= thresh) / float(n_fix) auc[rep] = np.trapz(tp, fp) return np.mean(auc) # Average across random splits def AUC_shuffled(fixation_map, saliency_map, other_map, n_rep=100, step_size=0.1): ''' This measures how well the saliency map of an image predicts the ground truth human fixations on the image. ROC curve created by sweeping through threshold values at fixed step size until the maximum saliency map value. True positive (tp) rate correspond to the ratio of saliency map values above threshold at fixation locations to the total number of fixation locations. False positive (fp) rate correspond to the ratio of saliency map values above threshold at random locations to the total number of random locations (as many random locations as fixations, sampled uniformly from fixation_map ON OTHER IMAGES), averaging over n_rep number of selections of random locations. Parameters ---------- saliency_map : real-valued matrix fixation_map : binary matrix Human fixation map. other_map : binary matrix, same shape as fixation_map A binary fixation map (like fixation_map) by taking the union of fixations from M other random images (Borji uses M=10). n_rep : int, optional Number of repeats for random sampling of non-fixated locations. step_size : int, optional Step size for sweeping through saliency map. Returns ------- AUC : float, between [0,1] ''' other_map = np.array(other_map, copy=False) > 0.5 if other_map.shape != fixation_map.shape: raise ValueError('other_map.shape != fixation_map.shape') # For each fixation, sample n_rep values (from fixated locations on other_map) on the saliency map def sample_other(other, S, F, n_rep, n_fix): fixated = np.nonzero(other)[0] indexer = map(lambda x: random.permutation(x)[:n_fix], np.tile(range(len(fixated)), [n_rep, 1])) r = fixated[np.transpose(indexer)] S_rand = S[r] # Saliency map values at random locations (including fixated locations!? underestimated) return S_rand return AUC_Borji(fixation_map, saliency_map, n_rep, step_size, partial(sample_other, other_map.ravel())) def similarity(gtsAnn, resAnn): """ Compute Sim score. For detailed explanation, refer to the DeepFix (2015) paper. """ # normalize gtsAnnNorm = gtsAnn / gtsAnn.sum() resAnnNorm = resAnn / resAnn.sum() simMap = np.minimum(gtsAnnNorm, resAnnNorm) return simMap.sum() def cc(gtsAnn, resAnn): """ Compute CC score. A simple implementation :param gtsAnn: ground-truth fixation map (X by X) :param resAnn: predicted saliency map (X by X) :return score: float : score """ fixationMap = gtsAnn - np.mean(gtsAnn) if np.max(fixationMap) > 0: fixationMap = fixationMap / np.std(fixationMap) salMap = resAnn -
np.mean(resAnn)
numpy.mean
# coding: utf-8 # In[1]: import numpy as np import pandas as pd import scipy.integrate as integrate from scipy.optimize import brentq as root import math import numpy as np import scipy.special as scp from scipy.special import iv # In[2]: def rvonmises(n, mu, kappa): vm = np.zeros(n) a = 1 + (1 + 4 * (kappa**2))**0.5 b = (a - (2 * a)**0.5)/(2 * kappa) r = (1 + b**2)/(2 * b) obs = 0 while (obs < n): U1 = np.random.uniform(0, 1, 1) z = np.cos(np.pi * U1) f = (1 + r * z)/(r + z) c = kappa * (r - f) U2 = np.random.uniform(0, 1, 1) if (c * (2 - c) - U2 > 0): U3 =
np.random.uniform(0, 1, 1)
numpy.random.uniform
#!/usr/bin/python # -*- coding: utf-8 -*- """ structure a statsmodel table @author: udacity, ucaiado Created on 10/07/2018 """ import numpy as np from statsmodels.iolib.table import SimpleTable from statsmodels.compat.python import zip_longest from statsmodels.iolib.tableformatting import fmt_2cols def convert_table_to_dict(table): ''' convert statsmodel table to dict :param table: StatsModel table. Parameters of the agent ''' l_aux = [y.strip() for y in
np.array(table.data)
numpy.array
import scipy.io.wavfile as scwav import numpy as np import pylab import librosa import pyworld as pw import os import scipy.io as scio from glob import glob from tqdm import tqdm from concurrent.futures import ProcessPoolExecutor from functools import partial from sklearn.manifold import TSNE def _power_to_db(S): return 20*np.log10(S) def _get_spect(filename, dim=8, mfcc=True): sr, data = scwav.read(filename=filename) data = np.asarray(data, np.float64) _, spect, _ = pw.wav2world(data, sr, frame_period=5) if spect.shape[0] > 128: q = np.random.randint(0, spect.shape[0] - 128) spect = spect[q:q+128] u_mat, s_mat, v_mat = np.linalg.svd(spect) rank1_appx = s_mat[0] * np.dot(u_mat[:,0:1], v_mat[0:1,:]) rank2_appx = rank1_appx + (s_mat[1] * np.dot(u_mat[:,1:2], v_mat[1:2,:])) rank3_appx = rank2_appx + (s_mat[2] * np.dot(u_mat[:,2:3], v_mat[2:3,:])) rank4_appx = rank3_appx + (s_mat[3] * np.dot(u_mat[:,3:4], v_mat[3:4,:])) rank5_appx = rank4_appx + (s_mat[4] * np.dot(u_mat[:,4:5], v_mat[4:5,:])) rank6_appx = rank5_appx + (s_mat[5] * np.dot(u_mat[:,5:6], v_mat[5:6,:])) rank7_appx = rank6_appx + (s_mat[6] * np.dot(u_mat[:,6:7], v_mat[6:7,:])) rank8_appx = rank7_appx + (s_mat[7] * np.dot(u_mat[:,7:8], v_mat[7:8,:])) if mfcc: mfc1 = pw.code_spectral_envelope(np.abs(rank1_appx), sr, dim) mfc2 = pw.code_spectral_envelope(np.abs(rank2_appx), sr, dim) mfc3 = pw.code_spectral_envelope(np.abs(rank3_appx), sr, dim) mfc4 = pw.code_spectral_envelope(np.abs(rank4_appx), sr, dim) mfc5 = pw.code_spectral_envelope(np.abs(rank5_appx), sr, dim) mfc6 = pw.code_spectral_envelope(np.abs(rank6_appx), sr, dim) mfc7 = pw.code_spectral_envelope(np.abs(rank7_appx), sr, dim) mfc8 = pw.code_spectral_envelope(np.abs(rank8_appx), sr, dim) else: mfc1 = rank1_appx mfc2 = None mfc3 = None mfc4 = None mfc5 = None mfc6 = None mfc7 = None mfc8 = None return [mfc1, mfc2, mfc3, mfc4, mfc5, mfc6, mfc7, mfc8] else: return None def _get_spect_no_abs(filename, dim=8, mfcc=True): sr, data = scwav.read(filename=filename) data = np.asarray(data, np.float64) _, spect, _ = pw.wav2world(data, sr, frame_period=5) if spect.shape[0] > 128: q = np.random.randint(0, spect.shape[0] - 128) spect = spect[q:q+128] u_mat, s_mat, v_mat = np.linalg.svd(spect) rank1_appx = s_mat[0] * np.dot(u_mat[:,0:1], v_mat[0:1,:]) rank2_appx = rank1_appx + (s_mat[1] * np.dot(u_mat[:,1:2], v_mat[1:2,:])) rank3_appx = rank2_appx + (s_mat[2] * np.dot(u_mat[:,2:3], v_mat[2:3,:])) rank4_appx = rank3_appx + (s_mat[3] * np.dot(u_mat[:,3:4], v_mat[3:4,:])) rank5_appx = rank4_appx + (s_mat[4] * np.dot(u_mat[:,4:5], v_mat[4:5,:])) rank6_appx = rank5_appx + (s_mat[5] * np.dot(u_mat[:,5:6], v_mat[5:6,:])) rank7_appx = rank6_appx + (s_mat[6] * np.dot(u_mat[:,6:7], v_mat[6:7,:])) rank8_appx = rank7_appx + (s_mat[7] * np.dot(u_mat[:,7:8], v_mat[7:8,:])) if mfcc: mfc1 = pw.code_spectral_envelope(rank1_appx, sr, dim) mfc2 = pw.code_spectral_envelope(rank2_appx, sr, dim) mfc3 = pw.code_spectral_envelope(rank3_appx, sr, dim) mfc4 = pw.code_spectral_envelope(rank4_appx, sr, dim) mfc5 = pw.code_spectral_envelope(rank5_appx, sr, dim) mfc6 = pw.code_spectral_envelope(rank6_appx, sr, dim) mfc7 = pw.code_spectral_envelope(rank7_appx, sr, dim) mfc8 = pw.code_spectral_envelope(rank8_appx, sr, dim) else: mfc1 = rank1_appx mfc2 = None mfc3 = None mfc4 = None mfc5 = None mfc6 = None mfc7 = None mfc8 = None return [mfc1, mfc2, mfc3, mfc4, mfc5, mfc6, mfc7, mfc8] else: return None if __name__ == '__main__': # sample_rate = 16000 # window_len = 0.005 # wav_file = '38.wav' # files = sorted(glob(os.path.join('/home/ravi/Downloads/Emo-Conv/neutral-angry/train/neutral', '*.wav'))) # wav_files = [os.path.basename(f) for f in files] # # min_val = [] # max_val = [] # for w in wav_files: # src = scwav.read(os.path.join('/home/ravi/Downloads/Emo-Conv/neutral-angry/train/neutral', w)) # src = np.asarray(src[1], np.float64) # f0_src, sp_src, ap_src = pw.wav2world(src, 16000, frame_period=5) # mfc_src = pw.code_spectral_envelope(sp_src, 16000, 23) # # tar = scwav.read(os.path.join('/home/ravi/Downloads/Emo-Conv/neutral-angry/train/angry', w)) # tar = np.asarray(tar[1], np.float64) # f0_tar, sp_tar, ap_tar = pw.wav2world(tar, 16000, frame_period=5) # mfc_tar = pw.code_spectral_envelope(sp_tar, 16000, 23) # # src_mfcc = librosa.feature.mfcc(y=src, sr=sample_rate, \ # hop_length=int(sample_rate*window_len), \ # win_length=int(sample_rate*window_len), \ # n_fft=1024, n_mels=128) # # tar_mfcc = librosa.feature.mfcc(y=tar, sr=sample_rate, \ # hop_length=int(sample_rate*window_len), \ # win_length=int(sample_rate*window_len), \ # n_fft=1024, n_mels=128) # # _, cords = librosa.sequence.dtw(X=src_mfcc, Y=tar_mfcc, metric='cosine') # cords = np.flipud(cords) # sp_src = sp_src[cords[:,0],:] # sp_tar = sp_tar[cords[:,1],:] # for i in range(10): # q = np.random.randint(0, len(cords)) # pylab.figure(), pylab.subplot(211) # pylab.plot(sp_src[cords[q,0],:], label='neutral') # pylab.plot(sp_tar[cords[q,1],:], label='angry') # pylab.grid(), pylab.title('Slice %d' % q), pylab.legend(loc=1) # # pylab.subplot(212) # pylab.plot(mfc_src[cords[q,0],:], label='neutral') # pylab.plot(mfc_tar[cords[q,1],:], label='angry') # pylab.grid(), pylab.title('Slice %d' % q), pylab.legend(loc=1) # u_src, sigma_src, v_src = np.linalg.svd(sp_src) # u_tar, sigma_tar, v_tar = np.linalg.svd(sp_tar) # # s_mat = np.zeros(sp_src.shape) # t_mat = np.zeros(sp_tar.shape) # s_mat_array = [] # t_mat_array = [] # for i in range(min([u_src.shape[0], v_src.shape[0]])): # x = np.dot(u_src[:,i:i+1], v_src[i:i+1,:]) # s_mat += sigma_src[i]*x # s_mat_array.append(s_mat) # pylab.figure(figsize=(15,15)), pylab.imshow(_power_to_db(s_mat.T ** 2)) # pylab.suptitle('#Components %d' % (i+1)) # pylab.savefig('/home/ravi/Desktop/svd_recon/src_'+str(i)+'.png') # pylab.close() # # for i in range(min([u_tar.shape[0], v_tar.shape[0]])): # y = np.dot(u_tar[:,i:i+1], v_tar[i:i+1,:]) # t_mat += sigma_tar[i]*y # t_mat_array.append(t_mat) # pylab.figure(figsize=(15,15)), pylab.imshow(_power_to_db(s_mat.T ** 2)) # pylab.suptitle('#Components %d' % (i+1)) # pylab.savefig('/home/ravi/Desktop/svd_recon/tar_'+str(i)+'.png') # pylab.close() # # break # s_mfc_array = np.asarray([pw.code_spectral_envelope(s, 16000, 4) for s in s_mat_array]) # t_mfc_array = np.asarray([pw.code_spectral_envelope(t, 16000, 4) for t in t_mat_array]) # # print(w) # min_val.append((np.min(s_mfc_array) ,np.min(t_mfc_array))) # max_val.append((np.max(s_mfc_array) ,np.max(t_mfc_array))) """ Cohort analysis """ src_list = sorted(glob(os.path.join('/home/ravi/Downloads/Emo-Conv/neutral-angry/train/neutral', '*.wav'))) tar_list = sorted(glob(os.path.join('/home/ravi/Downloads/Emo-Conv/neutral-angry/train/angry', '*.wav'))) executor = ProcessPoolExecutor(max_workers=8) src_futures = [] tar_futures = [] src_results = [] tar_results = [] dim = 8 times_sampling = 2 for sampling in range(times_sampling): for i in src_list: src_futures.append(executor.submit(partial(_get_spect_no_abs, i, dim, False))) # src_results.append(_get_spect_no_abs(i, dim)) # print(i) src_results = [src_future.result() for src_future in tqdm(src_futures)] for sampling in range(times_sampling): for i in tar_list: tar_futures.append(executor.submit(partial(_get_spect_no_abs, i, dim, False))) # tar_results.append(_get_spect_no_abs(i, dim)) # print(i) tar_results = [tar_future.result() for tar_future in tqdm(tar_futures)] src_mfcc = [i for i,j in zip(src_results, tar_results) if i!=None and j!=None] tar_mfcc = [j for i,j in zip(src_results, tar_results) if i!=None and j!=None] src_rank1 = np.asarray([i[0] for i in src_mfcc]) src_rank2 = np.asarray([i[1] for i in src_mfcc]) src_rank3 =
np.asarray([i[2] for i in src_mfcc])
numpy.asarray
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Mar 24 09:18:44 2020 @author: <NAME> <EMAIL> @author: matheustorquato <EMAIL> """ import functools, os import matplotlib.pyplot as plt import numpy as np import datetime as dt import pandas as pd import logging from functools import reduce import scipy.integrate as spi from platypus import NSGAII, Problem, Real #from pyswarms.single.global_best import GlobalBestPSO import pyswarms as ps from pyswarms.backend.topology import Star from pyswarms.utils.plotters import plot_cost_history from itertools import repeat import multiprocessing as mp class SEIRHUD: ''' SEIRHU Model''' def __init__(self,tamanhoPop,numeroProcessadores=None): self.N = tamanhoPop self.numeroProcessadores = numeroProcessadores def __cal_EDO(self,x,beta,gammaH,gammaU,delta,h,ia0,is0,e0): ND = len(x)-1 t_start = 0.0 t_end = ND t_inc = 1 t_range = np.arange(t_start, t_end + t_inc, t_inc) beta =
np.array(beta)
numpy.array
import numpy as np import random as rand import csv import pandas as pd # Set a seed for reproducibility SEED = 500; rand.seed(SEED) mu = 0 sigma = 1 length = 1000 # Number of params affecting model 50,000 SNP chip # Create linear model with parameter weights drawn randomly from a gaussian distribution effects =
np.ones(length)
numpy.ones
import pandas as pd import numpy as np import lightgbm as lgb from sklearn.model_selection import KFold from catboost import CatBoostRegressor from utils import * import argparse from sklearn import preprocessing import wordbatch from wordbatch.extractors import WordBag from wordbatch.models import FM_FTRL class TargetEncoder: # Adapted from https://www.kaggle.com/ogrellier/python-target-encoding-for-categorical-features def __repr__(self): return 'TargetEncoder' def __init__(self, cols, smoothing=1, min_samples_leaf=1, noise_level=0, keep_original=False): self.cols = cols self.smoothing = smoothing self.min_samples_leaf = min_samples_leaf self.noise_level = noise_level self.keep_original = keep_original @staticmethod def add_noise(series, noise_level): return series * (1 + noise_level * np.random.randn(len(series))) def encode(self, train, test, target): for col in self.cols: if self.keep_original: train[col + '_te'], test[col + '_te'] = self.encode_column(train[col], test[col], target) else: train[col], test[col] = self.encode_column(train[col], test[col], target) return train, test def encode_column(self, trn_series, tst_series, target): temp = pd.concat([trn_series, target], axis=1) # Compute target mean averages = temp.groupby(by=trn_series.name)[target.name].agg(["mean", "count"]) # Compute smoothing smoothing = 1 / (1 + np.exp(-(averages["count"] - self.min_samples_leaf) / self.smoothing)) # Apply average function to all target data prior = target.mean() # The bigger the count the less full_avg is taken into account averages[target.name] = prior * (1 - smoothing) + averages["mean"] * smoothing averages.drop(['mean', 'count'], axis=1, inplace=True) # Apply averages to trn and tst series ft_trn_series = pd.merge( trn_series.to_frame(trn_series.name), averages.reset_index().rename(columns={'index': target.name, target.name: 'average'}), on=trn_series.name, how='left')['average'].rename(trn_series.name + '_mean').fillna(prior) # pd.merge does not keep the index so restore it ft_trn_series.index = trn_series.index ft_tst_series = pd.merge( tst_series.to_frame(tst_series.name), averages.reset_index().rename(columns={'index': target.name, target.name: 'average'}), on=tst_series.name, how='left')['average'].rename(trn_series.name + '_mean').fillna(prior) # pd.merge does not keep the index so restore it ft_tst_series.index = tst_series.index return self.add_noise(ft_trn_series, self.noise_level), self.add_noise(ft_tst_series, self.noise_level) def rmse(y, y0): assert len(y) == len(y0) return np.sqrt(np.mean(np.power((y - y0), 2))) stopwords = {x: 1 for x in stopwords.words('russian')} non_alphanums = re.compile(u'[^A-Za-z0-9]+') non_alphanumpunct = re.compile(u'[^A-Za-z0-9\.?!,; \(\)\[\]\'\"\$]+') RE_PUNCTUATION = '|'.join([re.escape(x) for x in string.punctuation]) train = pd.read_csv('../input/train.csv', index_col = "item_id", parse_dates = ["activation_date"]) test = pd.read_csv('../input/test.csv', index_col = "item_id", parse_dates = ["activation_date"]) import string def normalize_text(text): text = text.lower().strip() for s in string.punctuation: text = text.replace(s, ' ') text = text.strip().split(' ') return u' '.join(x for x in text if len(x) > 1 and x not in stopwords) print(train.description[0]) print(normalize_text(train.description[0])) train['is_train'] = 1 test['is_train'] = 0 print('[{}] Compiled train / test'.format(time.time() - start_time)) print('Train shape: ', train.shape) print('Test shape: ', test.shape) y = train.deal_probability.copy() nrow_train = train.shape[0] merge = pd.concat([train, test]) submission = pd.DataFrame(test.index) print('[{}] Compiled merge'.format(time.time() - start_time)) print('Merge shape: ', merge.shape) del train del test gc.collect() print('[{}] Garbage collection'.format(time.time() - start_time)) print("Feature Engineering - Part 1") merge["price"] = np.log(merge["price"]+0.001) merge["price"].fillna(-999,inplace=True) merge["image_top_1"].fillna(-999,inplace=True) print("\nCreate Time Variables") merge["activation_weekday"] = merge['activation_date'].dt.weekday print(merge.head(5)) gc.collect() training_index = merge.loc[merge.activation_date<=pd.to_datetime('2017-04-07')].index validation_index = merge.loc[merge.activation_date>=pd.to_datetime('2017-04-08')].index merge.drop(["activation_date","image"],axis=1,inplace=True) #Drop user_id merge.drop(["user_id"], axis=1,inplace=True) print("\nText Features") textfeats = ["description", "title"] for cols in textfeats: merge[cols] = merge[cols].astype(str) merge[cols] = merge[cols].astype(str).fillna('missing') # FILL NA merge[cols] = merge[cols].str.lower() # Lowercase all text, so that capitalized words dont get treated differently merge[cols + '_num_stopwords'] = merge[cols].apply(lambda x: len([w for w in x.split() if w in stopwords])) # Count number of Stopwords merge[cols + '_num_punctuations'] = merge[cols].apply(lambda comment: (comment.count(RE_PUNCTUATION))) # Count number of Punctuations merge[cols + '_num_alphabets'] = merge[cols].apply(lambda comment: len([c for c in comment if c.isupper()])) # Count number of Alphabets merge[cols + '_num_digits'] = merge[cols].apply(lambda comment: (comment.count('[0-9]'))) # Count number of Digits merge[cols + '_num_letters'] = merge[cols].apply(lambda comment: len(comment)) # Count number of Letters merge[cols + '_num_words'] = merge[cols].apply(lambda comment: len(comment.split())) # Count number of Words merge[cols + '_num_unique_words'] = merge[cols].apply(lambda comment: len(set(w for w in comment.split()))) merge[cols + '_words_vs_unique'] = merge[cols+'_num_unique_words'] / merge[cols+'_num_words'] # Count Unique Words merge[cols + '_letters_per_word'] = merge[cols+'_num_letters'] / merge[cols+'_num_words'] # Letters per Word merge[cols + '_punctuations_by_letters'] = merge[cols+'_num_punctuations'] / merge[cols+'_num_letters'] # Punctuations by Letters merge[cols + '_punctuations_by_words'] = merge[cols+'_num_punctuations'] / merge[cols+'_num_words'] # Punctuations by Words merge[cols + '_digits_by_letters'] = merge[cols+'_num_digits'] / merge[cols+'_num_letters'] # Digits by Letters merge[cols + '_alphabets_by_letters'] = merge[cols+'_num_alphabets'] / merge[cols+'_num_letters'] # Alphabets by Letters merge[cols + '_stopwords_by_words'] = merge[cols+'_num_stopwords'] / merge[cols+'_num_words'] # Stopwords by Letters merge[cols + '_mean'] = merge[cols].apply(lambda x: 0 if len(x) == 0 else float(len(x.split())) / len(x)) * 10 # Mean # Extra Feature Engineering merge['title_desc_len_ratio'] = merge['title_num_letters']/merge['description_num_letters'] df_test = merge.loc[merge['is_train'] == 0] df_train = merge.loc[merge['is_train'] == 1] del merge gc.collect() df_test = df_test.drop(['is_train'], axis=1) df_train = df_train.drop(['is_train'], axis=1) print(df_train.shape) print(y.shape) if SUBMIT_MODE: y_train = y del y gc.collect() else: df_train, df_test, y_train, y_test = train_test_split(df_train, y, test_size=0.2, random_state=144) print('[{}] Splitting completed.'.format(time.time() - start_time)) wb = wordbatch.WordBatch(normalize_text, extractor=(WordBag, {"hash_ngrams": 2, "hash_ngrams_weights": [1.5, 1.0], "hash_size": 2 ** 29, "norm": None, "tf": 'binary', "idf": None, }), procs=8) wb.dictionary_freeze = True X_name_train = wb.fit_transform(df_train['title']) print(X_name_train.shape) X_name_test = wb.transform(df_test['title']) print(X_name_test.shape) del(wb) gc.collect() mask = np.where(X_name_train.getnnz(axis=0) > 3)[0] X_name_train = X_name_train[:, mask] print(X_name_train.shape) X_name_test = X_name_test[:, mask] print(X_name_test.shape) print('[{}] Vectorize `title` completed.'.format(time.time() - start_time)) X_train_1, X_train_2, y_train_1, y_train_2 = train_test_split(X_name_train, y_train, test_size = 0.5, shuffle = False) print('[{}] Finished splitting'.format(time.time() - start_time)) model = Ridge(solver="sag", fit_intercept=True, random_state=42, alpha=5) model.fit(X_train_1, y_train_1) print('[{}] Finished to train name ridge (1)'.format(time.time() - start_time)) name_ridge_preds1 = model.predict(X_train_2) name_ridge_preds1f = model.predict(X_name_test) print('[{}] Finished to predict name ridge (1)'.format(time.time() - start_time)) model = Ridge(solver="sag", fit_intercept=True, random_state=42, alpha=5) model.fit(X_train_2, y_train_2) print('[{}] Finished to train name ridge (2)'.format(time.time() - start_time)) name_ridge_preds2 = model.predict(X_train_1) name_ridge_preds2f = model.predict(X_name_test) print('[{}] Finished to predict name ridge (2)'.format(time.time() - start_time)) name_ridge_preds_oof =
np.concatenate((name_ridge_preds2, name_ridge_preds1), axis=0)
numpy.concatenate
import numpy as np #import matplotlib.pyplot as plt from skimage.measure import label,find_contours #from PIL import Image #from scipy.ndimage.morphology import distance_transform_edt import csv import sys #from scipy.interpolate import Rbf,interp2d from skimage.morphology import binary_opening #from scipy import ndimage from sklearn.linear_model import RANSACRegressor def get_contour(rad,thresh): """ Find the edge in the input radiograph. Parameters: rad (numpy.ndarray): Radiograph of a sharp edge sample thresh (float): The value at which a iso-valued contour (contour is the edge) is drawn Returns: numpy.ndarray: Coordinates along the longest detected contour """ contours = find_contours(rad,thresh) best_contour = contours[0] for contour in contours: if(len(contour)>len(best_contour)): best_contour = contour return(best_contour) def get_trans(rad,best_contour,trans_min,trans_max,thresh): """ Compute the ideal transmission image. Parameters: rad (numpy.ndarray): Radiograph of a sharp edge sample best_contour (numpy.ndarray): Coordinates of the longest contour that is assumed to be the edge trans_min (float): Minimum transmission value trans_max (float): Maximum transmission value thresh (float): Transmission value for the edge Returns: numpy.ndarray: Ideal transmission image """ window_interp = 5 #for interpolation. must be odd edge_thick = np.ones(rad.shape) #edge pixel will be labeled as 0 for row,col in best_contour: row_floor,col_floor = int(np.floor(row)),int(np.floor(col)) row_ceil,col_ceil = int(np.ceil(row)),int(np.ceil(col)) edge_thick[row_floor,col_floor],edge_thick[row_floor,col_ceil] = 0,0 edge_thick[row_ceil,col_floor],edge_thick[row_ceil,col_ceil] = 0,0 edge_thick = binary_opening(edge_thick) #erosion followed by dilation. Rids of bright pixels in edge voxels rows_edge,cols_edge = np.nonzero(edge_thick==0) #Get edge pixel locations labels,num = label(edge_thick,background=0,return_num=True) if(num != 2): raise ValueError("ERROR: Number of regions detected is {}. Two types of regions must be present in radiographs.".format(num)) val1 = np.mean(rad[labels==1]) val2 = np.mean(rad[labels==2]) trans = np.zeros(rad.shape) #Sample's pixel locations will be labeled as 1 trans[labels==0] = np.nan trans[labels==1] = trans_min if val1<=val2 else trans_max trans[labels==2] = trans_max if val1<=val2 else trans_min for row,col in best_contour: trans[int(round(row)),int(round(col))] = thresh ideal_trans = trans.copy() for row,col in zip(rows_edge,cols_edge): if(np.isnan(trans[row,col])): norm,ival = 0,0 for i in range(-int((window_interp-1)/2),int((window_interp-1)/2)+1): for j in range(-int((window_interp-1)/2),int((window_interp-1)/2)+1): row_new = row+i col_new = col+j if(i!=0 and j!=0 and row_new>=0 and row_new<trans.shape[0] and col_new>=0 and col_new<trans.shape[1]): if(np.isnan(trans[row_new,col_new]) == False): weight = 1.0/np.sqrt(i*i+j*j) ival += weight*trans[row_new,col_new] norm += weight ideal_trans[row,col] = ival/norm if norm != 0 else thresh if(norm == 0): print("WARNING: No valid value within window for interpolation") return(ideal_trans) def get_padded_trans(ideal_trans,bdary_mask_perc,pad_factor,rad_mask): """ Appropriately pad the ideal transmission image and the masks. Parameters: ideal_trans (numpy.ndarray): Ideal transmission image bdary_mask_perc (float): Percentage of image region that must be masked, i.e., excluded from blur estimation, close to the radiograph edges on each side (left, right, top, and bottom). Expressed as a percentage of the radiograph size. pad_factor (list [float,float]): Pad factor as expressed in multiples of input radiograph size rad_mask (numpy.ndarray): Boolean mask array over the radiograph where blur estimation is done. """ bdary_mask_perc /= 100 #Solves hw-(h-2*delta)(w-2*delta)=phw where h,w are idea_trans shape, p is bdary_mask_perc, and delta is delta_mask a = 4 b = -2*(ideal_trans.shape[0]+ideal_trans.shape[1]) c = bdary_mask_perc*ideal_trans.shape[0]*ideal_trans.shape[1] delta_mask = (-b-np.sqrt(b*b-4*a*c))/(2*a) if delta_mask < 0: raise ValueError("ERROR: delta_mask is negative. This should not occur. Contact the author of this python package.") # print("Delta mask is ",delta_mask) mask = np.zeros(ideal_trans.shape).astype(bool) row_min = int(round(delta_mask)) row_max = int(round(mask.shape[0]-delta_mask)) col_min = int(round(delta_mask)) col_max = int(round(mask.shape[1]-delta_mask)) mask[row_min:row_max,col_min:col_max] = True if rad_mask is not None: mask = np.bitwise_and(mask,rad_mask) norm_rad_mask = mask.copy() #pad_width0 = int(ideal_trans.shape[0]*(pad_factor[0]-1)/2.0-bdary_mask_perc*mask.shape[0]) #pad_width1 = int(ideal_trans.shape[1]*(pad_factor[1]-1)/2.0-bdary_mask_perc*mask.shape[1]) pad_width0 = int(ideal_trans.shape[0]*(pad_factor[0]-1)/2.0) pad_width1 = int(ideal_trans.shape[1]*(pad_factor[1]-1)/2.0) colidx,rowidx = np.meshgrid(np.arange(-pad_width1,ideal_trans.shape[1]+pad_width1),np.arange(-pad_width0,ideal_trans.shape[0]+pad_width0)) ideal_trans =
np.pad(ideal_trans,((pad_width0,pad_width0),(pad_width1,pad_width1)),mode='constant',constant_values=-1)
numpy.pad
import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) import matplotlib.pyplot as plt import re from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer from sklearn.decomposition import TruncatedSVD from sklearn import preprocessing, model_selection, metrics import lightgbm as lgb import gc train_df = pd.read_csv('../input/train.csv', parse_dates=["activation_date"]) test_df = pd.read_csv('../input/test.csv', parse_dates=["activation_date"]) import matplotlib.pyplot as plt import pandas as pd import numpy as np import seaborn as sns import random import nltk nltk.data.path.append("/media/sayantan/Personal/nltk_data") from nltk.stem.snowball import RussianStemmer from fuzzywuzzy import fuzz from nltk.corpus import stopwords from tqdm import tqdm from scipy.stats import skew, kurtosis from scipy.spatial.distance import cosine, cityblock, jaccard, canberra, euclidean, minkowski, braycurtis from nltk import word_tokenize stopwords = stopwords.words('russian') def genFeatures(x): x["activation_weekday"] = x["activation_date"].dt.weekday x["monthday"] = x["activation_date"].dt.day x["weekinmonday"] = x["monthday"] // 7 ##################Added in set 1 - 0.01 Improvement x['price_new'] = np.log1p(x.price) # log transform improves co-relation with deal_price x['count_null_in_row'] = x.isnull().sum(axis=1)# works x['has_description'] = x.description.isnull().astype(int) x['has_image'] = x.image.isnull().astype(int) x['has_image_top'] = x.image_top_1.isnull().astype(int) x['has_param1'] = x.param_1.isnull().astype(int) x['has_param2'] = x.param_2.isnull().astype(int) x['has_param3'] = x.param_3.isnull().astype(int) x['has_price'] = x.price.isnull().astype(int) #################Added in set 2 - 0.00x Improvement x["description"].fillna("NA", inplace=True) x["desc_nwords"] = x["description"].apply(lambda x: len(x.split())) x['len_description'] = x['description'].apply(lambda x: len(x)) x["title_nwords"] = x["title"].apply(lambda x: len(x.split())) x['len_title'] = x['title'].apply(lambda x: len(x)) x['params'] = x['param_1'].fillna('') + ' ' + x['param_2'].fillna('') + ' ' + x['param_3'].fillna('') x['params'] = x['params'].str.strip() x['len_params'] = x['params'].apply(lambda x: len(x)) x['words_params'] = x['params'].apply(lambda x: len(x.split())) x['symbol1_count'] = x['description'].str.count('↓') x['symbol2_count'] = x['description'].str.count('\*') x['symbol3_count'] = x['description'].str.count('✔') x['symbol4_count'] = x['description'].str.count('❀') x['symbol5_count'] = x['description'].str.count('➚') x['symbol6_count'] = x['description'].str.count('ஜ') x['symbol7_count'] = x['description'].str.count('.') x['symbol8_count'] = x['description'].str.count('!') x['symbol9_count'] = x['description'].str.count('\?') x['symbol10_count'] = x['description'].str.count(' ') x['symbol11_count'] = x['description'].str.count('-') x['symbol12_count'] = x['description'].str.count(',') #################### return x train_df = genFeatures(train_df) test_df = genFeatures(test_df) test_df['deal_probability']=10.0 ############################ english_stemmer = nltk.stem.SnowballStemmer('russian') def clean_text(text): #text = re.sub(r'(\d+),(\d+)', r'\1.\2', text) text = text.replace(u'²', '2') text = text.lower() text = re.sub(u'[^a-zа-я0-9]', ' ', text) text = re.sub('\s+', ' ', text) return text.strip() def stem_tokens(tokens, stemmer): stemmed = [] for token in tokens: #stemmed.append(stemmer.lemmatize(token)) stemmed.append(stemmer.stem(token)) return stemmed def preprocess_data(line, exclude_stopword=True, encode_digit=False): ## tokenize line = clean_text(line) tokens = [x.lower() for x in nltk.word_tokenize(line)] ## stem tokens_stemmed = stem_tokens(tokens, english_stemmer)#english_stemmer if exclude_stopword: tokens_stemmed = [x for x in tokens_stemmed if x not in stopwords] return ' '.join(tokens_stemmed) train_test = pd.concat((train_df, test_df), axis = 'rows') ## After cleaning => then find intersection train_test["title_clean"]= list(train_test[["title"]].apply(lambda x: preprocess_data(x["title"]), axis=1)) train_test["desc_clean"]= list(train_test[["description"]].apply(lambda x: preprocess_data(x["description"]), axis=1)) train_test["params_clean"]= list(train_test[["params"]].apply(lambda x: preprocess_data(x["params"]), axis=1)) train_test['count_common_words_title_desc'] = train_test.apply(lambda x: len(set(str(x['title_clean']).lower().split()).intersection(set(str(x['desc_clean']).lower().split()))), axis=1) train_test['count_common_words_title_params'] = train_test.apply(lambda x: len(set(str(x['title_clean']).lower().split()).intersection(set(str(x['params_clean']).lower().split()))), axis=1) train_test['count_common_words_params_desc'] = train_test.apply(lambda x: len(set(str(x['params_clean']).lower().split()).intersection(set(str(x['desc_clean']).lower().split()))), axis=1) print("Cleaned texts..") ################### # Count Nouns import pymorphy2 morph = pymorphy2.MorphAnalyzer(result_type=None) from fastcache import clru_cache as lru_cache @lru_cache(maxsize=1000000) def lemmatize_pos(word): _, tag, norm_form, _, _ = morph.parse(word)[0] return norm_form, tag.POS def getPOS(x, pos1 = 'NOUN'): lemmatized = [] x = clean_text(x) #x = re.sub(u'[.]', ' ', x) for s in x.split(): s, pos = lemmatize_pos(s) if pos != None: if pos1 in pos: lemmatized.append(s) return ' '.join(lemmatized) train_test['get_nouns_title'] = list(train_test.apply(lambda x: getPOS(x['title'], 'NOUN'), axis=1)) train_test['get_nouns_desc'] = list(train_test.apply(lambda x: getPOS(x['description'], 'NOUN'), axis=1)) train_test['get_adj_title'] = list(train_test.apply(lambda x: getPOS(x['title'], 'ADJ'), axis=1)) train_test['get_adj_desc'] = list(train_test.apply(lambda x: getPOS(x['description'], 'ADJ'), axis=1)) train_test['get_verb_title'] = list(train_test.apply(lambda x: getPOS(x['title'], 'VERB'), axis=1)) train_test['get_verb_desc'] = list(train_test.apply(lambda x: getPOS(x['description'], 'VERB'), axis=1)) # Count digits def count_digit(x): x = clean_text(x) return len(re.findall(r'\b\d+\b', x)) train_test['count_of_digit_in_title'] = list(train_test.apply(lambda x: count_digit(x['title']), axis=1)) train_test['count_of_digit_in_desc'] = list(train_test.apply(lambda x: count_digit(x['description']), axis=1)) train_test['count_of_digit_in_params'] = list(train_test.apply(lambda x: count_digit(x['params']), axis=1)) ## get unicode features count_unicode = lambda x: len([c for c in x if ord(c) > 1105]) count_distunicode = lambda x: len({c for c in x if ord(c) > 1105}) train_test['count_of_unicode_in_title'] = list(train_test.apply(lambda x: count_unicode(x['title']), axis=1)) train_test['count_of_unicode_in_desc'] = list(train_test.apply(lambda x: count_distunicode(x['description']), axis=1)) train_test['count_of_distuni_in_title'] = list(train_test.apply(lambda x: count_unicode(x['title']), axis=1)) train_test['count_of_distuni_in_desc'] = list(train_test.apply(lambda x: count_distunicode(x['description']), axis=1)) ### count_caps = lambda x: len([c for c in x if c.isupper()]) train_test['count_caps_in_title'] = list(train_test.apply(lambda x: count_caps(x['title']), axis=1)) train_test['count_caps_in_desc'] = list(train_test.apply(lambda x: count_caps(x['description']), axis=1)) import string count_punct = lambda x: len([c for c in x if c in string.punctuation]) train_test['count_punct_in_title'] = list(train_test.apply(lambda x: count_punct(x['title']), axis=1)) train_test['count_punct_in_desc'] = list(train_test.apply(lambda x: count_punct(x['description']), axis=1)) print("Computed POS Features and others..") train_test['count_common_nouns'] = train_test.apply(lambda x: len(set(str(x['get_nouns_title']).lower().split()).intersection(set(str(x['get_nouns_desc']).lower().split()))), axis=1) train_test['count_common_adj'] = train_test.apply(lambda x: len(set(str(x['get_adj_title']).lower().split()).intersection(set(str(x['get_adj_desc']).lower().split()))), axis=1) train_test['ratio_of_unicode_in_title'] = train_test['count_of_unicode_in_title'] / train_test['len_title'] train_test['ratio_of_unicode_in_desc'] = train_test['count_of_unicode_in_desc'] / train_test['len_description'] train_test['ratio_of_punct_in_title'] = train_test['count_punct_in_title'] / train_test['len_title'] train_test['ratio_of_punct_in_desc'] = train_test['count_punct_in_desc'] / train_test['len_description'] train_test['ratio_of_cap_in_title'] = train_test['count_caps_in_title'] / train_test['len_title'] train_test['ratio_of_cap_in_desc'] = train_test['count_caps_in_desc'] / train_test['len_description'] train_test['count_nouns_in_title'] = train_test["get_nouns_title"].apply(lambda x: len(x.split())) train_test['count_nouns_in_desc'] = train_test['get_nouns_desc'].apply(lambda x: len(x.split())) train_test['count_adj_in_title'] = train_test["get_adj_title"].apply(lambda x: len(x.split())) train_test['count_adj_in_desc'] = train_test['get_adj_desc'].apply(lambda x: len(x.split())) train_test['count_verb_title'] = train_test['get_verb_title'].apply(lambda x: len(x.split())) train_test['count_verb_desc'] = train_test['get_verb_desc'].apply(lambda x: len(x.split())) train_test['ratio_nouns_in_title'] = train_test["count_nouns_in_title"] / train_test["title_nwords"] train_test['ratio_nouns_in_desc'] = train_test["count_nouns_in_desc"] / train_test["desc_nwords"] train_test['ratio_adj_in_title'] = train_test["count_adj_in_title"] / train_test["title_nwords"] train_test['ratio_adj_in_desc'] = train_test["count_adj_in_desc"] / train_test["desc_nwords"] train_test['ratio_vrb_in_title'] = train_test["count_verb_title"] / train_test["title_nwords"] train_test['ratio_vrb_in_desc'] = train_test["count_verb_desc"] / train_test["desc_nwords"] train_test["title"]= list(train_test[["title"]].apply(lambda x: clean_text(x["title"]), axis=1)) train_test["description"]= list(train_test[["description"]].apply(lambda x: clean_text(x["description"]), axis=1)) train_test["params"]= list(train_test[["params"]].apply(lambda x: clean_text(x["params"]), axis=1)) ####################### ### Save ####################### train_df = train_test.loc[train_test.deal_probability != 10].reset_index(drop = True) test_df = train_test.loc[train_test.deal_probability == 10].reset_index(drop = True) for c in train_df.columns: if train_df[c].dtype == 'float64': train_df[c] = train_df[c].astype('float32') test_df[c] = test_df[c].astype('float32') train_df.to_feather('../train_basic_features.pkl') test_df.to_feather('../test__basic_features.pkl') ####################### ### Label Enc ####################### from sklearn.preprocessing import StandardScaler, OneHotEncoder, LabelEncoder, MinMaxScaler cat_vars = ["user_id", "region", "city", "parent_category_name", "category_name", "user_type", "param_1", "param_2", "param_3"] for col in cat_vars: lbl = preprocessing.LabelEncoder() lbl.fit(list(train_df[col].values.astype('str')) + list(test_df[col].values.astype('str'))) train_df[col] = lbl.transform(list(train_df[col].values.astype('str'))) test_df[col] = lbl.transform(list(test_df[col].values.astype('str'))) train_df.to_feather('../train_basic_features_lblencCats.pkl') test_df.to_feather('../test__basic_features_lblencCats.pkl') ####################### ### One hots ####################### train_df=pd.read_feather('../train_basic_features_lblencCats.pkl') test_df=pd.read_feather('../test__basic_features_lblencCats.pkl') from sklearn.externals import joblib le = OneHotEncoder() X = le.fit_transform(np.array(train_df.user_id.values.tolist() + test_df.user_id.values.tolist()).reshape(-1,1)) joblib.dump(X, "../user_id_onehot.pkl") X = le.fit_transform(np.array(train_df.region.values.tolist() + test_df.region.values.tolist()).reshape(-1,1)) joblib.dump(X, "../region_onehot.pkl") X = le.fit_transform(np.array(train_df.city.values.tolist() + test_df.city.values.tolist()).reshape(-1,1)) joblib.dump(X, "../city_onehot.pkl") X = le.fit_transform(np.array(train_df.parent_category_name.values.tolist() + test_df.parent_category_name.values.tolist()).reshape(-1,1)) joblib.dump(X, "../parent_category_name_onehot.pkl") X = le.fit_transform(np.array(train_df.category_name.values.tolist() + test_df.category_name.values.tolist()).reshape(-1,1)) joblib.dump(X, "../category_name_onehot.pkl") X = le.fit_transform(np.array(train_df.user_type.values.tolist() + test_df.user_type.values.tolist()).reshape(-1,1)) joblib.dump(X, "../user_type_onehot.pkl") X = le.fit_transform(np.array(train_df.param_1.values.tolist() + test_df.param_1.values.tolist()).reshape(-1,1)) joblib.dump(X, "../param_1_onehot.pkl") X = le.fit_transform(np.array(train_df.param_2.values.tolist() + test_df.param_2.values.tolist()).reshape(-1,1)) joblib.dump(X, "../param_2_onehot.pkl") X = le.fit_transform(np.array(train_df.param_3.values.tolist() + test_df.param_3.values.tolist()).reshape(-1,1)) joblib.dump(X, "../param_3_onehot.pkl") train_df.drop(cat_vars, inplace = True, axis = 'columns') test_df.drop(cat_vars, inplace = True, axis = 'columns') train_df.to_feather('../train_basic_features_woCats.pkl') test_df.to_feather('../test__basic_features_woCats.pkl') ####################### ### Tfidf ####################### train_df=pd.read_feather('../train_basic_features_woCats.pkl') test_df=pd.read_feather('../test__basic_features_woCats.pkl') from sklearn.externals import joblib ### TFIDF Vectorizer ### train_df['params'] = train_df['params'].fillna('NA') test_df['params'] = test_df['params'].fillna('NA') tfidf_vec = TfidfVectorizer(ngram_range=(1,3),max_features = 10000,#min_df=3, max_df=.85, analyzer='word', token_pattern= r'\w{1,}', use_idf=1, smooth_idf=0, sublinear_tf=1,) #TfidfVectorizer(ngram_range=(1,2)) full_tfidf = tfidf_vec.fit_transform(train_df['params'].values.tolist() + test_df['params'].values.tolist()) train_tfidf = tfidf_vec.transform(train_df['params'].values.tolist()) test_tfidf = tfidf_vec.transform(test_df['params'].values.tolist()) del full_tfidf print("TDIDF Params UNCLEAN..") joblib.dump([train_tfidf, test_tfidf], "../params_tfidf.pkl") ### TFIDF Vectorizer ### train_df['title_clean'] = train_df['title_clean'].fillna('NA') test_df['title_clean'] = test_df['title_clean'].fillna('NA') tfidf_vec = TfidfVectorizer(ngram_range=(1,2),max_features = 20000,#,min_df=3, max_df=.85, analyzer='word', token_pattern= r'\w{1,}', use_idf=1, smooth_idf=0, sublinear_tf=1,) full_tfidf = tfidf_vec.fit_transform(train_df['title_clean'].values.tolist() + test_df['title_clean'].values.tolist()) train_tfidf = tfidf_vec.transform(train_df['title_clean'].values.tolist()) test_tfidf = tfidf_vec.transform(test_df['title_clean'].values.tolist()) joblib.dump([train_tfidf, test_tfidf], "../title_tfidf.pkl") del full_tfidf print("TDIDF TITLE CLEAN..") ### TFIDF Vectorizer ### train_df['desc_clean'] = train_df['desc_clean'].fillna(' ') test_df['desc_clean'] = test_df['desc_clean'].fillna(' ') tfidf_vec = TfidfVectorizer(ngram_range=(1,2), max_features = 20000, #,min_df=3, max_df=.85, analyzer='word', token_pattern= r'\w{1,}', use_idf=1, smooth_idf=0, sublinear_tf=1,) full_tfidf = tfidf_vec.fit_transform(train_df['desc_clean'].values.tolist() + test_df['desc_clean'].values.tolist()) train_tfidf = tfidf_vec.transform(train_df['desc_clean'].values.tolist()) test_tfidf = tfidf_vec.transform(test_df['desc_clean'].values.tolist()) joblib.dump([train_tfidf, test_tfidf], "../desc_tfidf.pkl") del full_tfidf print("TDIDF DESC CLEAN..") ### TFIDF Vectorizer ### train_df['get_nouns_title'] = train_df['get_nouns_title'].fillna(' ') test_df['get_nouns_title'] = test_df['get_nouns_title'].fillna(' ') tfidf_vec = TfidfVectorizer(ngram_range=(1,1), max_features = 10000) full_tfidf = tfidf_vec.fit_transform(train_df['get_nouns_title'].values.tolist() + test_df['get_nouns_title'].values.tolist()) train_tfidf = tfidf_vec.transform(train_df['get_nouns_title'].values.tolist()) test_tfidf = tfidf_vec.transform(test_df['get_nouns_title'].values.tolist()) joblib.dump([train_tfidf, test_tfidf], "../nouns_title_tfidf.pkl") del full_tfidf print("TDIDF Title Noun..") ### TFIDF Vectorizer ### train_df['get_nouns_desc'] = train_df['get_nouns_desc'].fillna(' ') test_df['get_nouns_desc'] = test_df['get_nouns_desc'].fillna(' ') tfidf_vec = TfidfVectorizer(ngram_range=(1,1), max_features = 10000) full_tfidf = tfidf_vec.fit_transform(train_df['get_nouns_desc'].values.tolist() + test_df['get_nouns_desc'].values.tolist()) train_tfidf = tfidf_vec.transform(train_df['get_nouns_desc'].values.tolist()) test_tfidf = tfidf_vec.transform(test_df['get_nouns_desc'].values.tolist()) joblib.dump([train_tfidf, test_tfidf], "../nouns_desc_tfidf.pkl") del full_tfidf print("TDIDF Desc Noun..") ### TFIDF Vectorizer ### train_df['get_adj_title'] = train_df['get_adj_title'].fillna(' ') test_df['get_adj_title'] = test_df['get_adj_title'].fillna(' ') tfidf_vec = TfidfVectorizer(ngram_range=(1,1), max_features = 10000) full_tfidf = tfidf_vec.fit_transform(train_df['get_adj_title'].values.tolist() + test_df['get_adj_title'].values.tolist()) train_tfidf = tfidf_vec.transform(train_df['get_adj_title'].values.tolist()) test_tfidf = tfidf_vec.transform(test_df['get_adj_title'].values.tolist()) joblib.dump([train_tfidf, test_tfidf], "../adj_title_tfidf.pkl") del full_tfidf print("TDIDF TITLE Adj..") ### TFIDF Vectorizer ### train_df['get_adj_desc'] = train_df['get_adj_desc'].fillna(' ') test_df['get_adj_desc'] = test_df['get_adj_desc'].fillna(' ') tfidf_vec = TfidfVectorizer(ngram_range=(1,1), max_features = 10000) full_tfidf = tfidf_vec.fit_transform(train_df['get_adj_desc'].values.tolist() + test_df['get_adj_desc'].values.tolist()) train_tfidf = tfidf_vec.transform(train_df['get_adj_desc'].values.tolist()) test_tfidf = tfidf_vec.transform(test_df['get_adj_desc'].values.tolist()) joblib.dump([train_tfidf, test_tfidf], "../adj_desc_tfidf.pkl") del full_tfidf print("TDIDF Desc Adj..") ### TFIDF Vectorizer ### train_df['get_verb_title'] = train_df['get_verb_title'].fillna(' ') test_df['get_verb_title'] = test_df['get_verb_title'].fillna(' ') tfidf_vec = TfidfVectorizer(ngram_range=(1,1), max_features = 10000) full_tfidf = tfidf_vec.fit_transform(train_df['get_verb_title'].values.tolist() + test_df['get_verb_title'].values.tolist()) train_tfidf = tfidf_vec.transform(train_df['get_verb_title'].values.tolist()) test_tfidf = tfidf_vec.transform(test_df['get_verb_title'].values.tolist()) joblib.dump([train_tfidf, test_tfidf], "../verb_title_tfidf.pkl") del full_tfidf print("TDIDF TITLE Verb..") ### TFIDF Vectorizer ### train_df['get_verb_desc'] = train_df['get_verb_desc'].fillna(' ') test_df['get_verb_desc'] = test_df['get_verb_desc'].fillna(' ') tfidf_vec = TfidfVectorizer(ngram_range=(1,1), max_features = 10000) full_tfidf = tfidf_vec.fit_transform(train_df['get_verb_desc'].values.tolist() + test_df['get_verb_desc'].values.tolist()) train_tfidf = tfidf_vec.transform(train_df['get_verb_desc'].values.tolist()) test_tfidf = tfidf_vec.transform(test_df['get_verb_desc'].values.tolist()) joblib.dump([train_tfidf, test_tfidf], "../verb_desc_tfidf.pkl") del full_tfidf print("TDIDF Desc Verb..") ############################### # Sentence to seq ############################### print('Generate Word Sequences') train_df=pd.read_feather('../train_basic_features_woCats.pkl') test_df=pd.read_feather('../test__basic_features_woCats.pkl') from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences MAX_NUM_OF_WORDS = 100000 TIT_MAX_SEQUENCE_LENGTH = 100 df = pd.concat((train_df, test_df), axis = 'rows') tokenizer = Tokenizer(num_words=MAX_NUM_OF_WORDS) tokenizer.fit_on_texts(df['title'].tolist()) sequences = tokenizer.texts_to_sequences(df['title'].tolist()) titleSequences = pad_sequences(sequences, maxlen=TIT_MAX_SEQUENCE_LENGTH) joblib.dump(titleSequences, "../titleSequences.pkl") MAX_NUM_OF_WORDS = 10000 TIT_MAX_SEQUENCE_LENGTH = 20 tokenizer = Tokenizer(num_words=MAX_NUM_OF_WORDS) tokenizer.fit_on_texts(df['params'].tolist()) sequences = tokenizer.texts_to_sequences(df['params'].tolist()) titleSequences = pad_sequences(sequences, maxlen=TIT_MAX_SEQUENCE_LENGTH) joblib.dump(titleSequences, "../paramSequences.pkl") MAX_NUM_OF_WORDS = 100000 TIT_MAX_SEQUENCE_LENGTH = 100 tokenizer = Tokenizer(num_words=MAX_NUM_OF_WORDS) tokenizer.fit_on_texts(df['description'].tolist()) sequences = tokenizer.texts_to_sequences(df['description'].tolist()) titleSequences = pad_sequences(sequences, maxlen=TIT_MAX_SEQUENCE_LENGTH) joblib.dump(titleSequences, "../descSequences.pkl") #######OHC WeekDay from sklearn.preprocessing import StandardScaler, OneHotEncoder, LabelEncoder, MinMaxScaler le = OneHotEncoder() X = le.fit_transform(np.array(train_df.activation_weekday.values.tolist() + test_df.activation_weekday.values.tolist()).reshape(-1,1)) ################################################ # Cat encoding ################################################ train_df=pd.read_feather('../train_basic_features.pkl') test_df=pd.read_feather('../test__basic_features.pkl') def catEncode(train_char, test_char, y, colLst = [], nbag = 10, nfold = 20, minCount = 3, postfix = ''): train_df = train_char.copy() test_df = test_char.copy() if not colLst: print("Empty ColLst") for c in train_char.columns: data = train_char[[c]].copy() data['y'] = y enc_mat = np.zeros((y.shape[0],4)) enc_mat_test = np.zeros((test_char.shape[0],4)) for bag in np.arange(nbag): kf = model_selection.KFold(n_splits= nfold, shuffle=True, random_state=2017*bag) for dev_index, val_index in kf.split(range(data['y'].shape[0])): dev_X, val_X = data.iloc[dev_index,:], data.iloc[val_index,:] datax = dev_X.groupby([c]).agg([len,np.mean,np.std, np.median]) datax.columns = ['_'.join(col).strip() for col in datax.columns.values] # datax = datax.loc[datax.y_len > minCount] ind = c + postfix datax.rename(columns = {'y_mean': ('y_mean_' + ind), 'y_std': ('y_std_' + ind), 'y_len_': ('y_len' + ind), 'y_median_': ('y_median' + ind),}, inplace = True) # datax[c+'_medshftenc'] = datax['y_median']-med_y # datax.drop(['y_len','y_mean','y_std','y_median'],axis=1,inplace=True) datatst = test_char[[c]].copy() val_X = val_X.join(datax,on=[c], how='left').fillna(np.mean(y)) datatst = datatst.join(datax,on=[c], how='left').fillna(np.mean(y)) enc_mat[val_index,...] += val_X[list(set(datax.columns)-set([c]))] enc_mat_test += datatst[list(set(datax.columns)-set([c]))] enc_mat_test /= (nfold * nbag) enc_mat /= (nbag) enc_mat = pd.DataFrame(enc_mat) enc_mat.columns=[ind + str(x) for x in list(set(datax.columns)-set([c]))] enc_mat_test = pd.DataFrame(enc_mat_test) enc_mat_test.columns=enc_mat.columns train_df = pd.concat((enc_mat.reset_index(drop = True),train_df.reset_index(drop = True)), axis=1) test_df = pd.concat([enc_mat_test.reset_index(drop = True),test_df.reset_index(drop = True)],axis=1) else: print("Not Empty ColLst") data = train_char[colLst].copy() data['y'] = y enc_mat = np.zeros((y.shape[0],4)) enc_mat_test = np.zeros((test_char.shape[0],4)) for bag in np.arange(nbag): kf = model_selection.KFold(n_splits= nfold, shuffle=True, random_state=2017*bag) for dev_index, val_index in kf.split(range(data['y'].shape[0])): dev_X, val_X = data.iloc[dev_index,:], data.iloc[val_index,:] datax = dev_X.groupby(colLst).agg([len,np.mean,np.std, np.median]) datax.columns = ['_'.join(col).strip() for col in datax.columns.values] # datax = datax.loc[datax.y_len > minCount] ind = '_'.join(colLst) + postfix datax.rename(columns = {'y_mean': ('y_mean_' + ind), 'y_std': ('y_std_' + ind), 'y_len': ('y_len_' + ind), 'y_median': ('y_median_' + ind),}, inplace = True) datatst = test_char[colLst].copy() val_X = val_X.join(datax,on=colLst, how='left').fillna(np.mean(y)) datatst = datatst.join(datax,on=colLst, how='left').fillna(np.mean(y)) print(val_X[list(set(datax.columns)-set(colLst))].columns) enc_mat[val_index,...] += val_X[list(set(datax.columns)-set(colLst))] enc_mat_test += datatst[list(set(datax.columns)-set(colLst))] enc_mat_test /= (nfold * nbag) enc_mat /= (nbag) enc_mat = pd.DataFrame(enc_mat) enc_mat.columns=[ind + str(x) for x in list(set(datax.columns)-set([c]))] enc_mat_test = pd.DataFrame(enc_mat_test) enc_mat_test.columns=enc_mat.columns train_df = pd.concat((enc_mat.reset_index(drop = True),train_df.reset_index(drop = True)), axis=1) test_df = pd.concat([enc_mat_test.reset_index(drop = True),test_df.reset_index(drop = True)],axis=1) print(train_df.columns) print(test_df.columns) for c in train_df.columns: if train_df[c].dtype == 'float64': train_df[c] = train_df[c].astype('float32') test_df[c] = test_df[c].astype('float32') return train_df, test_df catCols = ['user_id', 'region', 'city', 'parent_category_name', 'category_name', 'user_type'] train_df, test_df = catEncode(train_df[catCols].copy(), test_df[catCols].copy(), train_df.deal_probability.values, nbag = 10, nfold = 10, minCount = 0) train_df.to_feather('../train_cat_targetenc.pkl') test_df.to_feather('../test_cat_targetenc.pkl') ################################################################ # Tfidf - part 2 ################################################################ import os; os.environ['OMP_NUM_THREADS'] = '1' from sklearn.decomposition import TruncatedSVD import nltk nltk.data.path.append("/media/sayantan/Personal/nltk_data") from nltk.stem.snowball import RussianStemmer from nltk.corpus import stopwords import time from typing import List, Dict from sklearn.feature_extraction import DictVectorizer from sklearn.feature_extraction.text import TfidfVectorizer as Tfidf from sklearn.model_selection import KFold from sklearn.externals import joblib from scipy.sparse import hstack, csr_matrix import pandas as pd import numpy as np import gc from sklearn.preprocessing import StandardScaler, OneHotEncoder, LabelEncoder, MinMaxScaler from sklearn import model_selection english_stemmer = nltk.stem.SnowballStemmer('russian') def clean_text(text): #text = re.sub(r'(\d+),(\d+)', r'\1.\2', text) text = text.replace(u'²', '2') text = text.lower() text = re.sub(u'[^a-zа-я0-9]', ' ', text) text = re.sub('\s+', ' ', text) return text.strip() def stem_tokens(tokens, stemmer): stemmed = [] for token in tokens: #stemmed.append(stemmer.lemmatize(token)) stemmed.append(stemmer.stem(token)) return stemmed def preprocess_data(line, exclude_stopword=True, encode_digit=False): ## tokenize line = clean_text(line) tokens = [x.lower() for x in nltk.word_tokenize(line)] ## stem tokens_stemmed = stem_tokens(tokens, english_stemmer)#english_stemmer if exclude_stopword: tokens_stemmed = [x for x in tokens_stemmed if x not in stopwords] return ' '.join(tokens_stemmed) stopwords = stopwords.words('russian') train_per=pd.read_csv('../input/train_active.csv', usecols = ['param_1', 'param_2', 'param_3'])#,'title','description']) test_per=pd.read_csv('../input/test_active.csv', usecols = ['param_1', 'param_2', 'param_3'])#,'title','description']) train_test = pd.concat((train_per, test_per), axis = 'rows') del train_per, test_per; gc.collect() train_test['params'] = train_test['param_1'].fillna('') + ' ' + train_test['param_2'].fillna('') + ' ' + train_test['param_3'].fillna('') import re train_test.drop(['param_1', 'param_2', 'param_3'], axis = 'columns', inplace=True) train_test["params"]= list(train_test[["params"]].apply(lambda x: clean_text(x["params"]), axis=1)) import re train_df=pd.read_feather('../train_basic_features_woCats.pkl') test_df=pd.read_feather('../test__basic_features_woCats.pkl') from sklearn.externals import joblib ### TFIDF Vectorizer ### train_df['params'] = train_df['params'].fillna('NA') test_df['params'] = test_df['params'].fillna('NA') tfidf_vec = TfidfVectorizer(ngram_range=(1,3),max_features = 10000,#min_df=3, max_df=.85, analyzer='word', token_pattern= r'\w{1,}', use_idf=1, smooth_idf=0, sublinear_tf=1,) #TfidfVectorizer(ngram_range=(1,2)) full_tfidf = tfidf_vec.fit_transform(train_test['params'].values.tolist() + train_df['params'].values.tolist() + test_df['params'].values.tolist()) train_tfidf = tfidf_vec.transform(train_df['params'].values.tolist()) test_tfidf = tfidf_vec.transform(test_df['params'].values.tolist()) del full_tfidf print("TDIDF Params UNCLEAN..") joblib.dump([train_tfidf, test_tfidf], "../params_tfidf2.pkl") tfidf_vec = TfidfVectorizer(ngram_range=(1,1),max_features = 10000,max_df=.4,#min_df=3, analyzer='word', token_pattern= r'\w{1,}', use_idf=1, smooth_idf=0, sublinear_tf=1,) #TfidfVectorizer(ngram_range=(1,2)) full_tfidf = tfidf_vec.fit_transform(train_test['params'].values.tolist() + train_df['params'].values.tolist() + test_df['params'].values.tolist()) train_tfidf = tfidf_vec.transform(train_df['params'].values.tolist()) test_tfidf = tfidf_vec.transform(test_df['params'].values.tolist()) del full_tfidf print("TDIDF Params UNCLEAN..") joblib.dump([train_tfidf, test_tfidf], "../params_tfidf3.pkl") del(train_test); gc.collect() train_per=pd.read_csv('../input/train_active.csv', usecols = ['title'])#,'title','description']) test_per=pd.read_csv('../input/test_active.csv', usecols = ['title'])#,'title','description']) train_test = pd.concat((train_per, test_per), axis = 'rows') del train_per, test_per; gc.collect() train_test.fillna('NA', inplace=True) train_test["title_clean"]= list(train_test[["title"]].apply(lambda x: preprocess_data(x["title"]), axis=1)) train_df['title_clean'] = train_df['title_clean'].fillna('NA') test_df['title_clean'] = test_df['title_clean'].fillna('NA') tfidf_vec = TfidfVectorizer(ngram_range=(1,2),max_features = 20000,#,min_df=3, max_df=.85, analyzer='word', token_pattern= r'\w{1,}', use_idf=1, smooth_idf=0, sublinear_tf=1,) full_tfidf = tfidf_vec.fit_transform(train_test['title_clean'].values.tolist()+train_df['title_clean'].values.tolist() + test_df['title_clean'].values.tolist()) train_tfidf = tfidf_vec.transform(train_df['title_clean'].values.tolist()) test_tfidf = tfidf_vec.transform(test_df['title_clean'].values.tolist()) joblib.dump([train_tfidf, test_tfidf], "../title_tfidf2.pkl") del full_tfidf print("TDIDF TITLE CLEAN..") train_df['title_clean'] = train_df['title_clean'].fillna('NA') test_df['title_clean'] = test_df['title_clean'].fillna('NA') tfidf_vec = TfidfVectorizer(ngram_range=(1,1),max_features = 20000, max_df=.4,#,min_df=3, analyzer='word', token_pattern= r'\w{1,}', use_idf=1, smooth_idf=0, sublinear_tf=1,) full_tfidf = tfidf_vec.fit_transform(train_test['title_clean'].values.tolist()+train_df['title_clean'].values.tolist() + test_df['title_clean'].values.tolist()) train_tfidf = tfidf_vec.transform(train_df['title_clean'].values.tolist()) test_tfidf = tfidf_vec.transform(test_df['title_clean'].values.tolist()) joblib.dump([train_tfidf, test_tfidf], "../title_tfidf3.pkl") del full_tfidf print("TDIDF TITLE CLEAN..") del(train_test); gc.collect() ###Too slow### ''' train_per=pd.read_csv('../input/train_active.csv', usecols = ['description'])#,'title','description']) test_per=pd.read_csv('../input/test_active.csv', usecols = ['description'])#,'title','description']) train_per.fillna(' ', inplace=True) test_per.fillna(' ', inplace=True) train_test["desc_clean"]= list(train_test[["description"]].apply(lambda x: preprocess_data(x["description"]), axis=1)) ### TFIDF Vectorizer ### train_df['desc_clean'] = train_df['desc_clean'].fillna(' ') test_df['desc_clean'] = test_df['desc_clean'].fillna(' ') tfidf_vec = TfidfVectorizer(ngram_range=(1,2), max_features = 20000, stop_words = stopwords#,min_df=3, analyzer='word', token_pattern= r'\w{1,}', use_idf=1, smooth_idf=0, sublinear_tf=1,) full_tfidf = tfidf_vec.fit_transform(train_test['desc_clean'].values.tolist()+train_df['desc_clean'].values.tolist() + test_df['desc_clean'].values.tolist()) train_tfidf = tfidf_vec.transform(train_df['desc_clean'].values.tolist()) test_tfidf = tfidf_vec.transform(test_df['desc_clean'].values.tolist()) joblib.dump([train_tfidf, test_tfidf], "../desc_tfidf2.pkl") del full_tfidf print("TDIDF DESC CLEAN..") tfidf_vec = TfidfVectorizer(ngram_range=(1,1), max_features = 20000, max_df=.4,#,min_df=3, analyzer='word', token_pattern= r'\w{1,}', use_idf=1, smooth_idf=0, sublinear_tf=1,) full_tfidf = tfidf_vec.fit_transform(train_test['desc_clean'].values.tolist()+train_df['desc_clean'].values.tolist() + test_df['desc_clean'].values.tolist()) train_tfidf = tfidf_vec.transform(train_df['desc_clean'].values.tolist()) test_tfidf = tfidf_vec.transform(test_df['desc_clean'].values.tolist()) joblib.dump([train_tfidf, test_tfidf], "../desc_tfidf3.pkl") del full_tfidf print("TDIDF DESC CLEAN..") ''' ########################################## # 13. Chargram -- too slow ########################################## from collections import Counter train_df=pd.read_feather('../train_basic_features_woCats.pkl') test_df=pd.read_feather('../test__basic_features_woCats.pkl') def char_ngrams(s): s = s.lower() s = s.replace(u' ', '') result = Counter() len_s = len(s) for n in [3, 4, 5]: result.update(s[i:i+n] for i in range(len_s - n + 1)) return ' '.join(list(result)) data = pd.concat((train_df, test_df), axis = 'rows') data['param_chargram'] = list(data[['params']].apply(lambda x: char_ngrams(x['params']), axis=1)) data['title_chargram'] = list(data[['title']].apply(lambda x: char_ngrams(x['title']), axis=1)) #data['desc_chargram'] = list(data[['description']].apply(lambda x: char_ngrams(x['description']), axis=1)) #data['count_common_chargram'] = data.apply(lambda x: len(set(str(x['title_chargram']).lower().split()).intersection(set(str(x['desc_chargram']).lower().split()))), axis=1) train_df = data.loc[data.deal_probability != 10].reset_index(drop = True) test_df = data.loc[data.deal_probability == 10].reset_index(drop = True) del(data); gc.collect() #####Chargram -TFIDF tfidf_vec = TfidfVectorizer(ngram_range=(1,3),max_features = 10000, min_df=3, max_df=.75) full_tfidf = tfidf_vec.fit_transform(train_df['title_chargram'].values.tolist() + test_df['title_chargram'].values.tolist()) train_tfidf = tfidf_vec.transform(train_df['title_chargram'].values.tolist()) test_tfidf = tfidf_vec.transform(test_df['title_chargram'].values.tolist()) from sklearn.externals import joblib joblib.dump([train_tfidf, test_tfidf], '../title_chargram_tfidf.pkl') tfidf_vec = TfidfVectorizer(ngram_range=(1,3),max_features = 10000, min_df=3, max_df=.75) full_tfidf = tfidf_vec.fit_transform(train_df['param_chargram'].values.tolist() + test_df['param_chargram'].values.tolist()) train_tfidf = tfidf_vec.transform(train_df['param_chargram'].values.tolist()) test_tfidf = tfidf_vec.transform(test_df['param_chargram'].values.tolist()) from sklearn.externals import joblib joblib.dump([train_tfidf, test_tfidf], '../param_chargram_tfidf.pkl') #######Chargram of Cat and Parent cat def clean_text(text): #text = re.sub(r'(\d+),(\d+)', r'\1.\2', text) text = text.replace(u'²', '2') text = text.lower() text = re.sub(u'[^a-zа-я0-9]', ' ', text) text = re.sub('\s+', ' ', text) return text.strip() train_df = pd.read_feather('../train_basic_features.pkl') test_df = pd.read_feather('../test__basic_features.pkl') data = pd.concat([train_df, test_df], axis= 'rows') data['categories'] = data["parent_category_name"].fillna(' ') + data["category_name"].fillna(' ') data['cat_chargram'] = list(data[['categories']].apply(lambda x: char_ngrams(x['categories']), axis=1)) train_df = data.loc[data.deal_probability != 10].reset_index(drop = True) test_df = data.loc[data.deal_probability == 10].reset_index(drop = True) del(data); gc.collect() tfidf_vec = TfidfVectorizer(ngram_range=(1,3),max_features = 1000, min_df=3, max_df=.75) full_tfidf = tfidf_vec.fit_transform(train_df['cat_chargram'].values.tolist() + test_df['cat_chargram'].values.tolist()) train_tfidf = tfidf_vec.transform(train_df['cat_chargram'].values.tolist()) test_tfidf = tfidf_vec.transform(test_df['cat_chargram'].values.tolist()) from sklearn.externals import joblib joblib.dump([train_tfidf, test_tfidf], '../cat_chargram_tfidf.pkl') ############################## ## New Kaggle Ftr ############################## import pandas as pd import gc used_cols = ['item_id', 'user_id'] train = pd.read_csv('../input/train.csv', usecols=used_cols) train_active = pd.read_csv('../input/train_active.csv', usecols=used_cols) test = pd.read_csv('../input/test.csv', usecols=used_cols) test_active = pd.read_csv('../input/test_active.csv', usecols=used_cols) train_periods = pd.read_csv('../input/periods_train.csv', parse_dates=['date_from', 'date_to']) test_periods = pd.read_csv('../input/periods_test.csv', parse_dates=['date_from', 'date_to']) train.head() all_samples = pd.concat([ train, train_active, test, test_active ]).reset_index(drop=True) all_samples.drop_duplicates(['item_id'], inplace=True) del train_active del test_active gc.collect() all_periods = pd.concat([ train_periods, test_periods ]) del train_periods del test_periods gc.collect() all_periods.head() all_periods['days_up'] = (all_periods['date_to'] - all_periods['date_from']).dt.days gp = all_periods.groupby(['item_id'])[['days_up']] gp_df = pd.DataFrame() gp_df['days_up_sum'] = gp.sum()['days_up'] gp_df['times_put_up'] = gp.count()['days_up'] gp_df.reset_index(inplace=True) gp_df.rename(index=str, columns={'index': 'item_id'}) gp_df.head() all_periods.drop_duplicates(['item_id'], inplace=True) all_periods = all_periods.merge(gp_df, on='item_id', how='left') all_periods.head() del gp del gp_df gc.collect() all_periods = all_periods.merge(all_samples, on='item_id', how='left') all_periods.head() gp = all_periods.groupby(['user_id'])[['days_up_sum', 'times_put_up']].mean().reset_index() \ .rename(index=str, columns={ 'days_up_sum': 'avg_days_up_user', 'times_put_up': 'avg_times_up_user' }) gp.head() n_user_items = all_samples.groupby(['user_id'])[['item_id']].count().reset_index() \ .rename(index=str, columns={ 'item_id': 'n_user_items' }) gp = gp.merge(n_user_items, on='user_id', how='left') gp.head() train = pd.read_csv('../input/train.csv') test = pd.read_csv('../input/test.csv') train = train.merge(gp, on='user_id', how='left') test = test.merge(gp, on='user_id', how='left') agg_cols = list(gp.columns)[1:] del gp gc.collect() train.head() train = train[['avg_days_up_user','avg_times_up_user','n_user_items']] test = test[['avg_days_up_user','avg_times_up_user','n_user_items']] train.to_feather('../train_kag_agg_ftr.ftr') test.to_feather('../test_kag_agg_ftr.ftr') def catEncode(train_char, test_char, y, colLst = [], nbag = 10, nfold = 20, minCount = 3, postfix = ''): train_df = train_char.copy() test_df = test_char.copy() if not colLst: print("Empty ColLst") for c in train_char.columns: data = train_char[[c]].copy() data['y'] = y enc_mat = np.zeros((y.shape[0],4)) enc_mat_test = np.zeros((test_char.shape[0],4)) for bag in
np.arange(nbag)
numpy.arange
import numpy as np import pandas as pd import pytest from pydantic import ValidationError from napari.layers.utils.string_encoding import ( ConstantStringEncoding, FormatStringEncoding, ManualStringEncoding, ) from napari.layers.utils.text_manager import TextManager @pytest.mark.filterwarnings('ignore::DeprecationWarning') def test_empty_text_manager_property(): """Test creating an empty text manager in property mode. This is for creating an empty layer with text initialized. """ properties = {'confidence': np.empty(0, dtype=float)} text_manager = TextManager( text='confidence', n_text=0, properties=properties ) assert text_manager.values.size == 0 # add a text element new_properties = {'confidence': np.array([0.5])} text_manager.add(new_properties, 1) np.testing.assert_equal(text_manager.values, ['0.5']) @pytest.mark.filterwarnings('ignore::DeprecationWarning') def test_add_many_text_property(): properties = {'confidence': np.empty(0, dtype=float)} text_manager = TextManager( text='confidence', n_text=0, properties=properties, ) text_manager.add({'confidence': np.array([0.5])}, 2) np.testing.assert_equal(text_manager.values, ['0.5'] * 2) @pytest.mark.filterwarnings('ignore::DeprecationWarning') def test_empty_text_manager_format(): """Test creating an empty text manager in formatted mode. This is for creating an empty layer with text initialized. """ properties = {'confidence': np.empty(0, dtype=float)} text = 'confidence: {confidence:.2f}' text_manager = TextManager(text=text, n_text=0, properties=properties) assert text_manager.values.size == 0 # add a text element new_properties = {'confidence': np.array([0.5])} text_manager.add(new_properties, 1) np.testing.assert_equal(text_manager.values, ['confidence: 0.50']) @pytest.mark.filterwarnings('ignore::DeprecationWarning') def test_add_many_text_formatted(): properties = {'confidence': np.empty(0, dtype=float)} text_manager = TextManager( text='confidence: {confidence:.2f}', n_text=0, properties=properties, ) text_manager.add({'confidence': np.array([0.5])}, 2) np.testing.assert_equal(text_manager.values, ['confidence: 0.50'] * 2) @pytest.mark.filterwarnings('ignore::DeprecationWarning') def test_text_manager_property(): n_text = 3 text = 'class' classes = np.array(['A', 'B', 'C']) properties = {'class': classes, 'confidence': np.array([0.5, 0.3, 1])} text_manager = TextManager(text=text, n_text=n_text, properties=properties) np.testing.assert_equal(text_manager.values, classes) # add new text with properties new_properties = {'class': np.array(['A']), 'confidence': np.array([0.5])} text_manager.add(new_properties, 1) expected_text_2 = np.concatenate([classes, ['A']]) np.testing.assert_equal(text_manager.values, expected_text_2) # remove the first text element text_manager.remove({0}) np.testing.assert_equal(text_manager.values, expected_text_2[1::]) @pytest.mark.filterwarnings('ignore::DeprecationWarning') def test_text_manager_format(): n_text = 3 text = 'confidence: {confidence:.2f}' classes =
np.array(['A', 'B', 'C'])
numpy.array
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2011 <NAME> <<EMAIL>> # Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html """ Automated tests for similarity algorithms (the similarities package). """ import logging import unittest import math import os import numpy import scipy from gensim import utils from gensim.corpora import Dictionary from gensim.models import word2vec from gensim.models import doc2vec from gensim.models import KeyedVectors from gensim.models import TfidfModel from gensim import matutils, similarities from gensim.models import Word2Vec, FastText from gensim.test.utils import ( datapath, get_tmpfile, common_texts as TEXTS, common_dictionary as DICTIONARY, common_corpus as CORPUS, ) from gensim.similarities import UniformTermSimilarityIndex from gensim.similarities import WordEmbeddingSimilarityIndex from gensim.similarities import SparseTermSimilarityMatrix from gensim.similarities import LevenshteinSimilarityIndex from gensim.similarities.docsim import _nlargest from gensim.similarities.levenshtein import levdist, levsim try: from pyemd import emd # noqa:F401 PYEMD_EXT = True except (ImportError, ValueError): PYEMD_EXT = False SENTENCES = [doc2vec.TaggedDocument(words, [i]) for i, words in enumerate(TEXTS)] @unittest.skip("skipping abstract base class") class _TestSimilarityABC(unittest.TestCase): """ Base class for SparseMatrixSimilarity and MatrixSimilarity unit tests. """ def factoryMethod(self): """Creates a SimilarityABC instance.""" return self.cls(CORPUS, num_features=len(DICTIONARY)) def test_full(self, num_best=None, shardsize=100): if self.cls == similarities.Similarity: index = self.cls(None, CORPUS, num_features=len(DICTIONARY), shardsize=shardsize) else: index = self.cls(CORPUS, num_features=len(DICTIONARY)) if isinstance(index, similarities.MatrixSimilarity): expected = numpy.array([ [0.57735026, 0.57735026, 0.57735026, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.40824831, 0.0, 0.40824831, 0.40824831, 0.40824831, 0.40824831, 0.40824831, 0.0, 0.0, 0.0, 0.0], [0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.5, 0.5, 0.0, 0.0, 0.0], [0.0, 0.0, 0.40824831, 0.0, 0.0, 0.0, 0.81649661, 0.0, 0.40824831, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.57735026, 0.57735026, 0.0, 0.0, 0.57735026, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1., 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.70710677, 0.70710677, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.57735026, 0.57735026, 0.57735026], [0.0, 0.0, 0.0, 0.0, 0.0, 0.57735026, 0.0, 0.0, 0.0, 0.0, 0.57735026, 0.57735026], ], dtype=numpy.float32) # HACK: dictionary can be in different order, so compare in sorted order self.assertTrue(numpy.allclose(sorted(expected.flat), sorted(index.index.flat))) index.num_best = num_best query = CORPUS[0] sims = index[query] expected = [(0, 0.99999994), (2, 0.28867513), (3, 0.23570226), (1, 0.23570226)][: num_best] # convert sims to full numpy arrays, so we can use allclose() and ignore # ordering of items with the same similarity value expected = matutils.sparse2full(expected, len(index)) if num_best is not None: # when num_best is None, sims is already a numpy array sims = matutils.sparse2full(sims, len(index)) self.assertTrue(numpy.allclose(expected, sims)) if self.cls == similarities.Similarity: index.destroy() def test_num_best(self): if self.cls == similarities.WmdSimilarity and not PYEMD_EXT: self.skipTest("pyemd not installed") for num_best in [None, 0, 1, 9, 1000]: self.testFull(num_best=num_best) def test_full2sparse_clipped(self): vec = [0.8, 0.2, 0.0, 0.0, -0.1, -0.15] expected = [(0, 0.80000000000000004), (1, 0.20000000000000001), (5, -0.14999999999999999)] self.assertTrue(matutils.full2sparse_clipped(vec, topn=3), expected) def test_scipy2scipy_clipped(self): # Test for scipy vector/row vec = [0.8, 0.2, 0.0, 0.0, -0.1, -0.15] expected = [(0, 0.80000000000000004), (1, 0.20000000000000001), (5, -0.14999999999999999)] vec_scipy = scipy.sparse.csr_matrix(vec) vec_scipy_clipped = matutils.scipy2scipy_clipped(vec_scipy, topn=3) self.assertTrue(scipy.sparse.issparse(vec_scipy_clipped)) self.assertTrue(matutils.scipy2sparse(vec_scipy_clipped), expected) # Test for scipy matrix vec = [0.8, 0.2, 0.0, 0.0, -0.1, -0.15] expected = [(0, 0.80000000000000004), (1, 0.20000000000000001), (5, -0.14999999999999999)] matrix_scipy = scipy.sparse.csr_matrix([vec] * 3) matrix_scipy_clipped = matutils.scipy2scipy_clipped(matrix_scipy, topn=3) self.assertTrue(scipy.sparse.issparse(matrix_scipy_clipped)) self.assertTrue([matutils.scipy2sparse(x) for x in matrix_scipy_clipped], [expected] * 3) def test_empty_query(self): index = self.factoryMethod() if isinstance(index, similarities.WmdSimilarity) and not PYEMD_EXT: self.skipTest("pyemd not installed") query = [] try: sims = index[query] self.assertTrue(sims is not None) except IndexError: self.assertTrue(False) def test_chunking(self): if self.cls == similarities.Similarity: index = self.cls(None, CORPUS, num_features=len(DICTIONARY), shardsize=5) else: index = self.cls(CORPUS, num_features=len(DICTIONARY)) query = CORPUS[:3] sims = index[query] expected = numpy.array([ [0.99999994, 0.23570226, 0.28867513, 0.23570226, 0.0, 0.0, 0.0, 0.0, 0.0], [0.23570226, 1.0, 0.40824831, 0.33333334, 0.70710677, 0.0, 0.0, 0.0, 0.23570226], [0.28867513, 0.40824831, 1.0, 0.61237246, 0.28867513, 0.0, 0.0, 0.0, 0.0] ], dtype=numpy.float32) self.assertTrue(numpy.allclose(expected, sims)) # test the same thing but with num_best index.num_best = 3 sims = index[query] expected = [ [(0, 0.99999994), (2, 0.28867513), (1, 0.23570226)], [(1, 1.0), (4, 0.70710677), (2, 0.40824831)], [(2, 1.0), (3, 0.61237246), (1, 0.40824831)] ] self.assertTrue(numpy.allclose(expected, sims)) if self.cls == similarities.Similarity: index.destroy() def test_iter(self): if self.cls == similarities.Similarity: index = self.cls(None, CORPUS, num_features=len(DICTIONARY), shardsize=5) else: index = self.cls(CORPUS, num_features=len(DICTIONARY)) sims = [sim for sim in index] expected = numpy.array([ [0.99999994, 0.23570226, 0.28867513, 0.23570226, 0.0, 0.0, 0.0, 0.0, 0.0], [0.23570226, 1.0, 0.40824831, 0.33333334, 0.70710677, 0.0, 0.0, 0.0, 0.23570226], [0.28867513, 0.40824831, 1.0, 0.61237246, 0.28867513, 0.0, 0.0, 0.0, 0.0], [0.23570226, 0.33333334, 0.61237246, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.70710677, 0.28867513, 0.0, 0.99999994, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.70710677, 0.57735026, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.70710677, 0.99999994, 0.81649655, 0.40824828], [0.0, 0.0, 0.0, 0.0, 0.0, 0.57735026, 0.81649655, 0.99999994, 0.66666663], [0.0, 0.23570226, 0.0, 0.0, 0.0, 0.0, 0.40824828, 0.66666663, 0.99999994] ], dtype=numpy.float32) self.assertTrue(numpy.allclose(expected, sims)) if self.cls == similarities.Similarity: index.destroy() def test_persistency(self): if self.cls == similarities.WmdSimilarity and not PYEMD_EXT: self.skipTest("pyemd not installed") fname = get_tmpfile('gensim_similarities.tst.pkl') index = self.factoryMethod() index.save(fname) index2 = self.cls.load(fname) if self.cls == similarities.Similarity: # for Similarity, only do a basic check self.assertTrue(len(index.shards) == len(index2.shards)) index.destroy() else: if isinstance(index, similarities.SparseMatrixSimilarity): # hack SparseMatrixSim indexes so they're easy to compare index.index = index.index.todense() index2.index = index2.index.todense() self.assertTrue(numpy.allclose(index.index, index2.index)) self.assertEqual(index.num_best, index2.num_best) def test_persistency_compressed(self): if self.cls == similarities.WmdSimilarity and not PYEMD_EXT: self.skipTest("pyemd not installed") fname = get_tmpfile('gensim_similarities.tst.pkl.gz') index = self.factoryMethod() index.save(fname) index2 = self.cls.load(fname) if self.cls == similarities.Similarity: # for Similarity, only do a basic check self.assertTrue(len(index.shards) == len(index2.shards)) index.destroy() else: if isinstance(index, similarities.SparseMatrixSimilarity): # hack SparseMatrixSim indexes so they're easy to compare index.index = index.index.todense() index2.index = index2.index.todense() self.assertTrue(numpy.allclose(index.index, index2.index)) self.assertEqual(index.num_best, index2.num_best) def test_large(self): if self.cls == similarities.WmdSimilarity and not PYEMD_EXT: self.skipTest("pyemd not installed") fname = get_tmpfile('gensim_similarities.tst.pkl') index = self.factoryMethod() # store all arrays separately index.save(fname, sep_limit=0) index2 = self.cls.load(fname) if self.cls == similarities.Similarity: # for Similarity, only do a basic check self.assertTrue(len(index.shards) == len(index2.shards)) index.destroy() else: if isinstance(index, similarities.SparseMatrixSimilarity): # hack SparseMatrixSim indexes so they're easy to compare index.index = index.index.todense() index2.index = index2.index.todense() self.assertTrue(numpy.allclose(index.index, index2.index)) self.assertEqual(index.num_best, index2.num_best) def test_large_compressed(self): if self.cls == similarities.WmdSimilarity and not PYEMD_EXT: self.skipTest("pyemd not installed") fname = get_tmpfile('gensim_similarities.tst.pkl.gz') index = self.factoryMethod() # store all arrays separately index.save(fname, sep_limit=0) index2 = self.cls.load(fname, mmap=None) if self.cls == similarities.Similarity: # for Similarity, only do a basic check self.assertTrue(len(index.shards) == len(index2.shards)) index.destroy() else: if isinstance(index, similarities.SparseMatrixSimilarity): # hack SparseMatrixSim indexes so they're easy to compare index.index = index.index.todense() index2.index = index2.index.todense() self.assertTrue(numpy.allclose(index.index, index2.index)) self.assertEqual(index.num_best, index2.num_best) def test_mmap(self): if self.cls == similarities.WmdSimilarity and not PYEMD_EXT: self.skipTest("pyemd not installed") fname = get_tmpfile('gensim_similarities.tst.pkl') index = self.factoryMethod() # store all arrays separately index.save(fname, sep_limit=0) # same thing, but use mmap to load arrays index2 = self.cls.load(fname, mmap='r') if self.cls == similarities.Similarity: # for Similarity, only do a basic check self.assertTrue(len(index.shards) == len(index2.shards)) index.destroy() else: if isinstance(index, similarities.SparseMatrixSimilarity): # hack SparseMatrixSim indexes so they're easy to compare index.index = index.index.todense() index2.index = index2.index.todense() self.assertTrue(numpy.allclose(index.index, index2.index)) self.assertEqual(index.num_best, index2.num_best) def test_mmap_compressed(self): if self.cls == similarities.WmdSimilarity and not PYEMD_EXT: self.skipTest("pyemd not installed") fname = get_tmpfile('gensim_similarities.tst.pkl.gz') index = self.factoryMethod() # store all arrays separately index.save(fname, sep_limit=0) # same thing, but use mmap to load arrays self.assertRaises(IOError, self.cls.load, fname, mmap='r') class TestMatrixSimilarity(_TestSimilarityABC): def setUp(self): self.cls = similarities.MatrixSimilarity class TestWmdSimilarity(_TestSimilarityABC): def setUp(self): self.cls = similarities.WmdSimilarity self.w2v_model = Word2Vec(TEXTS, min_count=1).wv def factoryMethod(self): # Override factoryMethod. return self.cls(TEXTS, self.w2v_model) @unittest.skipIf(PYEMD_EXT is False, "pyemd not installed") def test_full(self, num_best=None): # Override testFull. index = self.cls(TEXTS, self.w2v_model) index.num_best = num_best query = TEXTS[0] sims = index[query] if num_best is not None: # Sparse array. for i, sim in sims: # Note that similarities are bigger than zero, as they are the 1/ 1 + distances. self.assertTrue(numpy.alltrue(sim > 0.0)) else: self.assertTrue(sims[0] == 1.0) # Similarity of a document with itself is 0.0. self.assertTrue(numpy.alltrue(sims[1:] > 0.0)) self.assertTrue(numpy.alltrue(sims[1:] < 1.0)) @unittest.skipIf(PYEMD_EXT is False, "pyemd not installed") def test_non_increasing(self): ''' Check that similarities are non-increasing when `num_best` is not `None`.''' # NOTE: this could be implemented for other similarities as well (i.e. # in _TestSimilarityABC). index = self.cls(TEXTS, self.w2v_model, num_best=3) query = TEXTS[0] sims = index[query] sims2 = numpy.asarray(sims)[:, 1] # Just the similarities themselves. # The difference of adjacent elements should be negative. cond = sum(numpy.diff(sims2) < 0) == len(sims2) - 1 self.assertTrue(cond) @unittest.skipIf(PYEMD_EXT is False, "pyemd not installed") def test_chunking(self): # Override testChunking. index = self.cls(TEXTS, self.w2v_model) query = TEXTS[:3] sims = index[query] for i in range(3): self.assertTrue(numpy.alltrue(sims[i, i] == 1.0)) # Similarity of a document with itself is 0.0. # test the same thing but with num_best index.num_best = 3 sims = index[query] for sims_temp in sims: for i, sim in sims_temp: self.assertTrue(numpy.alltrue(sim > 0.0)) self.assertTrue(numpy.alltrue(sim <= 1.0)) @unittest.skipIf(PYEMD_EXT is False, "pyemd not installed") def test_iter(self): # Override testIter. index = self.cls(TEXTS, self.w2v_model) for sims in index: self.assertTrue(numpy.alltrue(sims >= 0.0)) self.assertTrue(numpy.alltrue(sims <= 1.0)) class TestSoftCosineSimilarity(_TestSimilarityABC): def setUp(self): self.cls = similarities.SoftCosineSimilarity self.tfidf = TfidfModel(dictionary=DICTIONARY) similarity_matrix = scipy.sparse.identity(12, format="lil") similarity_matrix[DICTIONARY.token2id["user"], DICTIONARY.token2id["human"]] = 0.5 similarity_matrix[DICTIONARY.token2id["human"], DICTIONARY.token2id["user"]] = 0.5 self.similarity_matrix = SparseTermSimilarityMatrix(similarity_matrix) def factoryMethod(self): return self.cls(CORPUS, self.similarity_matrix) def test_full(self, num_best=None): # Single query index = self.cls(CORPUS, self.similarity_matrix, num_best=num_best) query = DICTIONARY.doc2bow(TEXTS[0]) sims = index[query] if num_best is not None: # Sparse array. for i, sim in sims: self.assertTrue(numpy.alltrue(sim <= 1.0)) self.assertTrue(numpy.alltrue(sim >= 0.0)) else: self.assertAlmostEqual(1.0, sims[0]) # Similarity of a document with itself is 1.0. self.assertTrue(numpy.alltrue(sims[1:] >= 0.0)) self.assertTrue(numpy.alltrue(sims[1:] < 1.0)) # Corpora for query in ( CORPUS, # Basic text corpus. self.tfidf[CORPUS]): # Transformed corpus without slicing support. index = self.cls(query, self.similarity_matrix, num_best=num_best) sims = index[query] if num_best is not None: # Sparse array. for result in sims: for i, sim in result: self.assertTrue(numpy.alltrue(sim <= 1.0)) self.assertTrue(numpy.alltrue(sim >= 0.0)) else: for i, result in enumerate(sims): self.assertAlmostEqual(1.0, result[i]) # Similarity of a document with itself is 1.0. self.assertTrue(numpy.alltrue(result[:i] >= 0.0)) self.assertTrue(numpy.alltrue(result[:i] < 1.0)) self.assertTrue(numpy.alltrue(result[i + 1:] >= 0.0)) self.assertTrue(numpy.alltrue(result[i + 1:] < 1.0)) def test_non_increasing(self): """ Check that similarities are non-increasing when `num_best` is not `None`.""" # NOTE: this could be implemented for other similarities as well (i.e. in _TestSimilarityABC). index = self.cls(CORPUS, self.similarity_matrix, num_best=5) query = DICTIONARY.doc2bow(TEXTS[0]) sims = index[query] sims2 = numpy.asarray(sims)[:, 1] # Just the similarities themselves. # The difference of adjacent elements should be less than or equal to zero. cond = sum(numpy.diff(sims2) <= 0) == len(sims2) - 1 self.assertTrue(cond) def test_chunking(self): index = self.cls(CORPUS, self.similarity_matrix) query = [DICTIONARY.doc2bow(document) for document in TEXTS[:3]] sims = index[query] for i in range(3): self.assertTrue(numpy.alltrue(sims[i, i] == 1.0)) # Similarity of a document with itself is 1.0. # test the same thing but with num_best index.num_best = 5 sims = index[query] for i, chunk in enumerate(sims): expected = i self.assertAlmostEqual(expected, chunk[0][0], places=2) expected = 1.0 self.assertAlmostEqual(expected, chunk[0][1], places=2) def test_iter(self): index = self.cls(CORPUS, self.similarity_matrix) for sims in index: self.assertTrue(numpy.alltrue(sims >= 0.0)) self.assertTrue(numpy.alltrue(sims <= 1.0)) class TestSparseMatrixSimilarity(_TestSimilarityABC): def setUp(self): self.cls = similarities.SparseMatrixSimilarity def test_maintain_sparsity(self): """Sparsity is correctly maintained when maintain_sparsity=True""" num_features = len(DICTIONARY) index = self.cls(CORPUS, num_features=num_features) dense_sims = index[CORPUS] index = self.cls(CORPUS, num_features=num_features, maintain_sparsity=True) sparse_sims = index[CORPUS] self.assertFalse(scipy.sparse.issparse(dense_sims)) self.assertTrue(scipy.sparse.issparse(sparse_sims)) numpy.testing.assert_array_equal(dense_sims, sparse_sims.todense()) def test_maintain_sparsity_with_num_best(self): """Tests that sparsity is correctly maintained when maintain_sparsity=True and num_best is not None""" num_features = len(DICTIONARY) index = self.cls(CORPUS, num_features=num_features, maintain_sparsity=False, num_best=3) dense_topn_sims = index[CORPUS] index = self.cls(CORPUS, num_features=num_features, maintain_sparsity=True, num_best=3) scipy_topn_sims = index[CORPUS] self.assertFalse(scipy.sparse.issparse(dense_topn_sims)) self.assertTrue(scipy.sparse.issparse(scipy_topn_sims)) self.assertEqual(dense_topn_sims, [matutils.scipy2sparse(v) for v in scipy_topn_sims]) class TestSimilarity(_TestSimilarityABC): def setUp(self): self.cls = similarities.Similarity def factoryMethod(self): # Override factoryMethod. return self.cls(None, CORPUS, num_features=len(DICTIONARY), shardsize=5) def test_sharding(self): for num_best in [None, 0, 1, 9, 1000]: for shardsize in [1, 2, 9, 1000]: self.testFull(num_best=num_best, shardsize=shardsize) def test_reopen(self): """test re-opening partially full shards""" index = similarities.Similarity(None, CORPUS[:5], num_features=len(DICTIONARY), shardsize=9) _ = index[CORPUS[0]] # noqa:F841 forces shard close index.add_documents(CORPUS[5:]) query = CORPUS[0] sims = index[query] expected = [(0, 0.99999994), (2, 0.28867513), (3, 0.23570226), (1, 0.23570226)] expected = matutils.sparse2full(expected, len(index)) self.assertTrue(numpy.allclose(expected, sims)) index.destroy() def test_mmap_compressed(self): pass # turns out this test doesn't exercise this because there are no arrays # to be mmaped! def test_chunksize(self): index = self.cls(None, CORPUS, num_features=len(DICTIONARY), shardsize=5) expected = [sim for sim in index] index.chunksize = len(index) - 1 sims = [sim for sim in index] self.assertTrue(numpy.allclose(expected, sims)) index.destroy() def test_nlargest(self): sims = ([(0, 0.8), (1, 0.2), (2, 0.0), (3, 0.0), (4, -0.1), (5, -0.15)],) expected = [(0, 0.8), (1, 0.2), (5, -0.15)] self.assertTrue(_nlargest(3, sims), expected) class TestWord2VecAnnoyIndexer(unittest.TestCase): def setUp(self): try: import annoy # noqa:F401 except ImportError as e: raise unittest.SkipTest("Annoy library is not available: %s" % e) from gensim.similarities.annoy import AnnoyIndexer self.indexer = AnnoyIndexer def test_word2vec(self): model = word2vec.Word2Vec(TEXTS, min_count=1) index = self.indexer(model, 10) self.assertVectorIsSimilarToItself(model.wv, index) self.assertApproxNeighborsMatchExact(model.wv, model.wv, index) self.assertIndexSaved(index) self.assertLoadedIndexEqual(index, model) def test_fast_text(self): class LeeReader: def __init__(self, fn): self.fn = fn def __iter__(self): with utils.open(self.fn, 'r', encoding="latin_1") as infile: for line in infile: yield line.lower().strip().split() model = FastText(LeeReader(datapath('lee.cor')), bucket=5000) index = self.indexer(model, 10) self.assertVectorIsSimilarToItself(model.wv, index) self.assertApproxNeighborsMatchExact(model.wv, model.wv, index) self.assertIndexSaved(index) self.assertLoadedIndexEqual(index, model) def test_annoy_indexing_of_keyed_vectors(self): from gensim.similarities.annoy import AnnoyIndexer keyVectors_file = datapath('lee_fasttext.vec') model = KeyedVectors.load_word2vec_format(keyVectors_file) index = AnnoyIndexer(model, 10) self.assertEqual(index.num_trees, 10) self.assertVectorIsSimilarToItself(model, index) self.assertApproxNeighborsMatchExact(model, model, index) def test_load_missing_raises_error(self): from gensim.similarities.annoy import AnnoyIndexer test_index = AnnoyIndexer() self.assertRaises(IOError, test_index.load, fname='test-index') def assertVectorIsSimilarToItself(self, wv, index): vector = wv.get_normed_vectors()[0] label = wv.index_to_key[0] approx_neighbors = index.most_similar(vector, 1) word, similarity = approx_neighbors[0] self.assertEqual(word, label) self.assertAlmostEqual(similarity, 1.0, places=2) def assertApproxNeighborsMatchExact(self, model, wv, index): vector = wv.get_normed_vectors()[0] approx_neighbors = model.most_similar([vector], topn=5, indexer=index) exact_neighbors = model.most_similar(positive=[vector], topn=5) approx_words = [neighbor[0] for neighbor in approx_neighbors] exact_words = [neighbor[0] for neighbor in exact_neighbors] self.assertEqual(approx_words, exact_words) def assertAllSimilaritiesDisableIndexer(self, model, wv, index): vector = wv.get_normed_vectors()[0] approx_similarities = model.most_similar([vector], topn=None, indexer=index) exact_similarities = model.most_similar(positive=[vector], topn=None) self.assertEqual(approx_similarities, exact_similarities) self.assertEqual(len(approx_similarities), len(wv.vectors)) def assertIndexSaved(self, index): fname = get_tmpfile('gensim_similarities.tst.pkl') index.save(fname) self.assertTrue(os.path.exists(fname)) self.assertTrue(os.path.exists(fname + '.d')) def assertLoadedIndexEqual(self, index, model): from gensim.similarities.annoy import AnnoyIndexer fname = get_tmpfile('gensim_similarities.tst.pkl') index.save(fname) index2 = AnnoyIndexer() index2.load(fname) index2.model = model self.assertEqual(index.index.f, index2.index.f) self.assertEqual(index.labels, index2.labels) self.assertEqual(index.num_trees, index2.num_trees) class TestDoc2VecAnnoyIndexer(unittest.TestCase): def setUp(self): try: import annoy # noqa:F401 except ImportError as e: raise unittest.SkipTest("Annoy library is not available: %s" % e) from gensim.similarities.annoy import AnnoyIndexer self.model = doc2vec.Doc2Vec(SENTENCES, min_count=1) self.index = AnnoyIndexer(self.model, 300) self.vector = self.model.dv.get_normed_vectors()[0] def test_document_is_similar_to_itself(self): approx_neighbors = self.index.most_similar(self.vector, 1) doc, similarity = approx_neighbors[0] self.assertEqual(doc, 0) self.assertAlmostEqual(similarity, 1.0, places=2) def test_approx_neighbors_match_exact(self): approx_neighbors = self.model.dv.most_similar([self.vector], topn=5, indexer=self.index) exact_neighbors = self.model.dv.most_similar([self.vector], topn=5) approx_words = [neighbor[0] for neighbor in approx_neighbors] exact_words = [neighbor[0] for neighbor in exact_neighbors] self.assertEqual(approx_words, exact_words) def test_save(self): fname = get_tmpfile('gensim_similarities.tst.pkl') self.index.save(fname) self.assertTrue(os.path.exists(fname)) self.assertTrue(os.path.exists(fname + '.d')) def test_load_not_exist(self): from gensim.similarities.annoy import AnnoyIndexer self.test_index = AnnoyIndexer() self.assertRaises(IOError, self.test_index.load, fname='test-index') def test_save_load(self): from gensim.similarities.annoy import AnnoyIndexer fname = get_tmpfile('gensim_similarities.tst.pkl') self.index.save(fname) self.index2 = AnnoyIndexer() self.index2.load(fname) self.index2.model = self.model self.assertEqual(self.index.index.f, self.index2.index.f) self.assertEqual(self.index.labels, self.index2.labels) self.assertEqual(self.index.num_trees, self.index2.num_trees) class TestWord2VecNmslibIndexer(unittest.TestCase): def setUp(self): try: import nmslib # noqa:F401 except ImportError as e: raise unittest.SkipTest("NMSLIB library is not available: %s" % e) from gensim.similarities.nmslib import NmslibIndexer self.indexer = NmslibIndexer def test_word2vec(self): model = word2vec.Word2Vec(TEXTS, min_count=1) index = self.indexer(model) self.assertVectorIsSimilarToItself(model.wv, index) self.assertApproxNeighborsMatchExact(model.wv, model.wv, index) self.assertIndexSaved(index) self.assertLoadedIndexEqual(index, model) def test_fasttext(self): class LeeReader: def __init__(self, fn): self.fn = fn def __iter__(self): with utils.open(self.fn, 'r', encoding="latin_1") as infile: for line in infile: yield line.lower().strip().split() model = FastText(LeeReader(datapath('lee.cor')), bucket=5000) index = self.indexer(model) self.assertVectorIsSimilarToItself(model.wv, index) self.assertApproxNeighborsMatchExact(model.wv, model.wv, index) self.assertIndexSaved(index) self.assertLoadedIndexEqual(index, model) def test_indexing_keyedvectors(self): from gensim.similarities.nmslib import NmslibIndexer keyVectors_file = datapath('lee_fasttext.vec') model = KeyedVectors.load_word2vec_format(keyVectors_file) index = NmslibIndexer(model) self.assertVectorIsSimilarToItself(model, index) self.assertApproxNeighborsMatchExact(model, model, index) def test_load_missing_raises_error(self): from gensim.similarities.nmslib import NmslibIndexer self.assertRaises(IOError, NmslibIndexer.load, fname='test-index') def assertVectorIsSimilarToItself(self, wv, index): vector = wv.get_normed_vectors()[0] label = wv.index_to_key[0] approx_neighbors = index.most_similar(vector, 1) word, similarity = approx_neighbors[0] self.assertEqual(word, label) self.assertAlmostEqual(similarity, 1.0, places=2) def assertApproxNeighborsMatchExact(self, model, wv, index): vector = wv.get_normed_vectors()[0] approx_neighbors = model.most_similar([vector], topn=5, indexer=index) exact_neighbors = model.most_similar([vector], topn=5) approx_words = [word_id for word_id, similarity in approx_neighbors] exact_words = [word_id for word_id, similarity in exact_neighbors] self.assertEqual(approx_words, exact_words) def assertIndexSaved(self, index): fname = get_tmpfile('gensim_similarities.tst.pkl') index.save(fname) self.assertTrue(os.path.exists(fname)) self.assertTrue(os.path.exists(fname + '.d')) def assertLoadedIndexEqual(self, index, model): from gensim.similarities.nmslib import NmslibIndexer fname = get_tmpfile('gensim_similarities.tst.pkl') index.save(fname) index2 = NmslibIndexer.load(fname) index2.model = model self.assertEqual(index.labels, index2.labels) self.assertEqual(index.index_params, index2.index_params) self.assertEqual(index.query_time_params, index2.query_time_params) class TestDoc2VecNmslibIndexer(unittest.TestCase): def setUp(self): try: import nmslib # noqa:F401 except ImportError as e: raise unittest.SkipTest("NMSLIB library is not available: %s" % e) from gensim.similarities.nmslib import NmslibIndexer self.model = doc2vec.Doc2Vec(SENTENCES, min_count=1) self.index = NmslibIndexer(self.model) self.vector = self.model.dv.get_normed_vectors()[0] def test_document_is_similar_to_itself(self): approx_neighbors = self.index.most_similar(self.vector, 1) doc, similarity = approx_neighbors[0] self.assertEqual(doc, 0) self.assertAlmostEqual(similarity, 1.0, places=2) def test_approx_neighbors_match_exact(self): approx_neighbors = self.model.dv.most_similar([self.vector], topn=5, indexer=self.index) exact_neighbors = self.model.dv.most_similar([self.vector], topn=5) approx_tags = [tag for tag, similarity in approx_neighbors] exact_tags = [tag for tag, similarity in exact_neighbors] self.assertEqual(approx_tags, exact_tags) def test_save(self): fname = get_tmpfile('gensim_similarities.tst.pkl') self.index.save(fname) self.assertTrue(os.path.exists(fname)) self.assertTrue(os.path.exists(fname + '.d')) def test_load_not_exist(self): from gensim.similarities.nmslib import NmslibIndexer self.assertRaises(IOError, NmslibIndexer.load, fname='test-index') def test_save_load(self): from gensim.similarities.nmslib import NmslibIndexer fname = get_tmpfile('gensim_similarities.tst.pkl') self.index.save(fname) self.index2 = NmslibIndexer.load(fname) self.index2.model = self.model self.assertEqual(self.index.labels, self.index2.labels) self.assertEqual(self.index.index_params, self.index2.index_params) self.assertEqual(self.index.query_time_params, self.index2.query_time_params) class TestUniformTermSimilarityIndex(unittest.TestCase): def setUp(self): self.documents = [[u"government", u"denied", u"holiday"], [u"holiday", u"slowing", u"hollingworth"]] self.dictionary = Dictionary(self.documents) def test_most_similar(self): """Test most_similar returns expected results.""" # check that the topn works as expected index = UniformTermSimilarityIndex(self.dictionary) results = list(index.most_similar(u"holiday", topn=1)) self.assertLess(0, len(results)) self.assertGreaterEqual(1, len(results)) results = list(index.most_similar(u"holiday", topn=4)) self.assertLess(1, len(results)) self.assertGreaterEqual(4, len(results)) # check that the term itself is not returned index = UniformTermSimilarityIndex(self.dictionary) terms = [term for term, similarity in index.most_similar(u"holiday", topn=len(self.dictionary))] self.assertFalse(u"holiday" in terms) # check that the term_similarity works as expected index = UniformTermSimilarityIndex(self.dictionary, term_similarity=0.2) similarities = numpy.array([ similarity for term, similarity in index.most_similar(u"holiday", topn=len(self.dictionary))]) self.assertTrue(numpy.all(similarities == 0.2)) class TestSparseTermSimilarityMatrix(unittest.TestCase): def setUp(self): self.documents = [ [u"government", u"denied", u"holiday"], [u"government", u"denied", u"holiday", u"slowing", u"hollingworth"]] self.dictionary = Dictionary(self.documents) self.tfidf = TfidfModel(dictionary=self.dictionary) zero_index = UniformTermSimilarityIndex(self.dictionary, term_similarity=0.0) self.index = UniformTermSimilarityIndex(self.dictionary, term_similarity=0.5) self.identity_matrix = SparseTermSimilarityMatrix(zero_index, self.dictionary) self.uniform_matrix = SparseTermSimilarityMatrix(self.index, self.dictionary) self.vec1 = self.dictionary.doc2bow([u"government", u"government", u"denied"]) self.vec2 = self.dictionary.doc2bow([u"government", u"holiday"]) def test_empty_dictionary(self): with self.assertRaises(ValueError): SparseTermSimilarityMatrix(self.index, []) def test_type(self): """Test the type of the produced matrix.""" matrix = SparseTermSimilarityMatrix(self.index, self.dictionary).matrix self.assertTrue(isinstance(matrix, scipy.sparse.csc_matrix)) def test_diagonal(self): """Test the existence of ones on the main diagonal.""" matrix = SparseTermSimilarityMatrix(self.index, self.dictionary).matrix.todense() self.assertTrue(numpy.all(numpy.diag(matrix) == numpy.ones(matrix.shape[0]))) def test_order(self): """Test the matrix order.""" matrix = SparseTermSimilarityMatrix(self.index, self.dictionary).matrix.todense() self.assertEqual(matrix.shape[0], len(self.dictionary)) self.assertEqual(matrix.shape[1], len(self.dictionary)) def test_dtype(self): """Test the dtype parameter of the matrix constructor.""" matrix = SparseTermSimilarityMatrix(self.index, self.dictionary, dtype=numpy.float32).matrix.todense() self.assertEqual(numpy.float32, matrix.dtype) matrix = SparseTermSimilarityMatrix(self.index, self.dictionary, dtype=numpy.float64).matrix.todense() self.assertEqual(numpy.float64, matrix.dtype) def test_nonzero_limit(self): """Test the nonzero_limit parameter of the matrix constructor.""" matrix = SparseTermSimilarityMatrix(self.index, self.dictionary, nonzero_limit=100).matrix.todense() self.assertGreaterEqual(101, numpy.max(numpy.sum(matrix != 0, axis=0))) matrix = SparseTermSimilarityMatrix(self.index, self.dictionary, nonzero_limit=4).matrix.todense() self.assertGreaterEqual(5, numpy.max(numpy.sum(matrix != 0, axis=0))) matrix = SparseTermSimilarityMatrix(self.index, self.dictionary, nonzero_limit=1).matrix.todense() self.assertGreaterEqual(2, numpy.max(numpy.sum(matrix != 0, axis=0))) matrix = SparseTermSimilarityMatrix(self.index, self.dictionary, nonzero_limit=0).matrix.todense() self.assertEqual(1, numpy.max(numpy.sum(matrix != 0, axis=0))) self.assertTrue(numpy.all(matrix == numpy.eye(matrix.shape[0]))) def test_symmetric(self): """Test the symmetric parameter of the matrix constructor.""" matrix = SparseTermSimilarityMatrix(self.index, self.dictionary).matrix.todense() self.assertTrue(numpy.all(matrix == matrix.T)) matrix = SparseTermSimilarityMatrix( self.index, self.dictionary, nonzero_limit=1).matrix.todense() expected_matrix = numpy.array([ [1.0, 0.5, 0.0, 0.0, 0.0], [0.5, 1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 0.0, 1.0]]) self.assertTrue(numpy.all(expected_matrix == matrix)) matrix = SparseTermSimilarityMatrix( self.index, self.dictionary, nonzero_limit=1, symmetric=False).matrix.todense() expected_matrix = numpy.array([ [1.0, 0.5, 0.5, 0.5, 0.5], [0.5, 1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 0.0, 1.0]]) self.assertTrue(
numpy.all(expected_matrix == matrix)
numpy.all
import numpy as np import h5py # data file type h5py import time import copy import matplotlib.pyplot as plt from cfg import loadConfig def load_mnist(filename): """load MNIST data""" MNIST_data = h5py.File(filename, 'r') x_train = np.float32(MNIST_data['x_train'][:]) y_train = np.int32(np.array(MNIST_data['y_train'][:,0])) x_test =
np.float32(MNIST_data['x_test'][:])
numpy.float32
# 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])
numpy.array
import torch import numpy as np import os import sys # sys.path.append(os.path.dirname(os.path.abspath(__file__))) # noqa: E402 # from utils.reranking import re_ranking def euclidean_distance(qf, gf): m = qf.shape[0] n = gf.shape[0] dist_mat = torch.pow(qf, 2).sum(dim=1, keepdim=True).expand(m, n) + \ torch.pow(gf, 2).sum(dim=1, keepdim=True).expand(n, m).t() dist_mat.addmm_(qf, gf.t(), beta=1, alpha=-2) return dist_mat.cpu().numpy() def cosine_similarity(qf, gf): epsilon = 0.00001 dist_mat = qf.mm(gf.t()) qf_norm = torch.norm(qf, p=2, dim=1, keepdim=True) # mx1 gf_norm = torch.norm(gf, p=2, dim=1, keepdim=True) # nx1 qg_normdot = qf_norm.mm(gf_norm.t()) dist_mat = dist_mat.mul(1 / qg_normdot).cpu().numpy() dist_mat = np.clip(dist_mat, -1 + epsilon, 1 - epsilon) dist_mat = np.arccos(dist_mat) return dist_mat def eval_func(distmat, q_pids, g_pids, q_camids, g_camids, max_rank=50): """Evaluation with market1501 metric Key: for each query identity, its gallery images from the same camera view are discarded. """ num_q, num_g = distmat.shape # distmat g # q 1 3 2 4 # 4 1 2 3 if num_g < max_rank: max_rank = num_g print("Note: number of gallery samples is quite small, got {}".format(num_g)) indices = np.argsort(distmat, axis=1) # 0 2 1 3 # 1 2 3 0 matches = (g_pids[indices] == q_pids[:, np.newaxis]).astype(np.int32) # compute cmc curve for each query all_cmc = [] all_AP = [] num_valid_q = 0. # number of valid query for q_idx in range(num_q): # get query pid and camid q_pid = q_pids[q_idx] q_camid = q_camids[q_idx] # remove gallery samples that have the same pid and camid with query order = indices[q_idx] # select one row remove = (g_pids[order] == q_pid) & (g_camids[order] == q_camid) keep = np.invert(remove) # compute cmc curve # binary vector, positions with value 1 are correct matches orig_cmc = matches[q_idx][keep] if not np.any(orig_cmc): # this condition is true when query identity does not appear in gallery continue cmc = orig_cmc.cumsum() cmc[cmc > 1] = 1 all_cmc.append(cmc[:max_rank]) num_valid_q += 1. # compute average precision # reference: https://en.wikipedia.org/wiki/Evaluation_measures_(information_retrieval)#Average_precision num_rel = orig_cmc.sum() tmp_cmc = orig_cmc.cumsum() #tmp_cmc = [x / (i + 1.) for i, x in enumerate(tmp_cmc)] y = np.arange(1, tmp_cmc.shape[0] + 1) * 1.0 tmp_cmc = tmp_cmc / y tmp_cmc = np.asarray(tmp_cmc) * orig_cmc AP = tmp_cmc.sum() / num_rel all_AP.append(AP) assert num_valid_q > 0, "Error: all query identities do not appear in gallery" all_cmc = np.asarray(all_cmc).astype(np.float32) all_cmc = all_cmc.sum(0) / num_valid_q mAP = np.mean(all_AP) return all_cmc, mAP class R1_mAP_eval(): def __init__(self, num_query, max_rank=50, feat_norm=True, reranking=False): super(R1_mAP_eval, self).__init__() self.num_query = num_query self.max_rank = max_rank self.feat_norm = feat_norm self.reranking = reranking def reset(self): self.feats = [] self.pids = [] self.camids = [] def update(self, output): # called once for each batch feat, pid, camid = output self.feats.append(feat.cpu()) self.pids.extend(np.asarray(pid)) self.camids.extend(np.asarray(camid)) def compute(self): # called after each epoch feats = torch.cat(self.feats, dim=0) if self.feat_norm: print("The test feature is normalized") feats = torch.nn.functional.normalize( feats, dim=1, p=2) # along channel # query qf = feats[:self.num_query] q_pids = np.asarray(self.pids[:self.num_query]) q_camids = np.asarray(self.camids[:self.num_query]) # gallery gf = feats[self.num_query:] g_pids = np.asarray(self.pids[self.num_query:]) g_camids =
np.asarray(self.camids[self.num_query:])
numpy.asarray
"""This module provides the basic functions about deep learning""" # -*- coding: utf-8 -*- # date: 2021 # author: AllChooseC import numpy as np import torch from torch.utils.data.dataloader import DataLoader from torch.utils.data.sampler import SubsetRandomSampler from tqdm import tqdm class_distribution = [59.68, 8.68, 28.55, 3.08] # 2017 class_distribution = [59.22, 8.65, 28.80, 3.33] def split_indices(n, vld_pct, labels, compensation_factor, random_state=None): """This function is used to split the data into train and validation. Args: n: the number of train data vld_pct: the percentage of validation data random_state: keep the random results same each time calling the function Returns: the indexes of 2 divided datasets(train indices, validation indices). """ n_vld = int(vld_pct*n) # Determine size of validation set if random_state: np.random.seed(random_state) # Set the random seed(for reproducibility) idxs = np.random.permutation(n) # Create random permutation of 0 to n-1 split_sets = [idxs[:n_vld], idxs[n_vld:2*n_vld], idxs[2*n_vld:3*n_vld], idxs[3*n_vld:4*n_vld], idxs[4*n_vld:]] train_sets = [] vld_sets = [] for k in range(5): train_set = np.concatenate((split_sets[k], split_sets[(k+1)%5], split_sets[(k+2)%5], split_sets[(k+3)%5])) masks = [labels[train_set, i].astype(bool) for i in range(labels.shape[1])] sets = [train_set[mask] for mask in masks] lst = [] for idx, set_ in enumerate(sets): scale = int(100 * compensation_factor / class_distribution[idx]) + 1 set_ = np.tile(set_, scale) set_ = set_.reshape([-1, 1]) lst.append(set_) train_set = np.vstack(lst) train_set = train_set.squeeze()
np.random.shuffle(train_set)
numpy.random.shuffle
import moderngl import numpy as np ctx = moderngl.create_standalone_context() prog = ctx.program( vertex_shader=''' #version 330 in vec2 in_vert; in vec3 in_color; out vec3 v_color; void main() { v_color = in_color; gl_Position = vec4(in_vert, 0.0, 1.0); } ''', fragment_shader=''' #version 330 in vec3 v_color; out vec3 f_color; void main() { f_color = v_color; } ''', ) x = np.linspace(-1.0, 1.0, 50) y = np.random.rand(50) - 0.5 r = np.ones(50) g = np.zeros(50) b =
np.zeros(50)
numpy.zeros
import cftime import numpy as np import pandas as pd import xarray as xr from xclim.indices import generic class TestSelectResampleOp: def test_month(self, q_series): q = q_series(np.arange(1000)) o = generic.select_resample_op(q, "count", freq="YS", month=3) np.testing.assert_array_equal(o, 31) def test_season_default(self, q_series): # Will use freq='YS', so count J, F and D of each year. q = q_series(np.arange(1000)) o = generic.select_resample_op(q, "min", season="DJF") assert o[0] == 0 assert o[1] == 366 def test_season(self, q_series): q = q_series(np.arange(1000)) o = generic.select_resample_op(q, "count", freq="AS-DEC", season="DJF") assert o[0] == 31 + 29 class TestThresholdCount: def test_simple(self, tas_series): ts = tas_series(np.arange(365)) out = generic.threshold_count(ts, "<", 50, "Y") np.testing.assert_array_equal(out, [50, 0]) class TestDomainCount: def test_simple(self, tas_series): ts = tas_series(
np.arange(365)
numpy.arange
import numpy as np import math # This implementation of the rock pickup maneuver is based on # https://github.com/jojobilly/Rover-Simulation def yaw_to_target(Rover): if (len(Rover.rock_target_pos) != 2): return Rover.rock_target_yaw direction = np.array(Rover.rock_target_pos) - np.array(Rover.pos) norm = math.sqrt(direction[0] * direction[0] + direction[1] * direction[1]) if (norm > 0): direction /= norm if (direction[0] > 0): target_yaw = math.atan(direction[1]/direction[0]) elif (direction[0] < 0): target_yaw = math.atan(direction[1]/direction[0]) + np.pi elif direction[1] > 0: target_yaw = np.pi / 2 else: target_yaw = -np.pi / 2 if target_yaw < 0: target_yaw += np.pi * 2 return target_yaw * 180/np.pi def rock_pickup(Rover): # There could be no rocks visible from this position. But if we saw it # before we need to continue rotating to the target angle. if (len(Rover.rock_ang) == 0): Rover.no_rock_counter += 1 # In case we have not seen the rock for too long - give up trying. if Rover.no_rock_counter > Rover.no_rock_counter_threshold: Rover.rock_pickup_flag = False Rover.no_rock_counter = 0 # We have reached the target angle. Stop rotating and approach slowly. if np.abs(Rover.yaw - yaw_to_target(Rover)) < 10: Rover.steer = 0 Rover.throttle = .5 else: Rover.brake = 0 # The rock might be not visible now. But keep rotating to the # previously selected direction if np.abs(Rover.steer) < 3: Rover.steer = -4 return Rover else: # We see the rock, so set a flag which would result in calling this # function on the next iteration. Rover.rock_pickup_flag = True Rover.no_rock_counter = 0 Rover.rock_target_yaw = (int)(Rover.yaw +
np.mean(Rover.rock_ang * 180/np.pi)
numpy.mean
from __future__ import division import numpy as NP import multiprocessing as MP import itertools as IT import progressbar as PGB # import aipy as AP import astropy from astropy.io import fits import astropy.cosmology as CP import scipy.constants as FCNST import healpy as HP from distutils.version import LooseVersion import yaml, h5py from astroutils import writer_module as WM from astroutils import constants as CNST from astroutils import DSP_modules as DSP from astroutils import mathops as OPS from astroutils import geometry as GEOM from astroutils import lookup_operations as LKP import prisim from prisim import primary_beams as PB from prisim import interferometry as RI from prisim import baseline_delay_horizon as DLY try: from pyuvdata import UVBeam except ImportError: uvbeam_module_found = False else: uvbeam_module_found = True prisim_path = prisim.__path__[0]+'/' # cosmo100 = CP.FlatLambdaCDM(H0=100.0, Om0=0.27) # Using H0 = 100 km/s/Mpc cosmoPlanck15 = CP.Planck15 # Planck 2015 cosmology cosmo100 = cosmoPlanck15.clone(name='Modified Planck 2015 cosmology with h=1.0', H0=100.0) # Modified Planck 2015 cosmology with h=1.0, H= 100 km/s/Mpc ################################################################################# def _astropy_columns(cols, tabtype='BinTableHDU'): """ ---------------------------------------------------------------------------- !!! FOR INTERNAL USE ONLY !!! This internal routine checks for Astropy version and produces the FITS columns based on the version Inputs: cols [list of Astropy FITS columns] These are a list of Astropy FITS columns tabtype [string] specifies table type - 'BinTableHDU' (default) for binary tables and 'TableHDU' for ASCII tables Outputs: columns [Astropy FITS column data] ---------------------------------------------------------------------------- """ try: cols except NameError: raise NameError('Input cols not specified') if tabtype not in ['BinTableHDU', 'TableHDU']: raise ValueError('tabtype specified is invalid.') use_ascii = False if tabtype == 'TableHDU': use_ascii = True if astropy.__version__ == '0.4': columns = fits.ColDefs(cols, tbtype=tabtype) elif LooseVersion(astropy.__version__)>=LooseVersion('0.4.2'): columns = fits.ColDefs(cols, ascii=use_ascii) return columns ################################################################################ # def _gentle_clean(dd, _w, tol=1e-1, area=None, stop_if_div=True, maxiter=100, # verbose=False, autoscale=True): # if verbose: # print("Performing gentle clean...") # scale_factor = 1.0 # if autoscale: # scale_factor = NP.nanmax(NP.abs(_w)) # dd /= scale_factor # _w /= scale_factor # cc, info = AP.deconv.clean(dd, _w, tol=tol, area=area, stop_if_div=False, # maxiter=maxiter, verbose=verbose) # #dd = info['res'] # cc = NP.zeros_like(dd) # inside_res = NP.std(dd[area!=0]) # outside_res = NP.std(dd[area==0]) # initial_res = inside_res # #print(inside_res,'->',) # ncycle=0 # if verbose: # print("inside_res outside_res") # print(inside_res, outside_res) # inside_res = 2*outside_res #just artifically bump up the inside res so the loop runs at least once # while(inside_res>outside_res and maxiter>0): # if verbose: print('.',) # _d_cl, info = AP.deconv.clean(dd, _w, tol=tol, area=area, stop_if_div=stop_if_div, maxiter=maxiter, verbose=verbose, pos_def=True) # res = info['res'] # inside_res = NP.std(res[area!=0]) # outside_res = NP.std(res[area==0]) # dd = info['res'] # cc += _d_cl # ncycle += 1 # if verbose: print(inside_res*scale_factor, outside_res*scale_factor) # if ncycle>1000: break # info['ncycle'] = ncycle-1 # dd *= scale_factor # _w *= scale_factor # cc *= scale_factor # info['initial_residual'] = initial_res * scale_factor # info['final_residual'] = inside_res * scale_factor # return cc, info ################################################################################# def complex1dClean_arg_splitter(args, **kwargs): return complex1dClean(*args, **kwargs) def complex1dClean(inp, kernel, cbox=None, gain=0.1, maxiter=10000, threshold=5e-3, threshold_type='relative', verbose=False, progressbar=False, pid=None, progressbar_yloc=0): """ ---------------------------------------------------------------------------- Hogbom CLEAN algorithm applicable to 1D complex array Inputs: inp [numpy vector] input 1D array to be cleaned. Can be complex. kernel [numpy vector] 1D array that acts as the deconvolving kernel. Can be complex. Must be of same size as inp cbox [boolean array] 1D boolean array that acts as a mask for pixels which should be cleaned. Same size as inp. Only pixels with values True are to be searched for maxima in residuals for cleaning and the rest are not searched for. Default=None (means all pixels are to be searched for maxima while cleaning) gain [scalar] gain factor to be applied while subtracting clean component from residuals. This is the fraction of the maximum in the residuals that will be subtracted. Must lie between 0 and 1. A lower value will have a smoother convergence but take a longer time to converge. Default=0.1 maxiter [scalar] maximum number of iterations for cleaning process. Will terminate if the number of iterations exceed maxiter. Default=10000 threshold [scalar] represents the cleaning depth either as a fraction of the maximum in the input (when thershold_type is set to 'relative') or the absolute value (when threshold_type is set to 'absolute') in same units of input down to which inp should be cleaned. Value must always be positive. When threshold_type is set to 'relative', threshold mu st lie between 0 and 1. Default=5e-3 (found to work well and converge fast) assuming threshold_type is set to 'relative' threshold_type [string] represents the type of threshold specified by value in input threshold. Accepted values are 'relative' and 'absolute'. If set to 'relative' the threshold value is the fraction (between 0 and 1) of maximum in input down to which it should be cleaned. If set to 'asbolute' it is the actual value down to which inp should be cleaned. Default='relative' verbose [boolean] If set to True (default), print diagnostic and progress messages. If set to False, no such messages are printed. progressbar [boolean] If set to False (default), no progress bar is displayed pid [string or integer] process identifier (optional) relevant only in case of parallel processing and if progressbar is set to True. If pid is not specified, it defaults to the Pool process id progressbar_yloc [integer] row number where the progressbar is displayed on the terminal. Default=0 Output: outdict [dictionary] It consists of the following keys and values at termination: 'termination' [dictionary] consists of information on the conditions for termination with the following keys and values: 'threshold' [boolean] If True, the cleaning process terminated because the threshold was reached 'maxiter' [boolean] If True, the cleaning process terminated because the number of iterations reached maxiter 'inrms<outrms' [boolean] If True, the cleaning process terminated because the rms inside the clean box is below the rms outside of it 'iter' [scalar] number of iterations performed before termination 'rms' [numpy vector] rms of the residuals as a function of iteration 'inrms' [numpy vector] rms of the residuals inside the clean box as a function of iteration 'outrms' [numpy vector] rms of the residuals outside the clean box as a function of iteration 'res' [numpy array] uncleaned residuals at the end of the cleaning process. Complex valued and same size as inp 'cc' [numpy array] clean components at the end of the cleaning process. Complex valued and same size as inp ---------------------------------------------------------------------------- """ try: inp, kernel except NameError: raise NameError('Inputs inp and kernel not specified') if not isinstance(inp, NP.ndarray): raise TypeError('inp must be a numpy array') if not isinstance(kernel, NP.ndarray): raise TypeError('kernel must be a numpy array') if threshold_type not in ['relative', 'absolute']: raise ValueError('invalid specification for threshold_type') if not isinstance(threshold, (int,float)): raise TypeError('input threshold must be a scalar') else: threshold = float(threshold) if threshold <= 0.0: raise ValueError('input threshold must be positive') inp = inp.flatten() kernel = kernel.flatten() kernel /= NP.abs(kernel).max() kmaxind = NP.argmax(NP.abs(kernel)) if inp.size != kernel.size: raise ValueError('inp and kernel must have same size') if cbox is None: cbox = NP.ones(inp.size, dtype=NP.bool) elif isinstance(cbox, NP.ndarray): cbox = cbox.flatten() if cbox.size != inp.size: raise ValueError('Clean box must be of same size as input') cbox = NP.where(cbox > 0.0, True, False) # cbox = cbox.astype(NP.int) else: raise TypeError('cbox must be a numpy array') cbox = cbox.astype(NP.bool) if threshold_type == 'relative': lolim = threshold else: lolim = threshold / NP.abs(inp).max() if lolim >= 1.0: raise ValueError('incompatible value specified for threshold') # inrms = [NP.std(inp[cbox])] inrms = [NP.median(NP.abs(inp[cbox] - NP.median(inp[cbox])))] if inp.size - NP.sum(cbox) <= 2: outrms = None else: # outrms = [NP.std(inp[NP.invert(cbox)])] outrms = [NP.median(NP.abs(inp[NP.invert(cbox)] - NP.median(inp[NP.invert(cbox)])))] if not isinstance(gain, float): raise TypeError('gain must be a floating point number') else: if (gain <= 0.0) or (gain >= 1.0): raise TypeError('gain must lie between 0 and 1') if not isinstance(maxiter, int): raise TypeError('maxiter must be an integer') else: if maxiter <= 0: raise ValueError('maxiter must be positive') cc = NP.zeros_like(inp) res = NP.copy(inp) cond4 = False # prevrms = NP.std(res) # currentrms = [NP.std(res)] prevrms = NP.median(NP.abs(res - NP.median(res))) currentrms = [NP.median(NP.abs(res - NP.median(res)))] itr = 0 terminate = False if progressbar: if pid is None: pid = MP.current_process().name else: pid = '{0:0d}'.format(pid) progressbar_loc = (0, progressbar_yloc) writer=WM.Writer(progressbar_loc) progress = PGB.ProgressBar(widgets=[pid+' ', PGB.Percentage(), PGB.Bar(marker='-', left=' |', right='| '), PGB.Counter(), '/{0:0d} Iterations '.format(maxiter), PGB.ETA()], maxval=maxiter, fd=writer).start() while not terminate: itr += 1 indmaxres = NP.argmax(NP.abs(res*cbox)) maxres = res[indmaxres] ccval = gain * maxres cc[indmaxres] += ccval res = res - ccval * NP.roll(kernel, indmaxres-kmaxind) prevrms = NP.copy(currentrms[-1]) # currentrms += [NP.std(res)] currentrms += [NP.median(NP.abs(res - NP.median(res)))] # inrms += [NP.std(res[cbox])] inrms += [NP.median(NP.abs(res[cbox] - NP.median(res[cbox])))] # cond1 = NP.abs(maxres) <= inrms[-1] cond1 = NP.abs(maxres) <= lolim *
NP.abs(inp)
numpy.abs
# Copyright (c) 2020 NVIDIA Corporation. All rights reserved. # This work is licensed under the NVIDIA Source Code License - Non-commercial. Full # text can be found in LICENSE.md from __future__ import division import numpy as np import torch import torch.nn as nn import torch.nn.init as init import torch.nn.functional as F import torch.optim as optim import torch.utils.data from torch.autograd import Variable import os import datetime import re import matplotlib.pyplot as plt import time from transforms3d.quaternions import * from transforms3d.euler import * from transforms3d.axangles import * import scipy from ycb_render.ycb_renderer import * from decimal import * import cv2 from shutil import copyfile from networks.aae_models import * from config.config import cfg import matplotlib.patches as patches from mpl_toolkits.mplot3d import axes3d, Axes3D import gc class aae_trainer(nn.Module): def __init__(self, cfg_path, object_names, modality, config_new=None, aae_capacity=1, aae_code_dim=128, ckpt_path=None, obj_ctg='ycb', lr=0.0002): super(aae_trainer, self).__init__() self.cfg_path = cfg_path if config_new != None: self.cfg_all = config_new else: self.cfg_all = cfg self.obj_ctg = obj_ctg self.modality = modality if not os.path.exists('./checkpoints'): os.mkdir('./checkpoints') self.ckpt_dir = './checkpoints' self.AAE = AAE(object_names=object_names, modality=modality, capacity=aae_capacity, code_dim=aae_code_dim, model_path=ckpt_path) self.object_names = object_names self.use_GPU = (torch.cuda.device_count() > 0) self.code_dim = aae_code_dim if self.modality == 'rgbd': self.optimizer = optim.Adam(list(self.AAE.encoder.parameters()) + \ list(self.AAE.decoder.parameters()) + \ list(self.AAE.depth_decoder.parameters()), lr=lr) else: self.optimizer = optim.Adam(list(self.AAE.encoder.parameters()) + \ list(self.AAE.decoder.parameters()), lr=lr) self.mseloss = nn.MSELoss() self.l1_loss = nn.L1Loss() self.l1_recon_loss = nn.L1Loss(reduction='mean') if self.use_GPU: self.mseloss = self.mseloss.cuda() self.l1_loss = self.l1_loss.cuda() self.l1_recon_loss = self.l1_recon_loss.cuda() self.loss_history_recon = [] self.val_loss_history_recon = [] self.batch_size_train = self.cfg_all.TRAIN.BATCH_SIZE self.batch_size_val = self.cfg_all.TRAIN.VAL_BATCH_SIZE self.start_epoch = 1 self.codebook_dir = None self.log_dir = None self.checkpoint_path = None self.lb_shift = self.cfg_all.TRAIN.SHIFT_MIN self.ub_shift = self.cfg_all.TRAIN.SHIFT_MAX self.lb_scale = self.cfg_all.TRAIN.SCALE_MIN self.ub_scale = self.cfg_all.TRAIN.SCALE_MAX if ckpt_path is not None: self.load_ckpt(ckpt_path=ckpt_path) def set_log_dir(self, dataset_name='', model_path=None, now=None, ): # Set date and epoch counter as if starting a new model self.epoch = 0 if now == None: now = datetime.datetime.now() # If we have a model path with date and epochs use them if model_path: regex = r".*/\w+(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})/trans\_\w+(\d{4})\.pth" m = re.match(regex, model_path) if m: now = datetime.datetime(int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4)), int(m.group(5)), int(m.group(6))) # Directory for training logs self.log_dir = os.path.join(self.ckpt_dir, "{}_{}_{}_{:%Y%m%dT%H%M%S}".format( dataset_name, self.object_names[0], self.cfg_all.EXP_NAME, now)) # Path to save after each epoch. Include placeholders that get filled by Keras. self.checkpoint_path = os.path.join(self.log_dir, "ckpt_{}_*epoch*.pth".format( self.obj_ctg)) self.checkpoint_path = self.checkpoint_path.replace( "*epoch*", "{:04d}") def save_ckpt(self, epoch): print('=> Saving checkpoint to {} ...'.format(self.checkpoint_path.format(epoch))) torch.save({ 'epoch': epoch, 'log_dir': self.log_dir, 'checkpoint_path': self.checkpoint_path, 'aae_state_dict': self.AAE.state_dict(), 'optimizer': self.optimizer.state_dict(), 'loss_history_recon': self.loss_history_recon, 'val_loss_history_recon': self.val_loss_history_recon, }, self.checkpoint_path.format(epoch)) print('=> Finished saving checkpoint to {} ! '.format(self.checkpoint_path.format(epoch))) def load_ckpt(self, ckpt_path): if os.path.isfile(ckpt_path): print("=> Loading checkpoint from {} ...".format(ckpt_path)) checkpoint = torch.load(ckpt_path) self.start_epoch = checkpoint['epoch'] + 1 self.log_dir = checkpoint['log_dir'] self.checkpoint_path = checkpoint['checkpoint_path'] self.AAE.load_ckpt_weights(checkpoint['aae_state_dict']) self.optimizer.load_state_dict(checkpoint['optimizer']) self.loss_history_recon = checkpoint['loss_history_recon'] self.val_loss_history_recon = checkpoint['val_loss_history_recon'] print("=> Finished loading checkpoint from {} (epoch {})" .format(ckpt_path, checkpoint['epoch'])) else: print('=> Cannot find checkpoint file in {} !'.format(ckpt_path)) def plot_loss(self, loss, title, save=True, log_dir=None): loss = np.array(loss) plt.figure(title) plt.gcf().clear() plt.plot(loss, label='train') plt.xlabel('epoch') plt.ylabel('loss') plt.legend() if save: save_path = os.path.join(log_dir, "{}.png".format(title)) plt.savefig(save_path) plt.close() else: plt.show(block=False) plt.pause(0.1) def train_model(self, train_dataset, epochs, dstr_dataset=None, save_frequency=5): self.AAE.encoder.train() self.AAE.decoder.train() if self.modality == 'rgbd': self.AAE.depth_decoder.train() train_set = train_dataset print('train set size {}'.format(len(train_set))) if self.log_dir == None: self.set_log_dir(dataset_name=train_dataset._name) if not os.path.exists(self.log_dir) and save_frequency > 0: print('Create folder at {}'.format(self.log_dir)) os.makedirs(self.log_dir) copyfile(self.cfg_path, self.log_dir + '/config.yml') print('dataset workers %d' % (self.cfg_all.TRAIN.WORKERS)) train_generator = torch.utils.data.DataLoader(train_set, batch_size=self.batch_size_train, shuffle=True, num_workers=self.cfg_all.TRAIN.WORKERS) if dstr_dataset != None: print('background workers %d' % (self.cfg_all.TRAIN.DISTRACTOR_WORKERS)) train_dstr_generator = torch.utils.data.DataLoader(dstr_dataset, batch_size=self.batch_size_train, shuffle=True, num_workers=self.cfg_all.TRAIN.DISTRACTOR_WORKERS) else: train_dstr_generator = None train_steps = np.floor(len(train_set)/self.batch_size_train) train_steps = np.floor(train_steps/4) for epoch in np.arange(start=self.start_epoch, stop=(self.start_epoch+epochs)): print("Epoch {}/{}.".format(epoch, (self.start_epoch+epochs)-1)) if self.modality == 'rgbd': recon_loss_rgb, recon_loss_train = self.train_epoch_rgbd(train_generator, self.optimizer, train_steps, epoch, self.start_epoch + epochs - 1, dstrgenerator=train_dstr_generator) self.loss_history_recon.append(recon_loss_rgb + recon_loss_train) else: recon_loss_rgb, recon_loss_train = self.train_epoch_rgb(train_generator, self.optimizer, train_steps, epoch, self.start_epoch+epochs-1, dstrgenerator=train_dstr_generator) self.loss_history_recon.append(recon_loss_rgb + recon_loss_train) self.plot_loss(self.loss_history_recon, 'recon loss', save=True, log_dir=self.log_dir) if save_frequency > 0 and epoch % save_frequency == 0: self.save_ckpt(epoch) def train_epoch_rgbd(self, datagenerator, optimizer, steps, epoch, total_epoch, dstrgenerator=None): loss_sum_rgb = 0 loss_sum_depth = 0 step = 0 optimizer.zero_grad() if dstrgenerator != None: enum_dstrgenerator = enumerate(dstrgenerator) for inputs in datagenerator: # receiving data from the renderer images, images_target, pose_cam, mask,\ translation_target, scale_target, \ affine_target, roi_center, roi_size, roi_affine, depths, depths_target = inputs if self.use_GPU: images = images.cuda() images_target = images_target.cuda() mask = mask.cuda() roi_affine = roi_affine.cuda() roi_center = roi_center.cuda().float() roi_size = roi_size.cuda().float() # warp the images according to the center and size of rois grids = F.affine_grid(roi_affine, images.size()) images = F.grid_sample(images, grids) depths = F.grid_sample(depths, grids) mask = F.grid_sample(mask, grids) mask = 1 - mask # add random background and gaussian noise if dstrgenerator != None: _, images_dstr = next(enum_dstrgenerator) if images_dstr.size(0) != images.size(0): enum_dstrgenerator = enumerate(dstrgenerator) _, images_dstr = next(enum_dstrgenerator) if self.use_GPU: images_dstr = images_dstr.cuda() images = images + mask * images_dstr noise_level = np.random.uniform(0, 0.05) images += torch.randn_like(images) * noise_level # add random background to depth image _, depth_dstr = next(enum_dstrgenerator) if depth_dstr.size(0) != depths.size(0): enum_dstrgenerator = enumerate(dstrgenerator) _, depth_dstr = next(enum_dstrgenerator) if self.use_GPU: depth_dstr = depth_dstr.cuda() depths_background = torch.sum(mask * depth_dstr, dim=1, keepdim=True) / np.random.uniform(0.5, 2.0) depths = depths + depths_background depths += torch.rand_like(depths) * np.random.uniform(0, 0.05) depths = torch.clamp(depths, 0, 1) # construct tensor for roi information roi_info = torch.zeros(images.size(0), 5).float().cuda() roi_center += torch.from_numpy(np.random.uniform(self.cfg_all.TRAIN.SHIFT_MIN, self.cfg_all.TRAIN.SHIFT_MAX, size=(roi_info.size(0), 2))).float().cuda() roi_size = roi_size * torch.from_numpy(np.random.uniform(self.cfg_all.TRAIN.SCALE_MIN, self.cfg_all.TRAIN.SCALE_MAX, size=(roi_info.size(0), ))).float().cuda() roi_info[:, 0] = torch.arange(images.size(0)) roi_info[:, 1] = roi_center[:, 0] - roi_size / 2 roi_info[:, 2] = roi_center[:, 1] - roi_size / 2 roi_info[:, 3] = roi_center[:, 0] + roi_size / 2 roi_info[:, 4] = roi_center[:, 1] + roi_size / 2 roi_info_copy = roi_info.clone() roi_info_copy_depth = roi_info.clone() # # visualization for debugging # roi_info_copy2 = roi_info.clone() # images_roi = ROIAlign((128, 128), 1.0, 0)(images, roi_info_copy) # images_roi_disp = images_roi[0].permute(1, 2, 0).cpu().numpy() # depth_roi = ROIAlign((128, 128), 1.0, 0)(depths, roi_info_copy2) # depth_roi_disp = depth_roi[0, 0].cpu().numpy() # image_disp = images[0].permute(1, 2, 0).cpu().numpy() # depth_disp = depths[0, 0].cpu().numpy() # depth_target_disp = depths_target[0, 0].cpu().numpy() # mask_disp = mask[0].permute(1, 2, 0).repeat(1, 1, 3).cpu().numpy() # plt.figure() # plt.subplot(2, 3, 1) # plt.imshow(np.concatenate((image_disp, mask_disp), axis=1)) # plt.subplot(2, 3, 2) # plt.imshow(images_roi_disp) # plt.subplot(2, 3, 3) # plt.imshow(images_target[0].permute(1, 2, 0).cpu().numpy()) # plt.subplot(2, 3, 4) # plt.imshow(depth_disp) # plt.subplot(2, 3, 5) # plt.imshow(depth_roi_disp) # plt.subplot(2, 3, 6) # plt.imshow(depth_target_disp) # plt.show() # AAE forward pass images_input = torch.cat((images, depths), dim=1) outputs = self.AAE.forward_rgbd(images_input, roi_info) images_recnst = outputs[0] loss_reconstr = self.AAE.B_loss(images_recnst[:, :3, :, :], images_target.detach()) loss_depth = self.AAE.B_loss(images_recnst[:, [3], :, :], depths_target) loss = loss_reconstr + loss_depth loss_aae_rgb_data = loss_reconstr.data.cpu().item() loss_aae_depth_data = loss_depth.data.cpu().item() # AAE backward pass optimizer.zero_grad() try: loss.backward() except: pass optimizer.step() print("{}/{}: {}/{}, loss_rgb: {:.4f}, loss depth: {:.4f}".format(epoch, total_epoch, step + 1, int(steps), loss_aae_rgb_data, loss_aae_depth_data)) loss_sum_rgb += loss_aae_rgb_data / steps loss_sum_depth += loss_aae_depth_data / steps # display plot_n_comparison = 20 if step < plot_n_comparison: images_roi = ROIAlign((128, 128), 1.0, 0)(images, roi_info_copy) image = images_roi[0].detach().permute(1, 2, 0).cpu().numpy() image_target = images_target[0].permute(1, 2, 0).cpu().numpy() depths_roi = ROIAlign((128, 128), 1.0, 0)(depths, roi_info_copy_depth) depth = depths_roi[0, 0].detach().cpu().numpy() depth_target = depths_target[0, 0].cpu().numpy() depth_recon = images_recnst[0, 3].detach().cpu().numpy() image_recon = images_recnst[0, :3].detach().permute(1, 2, 0).cpu().numpy() disp = (image, image_target, image_recon, depth, depth_target, depth_recon) self.plot_comparison(disp, str(step)) if step==steps-1: break step += 1 return loss_sum_rgb, loss_sum_depth def train_epoch_rgb(self, datagenerator, optimizer, steps, epoch, total_epoch, dstrgenerator=None, visualize=False): loss_sum_rgb = 0 loss_sum_depth = 0 step = 0 optimizer.zero_grad() if dstrgenerator != None: enum_dstrgenerator = enumerate(dstrgenerator) for inputs in datagenerator: # receiving data from the renderer images, images_target, pose_cam, mask,\ translation_target, scale_target, \ affine_target, roi_center, roi_size, roi_affine, depths, depths_target = inputs if self.use_GPU: images = images.cuda() images_target = images_target.cuda() mask = mask.cuda() roi_affine = roi_affine.cuda() roi_center = roi_center.cuda().float() roi_size = roi_size.cuda().float() # warp the images according to the center and size of rois grids = F.affine_grid(roi_affine, images.size()) images = F.grid_sample(images, grids) depths = F.grid_sample(depths, grids) mask = F.grid_sample(mask, grids) mask = 1 - mask # add random background and gaussian noise if dstrgenerator != None: _, images_dstr = next(enum_dstrgenerator) if images_dstr.size(0) != images.size(0): enum_dstrgenerator = enumerate(dstrgenerator) _, images_dstr = next(enum_dstrgenerator) if self.use_GPU: images_dstr = images_dstr.cuda() images = images + mask * images_dstr noise_level = np.random.uniform(0, 0.05) images += torch.randn_like(images) * noise_level class_info = torch.ones((images.size(0), 1, 128, 128), dtype=torch.float32).cuda() # visualization if visualize: image_disp = images[0].permute(1, 2, 0).cpu().numpy() image_target_disp = images_target[0].permute(1, 2, 0).cpu().numpy() depth_disp = depths[0, 0].cpu().numpy() depth_target_disp = depths_target[0, 0].cpu().numpy() mask_disp = mask[0].permute(1, 2, 0).repeat(1, 1, 3).cpu().numpy() plt.figure() plt.subplot(2, 2, 1) im = np.concatenate((image_disp, mask_disp), axis=1) im =
np.clip(im * 255, 0, 255)
numpy.clip
# 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. import itertools import numpy as np from nums.core.array.application import ArrayApplication def test_quantile_percentile(app_inst: ArrayApplication): # see https://github.com/dask/dask/blob/main/dask/array/tests/test_percentiles.py qs = [0, 50, 100] methods = ["tdigest"] interpolations = ["linear"] np_x = np.ones((10,)) ba_x = app_inst.ones(shape=(10,), block_shape=(2,)) for q, method, interpolation in itertools.product(qs, methods, interpolations): assert app_inst.quantile( ba_x, q / 100, method=method, interpolation=interpolation ).get() == np.quantile(np_x, q / 100) assert app_inst.percentile( ba_x, q, method=method, interpolation=interpolation ).get() == np.percentile(np_x, q) np_x = np.array([0, 0, 5, 5, 5, 5, 20, 20]) ba_x = app_inst.array(np_x, block_shape=(3,)) for q, method, interpolation in itertools.product(qs, methods, interpolations): assert app_inst.quantile( ba_x, q / 100, method=method, interpolation=interpolation ).get() == np.quantile(np_x, q / 100) assert app_inst.percentile( ba_x, q, method=method, interpolation=interpolation ).get() == np.percentile(np_x, q) def test_quickselect(app_inst: ArrayApplication): # pylint: disable=protected-access # Simple tests np_x = np.array([3, 7, 2, 4, 5, 1, 5, 6]) ba_x = app_inst.array(np_x, block_shape=(3,)) ba_oids = ba_x.flattened_oids() correct = [7, 6, 5, 5, 4, 3, 2, 1] for i in range(-8, 8): value_oid = app_inst._quickselect(ba_oids, i) value = app_inst.cm.get(value_oid) assert value == correct[i] # Randomized tests shapes = [(50,), (437,), (1000,)] block_shapes = [(10,), (23,), (50,)] kth = [-50, -42, -25, -13, 0, 8, 25, 36, 49] for shape, block_shape, k in itertools.product(shapes, block_shapes, kth): ba_x = app_inst.random.random(shape=shape, block_shape=block_shape) ba_oids = ba_x.flattened_oids() value_oid = app_inst._quickselect(ba_oids, k) value = app_inst.cm.get(value_oid) assert value == np.partition(ba_x.get(), -k - 1)[-k - 1] def test_median(app_inst: ArrayApplication): # Simple tests np_x = np.array([7, 2, 4, 5, 1, 5, 6]) ba_x = app_inst.array(np_x, block_shape=(3,)) assert app_inst.median(ba_x).get() == np.median(np_x) np_x = np.array([3, 7, 2, 4, 5, 1, 5, 6]) ba_x = app_inst.array(np_x, block_shape=(3,)) assert app_inst.median(ba_x).get() == np.median(np_x) # Randomized tests shapes = [(50,), (437,), (1000,)] block_shapes = [(10,), (23,), (50,)] for shape, block_shape in itertools.product(shapes, block_shapes): ba_x = app_inst.random.random(shape=shape, block_shape=block_shape) assert app_inst.median(ba_x).get() == np.median(ba_x.get()) def test_top_k(app_inst: ArrayApplication): # Simple tests np_x = np.array([3, 7, 2, 4, 5, 1, 5, 6]) ba_x = app_inst.array(np_x, block_shape=(3,)) for k in range(1, len(np_x) + 1): # Largest ba_v, ba_i = app_inst.top_k(ba_x, k) np_v = np.partition(np_x, -k)[-k:] assert len(ba_v.get()) == k and len(ba_i.get()) == k for v, i in zip(ba_v.get(), ba_i.get()): assert v in np_v assert np_x[i] == v # Smallest ba_v, ba_i = app_inst.top_k(ba_x, k, largest=False) np_v =
np.partition(np_x, k - 1)
numpy.partition
# Copyright (c) Microsoft. All rights reserved. # Licensed under the MIT license. See LICENSE.md file in the project root # for full license information. # ============================================================================== import pytest import numpy as np from cntk import * def test_outputs(): fwd_state = placeholder("placeholder") prev_state = past_value(fwd_state, name="prev_state") z = abs(prev_state, "abs") output = z.output z = z.replace_placeholders({fwd_state: z.output}) fwd_state = None prev_state = None z = None for arg in output.owner.arguments: print("Argument name: {}, argument owner name {}".format(arg.name, arg.owner.name)) def test_0d_data_1d_sample_shape(): x = input(shape=(1,)) op = x + x with pytest.raises(ValueError): op.eval({x : [np.asarray(2)]}) def test_1d_NDArrayView_copy(): x = input(shape=(1,)) op = x + 1 result = op.eval({x : [
np.asarray([1])
numpy.asarray
import copy import gym from gym.spaces import Box, Discrete import numpy as np import random class SimpleContextualBandit(gym.Env): """Simple env w/ 2 states and 3 actions (arms): 0, 1, and 2. Episodes last only for one timestep, possible observations are: [-1.0, 1.0] and [1.0, -1.0], where the first element is the "current context". The highest reward (+10.0) is received for selecting arm 0 for context=1.0 and arm 2 for context=-1.0. Action 1 always yields 0.0 reward. """ def __init__(self, config=None): self.action_space = Discrete(3) self.observation_space = Box(low=-1.0, high=1.0, shape=(2,)) self.cur_context = None def reset(self): self.cur_context = random.choice([-1.0, 1.0]) return np.array([self.cur_context, -self.cur_context]) def step(self, action): rewards_for_context = { -1.0: [-10, 0, 10], 1.0: [10, 0, -10], } reward = rewards_for_context[self.cur_context][action] return ( np.array([-self.cur_context, self.cur_context]), reward, True, {"regret": 10 - reward}, ) class LinearDiscreteEnv(gym.Env): """Samples data from linearly parameterized arms. The reward for context X and arm i is given by X^T * theta_i, for some latent set of parameters {theta_i : i = 1, ..., k}. The thetas are sampled uniformly at random, the contexts are Gaussian, and Gaussian noise is added to the rewards. """ DEFAULT_CONFIG_LINEAR = { "feature_dim": 8, "num_actions": 4, "reward_noise_std": 0.01, } def __init__(self, config=None): self.config = copy.copy(self.DEFAULT_CONFIG_LINEAR) if config is not None and type(config) == dict: self.config.update(config) self.feature_dim = self.config["feature_dim"] self.num_actions = self.config["num_actions"] self.sigma = self.config["reward_noise_std"] self.action_space = Discrete(self.num_actions) self.observation_space = Box(low=-10, high=10, shape=(self.feature_dim,)) self.thetas = np.random.uniform(-1, 1, (self.num_actions, self.feature_dim)) self.thetas /=
np.linalg.norm(self.thetas, axis=1, keepdims=True)
numpy.linalg.norm
import random import os import time import sys from PIL import Image import numpy as np import pandas as pd import scipy from sklearn import datasets, linear_model, preprocessing, model_selection from sklearn.metrics import mean_squared_error, r2_score, roc_curve, auc from scipy.interpolate import interp1d from multiprocessing import Pool import pickle # compiled functions for metric calculation from metrics import compute_metrics # include io functions and initialize "metaseg" # NOTE: please check "metaseg_io.py", in particular "probs_gt_save" # for instructions on how to prepare your input data for MetaSeg. # Furthermore, please adjust the variables and paths in "global_defs.py" from metaseg_io import probs_gt_save, probs_gt_load, \ metrics_dump, metrics_load, \ components_dump, components_load, \ get_save_path_probs_i, \ get_save_path_metrics_i, get_save_path_components_i, \ get_iou_seg_vis_path_i, get_save_path_stats, \ get_img_path_fname, metaseg from metaseg_plot import add_scatterplot_vs_iou, make_scatterplots, \ plot_roc_curve, name_to_latex, generate_lasso_plots, \ plot_regression # NOTE: # "cs_labels" is included for the segmentations color code, this is only required for visualization. # Replace this if necessary and modify the lines in "visualize_metrics_i()" that contain "cs_labels" # accordingly. sys.path.append(metaseg.get("DEEPLAB_PARENT_DIR")) from deeplab import cs_labels np.random.seed( 0 ) def main(): metaseg.set_from_argv( sys.argv ) metaseg.print_attr() if metaseg.get("COMPUTE_METRICS"): compute_metrics_per_image() if metaseg.get("VISUALIZE_METRICS"): visualize_metrics() if metaseg.get("ANALYZE_METRICS"): analyze_metrics() def label_as_onehot(label, num_classes, shift_range=0): y = np.zeros((num_classes, label.shape[0], label.shape[1])) for c in range(shift_range,num_classes+shift_range): y[c-shift_range][label==c] = 1 y = np.transpose(y,(1,2,0)) # shape is (height, width, num_classes) return y.astype('uint8') def classes_to_categorical( classes, nc = None ): classes = np.squeeze( np.asarray(classes) ) if nc == None: nc = np.max(classes) classes = label_as_onehot( classes.reshape( (classes.shape[0],1) ), nc ).reshape( (classes.shape[0], nc) ) names = [ "C_"+str(i) for i in range(nc) ] return classes, names def visualize_segments( comp, metric ): R = np.asarray( metric ) R = 1-0.5*R G = np.asarray( metric ) B = 0.3+0.35*np.asarray( metric ) R = np.concatenate( (R, np.asarray([0,1])) ) G = np.concatenate( (G, np.asarray([0,1])) ) B = np.concatenate( (B, np.asarray([0,1])) ) components = np.asarray(comp.copy(), dtype='int16') components[components < 0] = len(R)-1 components[components == 0] = len(R) img = np.zeros( components.shape+(3,) ) for x in range(img.shape[0]): for y in range(img.shape[1]): img[x,y,0] = R[components[x,y]-1] img[x,y,1] = G[components[x,y]-1] img[x,y,2] = B[components[x,y]-1] img = np.asarray( 255*img ).astype('uint8') return img def metrics_to_nparray( metrics, names, normalize=False, non_empty=False, all_metrics=[] ): I = range(len(metrics['S_in'])) if non_empty == True: I = np.asarray(metrics['S_in']) > 0 M = np.asarray( [ np.asarray(metrics[ m ])[I] for m in names ] ) MM = [] if all_metrics == []: MM = M.copy() else: MM = np.asarray( [ np.asarray(all_metrics[ m ])[I] for m in names ] ) if normalize == True: for i in range(M.shape[0]): if names[i] != "class": M[i] = (
np.asarray(M[i])
numpy.asarray
if __name__ == '__main__': # This is a terrible hack just to be able to execute this file directly import sys sys.path.insert(0, '../') from worlds.game_objects import Actions import random, math, os, pickle import numpy as np """ Auxiliary class with the configuration parameters that the Game class needs """ class WaterWorldParams: def __init__(self, state_file = None, max_x = 1000, max_y = 700, b_num_colors = 6, b_radius = 20, b_velocity = 30, b_num_per_color = 10, use_velocities = True, ball_disappear = True): self.max_x = max_x self.max_y = max_y self.b_num_colors = b_num_colors self.b_radius = b_radius self.b_velocity = b_velocity self.a_vel_delta = b_velocity self.a_vel_max = 3*b_velocity self.b_num_per_color = b_num_per_color self.state_file = state_file self.use_velocities = use_velocities self.ball_disappear = ball_disappear class WaterWorld: def __init__(self, params): self.params = params self.use_velocities = params.use_velocities self._load_map() if params.state_file is not None: self.load_state(params.state_file) self.env_game_over = False # Setting up event detectors self.current_collisions_old = set() self._update_events() def _get_current_collision(self): ret = set() for b in self.balls: if self.agent.is_colliding(b): ret.add(b) return ret def _update_events(self): self.true_props = "" current_collisions = self._get_current_collision() for b in current_collisions - self.current_collisions_old: self.true_props += b.color self.current_collisions_old = current_collisions def execute_action(self, a, elapsedTime=0.1): action = Actions(a) # computing events self._update_events() # if balls disappear, then relocate balls that the agent is colliding before the action if self.params.ball_disappear: for b in self.balls: if self.agent.is_colliding(b): pos, vel = self._get_pos_vel_new_ball() b.update(pos, vel) # updating the agents velocity self.agent.execute_action(action) balls_all = [self.agent] + self.balls max_x, max_y = self.params.max_x, self.params.max_y # updating position for b in balls_all: b.update_position(elapsedTime) # handling collisions for i in range(len(balls_all)): b = balls_all[i] # walls if b.pos[0] - b.radius < 0 or b.pos[0] + b.radius > max_x: # Place ball against edge if b.pos[0] - b.radius < 0: b.pos[0] = b.radius else: b.pos[0] = max_x - b.radius # Reverse direction b.vel = b.vel * np.array([-1.0,1.0]) if b.pos[1] - b.radius < 0 or b.pos[1] + b.radius > max_y: # Place ball against edge if b.pos[1] - b.radius < 0: b.pos[1] = b.radius else: b.pos[1] = max_y - b.radius # Reverse directio b.vel = b.vel * np.array([1.0,-1.0]) def get_actions(self): """ Returns the list with the actions that the agent can perform """ return self.agent.get_actions() def get_state(self): return None # we are only using "simple reward machines" for the craft domain def get_true_propositions(self): """ Returns the string with the propositions that are True in this state """ return self.true_props # The following methods return different feature representations of the map ------------ def get_features(self): #_,features = self._get_features_Vis() _,features = self._get_features_HER() return features def _get_features_Vis(self): vel_max = float(self.params.a_vel_max) range_max = (self.params.max_x**2+self.params.max_y**2)**0.5 max_x = self.params.max_x max_y = self.params.max_y radius = self.params.b_radius agent = self.agent a_x, a_y = agent.pos[0], agent.pos[1] # The state space is even larger and continuous: # The agent has 30 eye sensors pointing in all # directions and in each direction is observes # 5 variables: the range, the type of sensed object (green, red), # and the velocity of the sensed object. # The agent's proprioception includes two additional sensors for # its own speed in both x and y directions. # This is a total of 152-dimensional state space. # map from object classes to numbers num_eyes = 16 # in practice, each eye goes to both sides num_classes = self.params.b_num_colors + 1 # I'm including the walls here # adding walls contact_points = {} for i in range(num_eyes): # features per eye: range, type, v_x, v_y angle_pos = i * 180 / num_eyes angle_neg = angle_pos + 180 # walls collisions col_pos = [] col_neg = [] if angle_pos == 0: col_pos.append(np.array([max_x, a_y])) col_neg.append(np.array([0, a_y])) elif angle_pos == 90: col_pos.append(np.array([a_x, max_y])) col_neg.append(np.array([a_x, 0])) else: m = math.tan(math.radians(angle_pos)) c = a_y - m * a_x w_n = np.array([(max_y - c)/m, max_y]) w_e = np.array([max_x, m*max_x + c]) w_w = np.array([0.0, c]) w_s = np.array([-c/m, 0.0]) if angle_pos < 90: col_pos.extend([w_n, w_e]) col_neg.extend([w_s, w_w]) else: col_pos.extend([w_n, w_w]) col_neg.extend([w_s, w_e]) # adding the points for p in col_pos: add_contact_point(contact_points, angle_pos, (dist(agent.pos,p),p,'W')) for p in col_neg: add_contact_point(contact_points, angle_neg, (dist(agent.pos,p),p,'W')) # Adding balls for b in self.balls: if agent.is_colliding(b): continue # computing the eyes that collide with this ball dd = dist(agent.pos, b.pos) theta = math.degrees(math.asin(b.radius/dd)) dx, dy = b.pos[0] - a_x, b.pos[1] - a_y alpha = normalize_angle(math.degrees(math.atan2(dy, dx))) alpha_plus = alpha + theta alpha_minus = alpha - theta if alpha_minus < 0: alpha_minus += 360 alpha_plus += 360 i = math.ceil((num_eyes * alpha_minus)/180) angle = i * 180 / num_eyes while angle <= alpha_plus: angle_real = normalize_angle(angle) # checking that the ball is in the rigth range if dd-b.radius < contact_points[angle_real][0]: p, q, r = b.pos[0], b.pos[1], b.radius if angle_real in [90, 270]: dis = r**2 - (a_x-p)**2 if dis < 0: # the line misses the ball print("It missed the ball?") else: # the line intersects the circle (in one or two points) for case in [-1,1]: x_p = a_x y_p = q+case*dis**0.5 c_p = np.array([x_p,y_p]) add_contact_point(contact_points, angle_real, (dist(agent.pos,c_p),c_p,b)) else: m = math.tan(math.radians(angle_real)) c = a_y - m * a_x A = m**2+1 B = 2*(m*c-m*q-p) C = q**2-r**2+p**2-2*c*q+c**2 dis = B**2-4*A*C if dis < 0: # the line misses the ball print("It missed the ball?", alpha, theta, alpha_minus, angle, alpha_plus) else: # the line intersects the circle (in one or two points) for case in [-1,1]: x_p = (-B+case*dis**0.5)/(2*A) y_p = m*x_p+c c_p = np.array([x_p,y_p]) add_contact_point(contact_points, angle_real, (dist(agent.pos,c_p),c_p,b)) i += 1 angle = i * 180 / num_eyes # range, type, v_x, v_y n_features_per_eye = 3+num_classes n_features = n_features_per_eye*2*num_eyes+2 features = np.zeros(n_features,dtype=np.float) colliding_points = [] for i in range(2*num_eyes): # features per eye: range, type, v_x, v_y dd, p, obj = contact_points[i * 180 / num_eyes] colliding_points.append(p) features[i*n_features_per_eye:(i+1)*n_features_per_eye] = get_eye_features(dd, obj, num_classes, range_max, vel_max) # adding the agents velocity features[n_features-2:n_features] = agent.vel / vel_max return colliding_points, features def _get_features_HER(self): # Absolute position and velocity of the anget + relative positions and velocities of the other balls # with respect to the agent if self.use_velocities: agent, balls = self.agent, self.balls n_features = 4 + len(balls) * 4 features = np.zeros(n_features,dtype=np.float) pos_max = np.array([float(self.params.max_x), float(self.params.max_y)]) vel_max = float(self.params.b_velocity + self.params.a_vel_max) features[0:2] = agent.pos/pos_max features[2:4] = agent.vel/float(self.params.a_vel_max) for i in range(len(balls)): # If the balls are colliding, I'll not include them # (because there us nothing that the agent can do about it) b = balls[i] if not self.params.ball_disappear or not agent.is_colliding(b): init = 4*(i+1) features[init:init+2] = (b.pos - agent.pos)/pos_max features[init+2:init+4] = (b.vel - agent.vel)/vel_max else: agent, balls = self.agent, self.balls n_features = 4 + len(balls) * 2 features = np.zeros(n_features,dtype=np.float) pos_max = np.array([float(self.params.max_x), float(self.params.max_y)]) vel_max = float(self.params.b_velocity + self.params.a_vel_max) features[0:2] = agent.pos/pos_max features[2:4] = agent.vel/float(self.params.a_vel_max) for i in range(len(balls)): # If the balls are colliding, I'll not include them # (because there us nothing that the agent can do about it) b = balls[i] if not self.params.ball_disappear or not agent.is_colliding(b): init = 2*i + 4 features[init:init+2] = (b.pos - agent.pos)/pos_max return [], features #return [b.pos for b in balls if not agent.is_colliding(b)], features def _is_collising(self, pos): for b in self.balls + [self.agent]: if np.linalg.norm(b.pos - np.array(pos), ord=2) < 2*self.params.b_radius: return True return False def _get_pos_vel_new_ball(self): max_x = self.params.max_x max_y = self.params.max_y radius = self.params.b_radius b_vel = self.params.b_velocity angle = random.random()*2*math.pi if self.use_velocities: vel = b_vel*math.sin(angle),b_vel*math.cos(angle) else: vel = 0.0, 0.0 while True: pos = 2*radius + random.random()*(max_x - 2*radius), 2*radius + random.random()*(max_y - 2*radius) if not self._is_collising(pos) and np.linalg.norm(self.agent.pos - np.array(pos), ord=2) > 4*radius: break return pos, vel # The following methods create the map ---------------------------------------------- def _load_map(self): # contains all the actions that the agent can perform actions = [Actions.up.value, Actions.left.value, Actions.right.value, Actions.down.value, Actions.none.value] max_x = self.params.max_x max_y = self.params.max_y radius = self.params.b_radius b_vel = self.params.b_velocity vel_delta = self.params.a_vel_delta vel_max = self.params.a_vel_max # Adding the agent pos_a = [2*radius + random.random()*(max_x - 2*radius), 2*radius + random.random()*(max_y - 2*radius)] self.agent = BallAgent("A", radius, pos_a, [0.0,0.0], actions, vel_delta, vel_max) # Adding the balls self.balls = [] colors = "abcdefghijklmnopqrstuvwxyz" for c in range(self.params.b_num_colors): for _ in range(self.params.b_num_per_color): color = colors[c] pos, vel = self._get_pos_vel_new_ball() ball = Ball(color, radius, pos, vel) self.balls.append(ball) def save_state(self, filename): # Saves the agent and balls positions and velocities with open(filename, 'wb') as output: pickle.dump(self.agent, output, pickle.HIGHEST_PROTOCOL) pickle.dump(self.balls, output, pickle.HIGHEST_PROTOCOL) def load_state(self, filename): # Load the agent and balls positions and velocities with open(filename, 'rb') as input: self.agent = pickle.load(input) self.balls = pickle.load(input) if not self.use_velocities: # Removing balls velocities for b in self.balls: b.vel =
np.array([0.0,0.0], dtype=np.float)
numpy.array
# Copyright (c) 2003-2019 by <NAME> # # TreeCorr is free software: redistribution and use in source and binary forms, # with or without modification, are permitted provided that the following # conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions, and the disclaimer given in the accompanying LICENSE # file. # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions, and the disclaimer given in the documentation # and/or other materials provided with the distribution. from __future__ import print_function import numpy as np import os import coord import time import fitsio import treecorr from test_helper import assert_raises, do_pickle, timer, get_from_wiki, CaptureLog, clear_save from test_helper import profile def generate_shear_field(npos, nhalo, rng=None): # We do something completely different here than we did for 2pt patch tests. # A straight Gaussian field with a given power spectrum has no significant 3pt power, # so it's not a great choice for simulating a field for 3pt tests. # Instead we place N SIS "halos" randomly in the grid. # Then we translate that to a shear field via FFT. if rng is None: rng = np.random.RandomState() # Generate x,y values for the real-space field x = rng.uniform(0,1000, size=npos) y = rng.uniform(0,1000, size=npos) nh = rng.poisson(nhalo) # Fill the kappa values with SIS halo profiles. xc = rng.uniform(0,1000, size=nh) yc = rng.uniform(0,1000, size=nh) scale = rng.uniform(20,50, size=nh) mass = rng.uniform(0.01, 0.05, size=nh) # Avoid making huge nhalo * nsource arrays. Loop in blocks of 64 halos nblock = (nh-1) // 64 + 1 kappa = np.zeros_like(x) gamma = np.zeros_like(x, dtype=complex) for iblock in range(nblock): i = iblock*64 j = (iblock+1)*64 dx = x[:,np.newaxis]-xc[np.newaxis,i:j] dy = y[:,np.newaxis]-yc[np.newaxis,i:j] dx[dx==0] = 1 # Avoid division by zero. dy[dy==0] = 1 dx /= scale[i:j] dy /= scale[i:j] rsq = dx**2 + dy**2 r = rsq**0.5 k = mass[i:j] / r # "Mass" here is really just a dimensionless normalization propto mass. kappa += np.sum(k, axis=1) # gamma_t = kappa for SIS. g = -k * (dx + 1j*dy)**2 / rsq gamma += np.sum(g, axis=1) return x, y, np.real(gamma), np.imag(gamma), kappa @timer def test_kkk_jk(): # Test jackknife and other covariance estimates for kkk correlations. # Note: This test takes a while! # The main version I think is a pretty decent test of the code correctness. # It shows that bootstrap in particular easily gets to within 50% of the right variance. # Sometimes within 20%, but because of the randomness there, it varies a bit. # Jackknife isn't much worse. Just a little below 50%. But still pretty good. # Sample and Marked are not great for this test. I think they will work ok when the # triangles of interest are mostly within single patches, but that's not the case we # have here, and it would take a lot more points to get to that regime. So the # accuracy tests for those two are pretty loose. if __name__ == '__main__': # This setup takes about 740 sec to run. nhalo = 3000 nsource = 5000 npatch = 32 tol_factor = 1 elif False: # This setup takes about 180 sec to run. nhalo = 2000 nsource = 2000 npatch = 16 tol_factor = 2 elif False: # This setup takes about 51 sec to run. nhalo = 1000 nsource = 1000 npatch = 16 tol_factor = 3 else: # This setup takes about 20 sec to run. # So we use this one for regular unit test runs. # It's pretty terrible in terms of testing the accuracy, but it works for code coverage. # But whenever actually working on this part of the code, definitely need to switch # to one of the above setups. Preferably run the name==main version to get a good # test of the code correctness. nhalo = 500 nsource = 500 npatch = 16 tol_factor = 4 file_name = 'data/test_kkk_jk_{}.npz'.format(nsource) print(file_name) if not os.path.isfile(file_name): nruns = 1000 all_kkks = [] rng1 = np.random.RandomState() for run in range(nruns): x, y, _, _, k = generate_shear_field(nsource, nhalo, rng1) print(run,': ',np.mean(k),np.std(k)) cat = treecorr.Catalog(x=x, y=y, k=k) kkk = treecorr.KKKCorrelation(nbins=3, min_sep=30., max_sep=100., min_u=0.9, max_u=1.0, nubins=1, min_v=0.0, max_v=0.1, nvbins=1) kkk.process(cat) print(kkk.ntri.ravel().tolist()) print(kkk.zeta.ravel().tolist()) all_kkks.append(kkk) mean_kkk = np.mean([kkk.zeta.ravel() for kkk in all_kkks], axis=0) var_kkk = np.var([kkk.zeta.ravel() for kkk in all_kkks], axis=0) np.savez(file_name, all_kkk=np.array([kkk.zeta.ravel() for kkk in all_kkks]), mean_kkk=mean_kkk, var_kkk=var_kkk) data = np.load(file_name) mean_kkk = data['mean_kkk'] var_kkk = data['var_kkk'] print('mean = ',mean_kkk) print('var = ',var_kkk) rng = np.random.RandomState(12345) x, y, _, _, k = generate_shear_field(nsource, nhalo, rng) cat = treecorr.Catalog(x=x, y=y, k=k) kkk = treecorr.KKKCorrelation(nbins=3, min_sep=30., max_sep=100., min_u=0.9, max_u=1.0, nubins=1, min_v=0.0, max_v=0.1, nvbins=1, rng=rng) kkk.process(cat) print(kkk.ntri.ravel()) print(kkk.zeta.ravel()) print(kkk.varzeta.ravel()) kkkp = kkk.copy() catp = treecorr.Catalog(x=x, y=y, k=k, npatch=npatch) # Do the same thing with patches. kkkp.process(catp) print('with patches:') print(kkkp.ntri.ravel()) print(kkkp.zeta.ravel()) print(kkkp.varzeta.ravel()) np.testing.assert_allclose(kkkp.ntri, kkk.ntri, rtol=0.05 * tol_factor) np.testing.assert_allclose(kkkp.zeta, kkk.zeta, rtol=0.1 * tol_factor, atol=1e-3 * tol_factor) np.testing.assert_allclose(kkkp.varzeta, kkk.varzeta, rtol=0.05 * tol_factor, atol=3.e-6) print('jackknife:') cov = kkkp.estimate_cov('jackknife') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_kkk)))) np.testing.assert_allclose(np.diagonal(cov), var_kkk, rtol=0.6 * tol_factor) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_kkk), atol=0.5*tol_factor) print('sample:') cov = kkkp.estimate_cov('sample') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_kkk)))) np.testing.assert_allclose(np.diagonal(cov), var_kkk, rtol=0.7 * tol_factor) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_kkk), atol=0.7*tol_factor) print('marked:') cov = kkkp.estimate_cov('marked_bootstrap') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_kkk)))) np.testing.assert_allclose(np.diagonal(cov), var_kkk, rtol=0.7 * tol_factor) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_kkk), atol=0.7*tol_factor) print('bootstrap:') cov = kkkp.estimate_cov('bootstrap') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_kkk)))) np.testing.assert_allclose(np.diagonal(cov), var_kkk, rtol=0.5 * tol_factor) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_kkk), atol=0.3*tol_factor) # Now as a cross correlation with all 3 using the same patch catalog. print('with 3 patched catalogs:') kkkp.process(catp, catp, catp) print(kkkp.zeta.ravel()) np.testing.assert_allclose(kkkp.zeta, kkk.zeta, rtol=0.1 * tol_factor, atol=1e-3 * tol_factor) print('jackknife:') cov = kkkp.estimate_cov('jackknife') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_kkk)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_kkk), atol=0.5*tol_factor) print('sample:') cov = kkkp.estimate_cov('sample') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_kkk)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_kkk), atol=0.8*tol_factor) print('marked:') cov = kkkp.estimate_cov('marked_bootstrap') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_kkk)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_kkk), atol=0.8*tol_factor) print('bootstrap:') cov = kkkp.estimate_cov('bootstrap') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_kkk)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_kkk), atol=0.3*tol_factor) # Repeat this test with different combinations of patch with non-patch catalogs: # All the methods work best when the patches are used for all 3 catalogs. But there # are probably cases where this kind of cross correlation with only some catalogs having # patches could be desired. So this mostly just checks that the code runs properly. # Patch on 1 only: print('with patches on 1 only:') kkkp.process(catp, cat) print(kkkp.zeta.ravel()) np.testing.assert_allclose(kkkp.zeta, kkk.zeta, rtol=0.1 * tol_factor, atol=1e-3 * tol_factor) print('jackknife:') cov = kkkp.estimate_cov('jackknife') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_kkk)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_kkk), atol=0.8*tol_factor) print('sample:') cov = kkkp.estimate_cov('sample') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_kkk)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_kkk), atol=0.8*tol_factor) print('marked:') cov = kkkp.estimate_cov('marked_bootstrap') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_kkk)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_kkk), atol=0.8*tol_factor) print('bootstrap:') cov = kkkp.estimate_cov('bootstrap') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_kkk)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_kkk), atol=0.8*tol_factor) # Patch on 2 only: print('with patches on 2 only:') kkkp.process(cat, catp, cat) print(kkkp.zeta.ravel()) np.testing.assert_allclose(kkkp.zeta, kkk.zeta, rtol=0.1 * tol_factor, atol=1e-3 * tol_factor) print('jackknife:') cov = kkkp.estimate_cov('jackknife') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_kkk)))) np.testing.assert_allclose(np.diagonal(cov), var_kkk, rtol=0.9 * tol_factor) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_kkk), atol=0.8*tol_factor) print('sample:') cov = kkkp.estimate_cov('sample') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_kkk)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_kkk), atol=0.8*tol_factor) print('marked:') cov = kkkp.estimate_cov('marked_bootstrap') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_kkk)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_kkk), atol=0.8*tol_factor) print('bootstrap:') cov = kkkp.estimate_cov('bootstrap') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_kkk)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_kkk), atol=0.8*tol_factor) # Patch on 3 only: print('with patches on 3 only:') kkkp.process(cat, cat, catp) print(kkkp.zeta.ravel()) np.testing.assert_allclose(kkkp.zeta, kkk.zeta, rtol=0.1 * tol_factor, atol=1e-3 * tol_factor) print('jackknife:') cov = kkkp.estimate_cov('jackknife') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_kkk)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_kkk), atol=0.8*tol_factor) print('sample:') cov = kkkp.estimate_cov('sample') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_kkk)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_kkk), atol=0.8*tol_factor) print('marked:') cov = kkkp.estimate_cov('marked_bootstrap') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_kkk)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_kkk), atol=0.8*tol_factor) print('bootstrap:') cov = kkkp.estimate_cov('bootstrap') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_kkk)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_kkk), atol=0.8*tol_factor) # Patch on 1,2 print('with patches on 1,2:') kkkp.process(catp, catp, cat) print(kkkp.zeta.ravel()) np.testing.assert_allclose(kkkp.zeta, kkk.zeta, rtol=0.1 * tol_factor, atol=1e-3 * tol_factor) print('jackknife:') cov = kkkp.estimate_cov('jackknife') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_kkk)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_kkk), atol=0.3*tol_factor) print('sample:') cov = kkkp.estimate_cov('sample') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_kkk)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_kkk), atol=0.8*tol_factor) print('marked:') cov = kkkp.estimate_cov('marked_bootstrap') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_kkk)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_kkk), atol=0.8*tol_factor) print('bootstrap:') cov = kkkp.estimate_cov('bootstrap') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_kkk)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_kkk), atol=0.4*tol_factor) # Patch on 2,3 print('with patches on 2,3:') kkkp.process(cat, catp) print(kkkp.zeta.ravel()) np.testing.assert_allclose(kkkp.zeta, kkk.zeta, rtol=0.1 * tol_factor, atol=1e-3 * tol_factor) print('jackknife:') cov = kkkp.estimate_cov('jackknife') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_kkk)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_kkk), atol=0.3*tol_factor) print('sample:') cov = kkkp.estimate_cov('sample') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_kkk)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_kkk), atol=0.7*tol_factor) print('marked:') cov = kkkp.estimate_cov('marked_bootstrap') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_kkk)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_kkk), atol=0.8*tol_factor) print('bootstrap:') cov = kkkp.estimate_cov('bootstrap') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_kkk)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_kkk), atol=0.3*tol_factor) # Patch on 1,3 print('with patches on 1,3:') kkkp.process(catp, cat, catp) print(kkkp.zeta.ravel()) np.testing.assert_allclose(kkkp.zeta, kkk.zeta, rtol=0.1 * tol_factor, atol=1e-3 * tol_factor) print('jackknife:') cov = kkkp.estimate_cov('jackknife') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_kkk)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_kkk), atol=0.3*tol_factor) print('sample:') cov = kkkp.estimate_cov('sample') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_kkk)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_kkk), atol=0.8*tol_factor) print('marked:') cov = kkkp.estimate_cov('marked_bootstrap') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_kkk)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_kkk), atol=0.8*tol_factor) print('bootstrap:') cov = kkkp.estimate_cov('bootstrap') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_kkk)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_kkk), atol=0.3*tol_factor) # Finally a set (with all patches) using the KKKCrossCorrelation class. kkkc = treecorr.KKKCrossCorrelation(nbins=3, min_sep=30., max_sep=100., min_u=0.9, max_u=1.0, nubins=1, min_v=0.0, max_v=0.1, nvbins=1, rng=rng) print('CrossCorrelation:') kkkc.process(catp, catp, catp) for k1 in kkkc._all: print(k1.ntri.ravel()) print(k1.zeta.ravel()) print(k1.varzeta.ravel()) np.testing.assert_allclose(k1.ntri, kkk.ntri, rtol=0.05 * tol_factor) np.testing.assert_allclose(k1.zeta, kkk.zeta, rtol=0.1 * tol_factor, atol=1e-3 * tol_factor) np.testing.assert_allclose(k1.varzeta, kkk.varzeta, rtol=0.05 * tol_factor, atol=3.e-6) print('jackknife:') cov = kkkc.estimate_cov('jackknife') print(np.diagonal(cov)) for i in range(6): v = np.diagonal(cov)[i*6:(i+1)*6] print('max log(ratio) = ',np.max(np.abs(np.log(v)-np.log(var_kkk)))) np.testing.assert_allclose(np.log(v), np.log(var_kkk), atol=0.5*tol_factor) print('sample:') cov = kkkc.estimate_cov('sample') print(np.diagonal(cov)) for i in range(6): v = np.diagonal(cov)[i*6:(i+1)*6] print('max log(ratio) = ',np.max(np.abs(np.log(v)-np.log(var_kkk)))) np.testing.assert_allclose(np.log(v), np.log(var_kkk), atol=0.8*tol_factor) print('marked:') cov = kkkc.estimate_cov('marked_bootstrap') print(np.diagonal(cov)) for i in range(6): v = np.diagonal(cov)[i*6:(i+1)*6] print('max log(ratio) = ',np.max(np.abs(np.log(v)-np.log(var_kkk)))) np.testing.assert_allclose(np.log(v), np.log(var_kkk), atol=0.8*tol_factor) print('bootstrap:') cov = kkkc.estimate_cov('bootstrap') print(np.diagonal(cov)) for i in range(6): v = np.diagonal(cov)[i*6:(i+1)*6] print('max log(ratio) = ',np.max(np.abs(np.log(v)-np.log(var_kkk)))) np.testing.assert_allclose(np.log(v), np.log(var_kkk), atol=0.5*tol_factor) # All catalogs need to have the same number of patches catq = treecorr.Catalog(x=x, y=y, k=k, npatch=2*npatch) with assert_raises(RuntimeError): kkkp.process(catp, catq) with assert_raises(RuntimeError): kkkp.process(catp, catq, catq) with assert_raises(RuntimeError): kkkp.process(catq, catp, catq) with assert_raises(RuntimeError): kkkp.process(catq, catq, catp) @timer def test_ggg_jk(): # Test jackknife and other covariance estimates for ggg correlations. if __name__ == '__main__': # This setup takes about 590 sec to run. nhalo = 5000 nsource = 5000 npatch = 32 tol_factor = 1 elif False: # This setup takes about 160 sec to run. nhalo = 2000 nsource = 2000 npatch = 16 tol_factor = 2 elif False: # This setup takes about 50 sec to run. nhalo = 1000 nsource = 1000 npatch = 16 tol_factor = 3 else: # This setup takes about 13 sec to run. nhalo = 500 nsource = 500 npatch = 8 tol_factor = 3 # I couldn't figure out a way to get reasonable S/N in the shear field. I thought doing # discrete halos would give some significant 3pt shear pattern, at least for equilateral # triangles, but the signal here is still consistent with zero. :( # The point is the variance, which is still calculated ok, but I would have rathered # have something with S/N > 0. # For these tests, I set up the binning to just accumulate all roughly equilateral triangles # in a small separation range. The binning always uses two bins for each to get + and - v # bins. So this function averages these two values to produce 1 value for each gamma. f = lambda g: np.array([np.mean(g.gam0), np.mean(g.gam1), np.mean(g.gam2), np.mean(g.gam3)]) file_name = 'data/test_ggg_jk_{}.npz'.format(nsource) print(file_name) if not os.path.isfile(file_name): nruns = 1000 all_gggs = [] rng1 = np.random.RandomState() for run in range(nruns): x, y, g1, g2, _ = generate_shear_field(nsource, nhalo, rng1) # For some reason std(g2) is coming out about 1.5x larger than std(g1). # Probably a sign of some error in the generate function, but I don't see it. # For this purpose I think it doesn't really matter, but it's a bit odd. print(run,': ',np.mean(g1),np.std(g1),np.mean(g2),np.std(g2)) cat = treecorr.Catalog(x=x, y=y, g1=g1, g2=g2) ggg = treecorr.GGGCorrelation(nbins=1, min_sep=20., max_sep=40., min_u=0.6, max_u=1.0, nubins=1, min_v=0.0, max_v=0.6, nvbins=1) ggg.process(cat) print(ggg.ntri.ravel()) print(f(ggg)) all_gggs.append(ggg) all_ggg = np.array([f(ggg) for ggg in all_gggs]) mean_ggg = np.mean(all_ggg, axis=0) var_ggg = np.var(all_ggg, axis=0) np.savez(file_name, mean_ggg=mean_ggg, var_ggg=var_ggg) data = np.load(file_name) mean_ggg = data['mean_ggg'] var_ggg = data['var_ggg'] print('mean = ',mean_ggg) print('var = ',var_ggg) rng = np.random.RandomState(12345) x, y, g1, g2, _ = generate_shear_field(nsource, nhalo, rng) cat = treecorr.Catalog(x=x, y=y, g1=g1, g2=g2) ggg = treecorr.GGGCorrelation(nbins=1, min_sep=20., max_sep=40., min_u=0.6, max_u=1.0, nubins=1, min_v=0.0, max_v=0.6, nvbins=1, rng=rng) ggg.process(cat) print(ggg.ntri.ravel()) print(ggg.gam0.ravel()) print(ggg.gam1.ravel()) print(ggg.gam2.ravel()) print(ggg.gam3.ravel()) gggp = ggg.copy() catp = treecorr.Catalog(x=x, y=y, g1=g1, g2=g2, npatch=npatch) # Do the same thing with patches. gggp.process(catp) print('with patches:') print(gggp.ntri.ravel()) print(gggp.vargam0.ravel()) print(gggp.vargam1.ravel()) print(gggp.vargam2.ravel()) print(gggp.vargam3.ravel()) print(gggp.gam0.ravel()) print(gggp.gam1.ravel()) print(gggp.gam2.ravel()) print(gggp.gam3.ravel()) np.testing.assert_allclose(gggp.ntri, ggg.ntri, rtol=0.05 * tol_factor) np.testing.assert_allclose(gggp.gam0, ggg.gam0, rtol=0.3 * tol_factor, atol=0.3 * tol_factor) np.testing.assert_allclose(gggp.gam1, ggg.gam1, rtol=0.3 * tol_factor, atol=0.3 * tol_factor) np.testing.assert_allclose(gggp.gam2, ggg.gam2, rtol=0.3 * tol_factor, atol=0.3 * tol_factor) np.testing.assert_allclose(gggp.gam3, ggg.gam3, rtol=0.3 * tol_factor, atol=0.3 * tol_factor) np.testing.assert_allclose(gggp.vargam0, ggg.vargam0, rtol=0.1 * tol_factor) np.testing.assert_allclose(gggp.vargam1, ggg.vargam1, rtol=0.1 * tol_factor) np.testing.assert_allclose(gggp.vargam2, ggg.vargam2, rtol=0.1 * tol_factor) np.testing.assert_allclose(gggp.vargam3, ggg.vargam3, rtol=0.1 * tol_factor) print('jackknife:') cov = gggp.estimate_cov('jackknife', func=f) print(np.diagonal(cov).real) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_ggg)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_ggg), atol=0.4*tol_factor) print('sample:') cov = gggp.estimate_cov('sample', func=f) print(np.diagonal(cov).real) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_ggg)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_ggg), atol=0.8*tol_factor) print('marked:') cov = gggp.estimate_cov('marked_bootstrap', func=f) print(np.diagonal(cov).real) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_ggg)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_ggg), atol=0.9*tol_factor) print('bootstrap:') cov = gggp.estimate_cov('bootstrap', func=f) print(np.diagonal(cov).real) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_ggg)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_ggg), atol=0.3*tol_factor) # Now as a cross correlation with all 3 using the same patch catalog. print('with 3 patched catalogs:') gggp.process(catp, catp, catp) print(gggp.gam0.ravel()) np.testing.assert_allclose(gggp.gam0, ggg.gam0, rtol=0.3 * tol_factor, atol=0.3 * tol_factor) np.testing.assert_allclose(gggp.gam1, ggg.gam1, rtol=0.3 * tol_factor, atol=0.3 * tol_factor) np.testing.assert_allclose(gggp.gam2, ggg.gam2, rtol=0.3 * tol_factor, atol=0.3 * tol_factor) np.testing.assert_allclose(gggp.gam3, ggg.gam3, rtol=0.3 * tol_factor, atol=0.3 * tol_factor) print('jackknife:') cov = gggp.estimate_cov('jackknife', func=f) print(np.diagonal(cov).real) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_ggg)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_ggg), atol=0.4*tol_factor) print('sample:') cov = gggp.estimate_cov('sample', func=f) print(np.diagonal(cov).real) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_ggg)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_ggg), atol=0.6*tol_factor) print('marked:') cov = gggp.estimate_cov('marked_bootstrap', func=f) print(np.diagonal(cov).real) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_ggg)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_ggg), atol=0.8*tol_factor) print('bootstrap:') cov = gggp.estimate_cov('bootstrap', func=f) print(np.diagonal(cov).real) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_ggg)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_ggg), atol=0.4*tol_factor) # The separate patch/non-patch combinations aren't that interesting, so skip them # for GGG unless running from main. if __name__ == '__main__': # Patch on 1 only: print('with patches on 1 only:') gggp.process(catp, cat) print('jackknife:') cov = gggp.estimate_cov('jackknife', func=f) print(np.diagonal(cov).real) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_ggg)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_ggg), atol=0.8*tol_factor) print('sample:') cov = gggp.estimate_cov('sample', func=f) print(np.diagonal(cov).real) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_ggg)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_ggg), atol=0.7*tol_factor) print('marked:') cov = gggp.estimate_cov('marked_bootstrap', func=f) print(np.diagonal(cov).real) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_ggg)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_ggg), atol=0.8*tol_factor) print('bootstrap:') cov = gggp.estimate_cov('bootstrap', func=f) print(np.diagonal(cov).real) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_ggg)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_ggg), atol=0.8*tol_factor) # Patch on 2 only: print('with patches on 2 only:') gggp.process(cat, catp, cat) print('jackknife:') cov = gggp.estimate_cov('jackknife', func=f) print(np.diagonal(cov).real) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_ggg)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_ggg), atol=0.8*tol_factor) print('sample:') cov = gggp.estimate_cov('sample', func=f) print(np.diagonal(cov).real) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_ggg)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_ggg), atol=0.7*tol_factor) print('marked:') cov = gggp.estimate_cov('marked_bootstrap', func=f) print(np.diagonal(cov).real) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_ggg)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_ggg), atol=0.8*tol_factor) print('bootstrap:') cov = gggp.estimate_cov('bootstrap', func=f) print(np.diagonal(cov).real) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_ggg)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_ggg), atol=0.8*tol_factor) # Patch on 3 only: print('with patches on 3 only:') gggp.process(cat, cat, catp) print('jackknife:') cov = gggp.estimate_cov('jackknife', func=f) print(np.diagonal(cov).real) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_ggg)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_ggg), atol=0.8*tol_factor) print('sample:') cov = gggp.estimate_cov('sample', func=f) print(np.diagonal(cov).real) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_ggg)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_ggg), atol=0.7*tol_factor) print('marked:') cov = gggp.estimate_cov('marked_bootstrap', func=f) print(np.diagonal(cov).real) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_ggg)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_ggg), atol=0.8*tol_factor) print('bootstrap:') cov = gggp.estimate_cov('bootstrap', func=f) print(np.diagonal(cov).real) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_ggg)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_ggg), atol=0.9*tol_factor) # Patch on 1,2 print('with patches on 1,2:') gggp.process(catp, catp, cat) print('jackknife:') cov = gggp.estimate_cov('jackknife', func=f) print(np.diagonal(cov).real) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_ggg)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_ggg), atol=0.6*tol_factor) print('sample:') cov = gggp.estimate_cov('sample', func=f) print(np.diagonal(cov).real) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_ggg)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_ggg), atol=0.6*tol_factor) print('marked:') cov = gggp.estimate_cov('marked_bootstrap', func=f) print(np.diagonal(cov).real) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_ggg)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_ggg), atol=0.8*tol_factor) print('bootstrap:') cov = gggp.estimate_cov('bootstrap', func=f) print(np.diagonal(cov).real) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_ggg)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_ggg), atol=0.5*tol_factor) # Patch on 2,3 print('with patches on 2,3:') gggp.process(cat, catp) print('jackknife:') cov = gggp.estimate_cov('jackknife', func=f) print(np.diagonal(cov).real) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_ggg)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_ggg), atol=0.6*tol_factor) print('sample:') cov = gggp.estimate_cov('sample', func=f) print(np.diagonal(cov).real) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_ggg)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_ggg), atol=0.8*tol_factor) print('marked:') cov = gggp.estimate_cov('marked_bootstrap', func=f) print(np.diagonal(cov).real) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_ggg)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_ggg), atol=1.0*tol_factor) print('bootstrap:') cov = gggp.estimate_cov('bootstrap', func=f) print(np.diagonal(cov).real) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_ggg)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_ggg), atol=0.3*tol_factor) # Patch on 1,3 print('with patches on 1,3:') gggp.process(catp, cat, catp) print('jackknife:') cov = gggp.estimate_cov('jackknife', func=f) print(np.diagonal(cov).real) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_ggg)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_ggg), atol=0.6*tol_factor) print('sample:') cov = gggp.estimate_cov('sample', func=f) print(np.diagonal(cov).real) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_ggg)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_ggg), atol=0.6*tol_factor) print('marked:') cov = gggp.estimate_cov('marked_bootstrap', func=f) print(np.diagonal(cov).real) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_ggg)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_ggg), atol=0.7*tol_factor) print('bootstrap:') cov = gggp.estimate_cov('bootstrap', func=f) print(np.diagonal(cov).real) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_ggg)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_ggg), atol=0.5*tol_factor) # Finally a set (with all patches) using the GGGCrossCorrelation class. gggc = treecorr.GGGCrossCorrelation(nbins=1, min_sep=20., max_sep=40., min_u=0.6, max_u=1.0, nubins=1, min_v=0.0, max_v=0.6, nvbins=1, rng=rng) print('CrossCorrelation:') gggc.process(catp, catp, catp) for g in gggc._all: print(g.ntri.ravel()) print(g.gam0.ravel()) print(g.vargam0.ravel()) np.testing.assert_allclose(g.ntri, ggg.ntri, rtol=0.05 * tol_factor) np.testing.assert_allclose(g.gam0, ggg.gam0, rtol=0.3 * tol_factor, atol=0.3 * tol_factor) np.testing.assert_allclose(g.vargam0, ggg.vargam0, rtol=0.05 * tol_factor) np.testing.assert_allclose(g.gam1, ggg.gam1, rtol=0.3 * tol_factor, atol=0.3 * tol_factor) np.testing.assert_allclose(g.vargam1, ggg.vargam1, rtol=0.05 * tol_factor) np.testing.assert_allclose(g.gam2, ggg.gam2, rtol=0.3 * tol_factor, atol=0.3 * tol_factor) np.testing.assert_allclose(g.vargam2, ggg.vargam2, rtol=0.05 * tol_factor) np.testing.assert_allclose(g.gam3, ggg.gam3, rtol=0.3 * tol_factor, atol=0.3 * tol_factor) np.testing.assert_allclose(g.vargam3, ggg.vargam3, rtol=0.05 * tol_factor) fc = lambda gggc: np.concatenate([ [np.mean(g.gam0), np.mean(g.gam1), np.mean(g.gam2), np.mean(g.gam3)] for g in gggc._all]) print('jackknife:') cov = gggc.estimate_cov('jackknife', func=fc) print(np.diagonal(cov).real) for i in range(6): v = np.diagonal(cov)[i*4:(i+1)*4] print('max log(ratio) = ',np.max(np.abs(np.log(v)-np.log(var_ggg)))) np.testing.assert_allclose(np.log(v), np.log(var_ggg), atol=0.4*tol_factor) print('sample:') cov = gggc.estimate_cov('sample', func=fc) print(np.diagonal(cov).real) for i in range(6): v = np.diagonal(cov)[i*4:(i+1)*4] print('max log(ratio) = ',np.max(np.abs(np.log(v)-np.log(var_ggg)))) np.testing.assert_allclose(np.log(v), np.log(var_ggg), atol=0.6*tol_factor) print('marked:') cov = gggc.estimate_cov('marked_bootstrap', func=fc) print(np.diagonal(cov).real) for i in range(6): v = np.diagonal(cov)[i*4:(i+1)*4] print('max log(ratio) = ',np.max(np.abs(np.log(v)-np.log(var_ggg)))) np.testing.assert_allclose(np.log(v), np.log(var_ggg), atol=0.8*tol_factor) print('bootstrap:') cov = gggc.estimate_cov('bootstrap', func=fc) print(np.diagonal(cov).real) for i in range(6): v = np.diagonal(cov)[i*4:(i+1)*4] print('max log(ratio) = ',np.max(np.abs(np.log(v)-np.log(var_ggg)))) np.testing.assert_allclose(np.log(v), np.log(var_ggg), atol=0.3*tol_factor) # Without func, don't check the accuracy, but make sure it returns something the right shape. cov = gggc.estimate_cov('jackknife') assert cov.shape == (48, 48) @timer def test_nnn_jk(): # Test jackknife and other covariance estimates for nnn correlations. if __name__ == '__main__': # This setup takes about 1200 sec to run. nhalo = 300 nsource = 2000 npatch = 16 source_factor = 50 rand_factor = 3 tol_factor = 1 elif False: # This setup takes about 250 sec to run. nhalo = 200 nsource = 1000 npatch = 16 source_factor = 50 rand_factor = 2 tol_factor = 2 else: # This setup takes about 44 sec to run. nhalo = 100 nsource = 500 npatch = 8 source_factor = 30 rand_factor = 1 tol_factor = 3 file_name = 'data/test_nnn_jk_{}.npz'.format(nsource) print(file_name) if not os.path.isfile(file_name): rng = np.random.RandomState() nruns = 1000 all_nnns = [] all_nnnc = [] t0 = time.time() for run in range(nruns): t2 = time.time() x, y, _, _, k = generate_shear_field(nsource * source_factor, nhalo, rng) p = k**3 p /= np.sum(p) ns = rng.poisson(nsource) select = rng.choice(range(len(x)), size=ns, replace=False, p=p) print(run,': ',np.mean(k),np.std(k),np.min(k),np.max(k)) cat = treecorr.Catalog(x=x[select], y=y[select]) ddd = treecorr.NNNCorrelation(nbins=3, min_sep=50., max_sep=100., bin_slop=0.2, min_u=0.8, max_u=1.0, nubins=1, min_v=0.0, max_v=0.2, nvbins=1) rx = rng.uniform(0,1000, rand_factor*nsource) ry = rng.uniform(0,1000, rand_factor*nsource) rand_cat = treecorr.Catalog(x=rx, y=ry) rrr = treecorr.NNNCorrelation(nbins=3, min_sep=50., max_sep=100., bin_slop=0.2, min_u=0.8, max_u=1.0, nubins=1, min_v=0.0, max_v=0.2, nvbins=1) rrr.process(rand_cat) rdd = ddd.copy() drr = ddd.copy() ddd.process(cat) rdd.process(rand_cat, cat) drr.process(cat, rand_cat) zeta_s, _ = ddd.calculateZeta(rrr) zeta_c, _ = ddd.calculateZeta(rrr, drr, rdd) print('simple: ',zeta_s.ravel()) print('compensated: ',zeta_c.ravel()) all_nnns.append(zeta_s.ravel()) all_nnnc.append(zeta_c.ravel()) t3 = time.time() print('time: ',round(t3-t2),round((t3-t0)/60),round((t3-t0)*(nruns/(run+1)-1)/60)) mean_nnns = np.mean(all_nnns, axis=0) var_nnns = np.var(all_nnns, axis=0) mean_nnnc = np.mean(all_nnnc, axis=0) var_nnnc = np.var(all_nnnc, axis=0) np.savez(file_name, mean_nnns=mean_nnns, var_nnns=var_nnns, mean_nnnc=mean_nnnc, var_nnnc=var_nnnc) data = np.load(file_name) mean_nnns = data['mean_nnns'] var_nnns = data['var_nnns'] mean_nnnc = data['mean_nnnc'] var_nnnc = data['var_nnnc'] print('mean simple = ',mean_nnns) print('var simple = ',var_nnns) print('mean compensated = ',mean_nnnc) print('var compensated = ',var_nnnc) # Make a random catalog with 2x as many sources, randomly distributed . rng = np.random.RandomState(1234) rx = rng.uniform(0,1000, rand_factor*nsource) ry = rng.uniform(0,1000, rand_factor*nsource) rand_cat = treecorr.Catalog(x=rx, y=ry) rrr = treecorr.NNNCorrelation(nbins=3, min_sep=50., max_sep=100., bin_slop=0.2, min_u=0.8, max_u=1.0, nubins=1, min_v=0.0, max_v=0.2, nvbins=1) t0 = time.time() rrr.process(rand_cat) t1 = time.time() print('Time to process rand cat = ',t1-t0) print('RRR:',rrr.tot) print(rrr.ntri.ravel()) # Make the data catalog x, y, _, _, k = generate_shear_field(nsource * source_factor, nhalo, rng=rng) print('mean k = ',np.mean(k)) print('min,max = ',np.min(k),np.max(k)) p = k**3 p /= np.sum(p) select = rng.choice(range(len(x)), size=nsource, replace=False, p=p) cat = treecorr.Catalog(x=x[select], y=y[select]) ddd = treecorr.NNNCorrelation(nbins=3, min_sep=50., max_sep=100., bin_slop=0.2, min_u=0.8, max_u=1.0, nubins=1, min_v=0.0, max_v=0.2, nvbins=1, rng=rng) rdd = ddd.copy() drr = ddd.copy() ddd.process(cat) rdd.process(rand_cat, cat) drr.process(cat, rand_cat) zeta_s1, var_zeta_s1 = ddd.calculateZeta(rrr) zeta_c1, var_zeta_c1 = ddd.calculateZeta(rrr, drr, rdd) print('DDD:',ddd.tot) print(ddd.ntri.ravel()) print('simple: ') print(zeta_s1.ravel()) print(var_zeta_s1.ravel()) print('DRR:',drr.tot) print(drr.ntri.ravel()) print('RDD:',rdd.tot) print(rdd.ntri.ravel()) print('compensated: ') print(zeta_c1.ravel()) print(var_zeta_c1.ravel()) # Make the patches with a large random catalog to make sure the patches are uniform area. big_rx = rng.uniform(0,1000, 100*nsource) big_ry = rng.uniform(0,1000, 100*nsource) big_catp = treecorr.Catalog(x=big_rx, y=big_ry, npatch=npatch, rng=rng) patch_centers = big_catp.patch_centers # Do the same thing with patches on D, but not yet on R. dddp = treecorr.NNNCorrelation(nbins=3, min_sep=50., max_sep=100., bin_slop=0.2, min_u=0.8, max_u=1.0, nubins=1, min_v=0.0, max_v=0.2, nvbins=1, rng=rng) rddp = dddp.copy() drrp = dddp.copy() catp = treecorr.Catalog(x=x[select], y=y[select], patch_centers=patch_centers) print('Patch\tNtot') for p in catp.patches: print(p.patch,'\t',p.ntot,'\t',patch_centers[p.patch]) print('with patches on D:') dddp.process(catp) rddp.process(rand_cat, catp) drrp.process(catp, rand_cat) # Need to run calculateZeta to get patch-based covariance with assert_raises(RuntimeError): dddp.estimate_cov('jackknife') zeta_s2, var_zeta_s2 = dddp.calculateZeta(rrr) print('DDD:',dddp.tot) print(dddp.ntri.ravel()) print('simple: ') print(zeta_s2.ravel()) print(var_zeta_s2.ravel()) np.testing.assert_allclose(zeta_s2, zeta_s1, rtol=0.05 * tol_factor) np.testing.assert_allclose(var_zeta_s2, var_zeta_s1, rtol=0.05 * tol_factor) # Check the _calculate_xi_from_pairs function. Using all pairs, should get total xi. ddd1 = dddp.copy() ddd1._calculate_xi_from_pairs(dddp.results.keys()) np.testing.assert_allclose(ddd1.zeta, dddp.zeta) # None of these are very good without the random using patches. # I think this is basically just that the approximations used for estimating the area_frac # to figure out the appropriate altered RRR counts isn't accurate enough when the total # counts are as low as this. I think (hope) that it should be semi-ok when N is much larger, # but this is probably saying that for 3pt using patches for R is even more important than # for 2pt. # Ofc, it could also be that this is telling me I still have a bug somewhere that I haven't # managed to find... :( print('jackknife:') cov = dddp.estimate_cov('jackknife') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_nnns)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_nnns), atol=2.3*tol_factor) print('sample:') cov = dddp.estimate_cov('sample') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_nnns)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_nnns), atol=1.2*tol_factor) print('marked:') cov = dddp.estimate_cov('marked_bootstrap') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_nnns)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_nnns), atol=1.3*tol_factor) print('bootstrap:') cov = dddp.estimate_cov('bootstrap') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_nnns)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_nnns), atol=2.2*tol_factor) zeta_c2, var_zeta_c2 = dddp.calculateZeta(rrr, drrp, rddp) print('compensated: ') print('DRR:',drrp.tot) print(drrp.ntri.ravel()) print('RDD:',rddp.tot) print(rddp.ntri.ravel()) print(zeta_c2.ravel()) print(var_zeta_c2.ravel()) np.testing.assert_allclose(zeta_c2, zeta_c1, rtol=0.05 * tol_factor, atol=1.e-3 * tol_factor) np.testing.assert_allclose(var_zeta_c2, var_zeta_c1, rtol=0.05 * tol_factor) print('jackknife:') cov = dddp.estimate_cov('jackknife') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_nnnc)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_nnnc), atol=2.6*tol_factor) print('sample:') cov = dddp.estimate_cov('sample') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_nnnc)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_nnnc), atol=3.8*tol_factor) print('marked:') cov = dddp.estimate_cov('marked_bootstrap') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_nnnc)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_nnnc), atol=2.3*tol_factor) print('bootstrap:') cov = dddp.estimate_cov('bootstrap') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_nnnc)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_nnnc), atol=2.6*tol_factor) # Now with the random also using patches # These are a lot better than the above tests. But still not nearly as good as we were able # to get in 2pt. I'm pretty sure this is just due to the fact that we need to have much # smaller catalogs to make it feasible to run this in a reasonable amount of time. I don't # think this is a sign of any bug in the code. print('with patched random catalog:') rand_catp = treecorr.Catalog(x=rx, y=ry, patch_centers=patch_centers) rrrp = rrr.copy() rrrp.process(rand_catp) drrp.process(catp, rand_catp) rddp.process(rand_catp, catp) print('simple: ') zeta_s2, var_zeta_s2 = dddp.calculateZeta(rrrp) print('DDD:',dddp.tot) print(dddp.ntri.ravel()) print(zeta_s2.ravel()) print(var_zeta_s2.ravel()) np.testing.assert_allclose(zeta_s2, zeta_s1, rtol=0.05 * tol_factor) np.testing.assert_allclose(var_zeta_s2, var_zeta_s1, rtol=0.05 * tol_factor) ddd1 = dddp.copy() ddd1._calculate_xi_from_pairs(dddp.results.keys()) np.testing.assert_allclose(ddd1.zeta, dddp.zeta) t0 = time.time() print('jackknife:') cov = dddp.estimate_cov('jackknife') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_nnns)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_nnns), atol=0.9*tol_factor) t1 = time.time() print('t = ',t1-t0) t0 = time.time() print('sample:') cov = dddp.estimate_cov('sample') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_nnns)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_nnns), atol=0.7*tol_factor) t1 = time.time() print('t = ',t1-t0) t0 = time.time() print('marked:') cov = dddp.estimate_cov('marked_bootstrap') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_nnns)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_nnns), atol=0.8*tol_factor) t1 = time.time() print('t = ',t1-t0) t0 = time.time() print('bootstrap:') cov = dddp.estimate_cov('bootstrap') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_nnns)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_nnns), atol=1.0*tol_factor) t1 = time.time() print('t = ',t1-t0) t0 = time.time() print('compensated: ') zeta_c2, var_zeta_c2 = dddp.calculateZeta(rrrp, drrp, rddp) print('DRR:',drrp.tot) print(drrp.ntri.ravel()) print('RDD:',rddp.tot) print(rddp.ntri.ravel()) print(zeta_c2.ravel()) print(var_zeta_c2.ravel()) np.testing.assert_allclose(zeta_c2, zeta_c1, rtol=0.05 * tol_factor, atol=1.e-3 * tol_factor) np.testing.assert_allclose(var_zeta_c2, var_zeta_c1, rtol=0.05 * tol_factor) t0 = time.time() print('jackknife:') cov = dddp.estimate_cov('jackknife') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_nnnc)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_nnnc), atol=0.8*tol_factor) t1 = time.time() print('t = ',t1-t0) t0 = time.time() print('sample:') cov = dddp.estimate_cov('sample') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_nnnc)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_nnnc), atol=0.8*tol_factor) t1 = time.time() print('t = ',t1-t0) t0 = time.time() print('marked:') cov = dddp.estimate_cov('marked_bootstrap') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_nnnc)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_nnnc), atol=0.8*tol_factor) t1 = time.time() print('t = ',t1-t0) t0 = time.time() print('bootstrap:') cov = dddp.estimate_cov('bootstrap') print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_nnnc)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_nnnc), atol=0.8*tol_factor) t1 = time.time() print('t = ',t1-t0) t0 = time.time() # I haven't implemented calculateZeta for the NNNCrossCorrelation class, because I'm not # actually sure what the right thing to do here is for calculating a single zeta vectors. # Do we do a different one for each of the 6 permutations? Or one overall one? # So rather than just do something, I'll wait until someone has a coherent use case where # they want this and can explain exactly what the right thing to compute is. # So to just exercise the machinery with NNNCrossCorrelation, I'm using a func parameter # to compute something equivalent to the simple zeta calculation. dddc = treecorr.NNNCrossCorrelation(nbins=3, min_sep=50., max_sep=100., bin_slop=0.2, min_u=0.8, max_u=1.0, nubins=1, min_v=0.0, max_v=0.2, nvbins=1, rng=rng) rrrc = treecorr.NNNCrossCorrelation(nbins=3, min_sep=50., max_sep=100., bin_slop=0.2, min_u=0.8, max_u=1.0, nubins=1, min_v=0.0, max_v=0.2, nvbins=1) print('CrossCorrelation:') dddc.process(catp, catp, catp) rrrc.process(rand_catp, rand_catp, rand_catp) def cc_zeta(corrs): d, r = corrs d1 = d.n1n2n3.copy() d1._sum(d._all) r1 = r.n1n2n3.copy() r1._sum(r._all) zeta, _ = d1.calculateZeta(r1) return zeta.ravel() print('simple: ') zeta_s3 = cc_zeta([dddc, rrrc]) print(zeta_s3) np.testing.assert_allclose(zeta_s3, zeta_s1.ravel(), rtol=0.05 * tol_factor) print('jackknife:') cov = treecorr.estimate_multi_cov([dddc,rrrc], 'jackknife', cc_zeta) print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_nnns)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_nnns), atol=0.9*tol_factor) print('sample:') cov = treecorr.estimate_multi_cov([dddc,rrrc], 'sample', cc_zeta) print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_nnns)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_nnns), atol=1.2*tol_factor) print('marked:') cov = treecorr.estimate_multi_cov([dddc,rrrc], 'marked_bootstrap', cc_zeta) print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_nnns)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_nnns), atol=1.5*tol_factor) print('bootstrap:') cov = treecorr.estimate_multi_cov([dddc,rrrc], 'bootstrap', cc_zeta) print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_nnns)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_nnns), atol=0.6*tol_factor) # Repeat with a 1-2 cross-correlation print('CrossCorrelation 1-2:') dddc.process(catp, catp) rrrc.process(rand_catp, rand_catp) print('simple: ') zeta_s3 = cc_zeta([dddc, rrrc]) print(zeta_s3) np.testing.assert_allclose(zeta_s3, zeta_s1.ravel(), rtol=0.05 * tol_factor) print('jackknife:') cov = treecorr.estimate_multi_cov([dddc,rrrc], 'jackknife', cc_zeta) print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-np.log(var_nnns)))) np.testing.assert_allclose(np.log(np.diagonal(cov)), np.log(var_nnns), atol=0.9*tol_factor) print('sample:') cov = treecorr.estimate_multi_cov([dddc,rrrc], 'sample', cc_zeta) print(np.diagonal(cov)) print('max log(ratio) = ',np.max(np.abs(np.log(np.diagonal(cov))-
np.log(var_nnns)
numpy.log
#------------------------------------------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]))) print('Mean dist: {}'.format(np.mean(dists_epoch[:, epoch]))) print('Mean mse: {}'.format(np.mean(mses_epoch[:, epoch]))) # Show flippings for a few training samples: plt.figure(figsize=(12, 12)) plt.pcolor(flipped[:300], cmap='Greys') plt.xlabel('Epoch') plt.ylabel('Training sample') plt.show() # Plot metrics on the training data: mean_ious_epoch = np.mean(ious_epoch, axis=0) mean_dists_epoch = np.mean(dists_epoch, axis=0) mean_mses_epoch = np.mean(mses_epoch, axis=0) plt.plot(mean_ious_epoch, label='Mean IoU') # between predicted and assigned true bboxes plt.plot(mean_dists_epoch, label='Mean distance') # relative to image size plt.plot(mean_mses_epoch, label='Mean MSE') plt.annotate(np.round(np.max(mean_ious_epoch), 3), (len(mean_ious_epoch)-1, mean_ious_epoch[-1]+0.03), horizontalalignment='right', color='b') plt.annotate(np.round(np.min(mean_dists_epoch), 3), (len(mean_dists_epoch)-1, mean_dists_epoch[-1]+0.03), horizontalalignment='right', color='g') plt.annotate(np.round(np.min(mean_mses_epoch), 3), (len(mean_mses_epoch)-1, mean_mses_epoch[-1]+0.03), horizontalalignment='right', color='r') plt.ylabel('IoU') plt.xlabel('Epoch') plt.legend() plt.ylim(0, 1) plt.show() # 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 # Show a few images and predicted bounding boxes from the test dataset: plt.figure(figsize=(12, 3)) for i_subplot in range(1, 5): plt.subplot(1, 4, i_subplot) i = np.random.randint(len(test_X)) plt.imshow(test_imgs[i].T, cmap='Greys', interpolation='none', origin='lower', extent=[0, img_size, 0, img_size]) for pred_bbox, exp_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.show() #--------------------------------Multiple rectangles or triangles---------------------------------------------# ## 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 = 16 min_rect_size = 3 max_rect_size = 8 num_objects = 2 # Initialize objects: bboxes = np.zeros((num_imgs, num_objects, 4)) imgs = np.zeros((num_imgs, img_size, img_size)) shapes = np.zeros((num_imgs, num_objects, 1)) # Generate images and bounding boxes: for i_img in range(num_imgs): for i_object in range(num_objects): if np.random.choice([True, False]): width, height = np.random.randint(min_rect_size, max_rect_size, size=2) x = np.random.randint(0, img_size - width) y =
np.random.randint(0, img_size - height)
numpy.random.randint
#! /usr/bin/ python # -*- coding: utf-8 -*- #------------------------------------------------------------------------------ # PROGRAM: worldlines.py #------------------------------------------------------------------------------ # Version 0.11 # 9 July, 2020 # Dr <NAME> # https://patternizer.github.io # patternizer AT gmail DOT com #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ # SETTINGS #------------------------------------------------------------------------------ generate_anyons = True generate_variants = True generate_networkx_edges = True generate_qubits = False generate_erdos_parameter = False generate_erdos_equivalence = False generate_adjacency = False qubit_logic = False plot_branchpoint_table = True plot_networkx_connections = True plot_networkx_non_circular = True plot_networkx_erdos_parameter = False plot_networkx_erdos_equivalence = False plot_networkx_connections_branchpoints = True plot_networkx_connections_dags = True plot_variants = True machine_learning = False write_log = True #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ # IMPORT PYTHON LIBRARIES #------------------------------------------------------------------------------ import numpy as np import pandas as pd import scipy as sp # import math # math.log(N,2) for entropy calculations import random from random import randint from random import randrange # Text Parsing libraries: import re from collections import Counter # Network Graph libraries: import networkx as nx from networkx.algorithms import approximation as aprx # Plotting libraries: import matplotlib import matplotlib.pyplot as plt import matplotlib.cm as cm from matplotlib import colors as mcol from pandas.plotting import register_matplotlib_converters register_matplotlib_converters() import plotly.express as px import plotly.graph_objects as go import plotly.figure_factory as ff from plotly.subplots import make_subplots from skimage import io import glob from PIL import Image # Silence library version notifications import warnings warnings.filterwarnings("ignore", category=UserWarning) # NLP Libraries # ML Libraries # App Deployment Libraries # import dash # import dash_core_components as dcc # import dash_html_components as html # import dash_bootstrap_components as dbc # from dash.dependencies import Input, Output, State # from flask import Flask # import json # import os #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ # METHODS #------------------------------------------------------------------------------ def word_in_line(word, line): """ Check if word is in line word, line - str returns - True if word in line, False if not """ pattern = r'(^|[^\w]){}([^\w]|$)'.format(word) pattern = re.compile(pattern, re.IGNORECASE) matches = re.search(pattern, text) return bool(matches) def discrete_colorscale(values, colors): """ values - categorical values colors - rgb or hex colorcodes for len(values)-1 eeturn - discrete colorscale, tickvals, ticktext """ if len(values) != len(colors)+1: raise ValueError('len(values) should be = len(colors)+1') values = sorted(values) nvalues = [(v-values[0])/(values[-1]-values[0]) for v in values] #normalized values colorscale = [] for k in range(len(colors)): colorscale.extend([[nvalues[k], colors[k]], [nvalues[k+1], colors[k]]]) tickvals = [((values[k]+values[k+1])/2.0) for k in range(len(values)-1)] ticktext = [f'{int(values[k])}' for k in range(len(values)-1)] return colorscale, tickvals, ticktext def rgb2hex(colorin): """ Convert (r,g,b) to hex """ r = int(colorin.split('(')[1].split(')')[0].split(',')[0]) g = int(colorin.split('(')[1].split(')')[0].split(',')[1]) b = int(colorin.split('(')[1].split(')')[0].split(',')[2]) return "#{:02x}{:02x}{:02x}".format(r,g,b) def parse_poem(input_file): """ Text parsing of poem and construction of branchpoint array """ print('parsing poem ...') # Store lines in a list linelist = [] with open (input_file, 'rt') as f: for line in f: if len(line)>1: # ignore empty lines linelist.append(line.strip()) else: continue # Store text as a single string textstr = '' for i in range(len(linelist)): if i < len(linelist) - 1: textstr = textstr + linelist[i] + ' ' else: textstr = textstr + linelist[i] # extract sentences into list # (ignore last entry which is '' due to final full stop) sentencelist = textstr.split('.')[0:-1] # Clean text and lower case all words str = textstr for char in '-.,\n': str = str.replace(char,' ') str = str.lower() wordlist = str.split() # Store unique words in an array uniquewordlist = [] for word in wordlist: if word not in uniquewordlist: uniquewordlist.append(word) # Word frequencies wordfreq = Counter(wordlist).most_common() # --> wordfreq[0][0] = 'the' and wordfreq[0][1] = '13' # Find branchpoints having word frequency > 1 branchpointlist = [] for word in range(len(wordfreq)-1): if wordfreq[word][1] > 1: branchpointlist.append(wordfreq[word][0]) else: continue # Branchpoint index array maxbranches = wordfreq[0][1] branchpointarray = np.zeros((len(branchpointlist), maxbranches), dtype='int') for k in range(len(branchpointlist)): index = [] for i, j in enumerate(wordlist): if j == branchpointlist[k]: index.append(i) branchpointarray[k,0:len(index)] = index # Filter out multiple branchpoint in single line only occurences # using word indices of branchpoints and line start and end indices lineindices = [] wordcount = 0 for i in range(len(linelist)): linelen = len(linelist[i].split()) lineindices.append([i, wordcount, wordcount+linelen-1]) wordcount += linelen mask = [] branchlinearray = [] for i in range(np.size(branchpointarray, axis=0)): # i.e. nbranchpoints branchpointindices = branchpointarray[i,:][branchpointarray[i,:]>0] linecounter = 0 for j in range(len(linelist)): branchpointcounter = 0 for k in range(len(branchpointindices)): if branchpointindices[k] in np.arange(lineindices[j][1],lineindices[j][2]+1): branchpointcounter += 1 branchlinearray.append([j,i,lineindices[j][1],branchpointindices[k],lineindices[j][2]]) if branchpointcounter > 0: linecounter += 1 if linecounter < 2: mask.append(i) a = np.array(branchpointarray) b = branchpointlist for i in range(len(mask)): a = np.delete(a,mask[i]-i,0) b = np.delete(b,mask[i]-i,0) branchpointarray = a branchpointlist = list(b) db = pd.DataFrame(branchpointarray) db.to_csv('branchpointarray.csv', sep=',', index=False, header=False, encoding='utf-8') return textstr, sentencelist, linelist, wordlist, uniquewordlist, wordfreq, branchpointlist, branchpointarray def generate_branchpoint_colormap(wordfreq, nbranchpoints, nwords, branchpointarray): """ Generate colormap using hexcolors for all branchpoints """ print('generating branchpoint_colormap ...') freq = [ wordfreq[i][1] for i in range(len(wordfreq)) ] nlabels = nbranchpoints cmap = px.colors.diverging.Spectral cmap_idx = np.linspace(0,len(cmap)-1, nlabels, dtype=int) colors = [cmap[i] for i in cmap_idx] hexcolors = [ rgb2hex(colors[i]) for i in range(len(colors)) ] branchpoint_colormap = [] for k in range(nwords): branchpoint_colormap.append('lightgrey') for j in range(np.size(branchpointarray, axis=0)): # i.e. nbranchpoints for i in range(np.size(branchpointarray, axis=1)): # i.e. maxfreq branchpoint_colormap[branchpointarray[j,i]] = hexcolors[j] return branchpoint_colormap, hexcolors def compute_networkx_edges(nwords, wordlist, branchpointarray): print('computing_networkx_edges ...') # Construct edgelist, labellist edgelist = [(i,i+1) for i in range(nwords-1)] labellist = [{i : wordlist[i]} for i in range(nwords)] df = pd.DataFrame() G = nx.Graph() G.add_edges_from(edgelist) for node in G.nodes(): G.nodes[node]['label'] = labellist[node] edge_colormap = [] for k in range(nwords-1): edge_colormap.append('lightgrey') for j in range(np.size(branchpointarray, axis=0)): # i.e. nbranchpoints branchpointedges = [] for i in range(np.size(branchpointarray, axis=1)): # i.e. maxfreq branchpointindices = branchpointarray[j,:] connections = branchpointindices[(branchpointindices != branchpointindices[i]) & (branchpointindices > 0)] for k in range(len(connections)): if branchpointindices[i] > 0: branchpointedges.append([branchpointindices[i], connections[k]]) G.add_edges_from(branchpointedges) # for l in range(int(len(branchpointedges)/2)): # NB 2-driectional edges # edge_colormap.append(hexcolors[j]) nedges = len(G.edges) # Generate non-circular form of the networkx graph N = nx.Graph() N.add_edges_from(edgelist) for j in range(np.size(branchpointarray, axis=0)): # i.e. nbranchpoints branchpointedges = [] for i in range(np.size(branchpointarray, axis=1)): # i.e. maxfreq branchpointindices = branchpointarray[j,:] connections = branchpointindices[(branchpointindices != branchpointindices[i]) & (branchpointindices > 0)] for k in range(len(connections)): if branchpointindices[i] > 0: branchpointedges.append([branchpointindices[i], connections[k]]) N.add_edges_from(branchpointedges) N.remove_edges_from(edgelist) N_degrees = [degree for node,degree in dict(N.degree()).items()] # degree of nodes notbranchpoints = [ node for node,degree in dict(N.degree()).items() if degree == 0 ] # each node in circular graph has 2 neighbours at start return nedges, notbranchpoints, G, N def compute_erdos_parameter(nwords, nedges): """ Compute Erdos-Renyi parameter estimate """ print('computing_erdos_parameter ...') edgelist = [(i,i+1) for i in range(nwords-1)] for connectivity in np.linspace(0,1,1000001): random.seed(42) E = nx.erdos_renyi_graph(nwords, connectivity) erdosedges = len(E.edges) if erdosedges == (nedges-len(edgelist)): # print("{0:.6f}".format(connectivity)) # print("{0:.6f}".format(erdosedges)) nerdosedges = len(E.edges) return nerdosedges, connectivity, E # break nerdosedges = len(E.edges) return nerdosedges, connectivity, E def compute_erdos_equivalence(nwords, nedges, N, notbranchpoints): """ Compute Erdos-Renyi equivalence probability """ print('computing_erdos_equivalence ...') # Compare Erdos-Renyi graph edges in reduced networks (branchpoint network) N.remove_nodes_from(notbranchpoints) mapping = { np.array(N.nodes)[i]:i for i in range(len(N.nodes)) } H = nx.relabel_nodes(N,mapping) maxdiff = len(H.edges) iterations = 100000 for i in range(iterations+1): E = nx.erdos_renyi_graph(len(H.nodes), connectivity) diff = H.edges - E.edges if len(diff) < maxdiff: maxdiff = len(diff) commonedges = H.edges - diff pEquivalence = i/iterations Equivalence = E return commonedges, pEquivalence, Equivalence def compute_anyons(linelist, wordlist, branchpointarray): """ Anyon construction: braiding """ print('generating_anyons ...') # Compute start and end word indices for each line of the poem lineindices = [] wordcount = 0 for i in range(len(linelist)): linelen = len(linelist[i].split()) lineindices.append([i, wordcount, wordcount+linelen-1]) wordcount += linelen # For each branchpoint find line index and word indices of line start, branchpoint and line end # branchlinearray: [line, branchpoint, wordstart, wordbranchpoint, wordend] branchlinearray = [] for i in range(np.size(branchpointarray, axis=0)): # i.e. nbranchpoints branchpointindices = branchpointarray[i,:][branchpointarray[i,:]>0] for j in range(len(linelist)): for k in range(len(branchpointindices)): if branchpointindices[k] in np.arange(lineindices[j][1],lineindices[j][2]+1): branchlinearray.append([j,i,lineindices[j][1],branchpointindices[k],lineindices[j][2]]) # Filter out multiple branchpoint in single line only occurences a = np.array(branchlinearray) mask = [] for i in range(len(branchlinearray)-2): if (a[i,0] == a[i+1,0]) & (a[i,1] == a[i+1,1]) & (a[i+2,1]!=a[i,1]): mask.append(i) mask.append(i+1) for i in range(len(mask)): a = np.delete(a,mask[i]-i,0) branchlinearray = a[a[:,0].argsort()] # Filter out start of line and end of line occurring branchpoints a = np.array(branchlinearray) mask = [] for i in range(len(branchlinearray)): if ((a[i,2] == a[i,3]) | (a[i,3] == a[i,4])): mask.append(i) for i in range(len(mask)): a = np.delete(a,mask[i]-i,0) branchlinearray = a[a[:,0].argsort()] # Anyons anyonarray = [] for i in range(len(linelist)): a = branchlinearray[branchlinearray[:,0]==i] if len(a) == 0: break for j in range(len(a)): anyon_pre = wordlist[a[j,2]:a[j,3]+1] b = branchlinearray[(branchlinearray[:,1]==a[j,1]) & (branchlinearray[:,0]!=a[j,0])] ####################################################### # For > 1 swaps, add additional anyon segment code here # + consider case of forward in 'time' constraint # + consider return to start line occurrence ####################################################### if len(b) == 0: break for k in range(len(b)): anyon_post = wordlist[b[k,3]+1:b[k,4]+1] anyon = anyon_pre + anyon_post anyonarray.append( [i, b[k,0], branchpointlist[a[j,1]], anyon, a[j,2], a[j,3], a[j,4] ]) df = pd.DataFrame(anyonarray) df.to_csv('anyonarray.csv', sep=',', index=False, header=False, encoding='utf-8') return anyonarray def compute_variants(linelist, anyonarray): """ Variant construction """ print('generating_variants ...') # generate variants of the poem df = pd.DataFrame(anyonarray) allpoemsidx = [] allpoems = [] allidx = [] nvariants = 0 for i in range(len(linelist)): a = df[df[0]==i] for j in range(len(a)): poem = [] lineidx = [] lines = np.arange(len(linelist)) while len(lines)>0: print(nvariants,i,j) if len(lines) == len(linelist): linestart = a[0].values[j] lineend = a[1].values[j] branchpoint = a[2].values[j] else: b = df[df[0]==lines[0]] linestart = b[0].values[0] lineend = np.setdiff1d( np.unique(b[1].values), lineidx )[0] branchpoint = df[ (df[0]==linestart) & (df[1]==lineend) ][2].values[0] lineidx.append(linestart) lineidx.append(lineend) branchpointstartpre = df[ (df[0]==linestart) & (df[1]==lineend) & (df[2]==branchpoint) ][4].values[0] branchpointstart = df[ (df[0]==linestart) & (df[1]==lineend) & (df[2]==branchpoint) ][5].values[0] branchpointstartpro = df[ (df[0]==linestart) & (df[1]==lineend) & (df[2]==branchpoint) ][6].values[0] branchpointendpre = df[ (df[0]==lineend) & (df[1]==linestart) & (df[2]==branchpoint) ][4].values[0] branchpointend = df[ (df[0]==lineend) & (df[1]==linestart) & (df[2]==branchpoint) ][5].values[0] branchpointendpro = df[ (df[0]==lineend) & (df[1]==linestart) & (df[2]==branchpoint) ][6].values[0] allidx.append([nvariants, linestart, lineend, branchpoint, branchpointstartpre, branchpointstart, branchpointstartpro]) allidx.append([nvariants, lineend, linestart, branchpoint, branchpointendpre, branchpointend, branchpointendpro]) poem.append(df[ (df[0]==linestart) & (df[1]==lineend) & (df[2]==branchpoint) ][3].values[0]) poem.append(df[ (df[0]==lineend) & (df[1]==linestart) & (df[2]==branchpoint) ][3].values[0]) lines = np.setdiff1d(lines,lineidx) nvariants += 1 poemsorted = [] for k in range(len(lineidx)): poemsorted.append(poem[lineidx.index(k)]) allpoems.append(poemsorted) allpoemsidx.append(lineidx) dp = pd.DataFrame(poemsorted) dp.to_csv('poem'+'_'+"{0:.0f}".format(nvariants-1).zfill(3)+'.csv', sep=',', index=False, header=False, encoding='utf-8') di = pd.DataFrame(allpoemsidx) di.to_csv('poem_allidx.csv', sep=',', index=False, header=False, encoding='utf-8') da = pd.DataFrame(allpoems) da.to_csv('poem_all.csv', sep=',', index=False, header=False, encoding='utf-8') dl = pd.DataFrame(allidx) dl.to_csv('allidx.csv', sep=',', index=False, header=False, encoding='utf-8') return nvariants, allpoemsidx, allpoems, allidx def generate_qubits(): """ Qubit contruction """ print('generating_qubits ...') def qubit_logic(): """ Apply gates to Bell states """ print('applying logic gates ...') def machine_learning(): """ Feature extraction """ print('extracting features ...') #------------------------------------------------------------------------------ #------------------------------------------------------------------------------ # LOAD POEM #------------------------------------------------------------------------------ """ Poem to generate quantum variants from """ #input_file = 'poem.txt' input_file = 'poem-v1.txt' textstr, sentencelist, linelist, wordlist, uniquewordlist, wordfreq, branchpointlist, branchpointarray = parse_poem(input_file) # Counts nsentences = len(sentencelist) # --> 4 nlines = len(linelist) # --> 8 nwords = len(wordlist) # --> 98 nunique = len(uniquewordlist) # --> 59 nbranchpoints = len(branchpointlist) # --> 20 if generate_networkx_edges == True: nedges, notbranchpoints, G, N = compute_networkx_edges(nwords, wordlist, branchpointarray) if generate_anyons == True: anyonarray = compute_anyons(linelist, wordlist, branchpointarray) if generate_variants == True: nvariants, allpoemsidx, allpoems, allidx = compute_variants(linelist, anyonarray) if generate_qubits == True: print('generating_qubits ...') if generate_erdos_parameter == True: nerdosedges, connectivity, E = compute_erdos_parameter(nwords, nedges) if generate_erdos_equivalence == True: commonedges, pEquivalence, Equivalence = compute_erdos_equivalence(nwords, nedges, N, notbranchpoints) if qubit_logic == True: print('applying logic gates ...') if machine_learning == True: print('extracting features ...') # ----------------------------------------------------------------------------- branchpoint_colormap, hexcolors = generate_branchpoint_colormap(wordfreq, nbranchpoints, nwords, branchpointarray) # ----------------------------------------------------------------------------- if plot_branchpoint_table == True: print('plotting_branchpoint_table ...') fig, ax = plt.subplots(figsize=(15,10)) plt.plot(np.arange(0,len(wordlist)), np.zeros(len(wordlist))) for k in range(len(branchpointlist)): plt.plot(np.arange(0,len(wordlist)), np.ones(len(wordlist))*k, color='black') a = branchpointarray[k,:] vals = a[a>0] plt.scatter(vals, np.ones(len(vals))*k, label=branchpointlist[k], s=100, facecolors=hexcolors[k], edgecolors='black') xticks = np.arange(0, len(wordlist)+0, step=10) xlabels = np.array(np.arange(0, len(wordlist), step=10).astype('str')) yticks = np.arange(0, len(branchpointlist), step=1) ylabels = np.array(np.arange(0, len(branchpointlist), step=1).astype('str')) plt.xticks(ticks=xticks, labels=xlabels) # Set label locations plt.yticks(ticks=yticks, labels=ylabels) # Set label locations plt.xticks(fontsize=20) plt.yticks(fontsize=20) plt.xlabel('word n in text', fontsize=20) plt.ylabel('branchpoint k in text (>1 connection)', fontsize=20) plt.title('Branch Analysis Plot', fontsize=20) plt.gca().invert_yaxis() box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * 0.8, box.height]) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=12) plt.savefig('branchplot.png') plt.close(fig) if plot_networkx_connections == True: print('plotting_networkx_connections ...') fig, ax = plt.subplots(figsize=(15,10)) nx.draw_circular(G, node_color=branchpoint_colormap, node_size=300, linewidths=0.5, font_size=12, font_weight='normal', with_labels=True) plt.title('Networkx (circularly connected): N(edges)=' + "{0:.0f}".format(len(G.edges)), fontsize=20) plt.savefig('networkx.png') plt.close(fig) if plot_networkx_non_circular == True: print('plotting_networkx_non_circular ...') fig, ax = plt.subplots(figsize=(15,10)) nx.draw_circular(N, node_color=branchpoint_colormap, node_size=300, linewidths=0.5, font_size=12, font_weight='normal', with_labels=True) plt.title('Networkx (non-circularly connected): N(edges)=' + "{0:.0f}".format(len(N.edges)), fontsize=20) plt.savefig('networkx_non_circular.png') if plot_networkx_erdos_parameter == True: print('plotting_networkx_erdos ...') fig, ax = plt.subplots(figsize=(15,10)) nx.draw_circular(E, node_color=branchpoint_colormap, node_size=300, linewidths=0.5, font_size=12, font_weight='normal', with_labels=True) plt.title('Erdős-Rényi Model: p=' + "{0:.6f}".format(connectivity) + ', N(edges)=' + "{0:.0f}".format(nerdosedges), fontsize=20) plt.savefig('networkx_erdos.png') plt.close(fig) if plot_networkx_erdos_equivalence == True: print('plotting_networkx_erdos_equivalence ...') fig, ax = plt.subplots(figsize=(15,10)) nx.draw_circular(Eequivalence, node_color='lightgrey', node_size=300, linewidths=0.5, font_size=12, font_weight='normal', with_labels=True) plt.title('Erdős-Rényi Model (equivalent): N(common edges)=' + "{0:.0f}".format(len(N.edges)-len(diff)), fontsize=20) plt.savefig('networkx_erdos_equivalence.png') if plot_variants == True: print('plotting_variants ...') di = pd.DataFrame(allpoemsidx) da = pd.DataFrame(allpoems) dl = pd.DataFrame(allidx) for i in range(nvariants): connectorstart = [] connectorend = [] fig, ax = plt.subplots(figsize=(15,10)) for k in range(len(linelist)): branchpoint = dl[(dl[0]==i)&(dl[1]==k)][3].values[0] linestart = dl[(dl[0]==i)&(dl[1]==k)][1].values[0] lineend = dl[(dl[0]==i)&(dl[1]==k)][2].values[0] plt.scatter(np.arange(0,len(linelist[k].split())), np.ones(len(linelist[k].split()))*k, color='black') if linestart < lineend: x1 =
np.arange(0, dl[(dl[0]==i)&(dl[1]==k)][5].values[0] - dl[(dl[0]==i)&(dl[1]==k)][4].values[0]+1)
numpy.arange
import glob import numpy as np import pandas as pd from shapely.geometry import LineString,MultiLineString,Point,MultiPoint from shapely.ops import linemerge import pyproj from sklearn.ensemble import RandomForestClassifier,ExtraTreesClassifier from sklearn.preprocessing import StandardScaler from sklearn.neighbors import KNeighborsClassifier from sklearn.ensemble import VotingClassifier from sklearn.svm import SVC import xgboost from tqdm import tqdm from sklearn.model_selection import cross_val_score from sklearn.model_selection import cross_val_predict from sklearn.metrics import confusion_matrix,accuracy_score import pickle import os import argparse
np.random.seed(10)
numpy.random.seed
'''A module for field''' from typing import Optional, List, Union, Iterator, Tuple, Any, Dict from itertools import chain import logging import hashlib import numpy as np from .._utils import trim_before_target, chain_sessions, restore_sessions, is_build_private_docs from .._utils.metaclass import DocStringInheritor, LoadClassInterface, copy_func, copy_property from .._utils.unordered_hash import UnorderedSha256, dumps from .tokenizer import SimpleTokenizer, Tokenizer, PretrainedTokenizer from .vocab import Vocab, GeneralVocab, PretrainedVocab, SimpleVocab from .context import FieldContext RawSentenceType = str TokenizedSentenceType = List[str] RawSessionType = List[RawSentenceType] TokenizedSessionType = List[TokenizedSentenceType] class Field(LoadClassInterface, metaclass=DocStringInheritor): '''A base class of data field, which specify the format of the dataset. See :ref:`Field<field_ref>` and :ref:`building a dataloader of customized task<customized_tasks_ref>` for usages. Notice :class:`Field` object may be shared between different fields, data sets or dataloader. Thus it only defines settings and do NOT stores data. ''' NOT_SPECIFIED_DOCS = r''' If any argument is not specified, the value will be first retrieved from :class:`FieldContext`. If still ``None``, default value will be used. ''' if is_build_private_docs(): __doc__ += r"""The data is exactly stored in :class:`_FieldContent`.""" DEFAULT_VOCAB_FROM_MAPPINGS = { "train": "train", "training": "train", "dev": "test", "development": "test", "valid": "test", "validation": "test", "test": "test", "evaluation": "test" } '''Dict[str, str]: Infer the set type (train, test, or extra) from the set name. For example, ``DEFAULT_VOCAB_FROM_MAPPINGS["dev"] == "test"`` means that the words from the "dev" set is used for test. ''' def get_vocab(self) -> Optional[Vocab]: '''Get :class:`Vocab` object for the field. ``None`` if the field do not have a :class:`Vocab`. ''' return None def get_tokenizer(self) -> Optional[Tokenizer]: '''Get :class:`Tokenizer` object for the field. ``None`` if the field do not have a :class:`Tokenizer`. ''' return None def _create(self, set_name: str) -> "_FieldContent": '''Create a :class:`_FieldContent` to store data which have been read. Arguments: set_name (str): specify the set name for the :class:`_FieldContent`, which may affect the vocab type. ''' raise NotImplementedError def _get_setting_hash(self, vocabs) -> str: '''Get setting hash for the field. ``vocabs`` are provided by :class:`LanguageProcessing`. This function only encode index of vocab, and other settings. It only encode index because encode the setting hash of vocabs cannot explain whether a :class:`Vocab` is shared between different vocabs or not. Arguments: vocabs (list): list of :class:`Vocab`. ''' raise NotImplementedError _GET_BATCH_DATA_DOCSTRING = '''data (Any): the data stored in dataloader.''' if is_build_private_docs(): _GET_BATCH_DATA_DOCSTRING = "data (Any): the data returned by :meth:`_FieldContent.get_data`." _GET_BATCH_RETURN_VALUE = '' _GET_BATCH_EXAMPLE = '' def get_batch(self, name: str, data: Dict[str, Any], indexes: List[int]) -> Dict[str, Any]: '''Invoked by :meth:`LanguageProcessing.get_batch`, return the batched data specified by this field. This function is for INTERNAL USE only, but it shows the data format of the returned batch. {_GET_BATCH_RETURN_VALUE} Arguments: name (str): name of the field. {_GET_BATCH_DATA_DOCSTRING} indexes (List[int]): the indexes of the data in this batch {_GET_BATCH_EXAMPLE} ''' raise NotImplementedError class _FieldContent(metaclass=DocStringInheritor): '''Store the content data of a field. Different from :class:`Field`, it won't be shared between fields or dataloader, and it can save data. ''' def __init__(self): self._original_data: List[Any] = [] self._raw_data_hash: str self._data_hash: str _GET_NEXT_ARG = r""" dataset (Iterator[str]): An iterator of the data file content. Generally, each element is a string, that ends with '\n'. """ def _get_next(self, dataset: Iterator[str]) -> Tuple[Any, int]: '''Read the next data from ``dataset`` and returns a 2-tuple (the data, and the number of elements it read from `dataset`). Arguments:{_GET_NEXT_ARG} ''' raise NotImplementedError def read_next(self, dataset: Iterator[str]) -> int: '''Read the next element from ``dataloader`` and store the elements. Returns the number of lines read. Arguments: dataset (Iterator[str]): An iterator of the data file. ''' if not isinstance(self._original_data, list): raise RuntimeError("read_next must be called before get_data") sent, lines = self._get_next(dataset) if lines != 0: self._original_data.append(sent) return lines def process_before_vocab(self): '''This function is called after all elements read, but before building vocabulary. ''' raise NotImplementedError def get_data_number(self) -> int: '''Get the number of elements in this field. ''' return len(self._original_data) def get_data(self) -> Any: '''Get the data, which will be stored in the :class:`LanguageProcessing`. ''' raise NotImplementedError def get_raw_data_hash(self) -> str: '''Return the raw data hash of this field content. ''' return self._raw_data_hash def get_data_hash(self) -> str: '''Return the data hash of this field content. ''' return self._data_hash class _SentenceContent(_FieldContent): '''Store the content data of :class:`Sentence` field. Different from :class:`Field`, it won't be shared between fields or dataloader, and it can save data. Arguments: field (Sentence): The corresponding field of this content. vocab_from (str): The type of vocab, must be one of ["train", "test", "extra", "default"] ''' def __init__(self, field: "Sentence", vocab_from: str): self.field = field self.vocab_from = vocab_from self._tmp_tokenized_data: Any = None super().__init__() def _get_next(self, dataset: Iterator[str]) -> Tuple[str, int]: """read the next sentence and returns a 2-tuple (the sentence and number of elements it reads from `dataset`). Note that it may raise StopIteration. Arguments:{_FieldContent._GET_NEXT_ARG} Examples: >>> dataset = iter(["I love NLP.\\n", "Yes I do\\n", "I love deep learning\\n"]) >>> field_content = _SentenceContent("Sentence", "test") >>> field_content._get_next(dataset) "I love NLP", 1 >>> field_content._get_next(dataset) "Yes I do", 1 >>> field_content._get_next(dataset) "I love deep learning", 1 """ return next(dataset).rstrip(), 1 def process_before_vocab(self): raw_data_hash = UnorderedSha256() for data in self._original_data: raw_data_hash.update_data(dumps(data)) self._raw_data_hash = raw_data_hash.hexdigest() self._tmp_tokenized_data = tokenized_sents = self.field.tokenize_sentences(self._original_data) data_hash = UnorderedSha256() for tokenized_sent in tokenized_sents: data_hash.update_data(dumps(tokenized_sent)) self._data_hash = data_hash.hexdigest() self.field.get_vocab().add_tokens(list(chain(*tokenized_sents)), self.vocab_from) def get_data(self): # allvocabs id_data = self.field.process_sentences(self._tmp_tokenized_data) return {"id": id_data, "str": self._original_data} if is_build_private_docs(): _GET_BATCH_DATA_DOCSTRING = 'data (Dict[str, Any]): the object returned by :meth:`_SentenceContent.get_data`. '\ "data['str'] is raw sentences. data['id'] is the ids of tokenized sentences." class _InfiniteLength: """Infinite length. A special value for `max_sent_length` and `max_turn_length`, which means that the sent_length and turn_length is unlimited. """ __instance = None def __new__(cls, *args, **kwargs): # Singleton if cls.__instance is None: obj = cls.__instance = object.__new__(cls) else: obj = cls.__instance return obj def __repr__(self): return 'INFINITE_LENGTH' __str__ = __repr__ class Sentence(Field): '''Bases: :class:`.dataloader.Field` A field for sentence. This class is a virtual class and the base of :class:`Sentence`, :class:`SentenceGPT2` and :class:`SentenceBERT`. {INIT_DOCSTRING} {SENTENCE_INPUT_FORMAT} ''' INIT_DOCSTRING = r''' {Field.NOT_SPECIFIED_DOCS} Arguments: {Sentence.TOKENIZER_DOCS} {Sentence.TOKENIZER_DEFAULT} {Sentence.VOCAB_DOCS} {Sentence.VOCAB_DEFAULT} {Sentence.VOCAB_FROM_MAPPINGS_DOCS} {Sentence.VOCAB_FROM_MAPPINGS_DEFAULT} {Sentence.MAX_SENT_LENGTH_DOCS} {Sentence.MAX_SENT_LENGTH_DEFAULT} {Sentence.CONVERT_TO_LOWER_LETTER_DOCS} {Sentence.CONVERT_TO_LOWER_LETTER_DEFAULT} ''' SENTENCE_INPUT_FORMAT = r""" Input Formats This field read one line of sentence per sample. """ TOKENIZER_DOCS = r""" tokenizer (:class:`Tokenizer`, str, optional): How to tokenize sentence. if ``str``, see :ref:`tokenizer<tokenizer_ref>` for possible value.""" TOKENIZER_DEFAULT = r'''No default value, ``KeyError`` will be raised.''' VOCAB_DOCS = r""" vocab (:class:`Vocab`, optional):The vocabulary used for this field. Sharing this object between fields can build vocabulary together. """ VOCAB_DEFAULT = r'''No default value, ``KeyError`` will be raised.''' VOCAB_FROM_MAPPINGS_DOCS = r""" vocab_from_mappings (Dict[str, str], optional): Infer the set type (train, test, or extra) from the set name. For example, ``DEFAULT_VOCAB_FROM_MAPPINGS["dev"] == "test"`` means that the words from the "dev" set is used for test.""" VOCAB_FROM_MAPPINGS_DEFAULT = r"""Default: See :ref:`the table<vocab_from_ref>` for default value.""" MAX_SENT_LENGTH_DOCS = r''' max_sent_length (int, _InfiniteLength, optional): All sentences longer than ``max_sent_length`` will be shortened to first ``max_sent_length`` tokens. If it's ``None`` or ``Sentence.INFINITE_LENGTH``, sentences won't be shortened no matter how long they are.''' MAX_SENT_LENGTH_DEFAULT = r'''Default: ``None``.''' CONVERT_TO_LOWER_LETTER_DOCS = r''' convert_to_lower_letter (bool, optional): Whether convert all the tokens to lower case after tokenization.''' CONVERT_TO_LOWER_LETTER_DEFAULT = r'''Default: ``False``.''' INFINITE_LENGTH = _InfiniteLength() def __init__(self, tokenizer: Union[None, Tokenizer, str] = None, \ vocab: Optional[Vocab] = None, \ vocab_from_mappings: Optional[Dict[str, str]] = None, \ max_sent_length: Union[int, _InfiniteLength, None] = None, \ convert_to_lower_letter: Optional[bool] = None): if self.__class__.__name__ == "Sentence": raise NotImplementedError("Sentence is an abstract class, use SentenceDefault instead.") with FieldContext.set_parameters(\ tokenizer=tokenizer,\ vocab=vocab,\ vocab_from_mappings=vocab_from_mappings,\ max_sent_length=max_sent_length,\ convert_to_lower_letter=convert_to_lower_letter): filled_tokenizer: Union[Tokenizer, str] = FieldContext.get("tokenizer", no_default=True) self.vocab: Vocab = FieldContext.get("vocab", no_default=True) self.vocab_from_mappings: Dict[str, str] = FieldContext.get("vocab_from_mappings", Field.DEFAULT_VOCAB_FROM_MAPPINGS) self.max_sent_length: int = FieldContext.get("max_sent_length", None) self.convert_to_lower_letter: bool = FieldContext.get("convert_to_lower_letter", False) if self.max_sent_length == Sentence.INFINITE_LENGTH: self.max_sent_length = None # max_sent_length is used for slice. So, None means that sent_length is unlimited. self.tokenizer: Tokenizer if isinstance(filled_tokenizer, str): self.tokenizer = SimpleTokenizer(filled_tokenizer) elif isinstance(filled_tokenizer, Tokenizer): self.tokenizer = filled_tokenizer else: raise TypeError("Unknown tokenizer type") def _create(self, set_name) -> _SentenceContent: try: return _SentenceContent(self, self.vocab_from_mappings[set_name]) except KeyError: raise KeyError("Unknown set_name %s, do not specify in the vocab_from_mappings" % set_name) from None @classmethod def get_pretrained_class(cls, pretrained): return { "gpt2": SentenceGPT2, "bert": SentenceBERT }[pretrained] def get_tokenizer(self): return self.tokenizer def get_vocab(self): return self.vocab def _get_setting_hash(self, vocabs) -> str: return hashlib.sha256(dumps( [self.__class__.__name__, \ #tokenizer_id, \ self.tokenizer.get_setting_hash(), \ vocabs.index(self.vocab), \ #self.vocab.get_setting_hash(), \ self.vocab_from_mappings, \ self.max_sent_length, \ self.convert_to_lower_letter \ ])).hexdigest() _SENTENCE_MORE_DOCSTRING = "" def tokenize_sentences(self, sentences: List[str]) -> List[List[str]]: '''Tokenize ``sentences``. {_SENTENCE_MORE_DOCSTRING} * Convert tokens to lower case if ``self.convert_to_lower_letter`` is ``True``. Arguments: sentences (List[str]): The list of sentence to be tokenized. ''' tokenized_sentences = self.tokenizer.tokenize_sentences(sentences) if self.convert_to_lower_letter: return [[token.lower() for token in tokens] for tokens in tokenized_sentences] else: return tokenized_sentences def tokenize(self, sentence: str) -> List[str]: '''Tokenize ``sentence``. {_SENTENCE_MORE_DOCSTRING} * Convert tokens to lower case if ``self.convert_to_lower_letter`` is ``True``. Arguments: sentence (str): The sentence to be tokenized. ''' tokenized_sentence = self.tokenizer.tokenize(sentence) if self.convert_to_lower_letter: return [token.lower() for token in tokenized_sentence] else: return tokenized_sentence CONVERT_TO_ID_ARG = r""" add_special (bool, optional): If ``True``, special tokens (e.g. ``go``, ``eos``) are added. Default: ``False``. only_frequent_word (bool, optional): If ``True``, rare vocabs will be replaced by ``unk_id``. Default: ``False``.""" def convert_tokens_to_ids(self, tokens: List[str], add_special=False, only_frequent_word=False) -> List[int]: '''Convert list of tokens to list of ids. {_SENTENCE_MORE_DOCSTRING} Arguments: tokens (List[str]): The tokens to be converted.{CONVERT_TO_ID_ARG} ''' ids = self.vocab.convert_tokens_to_ids(tokens, only_frequent_word=only_frequent_word) if add_special: ids = self.add_special_to_ids(ids) return ids CONVERT_FROM_ID_ARG = r""" remove_special (bool, optional): If ``True``, detect and try to do a reverse operation of ``add_special`` in :meth:`convert_tokens_to_ids`. It will not remove ``unk`` or special tokens in the middle of sentences. Default: ``True``. trim (bool, optional): If ``True``, use :meth:`trim_in_ids` to remove trailing ``pad`` and ``eos``. Default: ``True``.""" def convert_ids_to_tokens(self, ids: List[int], remove_special=True, trim=True) -> List[str]: '''Convert list of ids to list of tokens. {_SENTENCE_MORE_DOCSTRING} Arguments: ids (List[int]): The ids to be converted.{CONVERT_FROM_ID_ARG} ''' return self.vocab.convert_ids_to_tokens(\ self.remove_special_in_ids(ids, remove_special=remove_special, trim=trim)) def convert_ids_to_sentence(self, ids: List[int], remove_special=True, trim=True) -> str: '''Convert list of tokens to a sentence. {_SENTENCE_MORE_DOCSTRING} Arguments: ids (List[int]): The ids to be converted.{CONVERT_FROM_ID_ARG} ''' tokens = self.convert_ids_to_tokens(ids, remove_special=remove_special, trim=trim) return self.tokenizer.convert_tokens_to_sentence(tokens) def convert_sentence_to_ids(self, sentence: str, add_special=False, only_frequent_word=False) -> List[int]: '''Convert a sentence to a list of ids. {_SENTENCE_MORE_DOCSTRING} Arguments: sentence (str): The sentence to be converted.{CONVERT_TO_ID_ARG} ''' return self.process_sentences([sentence], add_special=add_special, \ only_frequent_word=only_frequent_word, cut=False)[0] def add_special_to_ids(self, ids: List[int]) -> List[int]: '''Add special tokens, such as ``go_id`` or ``eos_id`` to the input ``ids``. {_SENTENCE_MORE_DOCSTRING} Arguments: ids (List[int]): The input ids. ''' raise NotImplementedError REMOVE_SPECIAL_ARG = CONVERT_FROM_ID_ARG.replace(":meth:`convert_tokens_to_ids()`", ":meth:`add_special_to_ids`") def remove_special_in_ids(self, ids: List[int], remove_special=True, trim=True) -> List[int]: '''Remove special ids in input `ids`. {_SENTENCE_MORE_DOCSTRING} Arguments: ids (List[int]): Input ids.{CONVERT_FROM_ID_ARG} ''' raise NotImplementedError PROCESS_ARG = r""" add_special (bool, optional): If ``True``, special tokens (e.g. ``go``, ``eos``) are added. Default: ``True``. only_frequent_word (bool, optional): If ``True``, rare vocabs will be replaced by ``unk_id``. Default: ``False``.""" def process_sentences(self, sentences: Union[List[str], List[List[str]]], add_special=True, only_frequent_word=False, cut=True) -> List[List[int]]: '''Process input sentences. {_SENTENCE_MORE_DOCSTRING} * If sentences haven't been tokenized, tokenize them by invoking :meth:`Sentence.tokenize_sentences`. * Then, convert the list of tokens to a list of ids. * If ``self.max_sent_length`` is not ``None`` and ``cut`` is ``True``, sentences, whose length are more than ``self.max_sent_length``, are shorten to first ``self.max_sent_length`` tokens. Arguments: sentences (List[str], List[List[str]]): `sentences` can be a list of sentences or a list of lists of tokens. {PROCESS_ARG} cut (bool, optional): Whether to cut sentences with too many tokens. Default: ``True``. ''' # sentences: : Union[List[str], List[List[str]]] if not sentences: raise ValueError("sentences must not be empty.") # list of sentences if isinstance(sentences[0], str): sentences = self.tokenize_sentences(sentences) elif not sentences[0]: raise ValueError("sentences[0] must not be an empty string.") # list of list of str sentences = [self.convert_tokens_to_ids(tokens, add_special=add_special, only_frequent_word=only_frequent_word) for tokens in sentences] # list of list of id if cut and self.max_sent_length is not None: before_lengths = [len(sentence) for sentence in sentences] sentences = [sentence[:self.max_sent_length] for sentence in sentences] after_lengths = [len(sentence) for sentence in sentences] if len(sentences) > 1: logging.info("max length before cut: %d, cut percent: %.2f%%" % ( max(before_lengths), (sum(before_lengths) - sum(after_lengths)) / sum(before_lengths) * 100) ) # sentence cut return sentences if is_build_private_docs(): _GET_BATCH_DATA_DOCSTRING = '''data (Any): the object returned by :meth:`_SentenceContent.get_data`''' def get_batch(self, name: str, data: Dict[str, Any], indexes: List[int]) -> Dict[str, Any]: raise NotImplementedError def trim_in_ids(self, ids: List[int]) -> List[int]: '''Find the first special token indicating the sentence is over and remove all the tokens after it (included). Then remove all trailing ``pad``. {_SENTENCE_MORE_DOCSTRING} Arguments: ids (List[int]): The input ids. ''' raise NotImplementedError def _remove_special_in_ids(self, ids: List[int], go_id: int, eos_id: int) -> List[int]: '''Try to remove special token (``go_id`` at the beginning and the ``eos_id`` at the end) in ``ids``. {_SENTENCE_MORE_DOCSTRING} Arguments: ids (List[int]): the original ids go_id (int): go token eos_id (int): eos token ''' if not ids: return ids st, ed = 0, None if ids[0] == go_id: st = 1 if ids[-1] == eos_id: ed = -1 return ids[st:ed] # copy some functions from vocab _VOCAB_MORE_DOCSTRING = '''It calls the method with the identical name of the :class:`Vocab` instance, \ from ``self.get_vocab()``.''' frequent_vocab_size = copy_property(get_vocab, Vocab, "frequent_vocab_size") all_vocab_size = copy_property(get_vocab, Vocab, "all_vocab_size") frequent_vocab_list = copy_property(get_vocab, Vocab, "frequent_vocab_list") all_vocab_list = copy_property(get_vocab, Vocab, "all_vocab_list") get_special_tokens_mapping = copy_func(get_vocab, Vocab, "get_special_tokens_mapping") get_special_tokens_id = copy_func(get_vocab, Vocab, "get_special_tokens_id") pad_id = copy_property(get_vocab, Vocab, "pad_id") unk_id = copy_property(get_vocab, Vocab, "unk_id") go_id = copy_property(get_vocab, Vocab, "go_id") eos_id = copy_property(get_vocab, Vocab, "eos_id") class SentenceDefault(Sentence): '''Bases: :class:`.dataloader.Sentence`, :class:`.dataloader.Field` A common use field for sentence. {INIT_DOCSTRING} {SENTENCE_INPUT_FORMAT} ''' INIT_DOCSTRING = Sentence.INIT_DOCSTRING.replace(":class:Vocab", ":class:GeneralVocab") def __init__(self, tokenizer: Union[None, Tokenizer, str] = None, \ vocab: Optional[Vocab] = None, \ vocab_from_mappings: Optional[Dict[str, str]] = None, \ max_sent_length: Union[int, None, _InfiniteLength] = None, \ convert_to_lower_letter: Optional[bool] = None): super().__init__(tokenizer=tokenizer, \ vocab=vocab, vocab_from_mappings=vocab_from_mappings, max_sent_length=max_sent_length, \ convert_to_lower_letter=convert_to_lower_letter) self.vocab: Vocab def add_special_to_ids(self, ids: List[int]) -> List[int]: return [self.vocab.go_id] + ids + [self.vocab.eos_id] def remove_special_in_ids(self, ids: List[int], remove_special=True, trim=True) -> List[int]: if trim: ids = self.trim_in_ids(ids) if remove_special: ids = self._remove_special_in_ids(ids, self.vocab.go_id, self.vocab.eos_id) return ids _GET_BATCH_RETURN_VALUE = """ The function will return a dict, containing: * ``FIELDNAME`` (``np.ndarray[batch_size, max_sent_length_in_batch]``): Padded sentences in id formats. It only contains frequent vocabs, and rare words are replaced by ``unk_id``. * ``FIELDNAME_allvocabs`` (``np.ndarray[batch_size, max_sent_length_in_batch]``): Padded sentences in id formats. It contains frequent vocabs and rare vocabs. * ``FIELDNAME_length`` (``np.ndarray[batch_size]``): The length of sentences. * ``FIELDNAME_str`` (``List[str]``): The raw sentences. where * ``FIELDNAME`` is the name of the field. * ``batch_size`` is ``len(indexes)``. * ``max_sent_length_in_batch`` is the maximum length of sentences in the batch. """ _GET_BATCH_EXAMPLE = """ Examples: >>> # all_vocab_list = ["<pad>", "<unk>", "<go>", "<eos>", "Life", "is", "short", ".", >>> # "PHP", "the", "best", "language", "in", "world"] >>> # frequent_vocab_size = 11 >>> # frequent_vocab_list = ["<pad>", "<unk>", "<go>", "<eos>", "Life", "is", "short", ".", >>> # "PHP", "the", "best"] >>> field.get_batch('sent', data, [0, 1]) { "sent": numpy.array([ [2, 4, 5, 6, 7, 3, 0, 0, 0, 0, 0], # <go> Life is short . <eos> <pad> <pad> <pad> <pad> <pad> [2, 8, 5, 9, 10, 1, 1, 9, 1, 7, 3], # <go> PHP is the best <unk> <unk> the <unk> . <eos> ]), "sent_length": numpy.array([6, 11]), # length of sentences "sent_allvocabs": numpy.array([ [2, 4, 5, 6, 7, 3, 0, 0, 0, 0, 0], # <go> Life is short . <eos> <pad> <pad> <pad> <pad> <pad> [2, 8, 5, 9, 10, 11, 12, 9, 13, 7, 3], # <go> PHP is the best language in the world . <eos> ]), "sent_str": [ "Life is short.", "PHP is the best language in the world.", ], } """ def get_batch(self, name: str, data: Dict[str, Any], indexes: List[int]) -> Dict[str, Any]: if not isinstance(self.vocab, GeneralVocab): raise RuntimeError("Subclass must override get_batch if self.vocab is not a GeneralVocab.") res: Dict[str, Any] = {} data_id, data_str = data["id"], data["str"] batch_size = len(indexes) res[name + "_length"] = np.array([len(data_id[i]) for i in indexes], dtype=int) res_sent = res[name] = np.ones((batch_size, np.max(res[name + "_length"])), dtype=int) * self.vocab.pad_id for i, j in enumerate(indexes): sent = data_id[j] res_sent[i, :len(sent)] = sent res[name + "_allvocabs"] = res_sent.copy() res_sent[res_sent >= self.vocab.frequent_vocab_size] = self.vocab.unk_id res[name + "_str"] = [data_str[i] for i in indexes] return res def trim_in_ids(self, ids: List[int]) -> List[int]: ids = trim_before_target(list(ids), self.vocab.eos_id) idx = len(ids) while idx > 0 and ids[idx - 1] == self.vocab.pad_id: idx -= 1 ids = ids[:idx] return ids class SentenceGPT2(Sentence): '''Bases: :class:`.dataloader.Sentence`, :class:`.dataloader.Field` A field for sentence in the format of GPT2. {INIT_DOCSTRING} {SENTENCE_INPUT_FORMAT} ''' INIT_DOCSTRING = Sentence.INIT_DOCSTRING.replace(":class:Vocab", ":class:PretrainedVocab") def __init__(self, tokenizer: Union[None, PretrainedTokenizer] = None, \ vocab: Optional[PretrainedVocab] = None, \ vocab_from_mappings: Optional[Dict[str, str]] = None, \ max_sent_length: Union[int, None, _InfiniteLength] = None, \ convert_to_lower_letter: Optional[bool] = None): super().__init__(tokenizer=tokenizer, \ vocab=vocab, vocab_from_mappings=vocab_from_mappings,\ max_sent_length=max_sent_length, \ convert_to_lower_letter=convert_to_lower_letter) if not isinstance(self.tokenizer, PretrainedTokenizer) or self.tokenizer.get_tokenizer_class() != "GPT2Tokenizer": raise ValueError("You have to specify a pretrained tokenizer compatible with gpt2") self.inner_tokenizer = self.tokenizer.tokenizer if not isinstance(self.vocab, PretrainedVocab): raise ValueError("You have to specify a PretrainedVocab for SentenceGPT2 field") self.vocab: PretrainedVocab def add_special_to_ids(self, ids: List[int]) -> List[int]: return [self.vocab.eos_id] + ids + [self.vocab.eos_id] def remove_special_in_ids(self, ids: List[int], remove_special=True, trim=True) -> List[int]: if trim: ids = self.trim_in_ids(ids) if remove_special: ids = self._remove_special_in_ids(ids, self.vocab.eos_id, self.vocab.eos_id) return ids _GET_BATCH_RETURN_VALUE = SentenceDefault._GET_BATCH_RETURN_VALUE _GET_BATCH_EXAMPLE = """ Examples: >>> # This example is based on GPT2Tokenizer. The vocab files are in ./tests/dummy_gpt2vocab. >>> # field.eos_id = 413 # <|endoftext|>, also used for <pad>, <unk>, <go> >>> field.get_batch('sent', data, [0, 2]) { "sent": numpy.array([ [413, 6, 134, 321, 407, 107, 157, 121, 372, 201, 402, 105, 413, 413, 413, 413], # ['<|endoftext|>', 'A', 'Ġbicycle', 'Ġreplica', 'Ġwith', 'Ġa', 'Ġclock', 'Ġas', 'Ġthe', # 'Ġfront', 'Ġwheel', 'Ġ.', '<|endoftext|>', '<|endoftext|>', '<|endoftext|>', '<|endoftext|>'] [413, 6, 149, 370, 330, 384, 126, 298, 236, 130, 107, 255, 298, 149, 105, 413], # ['<|endoftext|>', 'A', 'Ġcar', 'Ġthat', 'Ġseems', 'Ġto', 'Ġbe', 'Ġparked', 'Ġillegally', # 'Ġbehind', 'Ġa', 'Ġlegally', 'Ġparked', 'Ġcar', 'Ġ.', '<|endoftext|>'] ]), "sent_length": numpy.array([13, 16]), # length of sentences "sent_allvocabs": numpy.array([ [413, 6, 134, 321, 407, 107, 157, 121, 372, 201, 402, 105, 413, 413, 413, 413], # ['<|endoftext|>', 'A', 'Ġbicycle', 'Ġreplica', 'Ġwith', 'Ġa', 'Ġclock', 'Ġas', 'Ġthe', # 'Ġfront', 'Ġwheel', 'Ġ.', '<|endoftext|>', '<|endoftext|>', '<|endoftext|>', '<|endoftext|>'] [413, 6, 149, 370, 330, 384, 126, 298, 236, 130, 107, 255, 298, 149, 105, 413], # ['<|endoftext|>', 'A', 'Ġcar', 'Ġthat', 'Ġseems', 'Ġto', 'Ġbe', 'Ġparked', 'Ġillegally', # 'Ġbehind', 'Ġa', 'Ġlegally', 'Ġparked', 'Ġcar', 'Ġ.', '<|endoftext|>'] ]), "sent_str": [ "A bicycle replica with a clock as the front wheel .", "A car that seems to be parked illegally behind a legally parked car .", ], } """ def get_batch(self, name: str, data: Dict[str, Any], indexes: List[int]) -> Dict[str, Any]: res: Dict[str, Any] = {} data_id, data_str = data["id"], data["str"] batch_size = len(indexes) res[name + "_length"] = np.array([len(data_id[i]) for i in indexes], dtype=int) res_sent = res[name] = np.ones((batch_size, np.max(res[name + "_length"])), dtype=int) * self.vocab.eos_id #res_attn = res[name + "_attnmask"] = np.zeros((batch_size, np.max(res[name + "_length"])), dtype=int) for i, j in enumerate(indexes): sent = data_id[j] res_sent[i, :len(sent)] = sent # res_attn[i, :len(sent)] = 1 res[name + "_allvocabs"] = res_sent.copy() res[name + "_str"] = [data_str[i] for i in indexes] return res def trim_in_ids(self, ids: List[int]) -> List[int]: if ids[0] == self.vocab.eos_id: ids = [self.vocab.eos_id] + trim_before_target(list(ids[1:]), self.vocab.eos_id) else: ids = trim_before_target(list(ids), self.vocab.eos_id) return ids class SentenceBERT(Sentence): '''Bases: :class:`.dataloader.Sentence`, :class:`.dataloader.Field` A field for sentence in the format of BERT. {INIT_DOCSTRING} {SENTENCE_INPUT_FORMAT} ''' INIT_DOCSTRING = Sentence.INIT_DOCSTRING.replace(":class:Vocab", ":class:PretrainedVocab") def __init__(self, tokenizer: Union[None, PretrainedTokenizer] = None, \ vocab: Optional[PretrainedVocab] = None, \ vocab_from_mappings: Optional[Dict[str, str]] = None, \ max_sent_length: Union[int, None, _InfiniteLength] = None, \ convert_to_lower_letter: Optional[bool] = None): super().__init__(tokenizer=tokenizer, \ vocab=vocab, vocab_from_mappings=vocab_from_mappings,\ max_sent_length=max_sent_length, \ convert_to_lower_letter=convert_to_lower_letter) if not isinstance(self.tokenizer, PretrainedTokenizer) or self.tokenizer.get_tokenizer_class() != "BertTokenizer": raise ValueError("You have to specify a pretrained tokenizer compatible with BERT") self.inner_tokenizer = self.tokenizer.tokenizer if not isinstance(self.vocab, PretrainedVocab): raise ValueError("You have to specify a PretrainedVocab for SentenceBERT field") self.vocab: PretrainedVocab def add_special_to_ids(self, ids: List[int]) -> List[int]: return [self.vocab.get_special_tokens_id("cls")] + ids + [self.vocab.get_special_tokens_id("sep")] def remove_special_in_ids(self, ids: List[int], remove_special=True, trim=True) -> List[int]: if trim: ids = self.trim_in_ids(ids) if remove_special: ids = self._remove_special_in_ids(ids, self.vocab.get_special_tokens_id("cls"), self.vocab.get_special_tokens_id("sep")) return ids _GET_BATCH_RETURN_VALUE = SentenceDefault._GET_BATCH_RETURN_VALUE _GET_BATCH_EXAMPLE = """ Examples: >>> # This example is based on BertTokenizer. The vocab files are in ./tests/dummy_bertvocab. >>> field.get_batch('sent', data, [0, 1]) { "sent": numpy.array([ [101, 147, 37, 29, 359, 102, 0, 0, 0, 0, 0, 0, 0], # ['<cls>', 'How', 'are', 'you', '?', '<sep>', '<pad>', '<pad>', '<pad>', '<pad>', '<pad>', '<pad>', '<pad>'] [101, 375, 334, 379, 127, 341, 350, 29, 328, 9, 29, 359, 102] # ['<cls>', 'i', ''', 'm', 'fine', '.', 'thank', 'you', '!', 'and', 'you', '?', '<sep>'] ]), "sent_length": numpy.array([6, 13]), # length of sentences, "sent_allvocabs": numpy.array([ [101, 147, 37, 29, 359, 102, 0, 0, 0, 0, 0, 0, 0], # ['<cls>', 'how', 'are', 'you', '?', '<sep>', '<pad>', '<pad>', '<pad>', '<pad>', '<pad>', '<pad>', '<pad>'] [101, 375, 334, 379, 127, 341, 350, 29, 328, 9, 29, 359, 102] # ['<cls>', 'i', ''', 'm', 'fine', '.', 'thank', 'you', '!', 'and', 'you', '?', '<sep>'] ]), "sent_str": [ "How are you?", "I'm fine. Thank you! And you?" ], } """ def get_batch(self, name: str, data: Dict[str, Any], indexes: List[int]) -> Dict[str, Any]: res: Dict[str, Any] = {} data_id, data_str = data["id"], data["str"] batch_size = len(indexes) res[name + "_length"] = np.array([len(data_id[i]) for i in indexes], dtype=int) res_sent = res[name] = np.ones((batch_size, np.max(res[name + "_length"])), dtype=int) * self.vocab.pad_id #res_attn = res[name + "_attnmask"] = np.zeros((batch_size, np.max(res[name + "_length"])), dtype=int) for i, j in enumerate(indexes): sent = data_id[j] res_sent[i, :len(sent)] = sent # res_attn[i, :len(sent)] = 1 res[name + "_allvocabs"] = res_sent.copy() res[name + "_str"] = [data_str[i] for i in indexes] return res def trim_in_ids(self, ids: List[int]) -> List[int]: # The first token can't be the sep token ids = trim_before_target(list(ids), self.vocab.get_special_tokens_id("sep")) return ids class _SessionContent(_FieldContent): '''Store the content data of :class:`Session` Field. Different from :class:`Field`, it won't be shared between fields or dataloader, and it can save data. ''' def __init__(self, field: "Session", vocab_from: str): self.field = field self.vocab_from = vocab_from self._tmp_tokenized_data: Any = None super().__init__() def _get_next(self, dataset: Iterator[str]) -> Tuple[List[str], int]: r"""read **several(one or more)** elements and returns a 2-tuple (the next session, and the number of elements it reads). The first several non-space elements in `dataset`, followed by a '\\n', are regarded as a session. The first element must not be empty string or '\\n'. Note that it may raise StopIteration. Arguments: {_FieldContent._GET_NEXT_ARG} Examples: >>> dataset = iter(["a\n", "b\n", "\n", "c\n", "d\e", "e\n", '\n']) >>> session_field = "Session" # For simplicity, `session_field` is a string, rather than a Session object. >>> field_content = _SessionContent(session_field, "test") >>> field_content._get_next(dataset) (['a', 'b'], 2) # The first session. '\n' separates sessions. >>> field_content._get_next(dataset) (['c', 'd', 'e'], 3) # The second(last) session. For the last session, it doesn't matter whether it's followed by '\n'. """ session: List[str] = [] lineno = 0 while True: try: line = next(dataset) lineno += 1 if line == '\n': break session.append(line.rstrip()) except StopIteration: break if not session: raise StopIteration return session, lineno def process_before_vocab(self): raw_data_hash = UnorderedSha256() for data in self._original_data: raw_data_hash.update_data(dumps(data)) self._raw_data_hash = raw_data_hash.hexdigest() self._tmp_tokenized_data = tokenized_sessions = self.field.tokenize_sessions(self._original_data) data_hash = UnorderedSha256() for tokenized_data in self._tmp_tokenized_data: data_hash.update_data(dumps(tokenized_data)) self._data_hash = data_hash.hexdigest() self.field.get_vocab().add_tokens(list(chain(*chain(*tokenized_sessions))), self.vocab_from) def get_data(self) -> Dict[str, list]: id_data = self.field.process_sessions(self._tmp_tokenized_data) return {"id": id_data, "str": self._original_data} class Session(Sentence): """Bases: :class:`.dataloader.Field` A field for session. Each session is a list of sentences. {Sentence.INIT_DOCSTRING} {MAX_TURN_LENGTH_DOCS} {MAX_TURN_LENGTH_DEFAULT} {SESSION_INPUT_FORMAT} """ SESSION_INPUT_FORMAT = r""" Input Format This field read multiple line of sentences per sample, until a blank line. """ MAX_TURN_LENGTH_DOCS = r""" max_turn_length (int, _InfiniteLength, optional): Set the maximum turn length of a session. If it's an integer, any session, whose turn length is more than ``max_turn_length`` is shortened to first ``max_sent_length`` turns. The left turns are ignored. If it's ``None`` or ``Sentence.INFINITE_LENGTH``, sessions won't be shortened and all turns are remained.""" MAX_TURN_LENGTH_DEFAULT = """Default: ``None``.""" def __init__(self, tokenizer: Union[None, Tokenizer, str] = None, vocab: Optional[Vocab] = None, vocab_from_mappings: Optional[Dict[str, str]] = None, max_sent_length: Union[int, None, _InfiniteLength] = None, convert_to_lower_letter: Optional[bool] = None, max_turn_length: Union[int, None, _InfiniteLength] = None,): if type(self) == Session: raise NotImplementedError( "%s is an abstract class. Please use %s instead." % (Session.__name__, SessionDefault.__name__)) super().__init__(tokenizer, vocab, vocab_from_mappings, max_sent_length, convert_to_lower_letter) with FieldContext.set_parameters(max_turn_length=max_turn_length): max_turn_length = FieldContext.get('max_turn_length', None) if max_turn_length == Sentence.INFINITE_LENGTH: max_turn_length = None # max_turn_length is used for slice. So, None means that turn_length is unlimited. if max_turn_length is not None: msg = "max_turn_length must be None or a positive integer" if not isinstance(max_turn_length, int): raise TypeError(msg) elif max_turn_length <= 0: raise ValueError(msg) self.max_turn_length = max_turn_length _SESSION_MORE_DOCSTRING = "" def tokenize_sessions(self, sessions: List[RawSessionType]) -> List[TokenizedSessionType]: '''Tokenize ``sessions``. {_SESSION_MORE_DOCSTRING} * Convert the tokens to lower case if ``self.convert_to_lower_letter`` is ``True``. Arguments: sessions (List[List[str]]): The list of sessions to be tokenized. ''' return [self.tokenize_sentences(session) for session in sessions] PROCESS_ARG = Sentence.PROCESS_ARG def process_sessions(self, sessions: List[TokenizedSessionType], add_special=True, only_frequent_word=False, cut=True): """Process input sessions. {_SESSION_MORE_DOCSTRING} * If ``self.max_turn_length`` is not ``None`` and ``cut`` is ``True``, sessions, whose length are more than ``self.max_turn_length``, are shorten to first ``self.max_turn_length`` sentences. * If sessions haven’t been tokenized, tokenize them by invoking :meth:`self.tokenize_sessions` * Then, convert the list of tokens to a list of ids. * If ``self.max_sent_length`` is not ``None`` and ``cut`` is ``True``, sentences, whose length are more than ``self.max_sent_length``, are shorten to first ``self.max_sent_length`` tokens. Arguments: sessions (List[List[str], List[List[str]]]): sentences in a session can be a str or a list of tokens. {PROCESS_ARG} cut (bool, optional): Whether to cut sessions/sentences with too many sentences/tokens. Default: ``True``. """ # Cut sessions. # If a session's turn length > `self.max_turn_length`, retain the first `self.max_turn_length` sentences and discard the rest. if cut and self.max_turn_length is not None: turn_length_before_cut = list(map(len, sessions)) max_turn_length_before_cut = max(turn_length_before_cut) sessions = [session[:self.max_turn_length] for session in sessions] turn_length_after_cut = list(map(len, sessions)) if len(sessions) > 1: logging.info("max turn length before cut: %d, cut percent: %.2f%%" % ( max_turn_length_before_cut, 100 * (1 - sum(turn_length_after_cut) / sum(turn_length_before_cut))) ) sentences: List[TokenizedSentenceType] session_length: List[int] sentences, session_lengths = chain_sessions(sessions) processed_sessions = self.process_sentences(sentences, add_special=add_special, only_frequent_word=only_frequent_word, cut=cut) processed_sessions = restore_sessions(processed_sessions, session_lengths) return processed_sessions def _create(self, set_name) -> _SessionContent: try: return _SessionContent(self, self.vocab_from_mappings[set_name]) except KeyError: raise KeyError("Unknown set_name %s, do not specify in the vocab_from_mappings" % set_name) from None def convert_multi_turn_tokens_to_ids(self, session: List[List[str]], add_special=False, only_frequent_word=False) -> \ List[List[int]]: '''Convert list of tokenized sentences to list of sentence ids. {_SESSION_MORE_DOCSTRING} Arguments: session (List[List[str]]): The tokenized sentences to be converted.{CONVERT_TO_ID_ARG} ''' return [self.convert_tokens_to_ids(sent, add_special, only_frequent_word) for sent in session] def convert_multi_turn_ids_to_tokens(self, session_ids, remove_special=True, trim=True): '''Convert list of sentence ids to list of sentences. {_SESSION_MORE_DOCSTRING} Arguments: session_ids (List[List[int]]): The sentence ids to be converted.{CONVERT_FROM_ID_ARG} ''' return [self.convert_ids_to_tokens(sent_ids, remove_special, trim) for sent_ids in session_ids] def multi_turn_trim_in_ids(self, session_ids: List[List[int]]) -> List[List[int]]: '''For each sentence ids in session, find the first special token indicating the sentence is over and remove all the tokens after it (included). Then remove all trailing ``pad``. {_SESSION_MORE_DOCSTRING} Arguments: session_ids (List[List[int]]): The input ids of session. ''' return [self.trim_in_ids(sent_ids) for sent_ids in session_ids] @classmethod def get_pretrained_class(cls, pretrained): return { "gpt2": SessionGPT2, "bert": SessionBERT }[pretrained] @classmethod def get_candidate_pretrained_class(cls, pretrained): return { "gpt2": SentenceCandidateGPT2, "bert": SentenceCandidateBERT }[pretrained] class SessionDefault(Session): '''Bases: :class:`.dataloader.Session`, :class:`.dataloader.Field` A common use field for sessions. {INIT_DOCSTRING} {SESSION_INPUT_FORMAT} ''' INIT_DOCSTRING = Sentence.INIT_DOCSTRING.replace(":class:Vocab", ":class:GeneralVocab") add_special_to_ids = SentenceDefault.add_special_to_ids remove_special_in_ids = SentenceDefault.remove_special_in_ids trim_in_ids = SentenceDefault.trim_in_ids _GET_BATCH_DATA_DOCSTRING = SentenceDefault._GET_BATCH_DATA_DOCSTRING.replace(_SentenceContent.__name__, _SessionContent.__name__).replace('sentences', 'sessions') _GET_BATCH_RETURN_VALUE = """ The function will return a dict, containing: * ``FIELDNAME`` (``np.ndarray[batch_size, max_turn_length_in_batch, max_sent_length_in_batch]``): Padded sessions in id formats. It only contains frequent vocabs, and rare words are replaced by ``unk_id``. * ``FIELDNAME_allvocabs`` (``np.ndarray[batch_size, max_turn_length_in_batch, max_sent_length_in_batch]``): Padded sessions in id formats. It contains frequent vocabs and rare vocabs. * ``FIELDNAME_turn_length`` (``np.ndarray[batch_size]``): The turn numbers of sessions. * ``FIELDNAME_sent_length`` (``List[List[int]]``): The length of sentences of sessions. * ``FIELDNAME_str`` (``List[str]``): The raw sessions. where * ``FIELDNAME`` is the name of the field. * ``batch_size`` is ``len(indexes)``. * ``max_turn_length_in_batch`` is the maximum turn number of sessions in the batch. * ``max_sent_length_in_batch`` is the maximum length of sentences in the batch. """ _GET_BATCH_EXAMPLE = r""" Examples: >>> # dataset = iter(['How are you?\n', "I'm fine. And you?\n", "I'm fine, too.\n", "\n", >>> # "How to install cotk?\n", "pip install cotk.\n", "\n"]) >>> # min_frequent_vocab_times = 2 >>> # all_vocab_list = ['<pad>', '<unk>', '<go>', '<eos>', '.', '?', "'", 'How', 'I', >>> # 'cotk', 'fine', 'install', 'm', 'you', ',', 'And', 'are', 'pip', 'to', 'too'] >>> # frequent_vocab_size = 14 >>> # frequent_vocab_list = ['<pad>', '<unk>', '<go>', '<eos>', '.', '?', "'", 'How', 'I', >>> # 'cotk', 'fine', 'install', 'm', 'you'] >>> # data = { >>> # 'id': [ >>> # [ >>> # [2, 7, 16, 13, 5, 3], >>> # [2, 8, 6, 12, 10, 4, 15, 13, 5, 3], >>> # [2, 8, 6, 12, 10, 14, 19, 4, 3], >>> # ], >>> # [ >>> # [2, 7, 18, 11, 9, 5, 3], >>> # [2, 17, 11, 9, 4, 3], >>> # ] >>> # ], >>> # 'str': [ >>> # [ >>> # 'How are you?', >>> # "I'm fine. And you?", >>> # "I'm fine, too." >>> # ], >>> # [ >>> # 'How to install cotk?', >>> # 'pip install cotk.' >>> # ] >>> # >>> # } >>> field.get_batch('session', data, [0, 1]) { 'session_turn_length': numpy.array([3, 2]), 'session_sent_length': [ [6, 10, 9], [7, 6] ], 'session': numpy.array([ [ [ 2, 7, 1, 13, 5, 3, 0, 0, 0, 0], # <go> How <unk> you? <eos> <pad> <pad> <pad> <pad> [ 2, 8, 6, 12, 10, 4, 1, 13, 5, 3], # <go> I'm fine. <unk> you? <eos> [ 2, 8, 6, 12, 10, 1, 1, 4, 3, 0] # <go> I'm fine <unk> <unk>. <eos> <pad> ], [ [ 2, 7, 1, 11, 9, 5, 3, 0, 0, 0], # <go> How <unk> install cotk? <eos> <pad> <pad> <pad> [ 2, 1, 11, 9, 4, 3, 0, 0, 0, 0], # <go> <unk> install cotk. <eos> <pad> <pad> <pad> <pad> [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] # all <pad> ] ]), 'session_allvocabs': numpy.array([ [ [ 2, 7, 16, 13, 5, 3, 0, 0, 0, 0], # <go> How are you? <eos> <pad> <pad> <pad> <pad> [ 2, 8, 6, 12, 10, 4, 15, 13, 5, 3], # <go> I'm fine. And you? <eos> [ 2, 8, 6, 12, 10, 14, 19, 4, 3, 0] # <go> I'm fine, too. <eos> <pad> ], [ [ 2, 7, 18, 11, 9, 5, 3, 0, 0, 0], # <go> How to install cotk? <eos> <pad> <pad> <pad> [ 2, 17, 11, 9, 4, 3, 0, 0, 0, 0], # <go> pip install cotk. <eos> <pad> <pad> <pad> <pad> [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] # all <pad> ] ]), 'session_str': [ [ 'How are you?', "I'm fine. And you?", "I'm fine, too." ], [ 'How to install cotk?', 'pip install cotk.' ] ] } """ def get_batch(self, name: str, data: Dict[str, Any], indexes: List[int]) -> Dict[str, Any]: if not isinstance(self.vocab, GeneralVocab): raise RuntimeError("Subclass must override get_batch if self.vocab is not a GeneralVocab.") res = {} data_id, data_str = data['id'], data['str'] batch_size = len(indexes) turn_lengths = res[name + "_turn_length"] = np.array([len(data_id[i]) for i in indexes], dtype=int) res[name + "_sent_length"] = [[len(sent) for sent in data_id[i]] for i in indexes] max_sent_length = max(map(max, res[name + "_sent_length"])) res_session = res[name] = np.zeros((batch_size, turn_lengths.max(), max_sent_length), dtype=int) for i, j in enumerate(indexes): session = data_id[j] session = [list(sent) + [0] * (max_sent_length-len(sent)) for sent in session] res_session[i, :len(session)] = np.array(session, dtype=int) res[name + "_allvocabs"] = res_session.copy() res_session[res_session >= self.vocab.frequent_vocab_size] = self.vocab.unk_id res[name + "_str"] = [data_str[i] for i in indexes] return res class SessionGPT2(Session): '''Bases: :class:`.dataloader.Session`, :class:`.dataloader.Field` A field for session in the format of GPT2. {INIT_DOCSTRING} {SESSION_INPUT_FORMAT} ''' INIT_DOCSTRING = Sentence.INIT_DOCSTRING.replace(":class:Vocab", ":class:PretrainedVocab") def __init__(self, tokenizer: Union[None, PretrainedTokenizer] = None, vocab: Optional[PretrainedVocab] = None, vocab_from_mappings: Optional[Dict[str, str]] = None, max_sent_length: Union[int, None, _InfiniteLength] = None, convert_to_lower_letter: Optional[bool] = None, max_turn_length: Union[int, None, _InfiniteLength] = None,): super().__init__(tokenizer, vocab, vocab_from_mappings, max_sent_length, convert_to_lower_letter, max_turn_length) if not isinstance(self.tokenizer, PretrainedTokenizer) or self.tokenizer.get_tokenizer_class() != "GPT2Tokenizer": raise ValueError("You have to specify a pretrained tokenizer compatible with gpt2") self.inner_tokenizer = self.tokenizer.tokenizer if not isinstance(self.vocab, PretrainedVocab): raise ValueError("You have to specify a PretrainedVocab for SentenceGPT2 field") self.vocab: PretrainedVocab add_special_to_ids = SentenceGPT2.add_special_to_ids remove_special_in_ids = SentenceGPT2.remove_special_in_ids trim_in_ids = SentenceGPT2.trim_in_ids _GET_BATCH_DATA_DOCSTRING = SessionDefault._GET_BATCH_DATA_DOCSTRING # TODO: update return value of get_batch. I have trouble with `GPT2Tokenizer.from_pretrained('gpt2')` # the following codes in Examples haven't been run. _GET_BATCH_EXAMPLE = r""" # NOTE: We only show the structure of return value of get_batch. The real value of each entry may depends on the loaded vocab. Examples: >>> from transformers.tokenization_gpt2 import GPT2Tokenizer >>> from cotk.dataloader.tokenizer import PretrainedTokenizer >>> tokenizer = GPT2Tokenizer.from_pretrained('gpt2') >>> field = SessionGPT2(PretrainedTokenizer(tokenizer)) >>> field_content = field._create('train') >>> dataset = iter(['How are you?\n', "I'm fine. Thank you! And you?\n", "I'm fine, too.\n", "\n", "How to install CoTk?\n", "pip install cotk.\n", "\n"]) >>> while True: ... try: ... field_content.read_next(dataset) ... except StopIteration: ... break >>> field_content.process_before_vocab() >>> field.vocab.build_vocab() >>> data = field_content.get_data() >>> data {'id': [[[2, 8, 18, 6, 5, 3], [2, 9, 7, 12, 10, 4, 17, 6, 13, 15, 6, 5, 3], [2, 9, 7, 12, 10, 14, 22, 4, 3]], [[2, 8, 21, 11, 16, 5, 3], [2, 20, 11, 19, 4, 3]]], 'str': [['How are you?', "I'm fine. Thank you! And you?", "I'm fine, too."], ['How to install CoTk?', 'pip install cotk.']]} >>> batch_data = field.get_batch('session', data, [1]) >>> batch_data {'session_turn_length': array([2]), 'session_sent_length': [[7, 6]], 'session': array([[[ 2, 8, 21, 11, 16, 5, 3], [ 2, 20, 11, 19, 4, 3, 0]]]), 'session_allvocabs': array([[[ 2, 8, 21, 11, 16, 5, 3], [ 2, 20, 11, 19, 4, 3, 0]]]), 'session_str': [['How to install CoTk?', 'pip install cotk.']]} >>> # 'session_turn_length' (`name` + '_turn_length') is a :class:`np.ndarray` object with shape == (batch size, ). Each element is the length of corresponding sssion. >>> # 'session_sent_length' (`name` + '_sent_length') is List[List[int]]. Each integer is the length of corresponding sentence. >>> # 'session' (`name`) is a :class:`np.ndarray` object with shape == (batch size, max turn length, max sentence length). >>> # batch_data['session'][i, j] is a sentence. batch_data['session'][i, j, k] is an id. >>> # If `self.max_turn_length` is not None and j >= `self.max_turn_length` or `self.max_sent_length` is not None and k >= `self.max_sent_length`, >>> # batch_data['session'][i, j, k] is `self.eos_id`. >>> # 'session_allvocabs' (`name` + '_allvocabs') is the same with 'session'.""" def get_batch(self, name: str, data: Dict[str, Any], indexes: List[int]) -> Dict[str, Any]: res = {} data_id, data_str = data['id'], data['str'] batch_size = len(indexes) turn_lengths = res[name + "_turn_length"] = np.array([len(data_id[i]) for i in indexes], dtype=int) res[name + "_sent_length"] = [[len(sent) for sent in data_id[i]] for i in indexes] max_sent_length = max(map(max, res[name + "_sent_length"])) res_session = res[name] = np.ones((batch_size, turn_lengths.max(), max_sent_length), dtype=int) * self.vocab.eos_id for i, j in enumerate(indexes): session = data_id[j] session = [list(sent) + [self.vocab.eos_id] * (max_sent_length - len(sent)) for sent in session] res_session[i, :len(session)] = np.array(session, dtype=int) res[name + "_allvocabs"] = res_session.copy() res[name + "_str"] = [data_str[i] for i in indexes] return res class SessionBERT(Session): '''Bases: :class:`.dataloader.Session`, :class:`.dataloader.Field` A field for session in the format of BERT. {INIT_DOCSTRING} {SESSION_INPUT_FORMAT} ''' INIT_DOCSTRING = Sentence.INIT_DOCSTRING.replace(":class:Vocab", ":class:PretrainedVocab") def __init__(self, tokenizer: Union[None, PretrainedTokenizer] = None, vocab: Optional[PretrainedVocab] = None, vocab_from_mappings: Optional[Dict[str, str]] = None, max_sent_length: Union[int, None, _InfiniteLength] = None, convert_to_lower_letter: Optional[bool] = None, max_turn_length: Union[int, None, _InfiniteLength] = None,): super().__init__(tokenizer, vocab, vocab_from_mappings, max_sent_length, convert_to_lower_letter, max_turn_length) if not isinstance(self.tokenizer, PretrainedTokenizer) or self.tokenizer.get_tokenizer_class() != "BertTokenizer": raise ValueError("You have to specify a pretrained tokenizer compatible with bert") self.inner_tokenizer = self.tokenizer.tokenizer if not isinstance(self.vocab, PretrainedVocab): raise ValueError("You have to specify a PretrainedVocab for SentenceBERT field") self.vocab: PretrainedVocab add_special_to_ids = SentenceBERT.add_special_to_ids remove_special_in_ids = SentenceBERT.remove_special_in_ids trim_in_ids = SentenceBERT.trim_in_ids _GET_BATCH_DATA_DOCSTRING = SessionDefault._GET_BATCH_DATA_DOCSTRING # TODO: update return value of get_batch. I have trouble with `BertTokenizer.from_pretrained('bert')` # the following codes in Examples haven't been run. _GET_BATCH_EXAMPLE = r""" # NOTE: We only show the structure of return value of get_batch. The real value of each entry may depends on the loaded vocab. Examples: >>> from transformers.tokenization_bert import BertTokenizer >>> from cotk.dataloader.tokenizer import PretrainedTokenizer >>> tokenizer = BertTokenizer.from_pretrained('bert') >>> field = SessionBERT(PretrainedTokenizer(tokenizer)) >>> field_content = field._create('train') >>> dataset = iter(['How are you?\n', "I'm fine. Thank you! And you?\n", "I'm fine, too.\n", "\n", "How to install CoTk?\n", "pip install cotk.\n", "\n"]) >>> while True: ... try: ... field_content.read_next(dataset) ... except StopIteration: ... break >>> field_content.process_before_vocab() >>> field.vocab.build_vocab() >>> data = field_content.get_data() >>> data {'id': [[[2, 8, 18, 6, 5, 3], [2, 9, 7, 12, 10, 4, 17, 6, 13, 15, 6, 5, 3], [2, 9, 7, 12, 10, 14, 22, 4, 3]], [[2, 8, 21, 11, 16, 5, 3], [2, 20, 11, 19, 4, 3]]], 'str': [['How are you?', "I'm fine. Thank you! And you?", "I'm fine, too."], ['How to install CoTk?', 'pip install cotk.']]} >>> batch_data = field.get_batch('session', data, [1]) >>> batch_data {'session_turn_length': array([2]), 'session_sent_length': [[7, 6]], 'session': array([[[ 2, 8, 21, 11, 16, 5, 3], [ 2, 20, 11, 19, 4, 3, 0]]]), 'session_allvocabs': array([[[ 2, 8, 21, 11, 16, 5, 3], [ 2, 20, 11, 19, 4, 3, 0]]]), 'session_str': [['How to install CoTk?', 'pip install cotk.']]} >>> # 'session_turn_length' (`name` + '_turn_length') is a :class:`np.ndarray` object with shape == (batch size, ). Each element is the length of corresponding sssion. >>> # 'session_sent_length' (`name` + '_sent_length') is List[List[int]]. Each integer is the length of corresponding sentence. >>> # 'session' (`name`) is a :class:`np.ndarray` object with shape == (batch size, max turn length, max sentence length). >>> # batch_data['session'][i, j] is a sentence. batch_data['session'][i, j, k] is an id. >>> # If `self.max_turn_length` is not None and j >= `self.max_turn_length` or `self.max_sent_length` is not None and k >= `self.max_sent_length`, >>> # batch_data['session'][i, j, k] is `self.pad_id`. >>> # 'session_allvocabs' (`name` + '_allvocabs') is the same with 'session'.""" def get_batch(self, name: str, data: Dict[str, Any], indexes: List[int]) -> Dict[str, Any]: res = {} data_id, data_str = data['id'], data['str'] batch_size = len(indexes) turn_lengths = res[name + "_turn_length"] = np.array([len(data_id[i]) for i in indexes], dtype=int) res[name + "_sent_length"] = [[len(sent) for sent in data_id[i]] for i in indexes] max_sent_length = max(map(max, res[name + "_sent_length"])) res_session = res[name] = np.ones((batch_size, turn_lengths.max(), max_sent_length), dtype=int) * self.vocab.pad_id for i, j in enumerate(indexes): session = data_id[j] session = [list(sent) + [self.vocab.pad_id] * (max_sent_length - len(sent)) for sent in session] res_session[i, :len(session)] =
np.array(session, dtype=int)
numpy.array
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. # # 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. """Lovasz-Softmax and Jaccard hinge loss in PaddlePaddle""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import paddle.fluid as fluid import numpy as np from utils.config import cfg def _cumsum(x): y =
np.array(x)
numpy.array
import unittest import numpy as np from tests import DataGenerator from sparseklearn.fastLA import dist_both_comp from sparseklearn.fastLA import dist_one_comp_one_full from sparseklearn.fastLA import pairwise_l2_distances_with_self from sparseklearn.fastLA import pairwise_l2_distances_with_full from sparseklearn.fastLA import mahalanobis_distance_spherical from sparseklearn.fastLA import mahalanobis_distance_diagonal from sparseklearn.fastLA import pairwise_mahalanobis_distances_spherical from sparseklearn.fastLA import pairwise_mahalanobis_distances_diagonal from sparseklearn.fastLA import update_weighted_first_moment from sparseklearn.fastLA import update_weighted_first_moment_array from sparseklearn.fastLA import compute_weighted_first_moment_array from sparseklearn.fastLA import update_weighted_first_and_second_moment from sparseklearn.fastLA import update_weighted_first_and_second_moment_array from sparseklearn.fastLA import compute_weighted_first_and_second_moment_array from sparseklearn.fastLA import apply_mask_to_full_sample from sparseklearn.fastLA import logdet_cov_diag class TestFastLAMethods(unittest.TestCase): def assertArrayEqual(self, x, y): self.assertTrue(np.allclose(x, y, rtol=1e-6)) def setUp(self): self.td = DataGenerator() def test_dist_both_comp(self): """ Distance between RHDX[1] and RHDX[3]. """ result = dist_both_comp( self.td.RHDX[1], self.td.RHDX[3], self.td.mask[1], self.td.mask[3], self.td.Q, self.td.P ) correct = np.sqrt(5/2. * 37) self.assertAlmostEqual(correct,result,places=6) def test_dist_one_comp_one_full(self): """ Distance between RHDX[1] and U[2]. """ result = dist_one_comp_one_full(self.td.RHDX[1], self.td.U[2], self.td.mask[1], self.td.Q, self.td.P) correct = np.sqrt(5/3. * 50) self.assertAlmostEqual(correct,result,places=6) def test_pairwise_l2_distances_with_self(self): """ Pairwise distances between rows of RHDX.""" result = np.zeros((self.td.N, self.td.N)) pairwise_l2_distances_with_self(result, self.td.RHDX, self.td.mask, self.td.N, self.td.Q, self.td.P) correct = self.td.correct_pairwise_l2_distances_with_self self.assertArrayEqual(correct, result) def test_pairwise_l2_distances_with_full(self): """Pairwise distances between rows of RHDX and rows of U.""" result = np.zeros((self.td.N, self.td.K)) pairwise_l2_distances_with_full(result, self.td.RHDX, self.td.U, self.td.mask, self.td.N, self.td.K, self.td.Q, self.td.P) correct = self.td.correct_pairwise_l2_distances_with_full self.assertArrayEqual(correct, result) def test_mahalanobis_distance_spherical(self): """ Mahalanobis distance ||RHDX[1] - U[2]|| with spherical covariance sigmasquared = 2.2. """ result = mahalanobis_distance_spherical(self.td.RHDX[1], self.td.U[2], self.td.mask[1], 2.2, self.td.Q, self.td.P) correct = np.sqrt(50 * 5/3 / 2.2) self.assertAlmostEqual(correct, result, places=6) def test_mahalanobis_distance_diagonal(self): """ Mahalanobis distance ||RHDX[1] - U[2]|| with diagonal covariance diagonal_covariances[2]. """ result = mahalanobis_distance_diagonal(self.td.RHDX[1], self.td.U[2], self.td.mask[1], self.td.diagonal_covariances[2], self.td.Q, self.td.P) correct = np.sqrt(57/8 * 5/3) self.assertAlmostEqual(correct, result, places=6) def test_pairwise_mahalanobis_distances_spherical(self): """ Mahalanobis distances ||RHDX - U|| with spherical_covariances. """ result = np.zeros((self.td.N,self.td.K)) pairwise_mahalanobis_distances_spherical(result, self.td.RHDX, self.td.U, self.td.mask, self.td.spherical_covariances, self.td.N, self.td.K, self.td.Q, self.td.P) correct = self.td.correct_pairwise_mahalanobis_distances_spherical self.assertArrayEqual(correct, result) def test_pairwise_mahalanobis_distances_diagonal(self): """ Mahalanobis distances ||RHDX - U|| with diagonal_covariances. """ result = np.zeros((self.td.N,self.td.K)) pairwise_mahalanobis_distances_diagonal(result, self.td.RHDX, self.td.U, self.td.mask, self.td.diagonal_covariances, self.td.N, self.td.K, self.td.Q, self.td.P) correct = self.td.correct_pairwise_mahalanobis_distances_diagonal self.assertArrayEqual(correct, result) def test_update_weighted_first_moment(self): """ Update a (init to zero) weighted mean and normalizer using HDX[1], W[1,0]. """ first_moment_to_update = np.zeros(self.td.P) normalizer_to_update = np.zeros(self.td.P) update_weighted_first_moment(first_moment_to_update, normalizer_to_update, self.td.RHDX[1], self.td.mask[1], self.td.W[1,0], self.td.Q, self.td.P) correct_moment = np.array([0, 0, 28, 16, 12], dtype = np.float64) correct_normalizer = np.array([0, 0, 4, 4, 4], dtype = np.float64) self.assertArrayEqual(correct_moment, first_moment_to_update) self.assertArrayEqual(correct_normalizer, normalizer_to_update) def test_update_weighted_first_and_second_moment(self): """ Update a (init to zero) weighted mean and normalizer using HDX[1], W[1,0]. """ first_moment_to_update = np.zeros(self.td.P) second_moment_to_update = np.zeros(self.td.P) normalizer_to_update = np.zeros(self.td.P) update_weighted_first_and_second_moment(first_moment_to_update, second_moment_to_update, normalizer_to_update, self.td.RHDX[1], self.td.mask[1], self.td.W[1,0], self.td.Q, self.td.P) correct_first_moment = np.array([0, 0, 28, 16, 12], dtype = np.float64) correct_second_moment = np.array([0, 0, 196, 64, 36]) correct_normalizer = np.array([0, 0, 4, 4, 4], dtype = np.float64) self.assertArrayEqual(correct_first_moment, first_moment_to_update) self.assertArrayEqual(correct_second_moment, second_moment_to_update) self.assertArrayEqual(correct_normalizer, normalizer_to_update) def test_update_weighted_first_moment_array(self): """ Update a set of 3 zero-initialized means using HDX[2], W[2,:].""" first_moment_array = np.zeros((self.td.K, self.td.P)) normalizer_array = np.zeros((self.td.K, self.td.P)) update_weighted_first_moment_array(first_moment_array, normalizer_array, self.td.RHDX[2], self.td.mask[2], self.td.W[2,:], self.td.K, self.td.Q, self.td.P) correct_first_moment_array = np.array([[ 2, 0, 8, 0, 7], [ 12, 0, 48, 0, 42], [ 8, 0, 32, 0, 28]], dtype = np.float64) correct_normalizer_array = np.array([[1,0,1,0,1], [6,0,6,0,6], [4,0,4,0,4]], dtype = np.float64) self.assertArrayEqual(correct_first_moment_array, first_moment_array) self.assertArrayEqual(correct_normalizer_array, normalizer_array) def test_update_weighted_first_and_second_moment_array(self): """ Update a set of 3 zero-initialized means using HDX[2], W[2,:].""" first_moment_array = np.zeros((self.td.K, self.td.P)) second_moment_array = np.zeros((self.td.K, self.td.P)) normalizer_array = np.zeros((self.td.K, self.td.P)) update_weighted_first_and_second_moment_array(first_moment_array, second_moment_array, normalizer_array, self.td.RHDX[2], self.td.mask[2], self.td.W[2,:], self.td.K, self.td.Q, self.td.P) correct_first_moment_array = np.array([[ 2, 0, 8, 0, 7], [ 12, 0, 48, 0, 42], [ 8, 0, 32, 0, 28]], dtype = np.float64) correct_second_moment_array = np.array([[ 4, 0, 64, 0, 49], [ 24, 0, 384, 0, 294], [ 16, 0, 256, 0, 196]], dtype = np.float64) correct_normalizer_array = np.array([[1,0,1,0,1], [6,0,6,0,6], [4,0,4,0,4]], dtype = np.float64) self.assertArrayEqual(correct_first_moment_array, first_moment_array) self.assertArrayEqual(correct_second_moment_array, second_moment_array) self.assertArrayEqual(correct_normalizer_array, normalizer_array) def test_compute_weighted_first_moment_array(self): """ Weighted first moments, one moment per col of W.""" first_moment_array = np.zeros((self.td.K, self.td.P)) compute_weighted_first_moment_array(first_moment_array, self.td.RHDX, self.td.mask, self.td.W, self.td.N, self.td.K, self.td.Q, self.td.P) correct_first_moment_array = np.dot(self.td.W.T, self.td.RRTHDX) / \ np.dot(self.td.W.T, (self.td.RRTHDX!=0).astype(int)) self.assertArrayEqual(first_moment_array, correct_first_moment_array) def test_compute_weighted_first_and_second_moment_array(self): """ Weighted first and second moments, one moment per col of W.""" first_moment_array = np.zeros((self.td.K, self.td.P)) second_moment_array = np.zeros((self.td.K, self.td.P)) compute_weighted_first_and_second_moment_array(first_moment_array, second_moment_array, self.td.RHDX, self.td.mask, self.td.W, self.td.N, self.td.K, self.td.Q, self.td.P) correct_first_moment_array = np.dot(self.td.W.T, self.td.RRTHDX) / \ np.dot(self.td.W.T, (self.td.RRTHDX!=0).astype(int)) correct_second_moment_array =
np.dot(self.td.W.T, self.td.RRTHDX**2)
numpy.dot
# @Date: 2019-05-13 # @Email: <EMAIL> <NAME> # @Last modified time: 2020-10-07 import sys #sys.path.insert(0, '/work/qiu/data4Keran/code/modelPredict') sys.path.insert(0, '/home/xx02tmp/code3/modelPredict') from img2mapC05 import img2mapC import numpy as np import time sys.path.insert(0, '/home/xx02tmp/code3/dataPrepare') import basic4dataPre import h5py import os import glob2 import scipy.io as sio from scipy import stats import scipy.ndimage import numpy.matlib from numpy import argmax from keras.utils import to_categorical import skimage.measure #image folder imgFile_s2='/home/xx02tmp/image/to run49/' #gt file folder foldRef_LCZ=imgFile_s2 #class number num_lcz=3 #stride to cut patches step=24 patch_shape = (48, 48, 6) #new line img_shape = (48, 48) #save folder foldS='/home/xx02tmp/patch/patch50_11_02_48/' params = {'dim_x': patch_shape[0], 'dim_y': patch_shape[1], 'dim_z': patch_shape[2], 'step': step, 'Bands': [0,1,2,3,4,5], 'scale':1.0, 'ratio':1, 'isSeg':0, 'nanValu':0, 'dim_x_img': img_shape[0],#the actuall extracted image patch 'dim_y_img': img_shape[1]} #name of images cities = ['summerrs2014_segA150sd'] #names of gt files cities_ = ['class14_segA5530vp02n1_tra'] citiesval = ['summerrs2014_segA150sd'] cities_val = ['class14_segA5530vp02n1_val'] #tra and vali patch numbers of each images patchNum = np.zeros((2,len(cities)), dtype= np.int64) ; #class number of each class classNum = np.zeros((len(cities),3), dtype= np.int64) ; #change here if not os.path.exists(foldS+'vali/'): os.makedirs(foldS+'vali/') if not os.path.exists(foldS+'trai/'): os.makedirs(foldS+'trai/') ###########training patch################# for idCity in np.arange(len(cities)): params['Bands'] = [0] params['scale'] = 1 img2mapCLass=img2mapC(**params); ###lcz to patches #load file prj0, trans0, ref0= img2mapCLass.loadImgMat(foldRef_LCZ+cities_[idCity]+'.tif') print('ref0 size', ref0.shape) ref = np.int8(ref0) #print('lcz file size', ref.shape, trans0, ref.dtype) # to patches patchLCZ, R, C = img2mapCLass.label2patches_all(ref, 1) print('lcz patches, beginning', patchLCZ.shape, patchLCZ.dtype) #load img file =imgFile_s2 + cities[idCity] + '.tif' params['Bands'] = [0,1,2,3,4,5] params['scale'] = 1.0#!!!!!!!!!!!!!!!!!!! img2mapCLass=img2mapC(**params); prj0, trans0, img_= img2mapCLass.loadImgMat(file) print('img size', img_.shape) #image to patches patch_summer, R, C, idxNan = img2mapCLass.Bands2patches(img_, 1) print('image patches', patch_summer.shape, patch_summer.dtype) #try not delete idxNan (by Karen) print('lcz patches, before delete idxNan', patchLCZ.shape, patchLCZ.dtype) patchLCZ = np.delete(patchLCZ, idxNan, axis=0) print('lcz patches, after delete idxNan', patchLCZ.shape, patchLCZ.dtype) ############manupulate the patches############ #delete patches without lcz #change here, try 0.5 c3Idx=basic4dataPre.patch2labelInx_lt(patchLCZ, 0, patchLCZ.shape[1], patchLCZ.shape[2]*patchLCZ.shape[1]*0.044*1) patchLCZ =
np.delete(patchLCZ, c3Idx, axis=0)
numpy.delete
import argparse import sys import os import shutil import time import math import h5py import torch import torch.nn as nn import torch.optim import torchvision.transforms as transforms import torch.nn.functional as F import torch.nn.parallel import torch.distributed as dist from torch.nn.parallel import DistributedDataParallel as DDP import numpy as np import matplotlib.pyplot as plt sys.path.append('../ResNet') import ResNet1d as rn sys.path.append('../') import Model_Util import Utilities from Dataset_Management import Artificial_DataLoader sys.path.append('./models') from backbone import build_backbone from transformer import build_transformer import detr as DT import matcher as mtchr sys.path.append('./mAP') from Scalable_mean_avg_precision import mean_average_precision def parse(): model_names = ['ResNet10', 'ResNet18', 'ResNet34', 'ResNet50', 'ResNet101', 'ResNet152'] optimizers = ['sgd', 'adam', 'adamw'] parser = argparse.ArgumentParser(description='Nanopore Translocation Detector Training') parser.add_argument('data', metavar='DIR', nargs='*', help='path(s) to dataset (if one path is provided, it is assumed\n' + 'to have subdirectories named "train" and "val"; alternatively,\n' + 'train and val paths can be specified directly by providing both paths as arguments)') parser.add_argument('counter', metavar='COUNTER', type=str, help='path to translocation counter') parser.add_argument('predictor', metavar='PREDICTOR', type=str, help='path to translocation feature predictor') parser.add_argument('--feature_predictor_arch', '-fpa', metavar='FEATURE_PREDICTOR_ARCH', default='ResNet18', choices=model_names, help='This is the architecture of the feature_predictor section in the backbone: ' + ' | '.join(model_names) + ' (default: ResNet18_Custom)') parser.add_argument('--pulse_counter_arch', '-pca', metavar='PULSE_COUNTER_ARCH', default='ResNet18', choices=model_names, help='This is the architecture of the pulse_counter section in the backbone: ' + ' | '.join(model_names) + ' (default: ResNet18_Counter)') parser.add_argument('--epochs', default=300, type=int, metavar='N', help='number of total epochs to run') parser.add_argument('--start-epoch', default=0, type=int, metavar='N', help='manual epoch number (useful on restarts)') parser.add_argument('-b', '--batch-size', default=6, type=int, metavar='N', help='mini-batch size per process (default: 6)') parser.add_argument('--lr-backbone', default=1e-5, type=float, metavar='LR', help='Backbone learning rate.') parser.add_argument('--lr', '--learning-rate', default=0.01, type=float, metavar='LR', help='Initial learning rate. Will be scaled by the value 1/learning rate modulator every learning-rate-scheduler-period epochs.') parser.add_argument('--lrs', '--learning-rate-scaling', default='linear', type=str, metavar='LRS', help='Function to scale the learning rate value (default: \'linear\').') parser.add_argument('--lrm', '--learning-rate-modulator', default=0.1, type=float, metavar='MOD', help='In the learning rate schedule, this is the value by which the learning rate will be multiplied every learning-rate-scheduler-period epochs (default: 0.1)') parser.add_argument('--lrsp', '--learning-rate-scheduler-period', default=100, type=int, metavar='PERIOD', help='In the learning rate schedule, this is the number of epochs that has to pass in order to modulate the learning rate (default: 100)') parser.add_argument('--momentum', default=0.9, type=float, metavar='M', help='momentum') parser.add_argument('--weight-decay', '--wd', default=1e-4, type=float, metavar='W', help='weight decay (default: 1e-4)') parser.add_argument('--warmup_epochs', default=10, type=int, metavar='W', help='Number of warmup epochs (default: 10)') parser.add_argument('--print-freq', '-p', default=10, type=int, metavar='N', help='print frequency (default: 10)') parser.add_argument('--val-freq', '-vf', default=5, type=int, metavar='VF', help='validation frequency in epochs (default: 5)') parser.add_argument('--resume', default='', type=str, metavar='PATH', help='path to latest checkpoint (default: none)') parser.add_argument('-e', '--evaluate', dest='evaluate', action='store_true', help='evaluate model on validation set') parser.add_argument('-stats', '--statistics', dest='statistics', action='store_true', help='Compute statistics about errors of a trained model on validation set') parser.add_argument('-r', '--run', dest='run', action='store_true', help='Run a trained model and plots a batch of predictions in noisy signals') parser.add_argument("--local_rank", default=0, type=int) parser.add_argument('--cpu', action='store_true', help='Runs CPU based version of the workflow.') parser.add_argument('-v', '--verbose', action='store_true', help='provides additional details as to what the program is doing') parser.add_argument('--optimizer', default='adamw', type=str, metavar='OPTIM', choices=optimizers, help='optimizer for training the network\n' + 'Choices are: ' + ' | '.join(optimizers) + ' (default: adamw)') parser.add_argument('-t', '--test', action='store_true', help='Launch test mode with preset arguments') parser.add_argument('-pth', '--plot-training-history', action='store_true', help='Only plots the training history of a trained model: Loss and validation errors') parser.add_argument('--transformer-hidden-dim', default=512, type=int, metavar='TRANSFORMER-HIDDEN-DIM', help='Hidden dimension of transformer on DETR model (default: 512)') parser.add_argument('--transformer-dropout', default=0.1, type=float, metavar='TRANSFORMER_DROPOUT', help='Dropout of transformer on DETR model (default: 0.1)') parser.add_argument('--transformer-num-heads', default=8, type=int, metavar='TRANSFORMER_NUM_HEADS', help='Number of heads of transformer on DETR model (default: 8)') parser.add_argument('--transformer-dim-feedforward', default=2048, type=int, metavar='TRANSFORMER_DIM_FEEDFORWARD', help='Feedforward dimension inside transformer on DETR model (default: 2048)') parser.add_argument('--transformer-num-enc-layers', default=6, type=int, metavar='TRANSFORMER_NUM_ENC_LAYERS', help='Number of encoder layers inside transformer on DETR model (default: 6)') parser.add_argument('--transformer-num-dec-layers', default=6, type=int, metavar='TRANSFORMER_NUM_DEC_LAYERS', help='Number of decoder layers inside transformer on DETR model (default: 6)') parser.add_argument('--transformer-pre-norm', dest='transformer-pre-norm', action='store_true', help='Configurization of transformer on DETR model (default: False)') parser.add_argument('--num-classes', default=1, type=int, metavar='NUM_CLASSES', help='The number of different translocation classes that DETR has to classify (default: 1)') parser.add_argument('--num-queries', default=75, type=int, metavar='NUM_QUERIES', help='The maximum number of translocations that DETR considers could exist in a window (default: 75)') parser.add_argument('--cost-class', default=1.0, type=float, metavar='COST_CLASS', help='This is the relative weight of the classification error in the Hungarian matching cost (default: 1.0)') parser.add_argument('--cost-bsegment', default=1.0, type=float, metavar='COST_BSEGMENT', help='This is the relative weight of the L1 error of the bounding segment coordinates in the Hungarian matching cost (default: 1.0)') parser.add_argument('--cost-giou', default=0.0, type=float, metavar='COST_GIOU', help='This is the relative weight of the giou loss of the bounding segment in the Hungarian matching cost (default: 0.0)') parser.add_argument('--loss_ce', default=1.0, type=float, metavar='LOSS_CE', help='This is the relative weight of the classification error in loss (default: 1.0)') parser.add_argument('--loss_bsegment', default=1.0, type=float, metavar='LOSS_BSEGMENT', help='This is the relative weight of the L1 error of the bounding segment coordinates in loss (default: 1.0)') parser.add_argument('--loss_giou', default=0.0, type=float, metavar='LOSS_GIOU', help='This is the relative weight of the giou loss of the bounding segment in the loss (default: 0.0)') parser.add_argument('--eos-coef', default=0.1, type=float, metavar='EOS_COEF', help='This is relative classification weight applied to the no-translocation category in the loss (default: 0.1)') args = parser.parse_args() return args def main(): global best_precision, args best_precision = 0 args = parse() if not len(args.data): raise Exception("error: No data set provided") args.distributed = False if 'WORLD_SIZE' in os.environ: args.distributed = int(os.environ['WORLD_SIZE']) > 1 args.gpu = 0 args.world_size = 1 if args.distributed: args.gpu = args.local_rank if not args.cpu: torch.cuda.set_device(args.gpu) torch.distributed.init_process_group(backend='gloo', init_method='env://') args.world_size = torch.distributed.get_world_size() args.total_batch_size = args.world_size * args.batch_size # Set the device device = torch.device('cpu' if args.cpu else 'cuda:' + str(args.gpu)) ####################################################################### # Start DETR contruction ####################################################################### # create DETR backbone # create backbone pulse counter if args.test: args.pulse_counter_arch = 'ResNet10' if args.local_rank==0 and args.verbose: print("=> creating backbone pulse counter '{}'".format(args.pulse_counter_arch)) if args.pulse_counter_arch == 'ResNet18': backbone_pulse_counter = rn.ResNet18_Counter() elif args.pulse_counter_arch == 'ResNet34': backbone_pulse_counter = rn.ResNet34_Counter() elif args.pulse_counter_arch == 'ResNet50': backbone_pulse_counter = rn.ResNet50_Counter() elif args.pulse_counter_arch == 'ResNet101': backbone_pulse_counter = rn.ResNet101_Counter() elif args.pulse_counter_arch == 'ResNet152': backbone_pulse_counter = rn.ResNet152_Counter() elif args.pulse_counter_arch == 'ResNet10': backbone_pulse_counter = rn.ResNet10_Counter() else: print("Unrecognized {} architecture for the backbone pulse counter" .format(args.pulse_counter_arch)) backbone_pulse_counter = backbone_pulse_counter.to(device) # create backbone feature predictor if args.test: args.feature_predictor_arch = 'ResNet10' if args.local_rank==0 and args.verbose: print("=> creating backbone feature predictor '{}'".format(args.feature_predictor_arch)) if args.feature_predictor_arch == 'ResNet18': backbone_feature_predictor = rn.ResNet18_Custom() elif args.feature_predictor_arch == 'ResNet34': backbone_feature_predictor = rn.ResNet34_Custom() elif args.feature_predictor_arch == 'ResNet50': backbone_feature_predictor = rn.ResNet50_Custom() elif args.feature_predictor_arch == 'ResNet101': backbone_feature_predictor = rn.ResNet101_Custom() elif args.feature_predictor_arch == 'ResNet152': backbone_feature_predictor = rn.ResNet152_Custom() elif args.feature_predictor_arch == 'ResNet10': backbone_feature_predictor = rn.ResNet10_Custom() else: print("Unrecognized {} architecture for the backbone feature predictor" .format(args.feature_predictor_arch)) backbone_feature_predictor = backbone_feature_predictor.to(device) # For distributed training, wrap the model with torch.nn.parallel.DistributedDataParallel. if args.distributed: if args.cpu: backbone_pulse_counter = DDP(backbone_pulse_counter) backbone_feature_predictor = DDP(backbone_feature_predictor) else: backbone_pulse_counter = DDP(backbone_pulse_counter, device_ids=[args.gpu], output_device=args.gpu) backbone_feature_predictor = DDP(backbone_feature_predictor, device_ids=[args.gpu], output_device=args.gpu) if args.verbose: print('Since we are in a distributed setting the backbone componets are replicated here in local rank {}' .format(args.local_rank)) # bring counter from a checkpoint if args.counter: # Use a local scope to avoid dangling references def bring_counter(): if os.path.isfile(args.counter): print("=> loading backbone pulse counter '{}'" .format(args.counter)) if args.cpu: checkpoint = torch.load(args.counter, map_location='cpu') else: checkpoint = torch.load(args.counter, map_location = lambda storage, loc: storage.cuda(args.gpu)) loss_history_1 = checkpoint['loss_history'] counter_error_history = checkpoint['Counter_error_history'] best_error_1 = checkpoint['best_error'] backbone_pulse_counter.load_state_dict(checkpoint['state_dict']) total_time_1 = checkpoint['total_time'] print("=> loaded counter '{}' (epoch {})" .format(args.counter, checkpoint['epoch'])) print("Counter best precision saved was {}" .format(best_error_1)) return best_error_1, backbone_pulse_counter, loss_history_1, counter_error_history, total_time_1 else: print("=> no counter found at '{}'" .format(args.counter)) best_error_1, backbone_pulse_counter, loss_history_1, counter_error_history, total_time_1 = bring_counter() else: raise Exception("error: No counter path provided") # bring predictor from a checkpoint if args.predictor: # Use a local scope to avoid dangling references def bring_predictor(): if os.path.isfile(args.predictor): print("=> loading backbone feature predictor '{}'" .format(args.predictor)) if args.cpu: checkpoint = torch.load(args.predictor, map_location='cpu') else: checkpoint = torch.load(args.predictor, map_location = lambda storage, loc: storage.cuda(args.gpu)) loss_history_2 = checkpoint['loss_history'] duration_error_history = checkpoint['duration_error_history'] amplitude_error_history = checkpoint['amplitude_error_history'] best_error_2 = checkpoint['best_error'] backbone_feature_predictor.load_state_dict(checkpoint['state_dict']) total_time_2 = checkpoint['total_time'] print("=> loaded predictor '{}' (epoch {})" .format(args.predictor, checkpoint['epoch'])) print("Predictor best precision saved was {}" .format(best_error_2)) return best_error_2, backbone_feature_predictor, loss_history_2, duration_error_history, amplitude_error_history, total_time_2 else: print("=> no predictor found at '{}'" .format(args.predictor)) best_error_2, backbone_feature_predictor, loss_history_2, duration_error_history, amplitude_error_history, total_time_2 = bring_predictor() else: raise Exception("error: No predictor path provided") # create backbone if args.local_rank==0 and args.verbose: print("=> creating backbone") if args.feature_predictor_arch == 'ResNet18': backbone=build_backbone(pulse_counter=backbone_pulse_counter, feature_predictor=backbone_feature_predictor, num_channels=512) elif args.feature_predictor_arch == 'ResNet34': backbone=build_backbone(pulse_counter=backbone_pulse_counter, feature_predictor=backbone_feature_predictor, num_channels=512) elif args.feature_predictor_arch == 'ResNet50': backbone=build_backbone(pulse_counter=backbone_pulse_counter, feature_predictor=backbone_feature_predictor, num_channels=2048) elif args.feature_predictor_arch == 'ResNet101': backbone=build_backbone(pulse_counter=backbone_pulse_counter, feature_predictor=backbone_feature_predictor, num_channels=2048) elif args.feature_predictor_arch == 'ResNet152': backbone=build_backbone(pulse_counter=backbone_pulse_counter, feature_predictor=backbone_feature_predictor, num_channels=2048) elif args.feature_predictor_arch == 'ResNet10': backbone=build_backbone(pulse_counter=backbone_pulse_counter, feature_predictor=backbone_feature_predictor, num_channels=512) else: print("Unrecognized {} architecture for the backbone feature predictor" .format(args.feature_predictor_arch)) backbone = backbone.to(device) # create DETR transformer if args.local_rank==0 and args.verbose: print("=> creating transformer") if args.test: args.transformer_hidden_dim = 64 args.transformer_num_heads = 2 args.transformer_dim_feedforward = 256 args.transformer_num_enc_layers = 2 args.transformer_num_dec_layers = 2 args.transformer_pre_norm = True transformer = build_transformer(hidden_dim=args.transformer_hidden_dim, dropout=args.transformer_dropout, nheads=args.transformer_num_heads, dim_feedforward=args.transformer_dim_feedforward, enc_layers=args.transformer_num_enc_layers, dec_layers=args.transformer_num_dec_layers, pre_norm=args.transformer_pre_norm) # create DETR in itself if args.local_rank==0 and args.verbose: print("=> creating DETR") detr = DT.DETR(backbone=backbone, transformer=transformer, num_classes=args.num_classes, num_queries=args.num_queries) detr = detr.to(device) # For distributed training, wrap the model with torch.nn.parallel.DistributedDataParallel. if args.distributed: if args.cpu: detr = DDP(detr) else: detr = DDP(detr, device_ids=[args.gpu], output_device=args.gpu) if args.verbose: print('Since we are in a distributed setting DETR model is replicated here in local rank {}' .format(args.local_rank)) # Set matcher if args.local_rank==0 and args.verbose: print("=> set Hungarian Matcher") matcher = mtchr.HungarianMatcher(cost_class=args.cost_class, cost_bsegment=args.cost_bsegment, cost_giou=args.cost_giou) # Set criterion if args.local_rank==0 and args.verbose: print("=> set criterion for the loss") weight_dict = {'loss_ce': args.loss_ce, 'loss_bsegment': args.loss_bsegment, 'loss_giou': args.loss_giou} losses = ['labels', 'segments', 'cardinality'] criterion = DT.SetCriterion(num_classes=args.num_classes, matcher=matcher, weight_dict=weight_dict, eos_coef=args.eos_coef, losses=losses) criterion = criterion.to(device) # Set optimizer optimizer = Model_Util.get_DETR_optimizer(detr, args) if args.local_rank==0 and args.verbose: print('Optimizer used for this run is {}'.format(args.optimizer)) # Set learning rate scheduler lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, args.lrsp, args.lrm) total_time = Utilities.AverageMeter() loss_history = [] precision_history = [] # Optionally resume from a checkpoint if args.resume: # Use a local scope to avoid dangling references def resume(): if os.path.isfile(args.resume): print("=> loading checkpoint '{}'" .format(args.resume)) if args.cpu: checkpoint = torch.load(args.resume, map_location='cpu') else: checkpoint = torch.load(args.resume, map_location = lambda storage, loc: storage.cuda(args.gpu)) loss_history = checkpoint['loss_history'] precision_history = checkpoint['precision_history'] start_epoch = checkpoint['epoch'] best_precision = checkpoint['best_precision'] detr.load_state_dict(checkpoint['state_dict']) criterion.load_state_dict(checkpoint['criterion']) optimizer.load_state_dict(checkpoint['optimizer']) lr_scheduler.load_state_dict(checkpoint['lr_scheduler']) total_time = checkpoint['total_time'] print("=> loaded checkpoint '{}' (epoch {})" .format(args.resume, checkpoint['epoch'])) return start_epoch, detr, criterion, optimizer, lr_scheduler, loss_history, precision_history, total_time, best_precision else: print("=> no checkpoint found at '{}'" .format(args.resume)) args.start_epoch, detr, criterion, optimizer, lr_scheduler, loss_history, precision_history, total_time, best_precision = resume() # Data loading code if len(args.data) == 1: traindir = os.path.join(args.data[0], 'train') valdir = os.path.join(args.data[0], 'val') else: traindir = args.data[0] valdir= args.data[1] if args.test: training_f = h5py.File(traindir + '/train_toy.h5', 'r') validation_f = h5py.File(valdir + '/validation_toy.h5', 'r') else: training_f = h5py.File(traindir + '/train.h5', 'r') validation_f = h5py.File(valdir + '/validation.h5', 'r') # this is the dataset for training sampling_rate = 10000 # This is the number of samples per second of the signals in the dataset if args.test: number_of_concentrations = 2 # This is the number of different concentrations in the dataset number_of_durations = 2 # This is the number of different translocation durations per concentration in the dataset number_of_diameters = 4 # This is the number of different translocation durations per concentration in the dataset window = 0.5 # This is the time window in seconds length = 20 # This is the time of a complete signal for certain concentration and duration else: number_of_concentrations = 20 # This is the number of different concentrations in the dataset number_of_durations = 5 # This is the number of different translocation durations per concentration in the dataset number_of_diameters = 15 # This is the number of different translocation durations per concentration in the dataset window = 0.5 # This is the time window in seconds length = 20 # This is the time of a complete signal for certain concentration and duration # Training Artificial Data Loader TADL = Artificial_DataLoader(args.world_size, args.local_rank, device, training_f, sampling_rate, number_of_concentrations, number_of_durations, number_of_diameters, window, length, args.batch_size) # this is the dataset for validating if args.test: number_of_concentrations = 2 # This is the number of different concentrations in the dataset number_of_durations = 2 # This is the number of different translocation durations per concentration in the dataset number_of_diameters = 4 # This is the number of different translocation durations per concentration in the dataset window = 0.5 # This is the time window in seconds length = 10 # This is the time of a complete signal for certain concentration and duration else: number_of_concentrations = 20 # This is the number of different concentrations in the dataset number_of_durations = 5 # This is the number of different translocation durations per concentration in the dataset number_of_diameters = 15 # This is the number of different translocation durations per concentration in the dataset window = 0.5 # This is the time window in seconds length = 10 # This is the time of a complete signal for certain concentration and duration # Validating Artificial Data Loader VADL = Artificial_DataLoader(args.world_size, args.local_rank, device, validation_f, sampling_rate, number_of_concentrations, number_of_durations, number_of_diameters, window, length, args.batch_size) if args.verbose: print('From rank {} training shard size is {}'. format(args.local_rank, TADL.get_number_of_avail_windows())) print('From rank {} validation shard size is {}'. format(args.local_rank, VADL.get_number_of_avail_windows())) if args.run: arguments = {'model': detr, 'device': device, 'epoch': 0, 'VADL': VADL} if args.local_rank == 0: run_model(args, arguments) return #if args.statistics: #arguments = {'model': model, #'device': device, #'epoch': 0, #'VADL': VADL} #[duration_errors, amplitude_errors] = compute_error_stats(args, arguments) #if args.local_rank == 0: #plot_stats(VADL, duration_errors, amplitude_errors) #return #if args.evaluate: #arguments = {'model': model, #'device': device, #'epoch': 0, #'VADL': VADL} #[duration_error, amplitude_error] = validate(args, arguments) #print('##Duration error {0}\n' #'##Amplitude error {1}'.format( #duration_error, #amplitude_error)) #return if args.plot_training_history and args.local_rank == 0: Model_Util.plot_detector_stats(loss_history, precision_history) hours = int(total_time.sum / 3600) minutes = int((total_time.sum % 3600) / 60) seconds = int((total_time.sum % 3600) % 60) print('The total training time was {} hours {} minutes and {} seconds' .format(hours, minutes, seconds)) hours = int(total_time.avg / 3600) minutes = int((total_time.avg % 3600) / 60) seconds = int((total_time.avg % 3600) % 60) print('while the average time during one epoch of training was {} hours {} minutes and {} seconds' .format(hours, minutes, seconds)) return for epoch in range(args.start_epoch, args.epochs): arguments = {'detr': detr, 'criterion': criterion, 'optimizer': optimizer, 'device': device, 'epoch': epoch, 'TADL': TADL, 'VADL': VADL, 'loss_history': loss_history, 'precision_history': precision_history} # train for one epoch epoch_time, avg_batch_time = train(args, arguments) total_time.update(epoch_time) # validate every val_freq epochs if epoch%args.val_freq == 0 and epoch != 0: # evaluate on validation set print("\nValidating ...\nComputing mean average precision (mAP) for epoch {}" .format(epoch)) precision = validate(args, arguments) else: precision = best_precision #if args.test: #break lr_scheduler.step() # remember the best detr and save checkpoint if args.local_rank == 0: if epoch%args.val_freq == 0: print('From validation we have precision is {} while best_precision is {}'.format(precision, best_precision)) is_best = precision > best_precision best_precision = max(precision, best_precision) Model_Util.save_checkpoint({ 'arch': 'DETR_' + args.feature_predictor_arch, 'epoch': epoch + 1, 'best_precision': best_precision, 'state_dict': detr.state_dict(), 'criterion': criterion.state_dict(), 'optimizer': optimizer.state_dict(), 'loss_history': loss_history, 'precision_history': precision_history, 'lr_scheduler': lr_scheduler.state_dict(), 'total_time': total_time }, is_best) print('##Detector precision {0}\n' '##Perf {1}'.format( precision, args.total_batch_size / avg_batch_time)) def train(args, arguments): batch_time = Utilities.AverageMeter() losses = Utilities.AverageMeter() # switch to train mode arguments['detr'].train() end = time.time() train_loader_len = int(math.ceil(arguments['TADL'].shard_size / args.batch_size)) i = 0 arguments['TADL'].reset_avail_winds(arguments['epoch']) ######################################################## #_, inputs, _, targets, _ = arguments['TADL'].get_batch() #targets = transform_targets(targets) #lr_scheduler = torch.optim.lr_scheduler.StepLR(arguments['optimizer'], args.lrsp, # args.lrm) ######################################################## ######################################################## #while True: ######################################################## while i * arguments['TADL'].batch_size < arguments['TADL'].shard_size: # get the noisy inputs and the labels _, inputs, _, targets, _ = arguments['TADL'].get_batch() mean = torch.mean(inputs, 1, True) inputs = inputs-mean # zero the parameter gradients arguments['optimizer'].zero_grad() # forward + backward + optimize inputs = inputs.unsqueeze(1) outputs = arguments['detr'](inputs) ######################################################## #inputs = inputs.squeeze(1) ######################################################## # Compute the loss targets = transform_targets(targets) loss_dict = arguments['criterion'].forward(outputs=outputs, targets=targets) weight_dict = arguments['criterion'].weight_dict loss = sum(loss_dict[k] * weight_dict[k] for k in loss_dict.keys() if k in weight_dict) # compute gradient and do optimizer step loss.backward() torch.nn.utils.clip_grad_norm_(arguments['detr'].parameters(), 0.1) arguments['optimizer'].step() #if args.test: #if i > 10: #break if i%args.print_freq == 0: #if i%args.print_freq == 0 and i != 0: # Every print_freq iterations, check the loss and speed. # For best performance, it doesn't make sense to print these metrics every # iteration, since they incur an allreduce and some host<->device syncs. # Average loss across processes for logging if args.distributed: reduced_loss = Utilities.reduce_tensor(loss.data, args.world_size) else: reduced_loss = loss.data # to_python_float incurs a host<->device sync losses.update(Utilities.to_python_float(reduced_loss), args.batch_size) if not args.cpu: torch.cuda.synchronize() batch_time.update((time.time() - end)/args.print_freq, args.print_freq) end = time.time() if args.local_rank == 0: print('Epoch: [{0}][{1}/{2}]\t' 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' 'Speed {3:.3f} ({4:.3f})\t' 'Loss {loss.val:.10f} ({loss.avg:.4f})'.format( arguments['epoch'], i, train_loader_len, args.world_size*args.batch_size/batch_time.val, args.world_size*args.batch_size/batch_time.avg, batch_time=batch_time, loss=losses)) i += 1 ######################################################## #lr_scheduler.step() ######################################################## arguments['loss_history'].append(losses.avg) return batch_time.sum, batch_time.avg def validate(args, arguments): average_precision = Utilities.AverageMeter() # switch to evaluate mode arguments['detr'].eval() end = time.time() val_loader_len = int(math.ceil(arguments['VADL'].shard_size / args.batch_size)) i = 0 arguments['VADL'].reset_avail_winds(arguments['epoch']) pred_segments = [] true_segments = [] while i * arguments['VADL'].batch_size < arguments['VADL'].shard_size: # get the noisy inputs and the labels _, inputs, _, targets, labels = arguments['TADL'].get_batch() mean = torch.mean(inputs, 1, True) inputs = inputs-mean with torch.no_grad(): # forward inputs = inputs.unsqueeze(1) outputs = arguments['detr'](inputs) for j in range(arguments['VADL'].batch_size): train_idx = int(j + i * arguments['VADL'].batch_size) probabilities = F.softmax(outputs['pred_logits'][j], dim=1) aux_pred_segments = outputs['pred_segments'][j] for probability, pred_segment in zip(probabilities.to('cpu'), aux_pred_segments.to('cpu')): #if probability[-1] < 0.9: if torch.argmax(probability) != args.num_classes: segment = [train_idx, np.argmax(probability[:-1]).item(), 1.0 - probability[-1].item(), pred_segment[0].item(), pred_segment[1].item()] pred_segments.append(segment) num_pulses = labels[j, 0] starts = targets[j, 0] widths = targets[j, 1] categories = targets[j, 3] for k in range(int(num_pulses.item())): segment = [train_idx, categories[k].item(), 1.0, starts[k].item(), widths[k].item()] true_segments.append(segment) i += 1 for threshold in np.arange(0.5, 0.95, 0.05): detection_precision=mean_average_precision(device=arguments['device'], pred_segments=pred_segments, true_segments=true_segments, iou_threshold=threshold, seg_format="mix", num_classes=1) if args.distributed: reduced_detection_precision = Utilities.reduce_tensor(detection_precision.data, args.world_size) else: reduced_detection_precision = detection_precision.data average_precision.update(Utilities.to_python_float(reduced_detection_precision)) if not args.evaluate: arguments['precision_history'].append(average_precision.avg) return average_precision.avg def compute_error_stats(args, arguments): # switch to evaluate mode arguments['model'].eval() duration_errors = torch.zeros(arguments['VADL'].shape) amplitude_errors = torch.zeros(arguments['VADL'].shape) arguments['VADL'].reset_avail_winds(arguments['epoch']) for i in range(arguments['VADL'].total_number_of_windows): if i % args.world_size == args.local_rank: (Cnp, Duration, Dnp, window) = np.unravel_index(i, arguments['VADL'].shape) # bring a new window times, noisy_signals, clean_signals, _, labels = arguments['VADL'].get_signal_window(Cnp, Duration, Dnp, window) if labels[0] > 0: times = times.unsqueeze(0) noisy_signals = noisy_signals.unsqueeze(0) clean_signals = clean_signals.unsqueeze(0) labels = labels.unsqueeze(0) mean = torch.mean(noisy_signals, 1, True) noisy_signals = noisy_signals-mean with torch.no_grad(): noisy_signals = noisy_signals.unsqueeze(1) external = torch.reshape(labels[:,0],[1,1]) outputs = arguments['model'](noisy_signals, external) noisy_signals = noisy_signals.squeeze(1) errors=abs((labels[:,1:].to('cpu') - outputs.data.to('cpu')*torch.Tensor([10**(-3), 10**(-10)]).repeat(1,1)) / labels[:,1:].to('cpu'))*100 errors=torch.mean(errors,dim=0) duration_errors[Cnp, Duration, Dnp, window] = errors[0] amplitude_errors[Cnp, Duration, Dnp, window] = errors[1] else: duration_errors[Cnp, Duration, Dnp, window] = torch.tensor(float('nan')) amplitude_errors[Cnp, Duration, Dnp, window] = torch.tensor(float('nan')) #if args.test: #if i > 10: #break if args.distributed: reduced_duration_error = Utilities.reduce_tensor_sum_dest(duration_errors.data, 0) reduced_amplitude_error = Utilities.reduce_tensor_sum_dest(amplitude_errors.data, 0) else: reduced_duration_error = duration_errors.data reduced_amplitude_error = amplitude_errors.data return [reduced_duration_error, reduced_amplitude_error] def plot_stats(VADL, reduced_duration_error, reduced_amplitude_error): mean_duration_error = reduced_duration_error.numpy() mean_duration_error = np.nanmean(mean_duration_error, 3) std_duration_error = reduced_duration_error.numpy() std_duration_error = np.nanstd(std_duration_error, 3) mean_amplitude_error = reduced_amplitude_error.numpy() mean_amplitude_error = np.nanmean(mean_amplitude_error, 3) std_amplitude_error = reduced_amplitude_error.numpy() std_amplitude_error =
np.nanstd(std_amplitude_error, 3)
numpy.nanstd
import numpy as np def read_file(test = True): if test: filename = '../tests/day7.txt' else: filename = '../input/day7.txt' with open(filename) as file: for line in file: temp = list(map(int,line.strip().split(','))) return
np.array(temp)
numpy.array
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Mar 4 10:09:21 2019 @author: nmei """ from autoreject import (AutoReject,get_rejection_threshold) import mne from glob import glob import re import os import numpy as np import pandas as pd import pickle #import faster # https://gist.github.com/wmvanvliet/d883c3fe1402c7ced6fc from sklearn.metrics import roc_auc_score,roc_curve from sklearn.metrics import ( classification_report, matthews_corrcoef, confusion_matrix, f1_score, log_loss, r2_score ) from sklearn.preprocessing import (MinMaxScaler, OneHotEncoder, FunctionTransformer, StandardScaler) from sklearn.pipeline import make_pipeline from sklearn.ensemble.forest import _generate_unsampled_indices from sklearn.utils import shuffle from sklearn.svm import SVC,LinearSVC from sklearn.calibration import CalibratedClassifierCV from sklearn.decomposition import PCA from sklearn.dummy import DummyClassifier from sklearn.feature_selection import (SelectFromModel, SelectPercentile, VarianceThreshold, mutual_info_classif, f_classif, chi2, f_regression, GenericUnivariateSelect) from sklearn.model_selection import (StratifiedShuffleSplit, cross_val_score) from sklearn.ensemble import RandomForestClassifier,BaggingClassifier,VotingClassifier from sklearn.neural_network import MLPClassifier from xgboost import XGBClassifier from itertools import product,combinations from sklearn.base import clone from sklearn.neighbors import KNeighborsClassifier from sklearn.tree import DecisionTreeClassifier from collections import OrderedDict from scipy import stats from collections import Counter from mpl_toolkits.axes_grid1 import make_axes_locatable from matplotlib import pyplot as plt from matplotlib.pyplot import cm from nilearn.plotting.img_plotting import (_load_anat, _utils, _plot_img_with_bg, _get_colorbar_and_data_ranges, _safe_get_data) import matplotlib.patches as patches try: #from mvpa2.datasets.base import Dataset from mvpa2.mappers.fx import mean_group_sample #from mvpa2.measures import rsa #from mvpa2.measures.searchlight import sphere_searchlight #from mvpa2.base.learner import ChainLearner #from mvpa2.mappers.shape import TransposeMapper #from mvpa2.generators.partition import NFoldPartitioner except: pass#print('pymvpa is not installed') try: # from tqdm import tqdm_notebook as tqdm from tqdm.auto import tqdm except: print('why is tqdm not installed?') def preprocessing_conscious(raw, events, session, tmin = -0, tmax = 1, notch_filter = 50, event_id = {'living':1,'nonliving':2}, baseline = (None,None), perform_ICA = False, lowpass = None, interpolate_bad_channels = True,): """ 0. re-reference - explicitly """ raw_ref ,_ = mne.set_eeg_reference(raw, ref_channels = 'average', projection = True,) raw_ref.apply_proj() # it might tell you it already has been re-referenced, but do it anyway # everytime before filtering, explicitly pick the type of channels you want # to perform the filters picks = mne.pick_types(raw_ref.info, meg = False, # No MEG eeg = True, # YES EEG eog = perform_ICA, # depends on ICA ) # regardless the bandpass filtering later, we should always filter # for wire artifacts and their oscillations raw_ref.notch_filter(np.arange(notch_filter,241,notch_filter), picks = picks) if lowpass is not None: raw_ref.filter(None,lowpass,) epochs = mne.Epochs(raw_ref, events, # numpy array event_id, # dictionary tmin = tmin, tmax = tmax, baseline = baseline, # range of time for computing the mean references for each channel and subtract these values from all the time points per channel picks = picks, detrend = 1, # detrend preload = True # must be true if we want to do further processing ) """ 1. if necessary, perform ICA """ if perform_ICA: picks = mne.pick_types(epochs.info, eeg = True, # YES EEG eog = False # NO EOG ) if interpolate_bad_channels: interpolation_list = faster_bad_channels(epochs,picks=picks) for ch_name in interpolation_list: epochs.info['bads'].append(ch_name) epochs = epochs.interpolate_bads() # ar = AutoReject( # picks = picks, # random_state = 12345, # ) # ar.fit(epochs) # _,reject_log = ar.transform(epochs,return_log=True) # calculate the noise covariance of the epochs noise_cov = mne.compute_covariance(epochs,#[~reject_log.bad_epochs], tmin = baseline[0], tmax = baseline[1], method = 'empirical', rank = None,) # define an ica function ica = mne.preprocessing.ICA(n_components = .99, n_pca_components = .99, max_pca_components = None, method = 'infomax', max_iter = int(3e3), noise_cov = noise_cov, random_state = 12345,) picks = mne.pick_types(epochs.info, eeg = True, # YES EEG eog = False # NO EOG ) ica.fit(epochs,#[~reject_log.bad_epochs], picks = picks, start = tmin, stop = tmax, decim = 3, tstep = 1. # Length of data chunks for artifact rejection in seconds. It only applies if inst is of type Raw. ) # search for artificial ICAs automatically # most of these hyperparameters were used in a unrelated published study ica.detect_artifacts(epochs,#[~reject_log.bad_epochs], eog_ch = ['FT9','FT10','TP9','TP10'], eog_criterion = 0.4, # arbitary choice skew_criterion = 1, # arbitary choice kurt_criterion = 1, # arbitary choice var_criterion = 1, # arbitary choice ) picks = mne.pick_types(epochs.info, eeg = True, # YES EEG eog = False # NO EOG ) epochs_ica = ica.apply(epochs,#,[~reject_log.bad_epochs], exclude = ica.exclude, ) epochs = epochs_ica.copy() else: picks = mne.pick_types(epochs.info, eeg = True, # YES EEG eog = False # NO EOG ) if interpolate_bad_channels: interpolation_list = faster_bad_channels(epochs,picks=picks) for ch_name in interpolation_list: epochs.info['bads'].append(ch_name) epochs = epochs.interpolate_bads() # pick the EEG channels for later use clean_epochs = epochs.pick_types(eeg = True, eog = False) return clean_epochs def preprocessing_unconscious(raw, events, session, tmin = -0, tmax = 1, notch_filter = 50, event_id = {'living':1,'nonliving':2}, baseline = (None,None), perform_ICA = False, eog_chs = [], ecg_chs = [],): # everytime before filtering, explicitly pick the type of channels you want # to perform the filters picks = mne.pick_types(raw.info, meg = True, # No MEG eeg = False, # NO EEG eog = True, # YES EOG ecg = True, # YES ECG ) # regardless the bandpass filtering later, we should always filter # for wire artifacts and their oscillations if type(notch_filter) is list: for item in notch_filter: raw.notch_filter(np.arange(item,301,item), picks = picks) else: raw.notch_filter(
np.arange(notch_filter,301,notch_filter)
numpy.arange
################################################################# #iris-recognition original code base was created by #github user mokosaur https://github.com/mokosaur/iris-recognition #code was forked from original on 4-4-2019 ################################################################ import math import numpy as np from skimage.util import view_as_blocks def polar2cart(radius, xCoordinate, yCoordinate, polarAngle): """Changes polar coordinates to cartesian coordinate system. :param radius: Radius :param xCoordinate: x coordinate of the origin :param yCoordinate: y coordinate of the origin :param polarAngle: Angle :return: Cartesian coordinates :rtype: tuple (int, int) """ xCartesian = int(xCoordinate + radius * math.cos(polarAngle)) yCartesian = int(yCoordinate + radius * math.sin(polarAngle)) return xCartesian, yCartesian def unravel_iris(eyeImage, xPupilCenter, yPupilCenter, pupilRadius, xIrisCenter, yIrisCenter, irisRadius, phase_width=300, iris_width=150): """Unravels the iris from the image and transforms it to a straightened representation. :param eyeImage: Image of an eye :param xPupilCenter: x coordinate of the pupil centre :param yPupilCenter: y coordinate of the pupil centre :param pupilRadius: Radius of the pupil :param xIrisCenter: x coordinate of the iris centre :param yIrisCenter: y coordinate of the iris centre :param irisRadius: Radius of the iris :param phase_width: Length of the transformed iris :param iris_width: Width of the transformed iris :return: Straightened image of the iris :rtype: ndarray """ if eyeImage.ndim > 2: eyeImage = eyeImage[:, :, 0].copy() iris = np.zeros((iris_width, phase_width)) theta =
np.linspace(0, 2 * np.pi, phase_width)
numpy.linspace
""" rnn_lstm_cell_test_cy.py Test the correctness of the LSTM-cell implementation. """ import os import unittest from random import random from numpy import asarray, ones, zeros from torch import float64, FloatTensor, tensor from torch.nn import LSTMCell as PytorchLSTM from population.utils.rnn_cell_util.cy.lstm_cy import LSTMCellCy as LSTMCell EPSILON = 1e-5 def get_lstm(input_size): """Get a LSTM-cell of the requested input-size, completely initialized with zeros.""" bias_h = zeros((4,)) weight_hh = zeros((4, 1)) weight_xh = zeros((4, input_size)) return LSTMCell( input_size=input_size, bias=bias_h, weight_hh=weight_hh, weight_xh=weight_xh, ) def get_pytorch_lstm(input_size, used_lstm): """Load in a PyTorch LSTM that is a copy of the currently used LSTM.""" lstm = PytorchLSTM(input_size, 1) lstm.bias_hh[:] = tensor(zeros((4,)), dtype=float64)[:] lstm.bias_ih[:] = tensor(used_lstm.bias, dtype=float64)[:] lstm.weight_hh[:] = tensor(used_lstm.weight_hh, dtype=float64)[:] lstm.weight_ih[:] = tensor(used_lstm.weight_xh, dtype=float64)[:] return lstm # noinspection PyArgumentList class LSTM(unittest.TestCase): """Test the custom numpy implementation of the LSTM-cell.""" def test_single_input_single_batch(self): """> Test when only one input given and batch-size is only one.""" # Folder must be root to load in make_net properly if os.getcwd().split('\\')[-1] == 'tests': os.chdir('..') # Get 'empty' LSTM lstm = get_lstm(1) # Completely zero LSTM, all inputs get ignored self.assertEqual(lstm(asarray([[0]])), 0) lstm.hx, lstm.c = asarray([]), asarray([]) # LSTM keeps own state, reset it self.assertEqual(lstm(asarray([[1]])), 0) lstm.hx, lstm.c = asarray([]), asarray([]) # LSTM keeps own state, reset it # Modify the LSTM to have weight-arrays of one lstm.weight_hh = asarray(ones((4, 1))) lstm.weight_xh = asarray(
ones((4, 1))
numpy.ones
""" Correlation module calculating connectivity values from data """ import logging import numpy as np import os from itertools import islice from pylsl import local_clock from scipy.signal import hilbert from scipy.signal import lfilter from scipy.stats import zscore from astropy.stats import circmean from itertools import product from osc4py3.as_allthreads import * from osc4py3 import oscbuildparse from osc4py3 import oscchannel as osch import warnings warnings.filterwarnings("ignore") current = os.path.dirname(__file__) LAST_CALCULATION = local_clock() ORDER = 5 class Correlation: def __init__(self, sample_rate, channel_count, mode, chn_type, corr_params, OSC_params, compute_pow, norm_params, window_length, COEFFICIENTS, HANN, CONNECTIONS, OUTLET, OUTLET_POWER): """ Class computing connectivity values :param sample_rate: sampling rate :param channel_count: channel count :param mode: connectivity mode. See notes for options. :param chn_type: compute all electrode pairs if 'all-to-all'; alternatively, compute only corresponding electrode pairs if 'one-to-one' :param corr_params: a list of three lists: frequency parameters, channel parameters, weight parameters :param OSC_params: OSC parameters for OSC transmission :param compute_pow: boolean variable determining whether to compute and transmit power values :param norm_params: a list of two numbers. min and max values for MinMax normalization :param COEFFICIENTS: band-pass filtering coefficients :param HANN: Hanning window coefficients :param CONNECTIONS: number of connections :param OUTLET: StreamOutlet object for connectivity value output :param OUTLET_POWER: StreamOutlet object for power value output Note: **supported connectivity measures** - 'envelope correlation': envelope correlation - 'power correlation': power correlation - 'plv': phase locking value - 'ccorr': circular correlation coefficient - 'coherence': coherence - 'imaginary coherence': imaginary coherence """ self.logger = logging.getLogger(__name__) self.sample_rate = sample_rate self.window_length = window_length # number of samples in the analysis window self.channel_count = channel_count self.freqParams, self.chnParams, self.weightParams = corr_params self.OSC_params = OSC_params self.compute_pow = compute_pow self.norm_min, self.norm_max = norm_params self.mode = mode self.chn_type = chn_type self.timestamp = None self.SAMPLE_RATE = self.sample_rate self.CHANNEL_COUNT = self.channel_count # read setup tools self.COEFFICIENTS = COEFFICIENTS self.HANN = HANN self.CONNECTIONS = CONNECTIONS self.OUTLET = OUTLET if self.compute_pow: self.OUTLET_POWER = OUTLET_POWER if OSC_params[0] is not None: self._setup_OSC() def run(self, buffers): """ running the analysis :return: connectivity values """ global LAST_CALCULATION trailing_timestamp = self._find_trailing_timestamp(buffers) if trailing_timestamp != LAST_CALCULATION: LAST_CALCULATION = trailing_timestamp # select data for analysis based on the last timestamp analysis_window = self._select_analysis_window(trailing_timestamp, buffers) # apply Hanning window # analysis_window = self._apply_window_weights(analysis_window) # band-pass filter and compute analytic signal analytic_matrix = self._calculate_all(analysis_window) # compute connectivity values rvalues = self._calculate_rvalues(analytic_matrix, self.mode) if self.compute_pow: power_values = self._calculate_power(analytic_matrix) self.OUTLET_POWER.push_sample(power_values, timestamp=trailing_timestamp) # sending LSL packets if self.OUTLET: self.logger.warning("Sending {} R values with timestamp {}".format(len(rvalues), trailing_timestamp)) self.OUTLET.push_sample(rvalues, timestamp=trailing_timestamp) # sending OSC packets if self.OSC_params[0] is not None: # if sending OSC sample_size = self.CONNECTIONS * len(self.freqParams) msg = oscbuildparse.OSCMessage("/Rvalues/me", ","+'f'*sample_size, rvalues) osc_send(msg, 'Rvalues') osc_process() return rvalues else: self.logger.debug("Still waiting for new data to arrive, skipping analysis") return def _clamp(self, n): """ helper function to clamp a float variable between 0 and 1 """ return max(min(1, n), 0) def _apply_window_weights(self, analysis_window): """ applying hanning window to data :param analysis_window: dictionary with EEG data streams :return: dictionary of the same shape after applying hanning window """ for uid in analysis_window.keys(): analysis_window[uid] = np.multiply(analysis_window[uid], self.HANN[:, None]) self.logger.debug("Applying window weights with %s samples and %s channels." % analysis_window[uid].shape) return analysis_window def _setup_OSC(self): """ setting up OSC outlet """ # reading params IP = self.OSC_params[0] port = int(self.OSC_params[1]) # Start the system. osc_startup() # Make client channels to send packets. try: osc_udp_client(IP, int(port), "Rvalues") except: osch.terminate_all_channels() osc_udp_client(IP, int(port), "Rvalues") # first message is empty (removed this bc it's causing OSC msg to be all zeros) # msg = oscbuildparse.OSCMessage("/Rvalues/me", ","+'f'*sample_size, [0]*sample_size) # osc_send(msg, 'Rvalues') def _calculate_power(self, analytic_matrix): """ compute power values from analytic signals :param analytic_matrix: shape is (n_freq_bands, n_subjects, n_channel_count, n_sample_size). filtered analytic signal :return: a vector that can be reshaped into (n_freq_bands, n_subjects, n_channel_count). Power values """ return np.nanmean(np.abs(analytic_matrix)**2, axis=3).reshape(-1) def _find_trailing_timestamp(self, buffers): trailing_timestamp = local_clock() for buffer in buffers.values():#self.buffers.values(): timestamp, _ = buffer[-1] if trailing_timestamp > timestamp: trailing_timestamp = timestamp return trailing_timestamp def _select_analysis_window(self, trailing_timestamp, buffers): """ construct the analysis window based on the timestamp from last window :param trailing_timestamp: timestamp from the last window :return: a dictionary containing data. each value is a matrix of size (n_sample_size, n_channel_count) """ analysis_window = {} for uid, buffer in buffers.items():#self.buffers.items(): # compute the sample start latest_sample_at, _ = buffer[-1] sample_offset = int(round((latest_sample_at - trailing_timestamp) * self.sample_rate)) sample_start = len(buffer) - self.window_length - sample_offset if sample_start < 0: self.logger.info("Not enough data to process in buffer {}, using dummy data".format(uid)) analysis_window[uid] = np.zeros((self.window_length, self.channel_count)) else: # take data from buffer timestamped_window = list(islice(buffer, sample_start, sample_start + self.window_length)) analysis_window[uid] = np.array([sample[1] for sample in timestamped_window]) return analysis_window def _calculate_all(self, analysis_window): """ compute analytic signal from the analysis window :param analysis_window: a dictionary containing data :return: a matrix of shape (n_freq_bands, n_subjects, n_channel_count, n_sample_size) """ all_analytic = zscore(np.swapaxes(np.array(list(analysis_window.values())),1,2), axis=-1) # shape = (n_sub, n_chn, n_times) all_analytic = np.array([hilbert(lfilter(coeff[0], coeff[1], all_analytic)) for c, coeff in enumerate(self.COEFFICIENTS)]) return all_analytic # helper function def _multiply_conjugate(self, real: np.ndarray, imag: np.ndarray, transpose_axes: tuple) -> np.ndarray: """ Helper function to compute the product of a complex array and its conjugate. It is designed specifically to collapse the last dimension of a four-dimensional array. Arguments: real: the real part of the array. imag: the imaginary part of the array. transpose_axes: axes to transpose for matrix multiplication. Returns: product: the product of the array and its complex conjugate. """ formula = 'ilm,imk->ilk' product = np.einsum(formula, real, real.transpose(transpose_axes)) + \ np.einsum(formula, imag, imag.transpose(transpose_axes)) - 1j * \ (np.einsum(formula, real, imag.transpose(transpose_axes)) - \ np.einsum(formula, imag, real.transpose(transpose_axes))) return product def compute_sync(self, complex_signal: np.ndarray, mode: str) -> np.ndarray: """ helper function for computing connectivity value. The result is a connectivity matrix of all possible electrode pairs between the dyad, including inter- and intra-brain connectivities. :param complex_signal: complex signal of shape (n_freq, 2, n_channel_count, n_sample_size). data for one dyad. :param mode: connectivity mode. see notes for details. :return: connectivity matrix of shape (n_freq, 2*n_channel_count, 2*channel_count) """ n_ch, n_freq, n_samp = complex_signal.shape[2], complex_signal.shape[0], \ complex_signal.shape[3] complex_signal = complex_signal.reshape(n_freq, 2 * n_ch, n_samp) transpose_axes = (0, 2, 1) if mode.lower() == 'plv': phase = complex_signal /
np.abs(complex_signal)
numpy.abs
"""Main spyke window""" from __future__ import division from __future__ import print_function __authors__ = ['<NAME>', '<NAME>'] import sys print('Running spyke in Python %d.%d' % (sys.version_info.major, sys.version_info.minor)) from .__version__ import check_LIBVERSIONS check_LIBVERSIONS(verbose=True) # set working directory to path of this module instead of path of script that launched python, # otherwise Qt4 has problems finding the spyke.ui file: from . import __path__ import os os.chdir(__path__[0]) import sys import platform import time import datetime import gc JSONPICKLENUMERICKEYPREFIX = 'json://' LENJSONPICKLENUMERICKEYPREFIX = len(JSONPICKLENUMERICKEYPREFIX) def sort_numeric_json_keys(keyval): """Process string keys to sort jsonpickle json:// keys properly as int placeholders in natural numeric order (1, 2, 3) instead of alpha order (1, 11, 12, ..., 2, 21, 22...)""" k, v = keyval #if type(k) not in [str, unicode]: # print('Unexpected key type:', type(k)) if k.startswith(JSONPICKLENUMERICKEYPREFIX): newk = k[LENJSONPICKLENUMERICKEYPREFIX:] # left strip prefix if newk.isdigit(): # sort json int keys as natural numbers ahead of string keys newk = int(newk) #print('k=%r, newk=%r' % (k, newk)) return newk return k import jsonpickle jsonpickle.set_preferred_backend('simplejson') # make default explicit jsonpickle.set_encoder_options('simplejson', indent=' ', separators=(',', ':'), #sort_keys=True, # overridden by item_sort_key callable item_sort_key=sort_numeric_json_keys ) import jsonpickle.ext.numpy as jsonpickle_numpy jsonpickle_numpy.register_handlers() try: import cPickle as pickle except ImportError: import pickle import random from copy import copy, deepcopy from struct import unpack from collections import OrderedDict as odict import numpy as np import scipy.stats # instantiate an IPython embedded shell which shows up in the terminal on demand # and on every exception: from IPython.terminal.ipapp import load_default_config from IPython.terminal.embed import InteractiveShellEmbed config = load_default_config() # automatically call the pdb debugger after every exception, override default config: config.TerminalInteractiveShell.pdb = True ipshell = InteractiveShellEmbed(display_banner=False, config=config) from PyQt4 import QtCore, QtGui, uic from PyQt4.QtCore import Qt, QByteArray getSaveFileName = QtGui.QFileDialog.getSaveFileName getExistingDirectory = QtGui.QFileDialog.getExistingDirectory SpykeUi, SpykeUiBase = uic.loadUiType('spyke.ui') import pylab as pl from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar from matplotlib.figure import Figure import pyximport pyximport.install(build_in_temp=False, inplace=True) from . import util # .pyx file from .gac import gac # .pyx file from . import core from .core import (toiter, tocontig, intround, intceil, printflush, lstrip, matlabize, g, iterable, ClusterChange, SpykeToolWindow, DJS, qvar2list, qvar2str, qvar2int, nullwavesat) from . import dat, nsx, surf, stream, probes from .stream import SimpleStream, MultiStream from .sort import Sort, SortWindow, NSLISTWIDTH, MEANWAVEMAXSAMPLES, NPCSPERCHAN from .plot import SpikePanel, ChartPanel, LFPPanel from .detect import Detector, calc_SPIKEDTYPE, DEBUG from .extract import Extractor from .cluster import Cluster, ClusterWindow from .__version__ import __version__ # spike window temporal window (us) SPIKETW = {'.dat': (-500, 1500), '.ns6': (-500, 1500), '.srf': (-400, 600), '.tsf': (-1000, 2000)} # chart window temporal window (us) CHARTTW = {'.dat': (-25000, 25000), '.ns6': (-25000, 25000), '.srf': (-25000, 25000), '.tsf': (-50000, 50000)} # LFP window temporal window (us) LFPTW = -500000, 500000 # zero out +/- this amount of time around each saturated timepoint when exporting # high-pass data to Kilosort2: SATURATIONWINDOW = 25000 # us # shift imported Kilosort2 spike times by this much for better positioning in sort window: KILOSORT2SHIFTCORRECT = -(66+2.0/3) # us, multiple of both 16.67 or 33.33 .ns6 tres # spatial channel layout: # UVPERUM affects vertical channel spacing and voltage gain (which is further multiplied by # each plot window's gain): UVPERUM = {'.dat': 5, '.ns6': 5, '.srf': 2, '.tsf': 20} # USPERUM affects horizontal channel spacing. Decreasing USPERUM increases horizontal overlap # between spike chans. For .srf data, 17 gives roughly no horizontal overlap for # self.tw[1] - self.tw[0] == 1000 us: # However, this also depends on the horizontal spacing of the probe sites, so really # this should be set according to probe type, not file type, or it should be scaled in # terms of fraction of the horizontal span of the probe site layout: USPERUM = {'.dat': 50, '.ns6': 50, '.srf': 17, '.tsf': 125} DYNAMICNOISEX = {'.dat': 4.5, '.ns6': 4.5, '.srf': 6, '.tsf': 3} # noise multiplier DT = {'.dat': 600, '.ns6': 600, '.srf': 400, '.tsf': 1500} # max time between spike peaks (us) SCREENWIDTH = 1920 # TODO: this should be found programmatically #SCREENHEIGHT = 1080 # TODO: this should be found programmatically WINDOWTITLEHEIGHT = 26 # TODO: this should be found programmatically BORDER = 2 # TODO: this should be found programmatically SPIKEWINDOWWIDTHPERCOLUMN = 80 SPIKEWINDOWHEIGHT = 658 + 2*BORDER # TODO: this should be calculated from SCREENHEIGHT CHARTWINDOWSIZE = 900+2*BORDER, SPIKEWINDOWHEIGHT LFPWINDOWSIZE = 250+2*BORDER, SPIKEWINDOWHEIGHT #SHELLSIZE = CHARTWINDOWSIZE[0], CHARTWINDOWSIZE[1]/2 CLUSTERWINDOWHEIGHT = 700 MAXRECENTFILES = 20 # anything > 10 will mess up keyboard accelerators, but who cares WINDOWUPDATEORDER = ['Spike', 'LFP', 'Chart'] # chart goes last cuz it's slowest # if updating at least this many selected spikes in .wave file, update them all # instead for speed: NDIRTYSIDSTHRESH = 200000 class SpykeWindow(QtGui.QMainWindow): """spyke's main window, uses gui layout generated by QtDesigner""" def __init__(self): QtGui.QMainWindow.__init__(self) self.ui = SpykeUi() self.ui.setupUi(self) # lay it out self.groupMenuFiltering() self.groupMenuCAR() self.groupMenuSampling() self.addRecentFileActions() self.updateRecentFiles() self.move(0, 0) # top left corner, to make space for data windows self.streampath = os.getcwd() # init self.sortpath = os.getcwd() # init for d in ('~/data', '/data'): # use first existing of these paths, if any path = os.path.expanduser(d) if os.path.exists(path): self.streampath = path self.sortpath = path break self.windows = {} # holds child windows self.t = None # current time position in recording (us) self.hpstream = None self.lpstream = None self.cchanges = core.Stack() # cluster change stack, for undo/redo self.cci = -1 # pointer to cluster change for the next undo (add 1 for next redo) self.dirtysids = set() # sids whose waveforms in .wave file are out of date # disable most widgets until a stream or a sort is opened: self.EnableStreamWidgets(False) self.EnableSortWidgets(False) self.EnableFilteringMenu(False) # disable by default, not all file types need filtering self.EnableCARMenu(False) # disable until stream is open self.EnableSamplingMenu(False) # disable until stream is open def addRecentFileActions(self): """Init recent file QActions and insert them into the right place in the File menu. Leave them invisible until needed""" self.recentFileActions = [] for i in range(MAXRECENTFILES): action = QtGui.QAction(self) action.setVisible(False) action.triggered.connect(self.OpenRecentFile) self.recentFileActions.append(action) self.ui.menuFile.insertAction(self.ui.actionSaveSort, action) self.ui.menuFile.insertSeparator(self.ui.actionSaveSort) def groupMenuFiltering(self): """Group filtering methods in filtering menu into a QActionGroup such that only one is ever active at a time. This isn't possible to do from within QtDesigner 4.7, so it's done here manually instead""" ui = self.ui filteringGroup = QtGui.QActionGroup(self) filteringGroup.addAction(ui.actionFiltmethNone) filteringGroup.addAction(ui.actionFiltmethBW) filteringGroup.addAction(ui.actionFiltmethBWNC) filteringGroup.addAction(ui.actionFiltmethWMLDR) def groupMenuCAR(self): """Group common average referencing methods in CAR menu into a QActionGroup such that only one is ever active at a time. This isn't possible to do from within QtDesigner 4.7, so it's done here manually instead""" ui = self.ui CARGroup = QtGui.QActionGroup(self) CARGroup.addAction(ui.actionCARNone) CARGroup.addAction(ui.actionCARMedian) CARGroup.addAction(ui.actionCARMean) def groupMenuSampling(self): """Group sampling rates in sampling menu into a QActionGroup such that only one is ever active at a time. This isn't possible to do from within QtDesigner 4.7, so it's done here manually instead""" ui = self.ui samplingGroup = QtGui.QActionGroup(self) samplingGroup.addAction(ui.action20kHz) samplingGroup.addAction(ui.action25kHz) samplingGroup.addAction(ui.action30kHz) samplingGroup.addAction(ui.action40kHz) samplingGroup.addAction(ui.action50kHz) samplingGroup.addAction(ui.action60kHz) samplingGroup.addAction(ui.action80kHz) samplingGroup.addAction(ui.action100kHz) samplingGroup.addAction(ui.action120kHz) @QtCore.pyqtSlot() def on_actionNewSort_triggered(self): self.DeleteSort() # don't create a new one until spikes exist @QtCore.pyqtSlot() def on_actionNewTrack_triggered(self): self.CreateNewTrack() def CreateNewTrack(self): """Create a new .track file""" exts = ['.ns6', '.dat', '.srf'] caption = "Create .track file from %s files" % ' '.join(exts) starexts = [ '*%s' % ext for ext in exts ] filter = ('%s files ' % ', '.join(exts) + '(%s)' % ' '.join(starexts) + ';;All files (*.*)') trackfname = getSaveFileName(self, caption=caption, directory=self.streampath, filter=filter) trackfname = str(trackfname) if not trackfname: return if not trackfname.endswith('.track'): trackfname += '.track' path = os.path.split(trackfname)[0] ls = os.listdir(path) fnames = {} for ext in exts: fnames = [ fname for fname in os.listdir(path) if fname.endswith(ext) ] if len(fnames) > 0: break if len(fnames) == 0: print("Couldn't find any .ns6, .dat, or .srf files in %r" % path) return fnames = sorted(fnames) trackstr = '\n'.join(fnames) with open(trackfname, 'w') as trackf: trackf.write(trackstr) trackf.write('\n') # end the file with a newline print('Wrote track file %r:' % trackfname) print(trackstr) self.OpenFile(trackfname) @QtCore.pyqtSlot() def on_actionOpen_triggered(self): getOpenFileName = QtGui.QFileDialog.getOpenFileName filter = (".dat, .ns6, .srf, .track, .tsf, .mat, .event, .sort & .json files " "(*.dat *.ns6 *.srf *.track *.tsf *.mat *.event*.zip *.sort *.json);;" "All files (*.*)") fname = getOpenFileName(self, caption="Open stream or sort or din", directory=self.streampath, filter=filter) fname = str(fname) if fname: self.OpenFile(fname) @QtCore.pyqtSlot() def on_actionSaveSort_triggered(self): try: self.sort except AttributeError: # sort doesn't exist return if self.sort.fname: self.SaveSortFile(self.sort.fname) # save to existing sort fname else: self.on_actionSaveSortAs_triggered() @QtCore.pyqtSlot() def on_actionSaveSortAs_triggered(self): """Save sort to new .sort/.json file""" fname = self.sort.fname if fname == '': # sort hasn't been previously saved # generate default fname with hpstream.fname: fname = self.hpstream.fname.replace(' ', '_') # and datetime: #dt = str(datetime.datetime.now()) # get a sort creation timestamp #dt = dt.split('.')[0] # ditch the us #dt = dt.replace(' ', '_') #dt = dt.replace(':', '.') #fname += '_' + dt fname += '.json' # add default sort fname extension defaultfname = os.path.join(self.sortpath, fname) fname = getSaveFileName(self, caption="Save sort As", directory=defaultfname, filter="Sort files (*.sort *.json);;" "All files (*.*)") fname = str(fname) if fname: head, tail = os.path.split(fname) base, ext = os.path.splitext(tail) if ext not in ['.sort', '.json']: raise ValueError('Sort file extension (.sort or .json) must be specified') oldsortpath = self.sortpath oldbase, oldext = os.path.splitext(self.sort.fname) # Don't force re-creation of new .wave file if the base name and path # are the same and the .wave file already exists. This means that when # overwriting a sort file with SaveAs, its .wave file is untouched: try: wavefileexists = os.path.exists(os.path.join(head, self.sort.wavefname)) except AttributeError: # self.sort.wavefname not set wavefileexists = False # at least as far as this Sort is concerned if head == oldsortpath and base == oldbase and wavefileexists: print('Skipping overwriting of existing .wave file: %s' % self.sort.wavefname) pass else: # force re-creation of .wave file self.sortpath = head # update sort path try: del self.sort.wavefname except AttributeError: pass self.SaveSortFile(tail) # always overwrites any existing .spike file @QtCore.pyqtSlot() def on_actionSaveTrackChans_triggered(self): self.SaveTrackChans() def SaveTrackChans(self): """Overwrite existing .track file, potentially saving a new set of enabled chans""" stream = self.hpstream if not stream.is_multi(): print("Stream is not a MultiStream, can't save a .track file") return trackfname = os.path.join(self.streampath, stream.fname) if not os.path.isfile(trackfname): raise RuntimeError('Somehow the current MultiStream has no existing .track file') trackstr = '' allchans = np.sort(stream.streams[0].f.fileheader.chans) if len(stream.chans) != len(allchans): # some chans are disabled, write them as a comment in .track file trackstr += '# enabledchans = %r\n' % list(stream.chans) else: assert (stream.chans == allchans).all() trackstr += '\n'.join(stream.fnames) with open(trackfname, 'w') as trackf: trackf.write(trackstr) trackf.write('\n') # end the file with a newline print('Wrote track file %r:' % trackfname) print(trackstr) @QtCore.pyqtSlot() def on_actionSaveParse_triggered(self): if self.hpstream.ext == '.srf': self.hpstream.pickle() else: print('Only .srf streams have complicated parsings that can be ' 'saved to a .parse file') def getUserInfo(self): """Get user info when exporting spikes""" dlg = uic.loadUi('userinfodialog.ui') dlg.setWindowTitle('Enter optional user initials/name and notes about the sort') sort = self.sort dlg.userLineEdit.insert(sort.user) dlg.notesTextEdit.insertPlainText(sort.notes) if dlg.exec_(): # returns 1 if OK, 0 if Cancel user = str(dlg.userLineEdit.text()).rstrip().upper() notes = str(dlg.notesTextEdit.toPlainText()).rstrip() if not user.isalpha(): print('User initials must be alphabetic characters only') sort.user = user sort.notes = notes return user, notes @QtCore.pyqtSlot() def on_actionExportPtcsFiles_triggered(self): userinfo = self.getUserInfo() if userinfo is None: return # cancel user, notes = userinfo path = getExistingDirectory(self, caption="Export .ptcs file(s) to", directory=self.sortpath) path = str(path) if path: self.sort.exportptcsfiles(path, self.sortpath, user=user, notes=notes) # don't update path @QtCore.pyqtSlot() def on_actionExportTsChIdFiles_triggered(self): path = getExistingDirectory(self, caption="Export .tschid file(s) to", directory=self.sortpath) path = str(path) if path: self.sort.exporttschid(path) # don't update path @QtCore.pyqtSlot() def on_actionExportDIN_triggered(self): path = getExistingDirectory(self, caption="Export .din file(s) to", directory=self.sortpath) path = str(path) if path: ## TODO: if sort doesn't exist, make a temporary fake with hpstream ## as its stream. That's all that's needed. self.sort.exportdin(path) # don't update path @QtCore.pyqtSlot() def on_actionExportTextheader_triggered(self): path = getExistingDirectory(self, caption="Export .textheader file(s) to", directory=self.sortpath) path = str(path) if path: ## TODO: if sort doesn't exist, make a temporary fake with hpstream ## as its stream. That's all that's needed. self.sort.exporttextheader(path) # don't update path @QtCore.pyqtSlot() def on_actionExportAll_triggered(self): path = getExistingDirectory(self, caption="Export .ptcs, .din and .textheader file(s) to", directory=self.sortpath) path = str(path) if path: self.sort.exportall(basepath=path, sortpath=self.sortpath) # don't update path @QtCore.pyqtSlot() def on_actionExportCSVFile_triggered(self): """Export "good" spikes to .csv file""" sortfname = os.path.join(self.sortpath, self.sort.fname) if sortfname == '': # sort hasn't been previously saved raise ValueError('Please save sort file before exporting to .csv') # generate default fname with sort fname + datetime: sortfname = sortfname.replace(' ', '_') dt = str(datetime.datetime.now()) # get an export timestamp dt = dt.split('.')[0] # ditch the us dt = dt.replace(' ', '_') dt = dt.replace(':', '.') ext = '.csv' defaultfname = sortfname + '_' + dt + ext caption = "Export spikes to %s file" % ext filter = "%s spike files (*%s);;All files (*.*)" % (ext, ext) fname = getSaveFileName(self, caption=caption, directory=defaultfname, filter=filter) fname = str(fname) if fname: before, sep, after = fname.partition(ext) if sep != ext: fname = before + ext # make sure it has extension sw = self.OpenWindow('Sort') # in case it isn't already open self.sort.exportcsv(fname) @QtCore.pyqtSlot() def on_actionExportSpikesZipFile_triggered(self): """Save selected spikes on selected channels and timepoints to binary .spikes.zip file""" self.exportSpikeWaveforms(format='binary') @QtCore.pyqtSlot() def on_actionExportSpikesCSVFile_triggered(self): """Save selected spikes on selected channels and timepoints to text .spikes.csv file""" self.exportSpikeWaveforms(format='text') def exportSpikeWaveforms(self, format): """Save selected spikes on selected channels and timepoints to binary .spikes.zip file or text .spikes.csv file""" if format == 'binary': ext = '.spikes.zip' elif format == 'text': ext = '.spikes.csv' else: raise ValueError("Invalid format: %r" % format) defaultfname = os.path.join(self.sortpath, self.sort.fname) if defaultfname == '': # sort hasn't been previously saved # generate default fname with hpstream.fname and datetime fname = self.hpstream.fname.replace(' ', '_') dt = str(datetime.datetime.now()) # get an export timestamp dt = dt.split('.')[0] # ditch the us dt = dt.replace(' ', '_') dt = dt.replace(':', '.') defaultfname = fname + '_' + dt defaultfname = defaultfname + ext caption = "Export spike waveforms to %s %s file" % (format, ext) filter = "%s spike waveform files (*%s);;All files (*.*)" % (format, ext) fname = getSaveFileName(self, caption=caption, directory=defaultfname, filter=filter) fname = str(fname) if fname: before, sep, after = fname.partition(ext) if sep != ext: fname = before + ext # make sure it has extension sids = self.GetAllSpikes() selchans = self.get_selchans(sids) sw = self.OpenWindow('Sort') # in case it isn't already open tis = sw.tis self.sort.exportspikewaves(sids, selchans, tis, fname, format) @QtCore.pyqtSlot() def on_actionExportHighPassDatFiles_triggered(self): self.export_hpstream() def export_hpstream(self, cat=False, gaps=False, checksat=False, satwin=None, export_msg='high-pass', export_ext='.filt.dat'): """Export high-pass stream to user-designated path, using current preprocessing settings (filtering, CAR, and resampling) and channel selection, to export_ext file(s) with associated export_ext.json file describing the preprocessing that was done. This can also be used to export raw data if the hpstream settings for filtering, CAR and resampling are set appropriately. Use export_msg and export_ext to communicate this. cat controls whether to concatenate all the exported data into a single .dat file. If gaps is True, gaps between streams in a Multistream are excluded from the .dat file; if gaps is False, gaps are not excluded from the .dat file and are zero-padded, resulting in one long continuous time range of data. If checksat is true, check for saturation in raw data, then null out +/- satwin us around any saturated data. This works best if the data is indeed high-pass""" if not self.hpstream: print('First open a stream!') return if self.hpstream.is_multi(): # self.hpstream is a MultiStream defaultpath = self.hpstream.streams[0].f.path # get path of first stream if cat: # export entire MultiStream to one file: hpstreams = [self.hpstream] else: # export each stream in MultiStream to a separate file hpstreams = self.hpstream.streams else: # self.hpstream is a single Stream assert cat == False # nonsensical for a single Stream defaultpath = self.hpstream.f.path hpstreams = [self.hpstream] caption = "Export %s data to %s files" % (export_msg, export_ext) path = str(getExistingDirectory(self, caption=caption, directory=defaultpath)) if not path: return print('Exporting %d channels:' % self.hpstream.nchans) print('chans = %s' % self.hpstream.chans) blocksize = int(float(self.ui.blockSizeLineEdit.text())) print('Exporting in blocks of %d us' % blocksize) for hps in hpstreams: fname = hps.fname + export_ext fullfname = os.path.join(path, fname) fulljsonfname = fullfname + '.json' print('Exporting %s data to %r' % (export_msg, fullfname)) with open(fullfname, 'wb') as datf: # collect tranges that will correspond to exported timepoints in .dat: tranges = np.array([[hps.t0, hps.t1]]) # 2D array if hps.is_multi() and gaps: # make gaps explicit by excluding them from tranges: tranges = hps.tranges # tranges of streams in MultiStream, 2D array nulltranges = [] t0s = np.arange(hps.t0, hps.t1, blocksize) for t0 in t0s: t1 = t0 + blocksize #print('%d to %d us' % (t0, t1)) printflush('.', end='') # succint progress indicator wave = hps(t0, t1, checksat=checksat, gaps=gaps) if checksat: satis = wave.satis # should have same shape as wave.data if satis.any(): wsatis = np.where(satis) # integer row and col indices satchanis = np.unique(wsatis[0]) # indices of rows that saturated satchans = wave.chans[satchanis] print() # newline print('Saturation in block (%d, %d) on chans %s' % (t0, t1, satchans)) ntwin = intround(satwin / hps.tres) # null the saturated periods: blocknulltranges = nullwavesat(wave, ntwin) # nx2 array nulltranges.append(blocknulltranges) #if t0 == t0s[-1]: # print('last block asked:', t0, t1) # print('last block received:', wave.ts[0], wave.ts[-1]) wave.data.T.tofile(datf) # write in column-major (Fortran) order print() # newline if len(nulltranges) == 0: nulltranges = None # default value else: # concatenate 2D arrays vertically: nulltranges = np.concatenate(nulltranges, axis=0) #nulltrangesfname = fullfname + '.0tranges.npy' #np.save(nulltrangesfname, nulltranges) print('Nulled %d time ranges' % len(nulltranges)) core.write_dat_json(hps, fulljsonfname, gaps=gaps, tranges=tranges, nulltranges=nulltranges) print('Done exporting %s data' % export_msg) # only return path and fname if we're only exporting to a single file: if len(hpstreams) == 1: return path, fname @QtCore.pyqtSlot() def on_actionExportLFPZipFiles_triggered(self): self.export_lpstream(format='binary') @QtCore.pyqtSlot() def on_actionExportLFPCSVFiles_triggered(self): self.export_lpstream(format='text') def export_lpstream(self, format='binary'): """Export low-pass stream (LFP) data as binary .lfp.zip file(s) or text .lfp.csv file(s) in user-designated basepath""" if not self.lpstream: print('First open a stream!') return format2ext = {'binary': '.lfp.zip', 'text': '.lfp.csv'} ext = format2ext[format] caption = "Export low-pass data to %s %s files" % (format, ext) basepath = getExistingDirectory(self, caption=caption, directory=self.sortpath) basepath = str(basepath) if not basepath: return if self.lpstream.is_multi(): # self.lpstream is a MultiStream lpstreams = self.lpstream.streams else: # self.lpstream is a single Stream lpstreams = [self.lpstream] print('Exporting low-pass data to:') for lps in lpstreams: path = os.path.join(basepath, lps.srcfnameroot) try: os.mkdir(path) except OSError: pass # path already exists? fullfname = os.path.join(path, lps.srcfnameroot+ext) print(fullfname) # collect low-pass data in blocks, to prevent MemoryErrors when trying to # low-pass filter an entire raw ephys data file: blocksize = int(float(self.ui.blockSizeLineEdit.text())) # allow exp notation t0s = np.arange(lps.t0, lps.t1, blocksize) data = [] for t0 in t0s: t1 = t0 + blocksize wave = lps[t0:t1] data.append(wave.data) # concatenate data blocks horizontally in time: data = np.hstack(data) if format == 'binary': chanpos = lps.probe.siteloc_arr() uVperAD = lps.converter.AD2uV(1) with open(fullfname, 'wb') as f: np.savez_compressed(f, data=data, chans=wave.chans, t0=lps.t0, t1=lps.t1, tres=lps.tres, chanpos=chanpos, chan0=lps.probe.chan0, probename=lps.probe.name, uVperAD=uVperAD) else: # format == 'text' np.savetxt(fullfname, data, fmt='%d', delimiter=',') # data should be int print('Done exporting low-pass data') @QtCore.pyqtSlot() def on_actionExportHighPassEnvelopeDatFiles_triggered(self): self.export_hp_envelope() @QtCore.pyqtSlot() def on_actionExportHighPassBipolarRefEnvelopeDatFiles_triggered(self): self.export_hp_envelope(bipolarref=True) def export_hp_envelope(self, sampfreq=2000, f0=None, f1=500, bipolarref=False): """Export envelope of high-pass stream to the same folder as the stream, or if this is a MultiStream, to the same folders as each of its constituent Streams. Use current preprocessing settings (filtering, CAR, and resampling), to .envl.dat file(s) with associated .envl.dat.json file describing the preprocessing that was done. Decimate output to get sampfreq. Export chans in order of depth, superficial to deep. bipolarref: optionally take each channel's raw data to be the difference of the two immediately spatially adjacent channels, before calculating the envelope""" if not self.hpstream: print('First open a stream!') return if self.hpstream.is_multi(): # self.hpstream is a MultiStream hpstreams = self.hpstream.streams else: # self.hpstream is a single Stream hpstreams = [self.hpstream] print('Exporting high-pass envelope data to:') for hps in hpstreams: assert hps.sampfreq % sampfreq == 0 decimatex = intround(hps.sampfreq / sampfreq) fullfname = os.path.join(hps.f.path, hps.fname + '.envl.dat') fulljsonfname = fullfname + '.json' print(fullfname) # excess data to get at either end of each block, to eliminate # filtering edge effects: xs = core.XSWIDEBANDPOINTS * hps.rawtres # us # sort channels for export by depth instead of by ID: # get ypos of each enabled site: enabledchans = self.hpstream.chans ypos = [ self.hpstream.probe.SiteLoc[chan][1] for chan in enabledchans ] ysortis = np.argsort(ypos) ychans = enabledchans[ysortis] with open(fullfname, 'wb') as datf: blocksize = int(float(self.ui.blockSizeLineEdit.text())) # allow exp notation t0s = np.arange(hps.t0, hps.t1, blocksize) for t0 in t0s: t1 = t0 + blocksize t0xs, t1xs = t0-xs, t1+xs wave = hps[t0xs:t1xs] # get excess range of data data = wave.data[ysortis] # sort chans by depth chans = wave.chans[ysortis] assert (chans == ychans).all() if bipolarref: # set each channel to be the difference of the two immediately # spatially adjacent channels: data[1:-1] = data[:-2] - data[2:] data[[0, -1]] = 0 # null out the first and last channel # get envelope of data by rectifying and low-pass filtering: data = core.envelope_filt(data, sampfreq=hps.sampfreq, f0=f0, f1=f1) # float64 # ensure data limits fall within int16: iint16 = np.iinfo(np.int16) assert data.max() <= iint16.max assert data.min() >= iint16.min data = np.int16(data) # convert float64 to int16 t0i, t1i = wave.ts.searchsorted([t0, t1]) # get indices to remove excess data = data[:, t0i:t1i:decimatex] # remove excess and decimate data.T.tofile(datf) # write in column-major (Fortran) order envelope = odict() envelope['meth'] = 'abs' envelope['bipolar_ref'] = bipolarref envelope['filter_meth'] = 'BW' envelope['f0'] = f0 envelope['f1'] = f1 core.write_dat_json(hps, fulljsonfname, sampfreq=sampfreq, chans=ychans, chan_order='depth', envelope=envelope) print('Done exporting high-pass envelope data') @QtCore.pyqtSlot() def on_actionExportWideBandDatKilosort2Files_triggered(self): self.export_wb_ks2_dat() @QtCore.pyqtSlot() def on_actionExportRawDataDatFiles_triggered(self): self.export_raw_dat() @QtCore.pyqtSlot() def on_actionExportKilosort2Files_triggered(self): fname = self.hpstream.fname if self.hpstream.is_multi(): # self.hpstream is a MultiStream path = self.hpstream.streams[0].f.path # get path of first stream else: # self.hpstream is a single Stream path = self.hpstream.f.path self.export_ks2(path, fname) def export_wb_ks2_dat(self): """Export wide-band ephys data for use in Kilosort2, while checking for and zeroing out any periods of saturation. Exports enabled chans concatenated across all files in current track, without gaps, to .dat file in user-designated path. This works by first turning off all filtering, CAR, and resampling, then calling self.export_hpstream(), then restoring filtering, CAR, and resampling settings""" print('Exporting wide-band gapless ephys data to .dat file for use in Kilosort2, ' 'removing any saturation') # save current hpstream filtering, CAR, and sampling settings: stream = self.hpstream if not stream: print('First open a stream!') return # check if this is already a .dat file, if so, we probably want to simply run # self.export_ks2() instead. Perhaps this block can be commented out for # exceptional cases, such as if an oe .dat file has periods of saturation or channels # to exclude, in which case a new .dat.dat file does indeed need to be exported # for Kilosort2: fname = self.hpstream.fname base, ext = os.path.splitext(fname) if ext == '.dat': print('*** NOTE: The currently open %s data stream is already a .dat file, and ' 'there may be no need to export another one (unless you want to ensure ' 'saturation periods are removed). If you want to simply ' 'export the Kilosort2 channel map, config, and run files, cancel with ' 'Ctrl+C and try again with the appropriate menu option' % fname) filtmeth = stream.filtmeth car = stream.car sampfreq = stream.sampfreq shcorrect = stream.shcorrect # set hpstream to show raw data: print('Temporarily disabling filtering, CAR, and resampling for raw export') self.SetFiltmeth(None) self.SetCAR(None) self.SetSampfreq(stream.rawsampfreq) if stream.ext != '.srf': self.SetSHCorrect(False) # leave it enabled for .srf, data is wrong w/o it # do the export: if stream.is_multi(): # it's a MultiStream cat, gaps = True, True # concatenate, export with timestamp gaps else: # it's a single Stream cat, gaps = False, False # nothing to concatenate result = self.export_hpstream(cat=cat, gaps=gaps, checksat=True, satwin=SATURATIONWINDOW, export_msg='wide-band', export_ext='.dat') if result: path, datfname = result # restore hpstream settings: print('Restoring filtering, CAR, and resampling settings') self.SetFiltmeth(filtmeth) self.SetCAR(car) self.SetSampfreq(sampfreq) self.SetSHCorrect(shcorrect) if not result: print('Wide-band data export cancelled') return # export Kilosort2 files: self.export_ks2(path, datfname) def export_ks2(self, path, datfname): """Export Kilosort2 channel map, config, and run files to path, for the specified .dat file""" stream = self.hpstream if not stream: print('First open a stream!') return base, ext = os.path.splitext(datfname) if ext != '.dat': print('Kilosort2 can only run on .dat files, %s is a %s file.\n' 'Maybe you first need to export to a .dat file?' % (datfname, ext)) return # write Kilosort2 channel map .mat file, indicate which chans are included in the .dat datfnameML = matlabize(datfname) # make suitable for use as MATLAB script name chanmapfname = datfnameML + '_ks2_chanmap.mat' fullchanmapfname = os.path.join(path, chanmapfname) core.write_ks2_chanmap_mat(stream, fullchanmapfname) # write Kilosort2 config .m file: with open('./templates/Kilosort2/ks2_config.m') as templateksconfigf: ksconfigstr = templateksconfigf.read() ksconfigstr = ksconfigstr.format(DATFNAME=datfname, KSRESULTSFOLDERNAME=datfname+'.ks2_results', CHANMAPFNAME=chanmapfname, NCHANS=stream.nchans, FS=stream.rawsampfreq, ) ksconfigfname = datfnameML + '_ks2_config.m' fullksconfigfname = os.path.join(path, ksconfigfname) with open(fullksconfigfname, 'w') as ksconfigf: ksconfigf.write(ksconfigstr) print('Wrote Kilosort2 config file %r' % fullksconfigfname) # write Kilosort2 run .m file: with open('./templates/Kilosort2/ks2_run.m') as templateksrunf: ksrunstr = templateksrunf.read() # can't use str.format() because the curly bracket field replacement # syntax in Python conflicts with Matlab cell array {i} indexing: #ksrunstr = ksrunstr.format(KSCONFIGFNAME=ksconfigfname) # use simple str.replace() instead: ksrunstr = ksrunstr.replace('{KSCONFIGFNAME}', ksconfigfname) ksrunfname = datfnameML + '_ks2_run.m' fullksrunfname = os.path.join(path, ksrunfname) with open(fullksrunfname, 'w') as ksrunf: ksrunf.write(ksrunstr) print('Wrote Kilosort2 run file %r' % fullksrunfname) def export_raw_dat(self): """Export raw ephys data of enabled chans concatenated across all files in current track, to .dat file in user-designated path. This works by first turning off all filtering, CAR, and resampling, then calling self.export_hpstream(), then restoring filtering, CAR, and resampling settings""" print('Exporting raw ephys data to .dat file') # save current hpstream filtering, CAR, and sampling settings: stream = self.hpstream if not stream: print('First open a stream!') return filtmeth = stream.filtmeth car = stream.car sampfreq = stream.sampfreq shcorrect = stream.shcorrect # set hpstream to show raw data: print('Temporarily disabling filtering, CAR, and resampling for raw export') self.SetFiltmeth(None) self.SetCAR(None) self.SetSampfreq(stream.rawsampfreq) if stream.ext != '.srf': self.SetSHCorrect(False) # leave it enabled for .srf, data is wrong w/o it # do the export: if stream.is_multi(): # it's a MultiStream cat = True # concatenate else: # it's a single Stream cat = False # nothing to concatenate result = self.export_hpstream(cat=cat, export_msg='raw', export_ext='.dat') if result: path, datfname = result # restore hpstream settings: print('Restoring filtering, CAR, and resampling settings') self.SetFiltmeth(filtmeth) self.SetCAR(car) self.SetSampfreq(sampfreq) self.SetSHCorrect(shcorrect) if not result: print('Raw data export cancelled') return @QtCore.pyqtSlot() def on_actionConvertKilosort2Npy2EventsZip_triggered(self): caption = "Convert relevant Kilosort2 .npy files to a single .events.zip file" path = getExistingDirectory(self, caption=caption, directory=self.streampath) path = str(path) if not path: return self.convert_kilosort2npy2eventszip(path) def update_sort_version(self): """Update self.sort to latest version""" s = self.sort v = float(s.__version__) # sort version lv = float(__version__) # latest version if v > lv: raise RuntimeError('Versioning error') if v == lv: print('No update necessary') return if v < 0.3: print("Can't auto update from sort version < 0.3") return if v == 0.3: v = self.update_0_3_to_0_4() if v == 0.4: v = self.update_0_4_to_0_5() if v == 0.5: v = self.update_0_5_to_0_6() if v == 0.6: v = self.update_0_6_to_0_7() if v == 0.7: v = self.update_0_7_to_0_8() if v == 0.8: v = self.update_0_8_to_0_9() if v == 0.9: v = self.update_0_9_to_1_0() if v == 1.0: v = self.update_1_0_to_1_1() if v == 1.1: v = self.update_1_1_to_1_2() if v == 1.2: v = self.update_1_2_to_1_3() if v == 1.3: v = self.update_1_3_to_1_4() if v == 1.4: v = self.update_1_4_to_2_0() if v == 2.0: v = self.update_2_0_to_2_1() print('Now save me!') def update_0_3_to_0_4(self): """Update sort 0.3 to 0.4: - reload all spike waveforms and fix all of their time values """ print('Updating sort from version 0.3 to 0.4') s = self.sort sids = np.arange(s.nspikes) s.reload_spikes(sids) # add sids to the set of dirtysids to be resaved to .wave file: self.dirtysids.update(sids) s.__version__ = '0.4' # update print('Done updating sort from version 0.3 to 0.4') return float(s.__version__) def update_0_4_to_0_5(self): """Update sort 0.4 to 0.5: - rename sort.sortfname to sort.fname """ print('Updating sort from version 0.4 to 0.5') s = self.sort s.fname = s.sortfname del s.sortfname s.__version__ = '0.5' # update print('Done updating sort from version 0.4 to 0.5') return float(s.__version__) def update_0_5_to_0_6(self): """Update sort 0.5 to 0.6: - rename sort.spikes field names 'phasetis' and 'dphase' to 'tis' and 'dt' respectively - remove unused 'cid', 's0' and 's1' fields from sort.spikes, reorder fields """ print('Updating sort from version 0.5 to 0.6') s = self.sort names = list(s.spikes.dtype.names) # convert from tuple phasetis_index = names.index('phasetis') dphase_index = names.index('dphase') assert (phasetis_index, dphase_index) == (13, 19) names[phasetis_index] = 'tis' # rename 'phasetis' to 'tis' names[dphase_index] = 'dt' # rename 'dphase' to 'dt' s.spikes.dtype.names = names # checks length and auto converts back to tuple # also rename fields in detector's SPIKEDTYPE: for i in [phasetis_index, dphase_index]: field = list(s.detector.SPIKEDTYPE[i]) field[0] = names[i] s.detector.SPIKEDTYPE[i] = tuple(field) # new name order, leaves out unused 'cid', 's0' and 's1' newnames = ['id', 'nid', 'chan', 'nchans', 'chans', 'chani', 't', 't0', 't1', 'dt', 'tis', 'aligni', 'V0', 'V1', 'Vpp', 'x0', 'y0', 'sx', 'sy'] olddtype = s.detector.SPIKEDTYPE # list of tuples oldnames = [ field[0] for field in olddtype ] newdtype = [] for name in newnames: newdtype.append(olddtype[oldnames.index(name)]) s.detector.SPIKEDTYPE = newdtype # replace detector's SPIKEDTYPE newspikes = np.empty(s.spikes.shape, dtype=newdtype) from numpy.lib import recfunctions as rfn newspikes = rfn.recursive_fill_fields(s.spikes, newspikes) # copy from old to new s.spikes = newspikes # overwrite # in cluster.pos and .normpos, remove 's0' and 's1', and rename 'dphase' to 'dt': for c in s.clusters.values(): c.pos.pop('s0') c.pos.pop('s1') c.pos['dt'] = c.pos.pop('dphase') c.normpos.pop('s0') c.normpos.pop('s1') c.normpos['dt'] = c.normpos.pop('dphase') s.__version__ = '0.6' # update print('Done updating sort from version 0.5 to 0.6') return float(s.__version__) def update_0_6_to_0_7(self): """Update sort 0.6 to 0.7: - replace sort.TW class attribute with sort.tw instance attribute """ print('Updating sort from version 0.6 to 0.7') s = self.sort # Sort.TW class attrib was (-500, 500) in version 0.6 s.tw = -500, 500 s.__version__ = '0.7' # update print('Done updating sort from version 0.6 to 0.7') return float(s.__version__) def update_0_7_to_0_8(self): """Update sort 0.7 to 0.8: - rename/move classes (done by core.unpickler_find_global()): - core.Stream -> stream.SurfStream - core.SimpleStream -> stream.SimpleStream - core.TrackStream -> stream.MultiStream - rename Stream attrib .srff -> .f - rename MultiStream attrib .srffnames -> .fnames - add potentially missing sort.npcsperchan attrib """ print('Updating sort from version 0.7 to 0.8') s = self.sort stream = s.stream classname = stream.__class__.__name__ if classname == 'SurfStream': f = stream.srff del stream.srff stream.f = f elif classname == 'SimpleStream': # don't think any existing saved SimpleStreams had a .srff attrib: pass elif classname == 'MultiStream': fnames = stream.srffnames del stream.srffnames stream.fnames = fnames else: raise RuntimeError("Don't know how to upgrade stream type %r" % classname) try: s.npcsperchan except AttributeError: s.npcsperchan = NPCSPERCHAN s.__version__ = '0.8' # update print('Done updating sort from version 0.7 to 0.8') return float(s.__version__) def update_0_8_to_0_9(self): """Update sort 0.8 to 0.9: - add sort.filtmeth attrib, init to None """ print('Updating sort from version 0.8 to 0.9') s = self.sort try: s.filtmeth except AttributeError: s.filtmeth = None s.__version__ = '0.9' # update print('Done updating sort from version 0.8 to 0.9') return float(s.__version__) def update_0_9_to_1_0(self): """Update sort 0.9 to 1.0: - add nlockchans and lockchans fields to spike record - add detector.lockrx attrib """ print('Updating sort from version 0.9 to 1.0') s = self.sort oldspikes = s.spikes olddtype = oldspikes.dtype.descr # [(fieldname, fieldtype)] tuples, ordered by offset oldnames = oldspikes.dtype.names # list of field names, ordered by offset oldfields = oldspikes.dtype.fields # {fieldname:(fielddtype, byte offset)} mapping newdtype = copy(olddtype) inserti = oldnames.index('t') # insert our new fields just before the 't' field assert inserti == 6 newdtype.insert(inserti, ('nlockchans', oldfields['nchans'][0])) # copy nchans type newdtype.insert(inserti+1, ('lockchans', oldfields['chans'][0])) # copy chans type s.detector.SPIKEDTYPE = newdtype # replace detector's SPIKEDTYPE newspikes = np.empty(oldspikes.shape, dtype=newdtype) # init newspikes from numpy.lib import recfunctions as rfn newspikes = rfn.recursive_fill_fields(oldspikes, newspikes) # copy from old to new # the new fields are redundant for old detection runs, but are used in the code # for displaying spike rasters: newspikes['nlockchans'] = oldspikes['nchans'] newspikes['lockchans'] = oldspikes['chans'] s.spikes = newspikes # overwrite from pprint import pprint print('Old dtype:') pprint(olddtype) print('New dtype:') pprint(s.spikes.dtype.descr) # add new detector.lockrx attrib, supercedes detector.lockr attrib s.detector.lockrx = 0.0 # set to 0 to indicate it wasn't used during detection s.__version__ = '1.0' # update print('Done updating sort from version 0.9 to 1.0') return float(s.__version__) def update_1_0_to_1_1(self): """Update sort 1.0 to 1.1: - add sort.car attrib, init to None """ print('Updating sort from version 1.0 to 1.1') s = self.sort try: s.car except AttributeError: s.car = None s.__version__ = '1.1' # update print('Done updating sort from version 1.0 to 1.1') return float(s.__version__) def update_1_1_to_1_2(self): """Update sort 1.1 to 1.2: - add stream.adapter, fileheader.adapter & fileheader.adaptername, init to None """ print('Updating sort from version 1.1 to 1.2') s = self.sort if s.stream.is_multi(): s.stream.adapter = None streams = s.stream.streams else: # it's a single stream streams = [s.stream] for stream in streams: # iterate over all single streams stream.adapter = None if stream.ext in ['.ns6', '.dat']: stream.f.fileheader.adapter = None stream.f.fileheader.adaptername = None s.__version__ = '1.2' # update print('Done updating sort from version 1.1 to 1.2') return float(s.__version__) def update_1_2_to_1_3(self): """Update sort 1.2 to 1.3: - rename class (done by core.unpickler_find_global()): - A1x64_Poly2_6mm_23s_160 -> A1x64 """ print('Updating sort from version 1.2 to 1.3') s = self.sort classname = s.probe.__class__.__name__ if s.probe.name == 'A1x64_Poly2_6mm_23s_160': print('sort.probe class is now %r' % classname) print('sort.probe.name was %r' % s.probe.name) s.probe.name = 'A1x64' # update name attribute print('sort.probe.name is now %r' % s.probe.name) s.__version__ = '1.3' # update print('Done updating sort from version 1.2 to 1.3') return float(s.__version__) def update_1_3_to_1_4(self): """Update sort 1.3 to 1.4: - add .tres attribute to all WaveForms, which should only be in Neuron.wave """ print('Updating sort from version 1.3 to 1.4') s = self.sort for nid, neuron in s.neurons.items(): print('n%d ' % nid, end='') wave = neuron.wave try: wave.tres except AttributeError: if wave.ts is None: # empty WaveForm, can't calculate tres print("Found empty WaveForm, setting missing neuron.wave.tres = None") wave.tres = None continue tres = s.tres # assign tres from sort print('Setting missing neuron.wave.tres = %f' % tres) wave.tres = tres s.__version__ = '1.4' # update print('Done updating sort from version 1.3 to 1.4') return float(s.__version__) def update_1_4_to_2_0(self): """Update sort 1.4 to 2.0: - mostly just to document new support for jsonpickle .json sort files - store window state QByteArray rawdata instead of full object """ print('Updating sort from version 1.4 to 2.0') s = self.sort for wintype in s.windowGeometries: # for compatibility with jsonpickle, instead of saving the QByteArray to the sort, # save its raw data as a (byte) string: s.windowGeometries[wintype] = s.windowGeometries[wintype].data() s.windowStates[wintype] = s.windowStates[wintype].data() s.__version__ = '2.0' # update print('Done updating sort from version 1.4 to 2.0.\n' 'Consider saving as .json instead of .sort\n' 'Click "File->Save Sort As" and then change the extension to .json') return float(s.__version__) def update_2_0_to_2_1(self): """Update sort 2.0 to 2.1: - add empty .user and .notes fields for use when exporting spikes """ print('Updating sort from version 2.0 to 2.1') s = self.sort s.user = '' s.notes = '' s.__version__ = '2.1' # update print('Done updating sort from version 2.0 to 2.1') return float(s.__version__) @QtCore.pyqtSlot() def on_actionCloseSort_triggered(self): # TODO: add confirmation dialog if Sort not saved self.CloseSortFile() print('Closed sort') @QtCore.pyqtSlot() def on_actionCloseStream_triggered(self): if self.hpstream is not None: self.CloseStream() print('Closed stream') @QtCore.pyqtSlot() def on_actionQuit_triggered(self): self.close() #self.destroy() # no longer seems necessary, causes segfault def closeEvent(self, event): self.on_actionCloseSort_triggered() self.on_actionCloseStream_triggered() QtGui.QMainWindow.closeEvent(self, event) def keyPressEvent(self, event): key = event.key() try: sw = self.windows['Sort'] except KeyError: QtGui.QMainWindow.keyPressEvent(self, event) # pass it on if key == Qt.Key_A: self.ui.plotButton.click() elif key == Qt.Key_X: self.ui.plotXcorrsButton.click() elif key == Qt.Key_N: self.ui.normButton.click() elif key in [Qt.Key_Escape, Qt.Key_E]: sw.clear() elif key == Qt.Key_R: # doesn't fire when certain widgets have focus sw.on_actionSelectRandomSpikes_triggered() elif key == Qt.Key_B: sw.on_actionAlignBest_triggered() @QtCore.pyqtSlot() def on_actionUndo_triggered(self): """Undo button click. Undo previous cluster change""" try: cc = self.cchanges[self.cci] except IndexError: print('Nothing to undo') return print('Undoing: %s' % cc.message) self.ApplyClusterChange(cc, direction='back') self.cci -= 1 # move pointer one change back on the stack print('Undo complete') @QtCore.pyqtSlot() def on_actionRedo_triggered(self): """Redo button click. Redo next cluster change""" try: cc = self.cchanges[self.cci+1] except IndexError: print('Nothing to redo') return print('Redoing: %s' % cc.message) self.ApplyClusterChange(cc, direction='forward') self.cci += 1 # move pointer one change forward on the stack print('Redo complete') @QtCore.pyqtSlot() def on_actionSpikeWindow_triggered(self): """Spike window toggle menu/button event""" self.ToggleWindow('Spike') @QtCore.pyqtSlot() def on_actionChartWindow_triggered(self): """Chart window toggle menu/button event""" self.ToggleWindow('Chart') @QtCore.pyqtSlot() def on_actionLFPWindow_triggered(self): """LFP window toggle menu/button event""" self.ToggleWindow('LFP') @QtCore.pyqtSlot() def on_actionSortWindow_triggered(self): """Sort window toggle menu/button event""" self.ToggleWindow('Sort') @QtCore.pyqtSlot() def on_actionClusterWindow_triggered(self): """Cluster window toggle menu/button event""" self.ToggleWindow('Cluster') @QtCore.pyqtSlot() def on_actionMPLWindow_triggered(self): """Matplotlib window toggle menu/button event""" self.ToggleWindow('MPL') @QtCore.pyqtSlot() def on_actionShell_triggered(self): """Shell window toggle menu/button event""" #self.ToggleWindow('Shell') # FIXME: this blocks until you Ctrl-D out of ipython: ipshell() @QtCore.pyqtSlot() def on_actionRasters_triggered(self): """Spike rasters toggle menu event""" self.ToggleRasters() @QtCore.pyqtSlot() def on_actionStims_triggered(self): """Spike stimulus edges toggle menu event""" self.ToggleStims() @QtCore.pyqtSlot() def on_actionTimeRef_triggered(self): """Time reference toggle menu event""" self.ToggleRef('TimeRef') @QtCore.pyqtSlot() def on_actionVoltageRef_triggered(self): """Voltage reference toggle menu event""" self.ToggleRef('VoltageRef') @QtCore.pyqtSlot() def on_actionScale_triggered(self): """Scale toggle menu event""" self.ToggleRef('Scale') @QtCore.pyqtSlot() def on_actionCaret_triggered(self): """Caret toggle menu event""" self.ToggleRef('Caret') @QtCore.pyqtSlot() def on_actionFiltmethNone_triggered(self): """None filtering menu choice event""" self.SetFiltmeth(None) @QtCore.pyqtSlot() def on_actionFiltmethBW_triggered(self): """Butterworth filtering menu choice event""" self.SetFiltmeth('BW') @QtCore.pyqtSlot() def on_actionFiltmethBWNC_triggered(self): """Non-causal Butterworth filtering menu choice event""" self.SetFiltmeth('BWNC') @QtCore.pyqtSlot() def on_actionFiltmethWMLDR_triggered(self): """WMLDR filtering menu choice event""" self.SetFiltmeth('WMLDR') @QtCore.pyqtSlot() def on_actionCARNone_triggered(self): """None CAR menu choice event""" self.SetCAR(None) @QtCore.pyqtSlot() def on_actionCARMedian_triggered(self): """Median CAR menu choice event""" self.SetCAR('Median') @QtCore.pyqtSlot() def on_actionCARMean_triggered(self): """Mean CAR menu choice event""" self.SetCAR('Mean') @QtCore.pyqtSlot() def on_action20kHz_triggered(self): """20kHz menu choice event""" self.SetSampfreq(20000) @QtCore.pyqtSlot() def on_action25kHz_triggered(self): """25kHz menu choice event""" self.SetSampfreq(25000) @QtCore.pyqtSlot() def on_action30kHz_triggered(self): """30kHz menu choice event""" self.SetSampfreq(30000) @QtCore.pyqtSlot() def on_action40kHz_triggered(self): """40kHz menu choice event""" self.SetSampfreq(40000) @QtCore.pyqtSlot() def on_action50kHz_triggered(self): """50kHz menu choice event""" self.SetSampfreq(50000) @QtCore.pyqtSlot() def on_action60kHz_triggered(self): """60kHz menu choice event""" self.SetSampfreq(60000) @QtCore.pyqtSlot() def on_action80kHz_triggered(self): """80kHz menu choice event""" self.SetSampfreq(80000) @QtCore.pyqtSlot() def on_action100kHz_triggered(self): """100kHz menu choice event""" self.SetSampfreq(100000) @QtCore.pyqtSlot() def on_action120kHz_triggered(self): """120kHz menu choice event""" self.SetSampfreq(120000) @QtCore.pyqtSlot() def on_actionSampleAndHoldCorrect_triggered(self): """Sample & hold menu event""" enable = self.ui.actionSampleAndHoldCorrect.isChecked() self.SetSHCorrect(enable) #def onFilePosLineEdit_textChanged(self, text): # updates immediately def on_filePosLineEdit_editingFinished(self): # updates on Enter/loss of focus text = str(self.ui.filePosLineEdit.text()) try: t = self.str2t[text] except KeyError: # convert to float to allow exp notation shorthand t = float(text) self.seek(t) @QtCore.pyqtSlot() def on_actionAboutSpyke_triggered(self): with open('../LICENSE', 'r') as lf: LICENSE = lf.read() system = """<p>Python %s, Qt %s, PyQt %s<br> %s</p>""" % (platform.python_version(), QtCore.QT_VERSION_STR, QtCore.PYQT_VERSION_STR, platform.platform()) text = """ <h2><a href=http://spyke.github.io>spyke</a> %s</h2> <p>A tool for neuronal waveform visualization and spike sorting</p> <p>Copyright &copy; 2008-2019 <a href=https://mspacek.github.io><NAME></a>, <NAME><br> <a href=http://swindale.ecc.ubc.ca>Swindale</a> Lab, University of British Columbia, Vancouver, Canada<br> <a href=http://www.neuro.bio.lmu.de/members/system_neuro_busse/busse_l/index.html> Busse</a> Lab, Ludwig-Maximilians-University, Munich, Germany</p> <p>Some functionality inherited from <NAME>'s Delphi program "SurfBawd".</p> <p>Many icons were copied from Ubuntu's <a href=http://launchpad.net/humanity>Humanity</a> icon theme.</p> <p>%s</p> %s""" % (__version__, LICENSE, system) QtGui.QMessageBox.about(self, "About spyke", text) @QtCore.pyqtSlot() def on_actionAboutQt_triggered(self): QtGui.QMessageBox.aboutQt(self) @QtCore.pyqtSlot() def on_filePosStartButton_clicked(self): self.seek(self.str2t['start']) @QtCore.pyqtSlot() def on_filePosEndButton_clicked(self): self.seek(self.str2t['end']) @QtCore.pyqtSlot(int) def on_slider_valueChanged(self, slideri): t = slideri * self.hpstream.tres self.seek(t) def update_slider(self): """Update slider limits and step sizes. Slider ticks are multiples of tres""" tres = self.hpstream.tres self.ui.slider.setRange(intround(self.trange[0] / tres), intround(self.trange[1] / tres)) self.ui.slider.setValue(intround(self.t / tres)) self.ui.slider.setSingleStep(1) self.ui.slider.setPageStep(intround((self.spiketw[1]-self.spiketw[0]) / tres)) self.ui.slider.setInvertedControls(True) @QtCore.pyqtSlot() def on_detectButton_clicked(self): """Detect pane Detect button click""" sort = self.CreateNewSort() # create a new sort, with bound stream self.get_detector() # update Sort's current detector with new one from widgets if sort.detector.extractparamsondetect: self.init_extractor() # init the Extractor # create struct array of spikes and 3D array of spike waveform data: sort.spikes, sort.wavedata = sort.detector.detect(logpath=self.streampath) sort.update_usids() # lock down filtmeth, car, sampfreq and shcorrect attribs: sort.filtmeth = sort.stream.filtmeth sort.car = sort.stream.car sort.sampfreq = sort.stream.sampfreq sort.shcorrect = sort.stream.shcorrect self.ui.progressBar.setFormat("%d spikes" % sort.nspikes) self.EnableSortWidgets(True) sw = self.OpenWindow('Sort') # ensure it's open if sort.nspikes > 0: self.on_plotButton_clicked() def init_extractor(self): """Initialize Extractor""" #XYmethod = self.XY_extract_radio_box.GetStringSelection() # hard code XYmethod for now, don't really need extract pane: if self.sort.probe.ncols == 1: XYmethod = 'Gaussian 1D' else: XYmethod = 'Gaussian 2D' # create Extractor, or eventually, call a self.get_extractor() method instead: ext = Extractor(self.sort, XYmethod, maxsigma=self.sort.detector.inclr) self.sort.extractor = ext # eventually, update extractor from multiple Extract pane widgets: #self.update_extractor(ext) def OnXYExtract(self, evt=None): """Extract pane XY Extract button click. Extracts (or re-extracts and overwrites) XY parameters from all sort.spikes, and stores them as spike attribs""" try: self.sort.extractor except AttributeError: self.init_extractor() #import cProfile #cProfile.runctx('self.sort.extractor.extract_all_XY()', globals(), locals()) self.sort.extractor.extract_all_XY() # adds extracted XY params to sort.spikes self.windows['Sort'].uslist.updateAll() # update any columns showing param values self.EnableSpikeWidgets(True) # enable cluster_pane def OnWaveletExtract(self, evt=None): """Extract pane wavelet Extract button click. Extracts (or re-extracts and overwrites) wavelet coefficients from all sort.spikes, and stores them as spike attribs""" try: self.sort.extractor except AttributeError: self.init_extractor() #import cProfile #cProfile.runctx('self.sort.extractor.extract_all_XY()', globals(), locals()) # extract coeffs of selected wavelet type, add coeffs to sort.spikes wavelet = self.wavelet_extract_radio_box.GetStringSelection() self.sort.extractor.extract_all_wcs(wavelet) self.windows['Sort'].uslist.updateAll() # update any columns showing param values self.EnableSpikeWidgets(True) # enable cluster_pane def OnTemporalExtract(self, evt=None): """Extract pane temporal Extract button click. Extracts (or re-extracts and overwrites) temporal params from all sort.spikes, and stores them as spike attribs""" try: self.sort.extractor except AttributeError: self.init_extractor() self.sort.extractor.extract_all_temporal() self.windows['Sort'].uslist.updateAll() # update any columns showing param values self.EnableSpikeWidgets(True) # enable cluster_pane @QtCore.pyqtSlot() def on_clusterButton_clicked(self): """Cluster pane Cluster button click""" s = self.sort spikes = s.spikes #sids = self.GetAllSpikes() # all selected spikes # always cluster all spikes in existing clusters, don't just cluster some subset, # since existing clusters are always deleted in apply_clustering and # ApplyClusterChange, and spikes that aren't in that subset would inadvertantly # become unsorted sids = np.concatenate([self.GetClusterSpikes(), self.GetUnsortedSpikes()]) sids.sort() oldclusters = self.GetClusters() # all selected clusters if len(sids) == 0: # nothing selected sids = spikes['id'] # all spikes (sorted) oldclusters = s.clusters.values() # all clusters dims = self.GetClusterPlotDims() comps = np.any([ dim.startswith('c') and dim[-1].isdigit() for dim in dims ]) subsidss = [] # sids grouped into subclusters, each to be clustered separately msgs = [] t0 = time.time() if comps and np.all(sids == spikes['id']): # doing PCA/ICA on all spikes if not oldclusters: print("No existing clusters to sequentially do PCA/ICA on and subcluster") return # partition data by existing clusters before clustering, # restrict to only clustered spikes: for oldcluster in oldclusters: subsidss.append(oldcluster.neuron.sids) msgs.append('oldcluster %d' % oldcluster.id) sids = np.concatenate(subsidss) # update sids.sort() else: # just the selected spikes subsidss.append(sids) msgs.append('%d selected sids' % len(sids)) nids = self.subcluster(sids, subsidss, msgs, dims) print('Clustering took %.3f sec' % (time.time()-t0)) self.apply_clustering(oldclusters, sids, nids, verb='GAC') def subcluster(self, sids, subsidss, msgs, dims): """Perform (sub)clustering according to subsids in subsidss. Incorporate results from each (sub)clustering into a single nids output array""" # init nids output array to be all unclustered: nids = np.zeros(len(sids), dtype=np.int32) for subsids, msg in zip(subsidss, msgs): print('Clustering %s on dims %r' % (msg, dims)) subnids = self.gac(subsids, dims) # subclustering result ci = subnids > 0 # consider only the clustered sids subsids = subsids[ci] subnids = subnids[ci] nidoffset = max(nids) + 1 nidsi = sids.searchsorted(subsids) nids[nidsi] = subnids + nidoffset return nids def chancombosplit(self): """Split spikes into clusters of unique channel combinations""" s = self.sort spikes = s.spikes sids = self.GetAllSpikes() # all selected spikes oldclusters = self.GetClusters() # all selected clusters if len(sids) == 0: # nothing selected sids = spikes['id'] # all spikes (sorted) oldclusters = s.clusters.values() # all clusters t0 = time.time() chans = spikes[sids]['chans'] chans = tocontig(chans) # string view won't work without contiguity # each row becomes a string: strchans = chans.view('S%d' % (chans.itemsize*chans.shape[1])) # each row in uchancombos is a unique combination of chans: uchancombos = np.unique(strchans).view(chans.dtype).reshape(-1, chans.shape[1]) if len(uchancombos) == 1: print("Selected spikes all share the same set of channels, can't chancombosplit") return # init to unclustered, shouldn't be any once done: nids = np.zeros(len(sids), dtype=np.int32) for comboi, chancombo in enumerate(uchancombos): nids[(chans == chancombo).all(axis=1)] = comboi + 1 if (nids == 0).any(): raise RuntimeError("There shouldn't be any unclustered points from chancombosplit") print('chancombosplit took %.3f sec' % (time.time()-t0)) self.apply_clustering(oldclusters, sids, nids, verb='chancombo split') def maxchansplit(self): """Split spikes into clusters by maxchan""" s = self.sort spikes = s.spikes sids = self.GetAllSpikes() # all selected spikes oldclusters = self.GetClusters() # all selected clusters if len(sids) == 0: # nothing selected sids = spikes['id'] # all spikes (sorted) oldclusters = s.clusters.values() # all clusters t0 = time.time() maxchans = spikes[sids]['chan'] umaxchans = np.unique(maxchans) if len(umaxchans) == 1: print("Selected spikes all share the same set of max channels, can't maxchansplit") return # init to unclustered, shouldn't be any once done: nids = np.zeros(len(sids), dtype=np.int32) for maxchani, maxchan in enumerate(umaxchans): nids[maxchans == maxchan] = maxchani + 1 if (nids == 0).any(): raise RuntimeError("There shouldn't be any unclustered points from maxchansplit") print('maxchansplit took %.3f sec' % (time.time()-t0)) self.apply_clustering(oldclusters, sids, nids, verb='maxchan split') def densitysplit(self): """Split cluster pair by density along line between their centers in current cluster space""" s = self.sort spikes = s.spikes oldclusters = self.GetClusters() # all selected clusters if len(oldclusters) != 2: print("Need to select exactly 2 clusters to split them by density") return dims = self.GetClusterPlotDims() try: X, sids = self.get_param_matrix(dims=dims) except RuntimeError as err: print(err) return nids = s.spikes['nid'][sids] # copy unids = np.unique(nids) assert len(unids) == 2 # centers of both clusters, use median: i0 = nids == unids[0] i1 = nids == unids[1] c0 = np.median(X[i0], axis=0) # ndims vector c1 = np.median(X[i1], axis=0) # line connecting the centers of the two clusters, wrt c0 line = c1-c0 line /= np.linalg.norm(line) # make it unit length #print('c0=%r, c1=%r, line=%r' % (c0, c1, line)) proj = np.dot(X-c0, line) # projection of each point onto line nbins = max(intround(np.sqrt(len(proj))), 2) # good heuristic #print('nbins = %d' % nbins) hist, edges = np.histogram(proj, bins=nbins) ei0, ei1 = edges.searchsorted((np.median(proj[i0]), np.median(proj[i1]))) # find histogram min between cluster medians: threshi = hist[ei0:ei1].argmin() thresh = edges[ei0:ei1][threshi] #print('thresh is %.3f' % thresh) #print('ei0, ei1: %d, %d' % (ei0, ei1)) assert ei0 < ei1 # think this is always the case because projections are wrt c0 nids[proj < thresh] = unids[0] # overwrite nid values in nids, since it's a copy nids[proj >= thresh] = unids[1] self.apply_clustering(oldclusters, sids, nids, verb='density split') def randomsplit(self): """Randomly split each selected cluster in half. This is done to increase gac() speed""" oldclusters = self.GetClusters() # all selected clusters subsidss = [] for cluster in oldclusters: subsidss.append(cluster.neuron.sids) sids = np.concatenate(subsidss) sids.sort() destsubsidss = [] for subsids in subsidss: np.random.shuffle(subsids) # shuffle in-place spliti = len(subsids) // 2 destsubsids0 = subsids[:spliti] destsubsids0.sort() # sids should always go out sorted destsubsidss.append(destsubsids0) destsubsids1 = subsids[spliti:] destsubsids1.sort() destsubsidss.append(destsubsids1) # init to unclustered, shouldn't be any once done: nids = np.zeros(len(sids), dtype=np.int32) for i, destsubsids in enumerate(destsubsidss): nids[sids.searchsorted(destsubsids)] = i + 1 if (nids == 0).any(): raise RuntimeError("There shouldn't be any unclustered points from randomsplit") self.apply_clustering(oldclusters, sids, nids, verb='randomly split') def gac(self, sids, dims): """Cluster sids along dims, using NVS's gradient ascent algorithm""" s = self.sort norm = self.ui.normButton.isChecked() data, sids = self.get_param_matrix(sids=sids, dims=dims, norm=norm, scale=True) data = tocontig(data) # ensure it's contiguous for gac() # grab gac() params and run it self.update_sort_from_cluster_pane() npoints, ndims = data.shape print('Clustering %d points in %d-D space' % (npoints, ndims)) t0 = time.time() nids = gac(data, sigma=s.sigma, rmergex=s.rmergex, rneighx=s.rneighx, alpha=s.alpha, maxgrad=s.maxgrad, maxnnomerges=1000, minpoints=s.minpoints) # nids from gac() are 0-based, but we want our single unit nids to be 1-based, # to leave room for junk cluster at 0 and multiunit clusters at nids < 0. So add 1: nids += 1 print('GAC took %.3f sec' % (time.time()-t0)) return nids def get_selchans(self, sids): """Return user selected chans. If none, automatically select and return chans within a radius encompassing 95% percent of sx values in sids, centered on average position of sids. Could also use a multiple of this derived sx to select more or fewer chans""" spikes = self.sort.spikes panel = self.windows['Sort'].panel selchans = panel.chans_selected # a list selchans.sort() if selchans and panel.manual_selection: return selchans # always return whatever's manually selected sxs = spikes['sx'][sids] sxs = np.sort(sxs) # get a sorted copy sxi = int(len(sxs) * 0.95) # round down, index > ~95% percent of values sx = sxs[sxi] dm = self.sort.detector.dm # DistanceMatrix spos = np.vstack((spikes['x0'][sids], spikes['y0'][sids])).T # sids x 2 meanpos = spos.mean(axis=0) # mean spike position chanpos = np.asarray(dm.coords) # positions of enabled chans # Euclidean chan distances from meanpos: d = np.sqrt(np.sum((chanpos - meanpos)**2, axis=1)) # chans within sx of meanpos: selchans = sorted(dm.chans[d <= sx].tolist()) # from int64 to list for clean jsonpickle print('Selection center: %.1f, %.1f um' % (meanpos[0], meanpos[1])) print('Selection radius: %.1f um' % sx) panel.chans_selected = selchans panel.update_selvrefs() panel.draw_refs() panel.manual_selection = False return selchans def apply_clustering(self, oldclusters, sids, nids, verb=''): """Delete old clusters and replace the existing clustering of the desired sids with their new nids""" s = self.sort spikes = s.spikes sw = self.windows['Sort'] cw = self.windows['Cluster'] # deselect all clusters before potentially deleting any unselected # clusters, to avoid lack of Qt selection event when selection values # (not rows) change. Also, deselect usids while we're at it: self.SelectClusters(s.clusters, on=False) sw.uslist.clearSelection() # delete junk cluster if it exists and isn't in oldclusters, # add this deletion to cluster change stack if 0 in s.clusters and 0 not in [ c.id for c in oldclusters ]: # save some undo/redo stuff message = 'delete junk cluster 0' cc = ClusterChange(s.neurons[0].sids, spikes, message) cc.save_old([s.clusters[0]], s.norder, s.good) # delete it s.remove_neuron(0) # save more undo/redo stuff cc.save_new([], s.norder, s.good) self.AddClusterChangeToStack(cc) print(cc.message) # save some undo/redo stuff message = '%s clusters %r' % (verb, [ c.id for c in oldclusters ]) cc = ClusterChange(sids, spikes, message) cc.save_old(oldclusters, s.norder, s.good) # start insertion indices of new clusters from first selected cluster, if any unids = np.unique(nids) nnids = len(unids) insertis = [None] * nnids if len(oldclusters) > 0: startinserti = s.norder.index(oldclusters[0].id) insertis = range(startinserti, startinserti+nnids) # delete old clusters self.DelClusters(oldclusters, update=False) # apply new clusters newclusters = [] for nid, inserti in zip(unids, insertis): ii, = np.where(nids == nid) nsids = sids[ii] # sids belonging to this nid if nid != 0: nid = None # auto generate a new nid cluster = self.CreateCluster(update=False, id=nid, inserti=inserti) newclusters.append(cluster) neuron = cluster.neuron sw.MoveSpikes2Neuron(nsids, neuron, update=False) if len(nsids) == 0: raise RuntimeError('WARNING: neuron %d has no spikes for some reason' % neuron.id) cluster.update_pos() # save more undo/redo stuff cc.save_new(newclusters, s.norder, s.good) self.AddClusterChangeToStack(cc) # now do some final updates self.UpdateClustersGUI() if len(sids) != len(spikes) or not np.all(sids == spikes['id']): # if clustering only some spikes, select all newly created cluster(s) self.SelectClusters(newclusters) if len(sids) == len(cw.glWidget.sids) and np.all(sids == cw.glWidget.sids): self.ColourPoints(newclusters) # just recolour else: self.on_plotButton_clicked() # need to do a full replot cc.message += ' into %r' % [c.id for c in newclusters] print(cc.message) @QtCore.pyqtSlot() def on_x0y0VppButton_clicked(self): """Cluster pane x0y0Vpp button click. Set plot dims to x0, y0, and Vpp""" self.SetPlotDims('x0', 'y0', 'Vpp') @QtCore.pyqtSlot() def on_c0c1c2Button_clicked(self): """Cluster pane c0c1c2 button click. Set plot dims to c0, c1, and c2""" s = self.sort ctrl = QtGui.QApplication.instance().keyboardModifiers() == Qt.ControlModifier if ctrl: try: del s.X[s.get_Xhash(*self.get_Xhash_args())] # force recalc except (AttributeError, KeyError): pass self.SetPlotDims('c0', 'c1', 'c2') @QtCore.pyqtSlot() def on_c0c1tButton_clicked(self): """Cluster pane c0c1t button click. Set plot dims to c0, c1, and t""" s = self.sort ctrl = QtGui.QApplication.instance().keyboardModifiers() == Qt.ControlModifier if ctrl: try: del s.X[s.get_Xhash(*self.get_Xhash_args())] # force recalc except (AttributeError, KeyError): pass self.SetPlotDims('c0', 'c1', 't') def SetPlotDims(self, x, y, z): """Set plot dimensions to x, y, z, and replot""" xi = self.ui.xDimComboBox.findText(x) yi = self.ui.yDimComboBox.findText(y) zi = self.ui.zDimComboBox.findText(z) self.ui.xDimComboBox.setCurrentIndex(xi) self.ui.yDimComboBox.setCurrentIndex(yi) self.ui.zDimComboBox.setCurrentIndex(zi) self.on_plotButton_clicked() # replot def get_param_matrix(self, sids=None, dims=None, norm=False, scale=True): """Given list of dims, get clustering parameter matrix according to current selection of sids and channels""" s = self.sort sw = self.OpenWindow('Sort') # in case it isn't already open cw = self.OpenWindow('Cluster') # in case it isn't already open comps = np.any([ dim.startswith('c') and dim[-1].isdigit() for dim in dims ]) # calc RMS error between each spike and its clusters median waveform, if any? rmserror = np.any([ dim == 'RMSerror' for dim in dims ]) if sids is None: sids = self.GetAllSpikes() # only selected spikes if len(sids) == 0: # if none selected if comps: # if component analysis selected raise RuntimeError('Need non-empty spike selection to do component analysis') else: # return all spike ids sids = self.sort.spikes['id'] kind = None tis = None selchans = None if comps or rmserror: tis = sw.tis # waveform time indices to include, centered on spike selchans = self.get_selchans(sids) if comps: kind = str(self.ui.componentAnalysisComboBox.currentText()) norm = self.ui.normButton.isChecked() X = s.get_param_matrix(kind=kind, sids=sids, tis=tis, selchans=selchans, norm=norm, dims=dims, scale=scale) return X, sids def get_Xhash_args(self): """Return currently selected clustering paramaters that would be used to generate the identifying hash for the dimension reduced matrix if it were to be calculated at this point in time""" sw = self.OpenWindow('Sort') # in case it isn't already open kind = str(self.ui.componentAnalysisComboBox.currentText()) sids = self.GetAllSpikes() # only selected spikes tis = sw.tis # waveform time indices to include, centered on spike selchans = np.asarray(self.get_selchans(sids)) chans = self.sort.get_common_chans(sids, selchans)[0] npcsperchan = self.sort.npcsperchan norm = self.ui.normButton.isChecked() return kind, sids, tis, chans, npcsperchan, norm @QtCore.pyqtSlot() def on_plotButton_clicked(self): """Cluster pane plot button click. Plot points and colour them according to their clusters.""" s = self.sort ctrl = QtGui.QApplication.instance().keyboardModifiers() == Qt.ControlModifier if ctrl: try: del s.X[s.get_Xhash(*self.get_Xhash_args())] # force recalc except (AttributeError, KeyError): pass cw = self.OpenWindow('Cluster') # in case it isn't already open dims = self.GetClusterPlotDims() try: X, sids = self.get_param_matrix(dims=dims) except RuntimeError as err: print(err) return if len(X) == 0: return # nothing to plot nids = s.spikes['nid'][sids] cw.plot(X, sids, nids) sw = self.OpenWindow('Sort') # in case it isn't already open sw.PlotClusterHistogram(X, nids) # auto update cluster histogram plot @QtCore.pyqtSlot() def on_normButton_clicked(self): """Cluster pane norm button click""" if self.ui.normButton.isChecked(): print('Normalizing spike amplitudes') else: print('Un-normalizing spike amplitudes') self.windows['Sort'].panel.updateAllItems() # refresh plotted waveforms self.on_plotButton_clicked() # refresh cluster plot @QtCore.pyqtSlot() def get_cleaning_density_hist(self): """Calculate histogram of point densities of selected spikes over selected clustering dimensions from origin""" dims = self.GetClusterPlotDims() X, sids = self.get_param_matrix(dims=dims) # each dim in X has 0 mean, so X is centered on origin X = np.float64(X) # convert to double precision ndims = X.shape[1] r = np.sqrt(np.square(X).sum(axis=1)) # all +ve values r /= r.std() # normalize to unit variance nbins = intround(np.sqrt(len(X))) # good heuristic rhist, edges = np.histogram(r, nbins) # distance hist, edges includes the right edge ledges = edges[:-1] # keep just the left edges, discard the last right edge assert len(ledges) == nbins binwidth = ledges[1] - ledges[0] # density histogram: npoints / fractional volume dhist = np.float64(rhist) / np.diff(edges**ndims) dhist /= (dhist * binwidth).sum() # normalize to unit area return dhist, ledges, binwidth, ndims, sids, r @QtCore.pyqtSlot() def on_cleanHistButton_clicked(self): """Cluster pane cleaning hist button click. Plot histogram of point densities of selected spikes over selected clustering dimensions from origin, compare to Gaussian. Note that each time you reject points > nstds away from origin, the distrib may get less and less Gaussian, and more and more uniform""" dhist, ledges, binwidth, ndims, sids, r = self.get_cleaning_density_hist() ris = ledges + (binwidth / 2) # center values of bins gauss = g(0, 1, ris) gauss /= (gauss * binwidth).sum() # normalize to unit area djs = DJS(dhist, gauss) mplw = self.OpenWindow('MPL') a = mplw.ax a.clear() mplw.setWindowTitle('Density Histogram') a.bar(ledges, dhist, width=binwidth) a.plot(ris, gauss, '-') # plot Gaussian on top of density histogram a.set_title('%dD cluster density histogram, DJS = %.3f' % (ndims, djs)) a.set_xlabel('nstdevs') a.set_ylabel('Normalized density') mplw.f.tight_layout(pad=0.3) # crop figure to contents mplw.figurecanvas.draw() @QtCore.pyqtSlot() def on_cleanButton_clicked(self): """Cluster pane clean button click. Set as unsorted those points that fall outside of nstds distance away in the cluster density histogram plotted above""" # r vals are in nstds units: dhist, ledges, binwidth, ndims, sids, r = self.get_cleaning_density_hist() nstds = self.ui.cleanNstdsSpinBox.value() nids = self.sort.spikes[sids]['nid'] unids = np.unique(nids) oldclusters = [ self.sort.clusters[unid] for unid in unids ] nids[r > nstds] = 0 # set some sids to cluster 0, ie unclustered self.apply_clustering(oldclusters, sids, nids, verb='clean') @QtCore.pyqtSlot() def on_calcMatchErrorsButton_clicked(self): """Match pane calc button click. Calculate rmserror between all clusters and all unsorted spikes. Also calculate which cluster each unsorted spike matches best""" spikes = self.sort.spikes wavedata = self.sort.wavedata cids = np.sort(list(self.sort.clusters)) sids = self.sort.usids.copy() ncids, nsids = len(cids), len(sids) print('Calculating rmserror between all %d clusters and all %d unsorted spikes' % (ncids, nsids)) errs = np.empty((ncids, nsids), dtype=np.float32) errs.fill(np.inf) # TODO: replace with sparse matrix with np.inf as default value for cidi, cid in enumerate(cids): neuron = self.sort.neurons[cid] for sidi, sid in enumerate(sids): chan = spikes['chan'][sid] nchans = spikes['nchans'][sid] chans = spikes['chans'][sid][:nchans] # TODO: this is a bit wasteful if no chans are in common: sdata = wavedata[sid, :nchans] try: ndata, sdata = neuron.getCommonWaveData(chan, chans, sdata) except ValueError: # not comparable continue errs[cidi, sidi] = core.rms(ndata - sdata) errs = self.sort.converter.AD2uV(errs) # convert from AD units to uV, np.infs are OK self.match = Match(cids, sids, errs) print('Done calculating rmserror between all %d clusters and all %d unsorted spikes' % (ncids, nsids)) return self.match @QtCore.pyqtSlot() def on_plotMatchErrorsButton_clicked(self): """Match pane plot match errors button click. Plot histogram of rms error between current cluster and all unclustered spikes that best fit the current cluster""" cluster = self.GetCluster() cid = cluster.id if not hasattr(self, 'match') or self.match == None: self.match = self.on_calcMatchErrorsButton_clicked() # (re)calc errs = self.match.get_best_errs(cid) if len(errs) == 0: print('No unsorted spikes fit cluster %d' % cid) return f = pl.gcf() pl.clf() f.canvas.parent().setWindowTitle('cluster %d rmserror histogram' % cid) binsize = self.ui.matchErrorPlotBinSizeSpinBox.value() pl.hist(errs, bins=np.arange(0, 50, binsize)) pl.title('RMS error between cluster %d and %d unsorted spikes' % (cid, len(errs))) pl.xlabel('RMS error (uV)') pl.ylabel('Count') @QtCore.pyqtSlot() def on_matchButton_clicked(self): """Deselect any selected unsorted spikes in uslist, and then select unsorted spikes that fall below match error threshold and fit the current cluster best""" cluster = self.GetCluster() cid = cluster.id if not hasattr(self, 'match') or self.match == None: self.match = self.on_calcMatchErrorsButton_clicked() # (re)calc errs = self.match.get_best_errs(cid) if len(errs) == 0: print('No unsorted spikes fit cluster %d' % cid) return bestsids = self.match.best[cid] thresh = self.ui.matchThreshSpinBox.value() sids = bestsids[errs <= thresh] sidis = self.sort.usids.searchsorted(sids) # clear uslist selection, select sidis rows in uslist sw = self.windows['Sort'] sw.uslist.clearSelection() sw.uslist.selectRows(sidis, on=True, scrollTo=False) print('Matched %d spikes to cluster %d' % (len(sids), cid)) @QtCore.pyqtSlot() def on_plotXcorrsButton_clicked(self): """Plot all cross/auto correlograms for all selected neurons, and display them in an upper or lower triangle configuration""" ## TODO: for now, just plot a single cross/auto correlogram clusters = self.GetClusters() xsids = clusters[0].neuron.sids if len(clusters) == 1: autocorr = True ysids = xsids # x and y are identical elif len(clusters) == 2: autocorr = False ysids = clusters[1].neuron.sids else: raise NotImplementedError("Can't handle more than one xcorr for now") xspikets = self.sort.spikes['t'][xsids] yspikets = self.sort.spikes['t'][ysids] ## TODO: spikes['t'][sids] is very different from spikes[sids]['t'] ! ## The first is C contig, the second is not! The first probably makes a copy, ## while the second does not. First is much much faster for array ops, while ## the second conserves memory, and avoids needless copying, which might be faster ## if no array ops are involved. Should check all the code that pulls stuff out of ## the spikes recarray, and choose the best one more carefully! trange = self.ui.xcorrsRangeSpinBox.value() * 1000 # convert to us trange = max(1000, trange) # enforce min trange, in us trange = np.array([-trange, trange]) # convert to a +/- array, in us t0 = time.time() dts = util.xcorr(xspikets, yspikets, trange=trange) # delta timepoints of y wrt x (us) print('xcorr calc took %.3f sec' % (time.time()-t0)) if autocorr: dts = dts[dts != 0] # remove 0s for autocorr #print(dts) dts = dts / 1000 # in ms, converts to float64 array trange = trange / 1000 # in ms, converts to float64 array nbins = intround(np.sqrt(len(dts))) # good heuristic nbins = max(20, nbins) # enforce min nbins nbins = min(100, nbins) # enforce max nbins t = np.linspace(start=trange[0], stop=trange[1], num=nbins, endpoint=True) n = np.histogram(dts, bins=t, density=False)[0] binwidth = t[1] - t[0] # all should be equal width # plot: mplw = self.OpenWindow('MPL') a = mplw.ax a.clear() # omit last right edge in t: a.bar(t[:-1], height=n, width=binwidth, color='k', edgecolor='k') a.set_xlim(t[0], t[-1]) a.set_xlabel('ISI (ms)') a.set_ylabel('count') if autocorr: windowtitle = "n%d autocorr" % clusters[0].id else: windowtitle = "xcorr n%d wrt n%d" % (clusters[1].id, clusters[0].id) mplw.setWindowTitle(windowtitle) title = windowtitle + ', binwidth: %.2f ms' % binwidth print(title) a.set_title(title) #a.set_ylabel('ISI rate (Hz)') mplw.f.tight_layout(pad=0.3) # crop figure to contents mplw.figurecanvas.draw() @QtCore.pyqtSlot() def on_ISICleanButton_clicked(self): """If only one cluster is selected, split off any duplicate spikes within that cluster, according to the ISI threshold. If multiple clusters or no clusters are selected, remove any duplicate spikes within selected clusters or all clusters, respectively, according to the same single ISI threshold. As implemented, the latter is not undoable""" clusters = self.GetClusters() minISI = self.ui.minISISpinBox.value() spikes = self.sort.spikes nids = [ cluster.id for cluster in clusters ] # selected neurons, in norder if len(nids) == 0: # if no neurons selected, clean all neurons nids = sorted(self.sort.neurons) rmsidss = {} # dict of lists of sids to split off or remove, indexed by nid print('Duplicate spikes:') for nid in nids: # For each pair of duplicate spikes, keep whichever has the most channel overlap # with neuron template. If they have same amount of overlap, keep the first one neuron = self.sort.neurons[nid] rmsids = [] # list of sids to remove for this neuron # pick out the first sid of each pair of duplicate sids, if any: sidis = np.where(np.diff(spikes['t'][neuron.sids]) <= minISI)[0] if len(sidis) == 0: continue # skip to next nid #x0, y0 = neuron.cluster.pos['x0'], neuron.cluster.pos['y0'] for sidi in sidis: sid0 = neuron.sids[sidi] # 1st spike in each pair sid1 = neuron.sids[sidi+1] # 2nd spike in each pair nchans0 = spikes['nchans'][sid0] nchans1 = spikes['nchans'][sid1] chans0 = spikes['chans'][sid0][:nchans0] chans1 = spikes['chans'][sid1][:nchans1] ncommon0 = len(np.intersect1d(neuron.chans, chans0)) ncommon1 = len(np.intersect1d(neuron.chans, chans1)) if ncommon0 >= ncommon1: # sid0 has more template chan overlap, or both are equal, keep sid0 rmsid = sid1 else: # sid1 has more template chan overlap, keep it rmsid = sid0 """ # code for choosing the one closest to template mean position, not as robust: d02 = (spikes['x0'][sid] - x0)**2 + (spikes['y0'][sid] - y0)**2 d12 = (spikes['x0'][sid+1] - x0)**2 + (spikes['y0'][sid+1] - y0)**2 if d02 <= d12: rmsid = sid + 1 else: rmsid = sid """ rmsids.append(rmsid) print('n%d: %r' % (nid, rmsids)) rmsidss[nid] = rmsids nrm = sum([ len(rmsids) for rmsids in rmsidss.values() ]) print('Found %d duplicate spikes' % nrm) if nrm == 0: return sw = self.windows['Sort'] if len(nids) == 1: # split duplicate spikes from single cluster into cluster 0 sidis = neuron.sids.searchsorted(rmsids) sw.nslist.selectRows(sidis) # select spikes to split off from single cluster self.SplitSpikes(delete=True) # split them off into cluster 0 (undoable) return # otherwise, remove duplicate spikes from multiple clusters: val = QtGui.QMessageBox.question(self, "Remove %d duplicate spikes" % nrm, "Are you sure? This will clear the undo/redo stack, and is not undoable.", QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) if val == QtGui.QMessageBox.No: return # do the actual removal: for nid, rmsids in rmsidss.items(): neuron = self.sort.neurons[nid] neuron.sids = np.setdiff1d(neuron.sids, rmsids) # remove from source neuron spikes['nid'][rmsids] = 0 # set to junk in spikes struct array neuron.wave.data = None # trigger template mean update if neuron in sw.nslist.neurons: sw.nslist.neurons = sw.nslist.neurons # trigger nslist refresh # update usids and uslist: self.sort.update_usids() sw.uslist.updateAll() # cluster changes in stack no longer applicable, reset cchanges: del self.cchanges[:] print('Removed %d duplicate spikes' % nrm) def GetSortedSpikes(self): """Return IDs of selected sorted spikes""" sw = self.windows['Sort'] srows = sw.nslist.selectedRows() return sw.nslist.sids[srows] def GetUnsortedSpikes(self): """Return IDs of selected unsorted spikes""" sw = self.windows['Sort'] srows = sw.uslist.selectedRows() return self.sort.usids[srows] def GetClusterSpikes(self): """Return sorted IDs of all spikes of selected clusters""" clusters = self.GetClusters() if len(clusters) == 0: return np.array([], dtype=np.int64) sids = [] for cluster in clusters: sids.append(cluster.neuron.sids) sids = np.concatenate(sids) sids.sort() return sids def GetSpikes(self): """Return IDs of explicitly selected spikes""" sw = self.windows['Sort'] return np.concatenate([ self.GetSortedSpikes(), self.GetUnsortedSpikes() ]) def GetSpike(self): """Return ID of just one selected spike, from nslist or uslist""" sids = self.GetSpikes() nselected = len(sids) if nselected != 1: raise RuntimeError("Can't figure out which of the %d selected spike IDs you want" % nselected) return sids[0] def GetAllSpikes(self): """Return sorted IDs of all selected spikes, whether explicitly or implicitly selected""" sids = [] ssids = self.GetSortedSpikes() sids.append(ssids) # if no sorted spikes explicitly selected, check if any clusters are: if len(ssids) == 0: sids.append(self.GetClusterSpikes()) # include any selected usids as well sids.append(self.GetUnsortedSpikes()) sids = np.concatenate(sids) sids.sort() return sids def GetClusterIDs(self): """Return list of IDs of currently selected clusters, in norder""" sw = self.windows['Sort'] cids = [ qvar2int(i.data()) for i in sw.nlist.selectedIndexes() ] #cids.sort() # don't do regular sort, sort by norder ciis = np.argsort([ self.sort.norder.index(cid) for cid in cids ]) return [ cids[cii] for cii in ciis ] # in norder def GetClusters(self): """Return list of currently selected clusters, in norder""" cids = self.GetClusterIDs() # already in norder return [ self.sort.clusters[cid] for cid in cids ] def GetCluster(self): """Return just one selected cluster""" clusters = self.GetClusters() nselected = len(clusters) if nselected != 1: raise RuntimeError("Can't figure out which of the %d selected clusters you want" % nselected) return clusters[0] def SelectClusters(self, clusters, on=True): """Select/deselect clusters""" clusters = toiter(clusters) try: selnids = [ cluster.id for cluster in clusters ] except AttributeError: # assume they're ints selnids = [ cluster for cluster in clusters ] rows = [ self.sort.norder.index(selnid) for selnid in selnids ] nlist = self.windows['Sort'].nlist nlist.selectRows(rows, on) #print('Set rows %r to %r' % (rows, on)) def ToggleCluster(self, cluster): """Toggle selection of given cluster""" sw = self.windows['Sort'] try: nid = cluster.id except AttributeError: # assume it's an int nid = cluster row = self.sort.norder.index(nid) on = not sw.nlist.rowSelected(row) sw.nlist.selectRows(row, on=on) return on def SelectSpikes(self, sids, on=True, nslistplot=True): """Set selection state of given spikes, as well as their current clusters, if any""" sw = self.windows['Sort'] nids = self.sort.spikes['nid'][sids] # select/deselect any unclustered spikes: usids = sids[nids == 0] if len(usids) > 0: usrows = self.sort.usids.searchsorted(usids) sw.uslist.selectRows(usrows, on=on) # select/deselect any clustered spikes, as well as their clusters: csids = sids[nids != 0] # clustered spike ids unids = np.unique(nids) unids = unids[unids != 0] # remove cluster 0 # get currently selected sids in nslist, and the unids they belong to: selsids = sw.nslist.sids[sw.nslist.selectedRows()] # hopefully don't need a copy selunids = sw.nslist.nids if on == True: # find clustered spikes to add to selection: # add csids to selsids (get values in csids that aren't in selsids): csids = np.setdiff1d(csids, selsids, assume_unique=True) # to add allcsids = np.union1d(csids, selsids) # final elif on == False: # find clustered spikes to remove from selection: # remove csids from selsids: csids = np.intersect1d(csids, selsids, assume_unique=True) # to remove allcsids = np.setdiff1d(csids, selsids, assume_unique=True) # final else: raise ValueError("Invalid 'on' value: %r" % on) if len(csids) == 0: return # no clustered spikes to add or remove newunids = np.unique(self.sort.spikes['nid'][allcsids]) # excludes cluster 0 # select any new clusters so nslist has correct contents, this # changes contents of nslist and hence clears any currently selected sids: addunids = np.setdiff1d(newunids, selunids) if len(addunids) > 0: # all nids will be in sort.norder list, find their positions addnlistrows = [ self.sort.norder.index(unid) for unid in addunids ] sw.nlist.selectRows(addnlistrows, on=True) # now do the clustered spike selection: nslistrows = sw.nslist.sids.searchsorted(csids) # nslist.sids is sorted #t0 = time.time() sw.nslist.fake_selectRows(nslistrows, on=on, plot=nslistplot) #print('nslist.fake_selectRows took %.3f sec' % (time.time()-t0)) def CreateCluster(self, update=True, id=None, inserti=None): """Create a new cluster, add it to the GUI, return it""" s = self.sort neuron = s.create_neuron(id, inserti=inserti) sw = self.windows['Sort'] if update: sw.nlist.updateAll() cluster = Cluster(neuron) s.clusters[cluster.id] = cluster neuron.cluster = cluster try: cw = self.windows['Cluster'] # don't force its display by default except KeyError: cw = self.OpenWindow('Cluster') return cluster def DelClusters(self, clusters, update=True): """Delete clusters from the GUI, and delete clusters and their neurons from the Sort.""" clusters = toiter(clusters) self.SelectClusters(clusters, on=False) # first deselect them all sw = self.windows['Sort'] cw = self.windows['Cluster'] self.ColourPoints(clusters, setnid=0) # decolour before clusters lose their sids for cluster in clusters: sw.RemoveNeuron(cluster.neuron, update=update) cw.glWidget.updateGL() if update: self.UpdateClustersGUI() def UpdateClustersGUI(self): """Update lots of stuff after modifying clusters, here as a separate method for speed, only call when really needed""" s = self.sort sw = self.windows['Sort'] sw.nlist.updateAll() s.update_usids() sw.uslist.updateAll() def ColourPoints(self, clusters, setnid=None): """Colour the points that fall within each cluster (as specified by cluster.neuron.sids) the same colour as the cluster itself. Or, if setnid != None, colour all points in clusters according to setnid value""" clusters = toiter(clusters) gw = self.windows['Cluster'].glWidget for cluster in clusters: neuron = cluster.neuron # not all (or any) of neuron.sids may currently be plotted commonsids = np.intersect1d(neuron.sids, gw.sids) if len(commonsids) > 0: sidis = gw.sids.searchsorted(commonsids) # set new nids for commonsids in glWidget: if setnid == None: gw.nids[sidis] = neuron.id else: gw.nids[sidis] = setnid gw.colour(commonsids) # recolour commonsids according to their nids gw.updateGL() def GetClusterPlotDims(self): """Return 3-tuple of strings of cluster dimension names, in (x, y, z) order""" x = str(self.ui.xDimComboBox.currentText()) y = str(self.ui.yDimComboBox.currentText()) z = str(self.ui.zDimComboBox.currentText()) return x, y, z def AddClusterChangeToStack(self, cc): """Adds cc to the cluster change stack, removing any potential redo changes""" self.cci += 1 del self.cchanges[self.cci::] # remove any existing redo cluster changes self.cchanges.append(cc) # add to stack # TODO: check if stack has gotten too long, if so, remove some from the start # and update self.cci appropriately def ApplyClusterChange(self, cc, direction): """Apply cluster change described in cc, in either the forward or backward direction, to the current set of clusters""" s = self.sort spikes = s.spikes sw = self.windows['Sort'] cw = self.windows['Cluster'] sids = cc.sids # reverse meaning of 'new' and 'old' if direction == 'forward', ie if redoing if direction == 'back': #newnids = cc.newnids # not needed oldnids = cc.oldnids newunids = cc.newunids oldunids = cc.oldunids poss = cc.oldposs normposs = cc.oldnormposs norder = cc.oldnorder good = cc.oldgood else: # direction == 'forward' #newnids = cc.oldnids # not needed oldnids = cc.newnids newunids = cc.oldunids oldunids = cc.newunids poss = cc.newposs normposs = cc.newnormposs norder = cc.newnorder good = cc.newgood # delete newly added clusters newclusters = [ s.clusters[nid] for nid in newunids ] self.SelectClusters(newclusters, on=False) # deselect new clusters # temporarily deselect any bystander clusters to get around fact that # selections are row-based in Qt, not value-based, which means selection # changes happen without a selectionChanged event when the rowCount changes bystanders = self.GetClusters() self.SelectClusters(bystanders, on=False) self.DelClusters(newclusters, update=False) # del new clusters # restore relevant spike fields spikes['nid'][sids] = oldnids # restore the old clusters oldclusters = [] dims = self.GetClusterPlotDims() t0 = time.time() # NOTE: oldunids are not necessarily sorted for nid, pos, normpos in zip(oldunids, poss, normposs): nsids = sids[oldnids == nid] # sids belonging to this nid cluster = self.CreateCluster(update=False, id=nid) oldclusters.append(cluster) neuron = cluster.neuron sw.MoveSpikes2Neuron(nsids, neuron, update=False) cluster.pos = pos cluster.normpos = normpos # restore norder and good s.norder = copy(norder) s.good = copy(good) # now do some final updates self.UpdateClustersGUI() self.ColourPoints(oldclusters) #print('Applying clusters to plot took %.3f sec' % (time.time()-t0)) # select newly recreated oldclusters self.SelectClusters(oldclusters) # restore bystander selections self.SelectClusters(bystanders) #print('oldclusters: %r' % [c.id for c in oldclusters]) #print('newclusters: %r' % [c.id for c in newclusters]) #print('bystanders: %r' % [c.id for c in bystanders]) def SplitSpikes(self, delete=False): """Split off explicitly selected spikes from their clusters (if any). More accurately, split selected cluster(s) into new cluster(s) plus a destination cluster, whose ID depends on the delete arg. This process is required to allow undo/redo""" oldclusters = self.GetClusters() s = self.sort spikes = s.spikes sids = np.concatenate([self.GetClusterSpikes(), self.GetUnsortedSpikes()]) sids.sort() if len(sids) == 0: return # do nothing if delete: newnid = 0 # junk cluster else: newnid = s.nextnid selsids = self.GetSpikes() # explicitly selected spikes selsidis = sids.searchsorted(selsids) nids = spikes[sids]['nid'] # seems to return a copy nids[selsidis] = newnid # doesn't seem to overwrite nid values in spikes recarray self.apply_clustering(oldclusters, sids, nids, verb='split') def updateTitle(self): """Update main spyke window title based on open stream and sort, if any""" if hasattr(self.hpstream, 'fname'): title = self.hpstream.fname if hasattr(self, 'sort') and self.sort.fname: title += ', ' + self.sort.fname elif hasattr(self, 'sort') and self.sort.fname: title = self.sort.fname else: title = 'spyke' self.setWindowTitle(title) # update the title def OpenRecentFile(self): """Open a filename from the clicked recent file in the File menu""" action = self.sender() if action: fullfname = qvar2str(action.data()) self.OpenFile(fullfname) def updateRecentFiles(self, fullfname=None): """Update list of recent files in File menu, optionally specifying the last fname opened or closed, which should hence go to the top of the list. Some of this code is taken from PySide's examples/mainwindows/recentfiles.py""" settings = QtCore.QSettings('spyke', 'spyke') # retrieve setting fullfnames = qvar2list(settings.value('recentFileList')) for i in range(len(fullfnames)): # Py2: convert each entry from QVariant to QString fullfnames[i] = qvar2str(fullfnames[i]) if fullfname: try: fullfnames.remove(fullfname) except ValueError: pass fullfnames.insert(0, fullfname) del fullfnames[MAXRECENTFILES:] settings.setValue('recentFileList', fullfnames) # update setting # update menu to match fullfnames: nrecent = len(fullfnames) for i, fullfname in enumerate(fullfnames): text = "&%d %s" % (i, fullfname) # add keyboard accelerator self.recentFileActions[i].setText(text) self.recentFileActions[i].setData(fullfname) self.recentFileActions[i].setVisible(True) for j in range(nrecent, MAXRECENTFILES): self.recentFileActions[j].setVisible(False) def OpenFile(self, fname): """Open a stream or sort or digital signal file. fname in this case must contain a full path""" print('Opening file %r' % fname) head, tail = os.path.split(fname) assert head # make sure fname has a path to it base, ext = os.path.splitext(tail) if ext in ['.dat', '.ns6', '.srf', '.track', '.tsf', '.mat']: self.streampath = head self.OpenStreamFile(tail) elif ext == '.zip': subext = os.path.splitext(base)[1] self.eventspath = head if subext == '.eventwaves': self.OpenEventWavesFile(tail) elif subext == '.events': self.OpenEventsFile(tail) elif ext in ['.sort', '.json']: self.sortpath = head self.OpenSortFile(tail) else: critical = QtGui.QMessageBox.critical critical(self, "Error", "%s is not a .dat, .ns6, .srf, .track, .tsf, .mat, " ".event*.zip, .sort or .json file" % fname) def OpenStreamFile(self, fname): """Open a stream (.dat, .ns6, .srf, .track, or .tsf file) and update display accordingly. fname is assumed to be relative to self.streampath. File names in a .track file can be relative to self.streampath or absolute""" if self.hpstream is not None: self.CloseStream() # in case a stream is already open enabledchans = None ext = os.path.splitext(fname)[1] if ext == '.dat': f = dat.File(fname, self.streampath) # parses immediately self.hpstream = f.hpstream # highpass record (spike) stream self.lpstream = f.lpstream # lowpassmultichan record (LFP) stream # if .din.npy file exists with same base name, open that as well and # assume it contains stimulus information from AG Busse Busse Open-Ephys base, ext = os.path.splitext(fname) dinnpyfname = base + '.din.npy' if os.path.exists(os.path.join(self.streampath, dinnpyfname)): self.OpenDINNPYFile(dinnpyfname) elif ext == '.ns6': f = nsx.File(fname, self.streampath) # parses immediately self.hpstream = f.hpstream # highpass record (spike) stream self.lpstream = f.lpstream # lowpassmultichan record (LFP) stream elif ext == '.srf': f = surf.File(fname, self.streampath) f.parse() # TODO: parsing progress dialog self.hpstream = f.hpstream # highpass record (spike) stream self.lpstream = f.lpstream # lowpassmultichan record (LFP) stream elif ext == '.track': fs = [] with open(os.path.join(self.streampath, fname), 'r') as trackfile: for line in trackfile: # one filename per line line = line.strip() # remove leading and trailing whitespace print('%s' % line) if not line: # blank line continue if line.startswith('#'): # comment line line = lstrip(line, '#') # remove comment character line = line.replace(' ', '') # remove all spaces if line.startswith('enabledchans='): # it's a comment line describing which chans have been set to # enabled for this track enabledchans = np.asarray(eval(lstrip(line, 'enabledchans='))) assert iterable(enabledchans) continue # to next line path, fn = os.path.split(line) # allow absolute file paths if not path: path = self.streampath fext = os.path.splitext(fn)[1] if fext == '.dat': f = dat.File(fn, path) elif fext == '.ns6': f = nsx.File(fn, path) elif fext == '.srf': f = surf.File(fn, path) f.parse() else: raise ValueError('Unknown extension %r' % fext) fs.append(f) # build up list of open and parsed data file objects self.hpstream = MultiStream(fs, fname, kind='highpass') self.lpstream = MultiStream(fs, fname, kind='lowpass') ext = fext # for setting *tw variables below elif ext == '.tsf': self.hpstream, self.lpstream = self.OpenTSFFile(fname) elif ext == '.mat': self.hpstream = self.OpenQuirogaMATFile(fname) ext = '.srf' # use same *tw variables as for .srf else: raise ValueError('Unknown extension %r' % ext) # if a sort is already open, try rebinding new stream to the sort. If they don't match, # abort opening of the new stream: try: self.sort.stream = self.hpstream # restore newly opened stream to sort except AttributeError: # no sort yet pass except ValueError: # from sort.set_stream() print('Aborting opening of the stream') self.CloseStream() raise # re-raise the ValueError from sort.set_stream() self.updateTitle() self.updateRecentFiles(os.path.join(self.streampath, fname)) self.ui.__dict__['actionFiltmeth%s' % self.hpstream.filtmeth ].setChecked(True) self.ui.__dict__['actionCAR%s' % self.hpstream.car ].setChecked(True) try: sampfreqkHz = self.hpstream.sampfreq / 1000 self.ui.__dict__['action%dkHz' % sampfreqkHz].setChecked(True) except KeyError: print('WARNING: %d kHz is not a sampling menu option' % sampfreqkHz) self.ui.actionSampleAndHoldCorrect.setChecked(self.hpstream.shcorrect) self.spiketw = SPIKETW[ext] # spike window temporal window (us) self.charttw = CHARTTW[ext] # chart window temporal window (us) self.lfptw = LFPTW # lfp window temporal window (us) self.uVperum = UVPERUM[ext] self.usperum = USPERUM[ext] self.ui.dynamicNoiseXSpinBox.setValue(DYNAMICNOISEX[ext]) self.ui.dtSpinBox.setValue(DT[ext]) # if a sort file is already open, enable only those channels that were used # by the sort's Detector: try: enabledchans = self.sort.detector.chans except AttributeError: pass if enabledchans is None: self.chans_enabled = self.hpstream.chans else: print('Setting enabled chans = %s' % enabledchans) self.chans_enabled = enabledchans self.trange = self.hpstream.t0, self.hpstream.t1 # us self.t = self.trange[0] # init current timepoint (us) self.str2t = {'start': self.trange[0], 'now' : self.t, 'end' : self.trange[1]} self.SPIKEWINDOWWIDTH = self.hpstream.probe.ncols * SPIKEWINDOWWIDTHPERCOLUMN self.OpenWindow('Spike') self.OpenWindow('Chart') self.ui.filePosLineEdit.setText('%.1f' % self.t) self.ui.filePosStartButton.setText('%.1f' % self.trange[0]) self.ui.filePosEndButton.setText('%.1f' % self.trange[1]) self.update_slider() # set slider limits and step sizes self.EnableStreamWidgets(True) def OpenDINNPYFile(self, fname): """Open .din.npy file, assume that it is an AG Busse Open-Ephys file that contains stimulus timing information""" from expio.oe import DINFile # AG Busse experimental I/O library print('Opening file %r' % os.path.join(self.streampath, fname)) dinf = DINFile(fname, self.streampath) stimriseis, stimfallis = dinf.trangeis('stim') self.stimtons = dinf.tsec[stimriseis] * 1e6 # us self.stimtoffs = dinf.tsec[stimfallis] * 1e6 self.ui.actionStims.setEnabled(True) self.ShowStims() def OpenQuirogaMATFile(self, fname): """Open Quiroga's .mat files containing single channel synthetic highpass spike data. Return a SimpleStream. Assume no sample-and-hold correction is required, and no highpass filtering is required""" import scipy.io fname = os.path.join(self.streampath, fname) d = scipy.io.loadmat(fname, squeeze_me=True) #chan = d['chan'] # this field isn't always present #assert chan == 1 nchans = 1 wavedata = d['data'] # float64, mV wavedata = wavedata * 1000 # uV assert wavedata.ndim == 1 nt = len(wavedata) wavedata.shape = nchans, -1 # enforce 2D # convert to int16, assume ADC resolution for this data was <= 16 bits, # use some reasonable gain values, check they don't saturate 16 bits: intgain = 1 extgain = 2000 converter = core.Converter(intgain=intgain, extgain=extgain) wavedata = converter.uV2AD(wavedata, dtype=np.int64) # check for saturation: wdmin, wdmax = wavedata.min(), wavedata.max() print('gain = %d' % (intgain*extgain)) print('wavedata.min() = %d, wavedata.max() = %d' % (wdmin, wdmax)) if wdmin <= -2**15 or wdmax >= 2**15-1: raise RuntimeError("wavedata has saturated int16. Try reducing gain") wavedata = np.int16(wavedata) # downcast to int16 siteloc = np.empty((nchans, 2)) siteloc[0] = 0, 0 rawtres = float(d['samplingInterval']) # ms rawtres = rawtres / 1000 # sec rawsampfreq = intround(1 / rawtres) # Hz masterclockfreq = None stream = SimpleStream(fname, wavedata, siteloc, rawsampfreq, masterclockfreq, intgain, extgain, shcorrect=False, bitshift=None) truth = core.EmptyClass() truth.spiketis = d['spike_times'] assert truth.spiketis[-1] < nt truth.spikets = truth.spiketis * rawtres # unsure what the other arrays in this field are for: truth.sids = d['spike_class'][0] assert int(d['startData']) == 0 stream.truth = truth return stream def OpenTSFFile(self, fname): """Open NVS's "test spike file" .tsf format for testing spike sorting performance. This describes a single 2D contiguous array of raw waveform data, within which are embedded a number of spikes from a number of neurons. The ground truth is typically listed at the end of the file. Return a highpass and lowpass SimpleStream. For .tsf files that only have highpass, return None as a lowpass stream. fname is assumed to be relative to self.streampath. .tsf file TODO: - make data column-major for better seeking in time - move nchans field before siteloc field - make maxchans 0 based, ie same as labelled on probe design by UMich - would be better to keep spikes sorted in time, instead of by cluster id - no need for 64 extgain values, they're all the same, whether you're exporting spike or LFP data. And if for some reason they could've been different, length of extgains vector should be nchans, not fixed 64. Also, if extgains is a vector, then so should intgains - number cluster ids in vertically spatial order, by mean of their template's vertical spatial position, not just by their maxchan - subtle difference - are .tsf spike times all aligned to +ve 0 crossing? One difference from .sort is that they're all truncated to the nearest 25kHz sample point. Maybe it would be best to save the spike time in us instead of in 25kHz sample point indices - add some kind of datetime stamp, ala .srf. Maybe datetime the .tsf file was generated - increment format number. Maybe we should ultimately make a .nvs file type, similar to .tsf format, for sharing with others, as a simplified .srf file. Would require adding an LFP channel field to the end, or just make the LFP chans look like normal spike chans, way oversampled - add more cells, make some fraction of them bursting, give bursting cells some prob distrib over number of spikes per burst, make each spike in a burst say 5 or 10% smaller than the previous spike adaptation - maybe even simulate spatial drift? That would be more difficult - need far more spikes. Enforce a power law distribution in number spikes per cell - main thing is to look at how close in space and time spikes can be seeded and still be detected and clustered correctly """ with open(os.path.join(self.streampath, fname), 'rb') as f: header = f.read(16).decode() assert header == 'Test spike file ' version, = unpack('i', f.read(4)) if version == 1002: return self.OpenTSFFile_1002(fname) elif version == 1000: return self.OpenTSFFile_1000(fname) def OpenTSFFile_1002(self, fname): """Open TSF file, version 1002. Assume no sample-and-hold correction is required, assume wavedata already has the correct 0 voltage offset (i.e., is signed), assume no bitshift is required (data is 16 bit, not 12). Assume wavedata is wideband, containing both spike and LFP data""" try: f = open(os.path.join(self.streampath, fname), 'rb') except IOError: print("Can't find file %r" % fname) return header = f.read(16).decode() assert header == 'Test spike file ' version, = unpack('i', f.read(4)) assert version == 1002 rawsampfreq, = unpack('i', f.read(4)) # Hz masterclockfreq = None nchans, = unpack('i', f.read(4)) nt, = unpack('i', f.read(4)) intgain = 1 # assumed extgain, = unpack('f', f.read(4)) print('extgain: %f' % extgain) siteloc = np.zeros((nchans, 2), dtype=np.int16) readloc = np.zeros(nchans, dtype=np.int32) # optimal chan display order #print('readloc:', readloc) for i in range(nchans): # these two data types really shouldn't be intertwined like this: siteloc[i, :] = unpack('hh', f.read(4)) readloc[i], = unpack('i', f.read(4)) # read row major data, ie, chan loop is outer loop: wavedata = np.fromfile(f, dtype=np.int16, count=nchans*nt) wavedata.shape = nchans, nt nspikes, = unpack('i', f.read(4)) print("%d ground truth spikes" % nspikes) # filter into highpass data: hpwavedata = core.WMLDR(wavedata) # assume all 16 bits are actually used, not just 12 bits, so no bitshift is required: hpstream = SimpleStream(fname, hpwavedata, siteloc, rawsampfreq, masterclockfreq, intgain, extgain, shcorrect=False, bitshift=False, tsfversion=version) lpstream = None ## TODO: implement this if nspikes > 0: truth = core.EmptyClass() truth.spikets = np.fromfile(f, dtype=np.int32, count=nspikes) truth.nids = np.fromfile(f, dtype=np.int32, count=nspikes) truth.maxchans = np.fromfile(f, dtype=np.int32, count=nspikes) assert truth.maxchans.min() >= 1 # NVS stores these as 1-based truth.maxchans -= 1 # convert to proper 0-based maxchan ids self.renumber_tsf_truth(truth, hpstream) hpstream.truth = truth pos = f.tell() f.seek(0, 2) nbytes = f.tell() f.close() print('Read %d bytes, %s is %d bytes long' % (pos, fname, nbytes)) return hpstream, lpstream def OpenTSFFile_1000(self, fname): """Open TSF file, version 1000. Assume wavedata is highpass spike data only""" try: f = open(os.path.join(self.streampath, fname), 'rb') except IOError: print("Can't find file %r" % fname) return header = f.read(16).decode() assert header == 'Test spike file ' version, = unpack('i', f.read(4)) assert version == 1000 nchans = 54 # assumed siteloc = np.fromfile(f, dtype=np.int16, count=nchans*2) siteloc.shape = nchans, 2 rawsampfreq, = unpack('i', f.read(4)) # 25k masterclockfreq, = unpack('i', f.read(4)) # 1M extgains = np.fromfile(f, dtype=np.uint16, count=64) extgain = extgains[0] intgain, = unpack('H', f.read(2)) # this nchans field should've been above siteloc field: nchans2, = unpack('i', f.read(4)) assert nchans == nchans2 # make sure above assumption was right nt, = unpack('i', f.read(4)) # 7.5M, eq'v to 300 sec data total # read row major data, ie, chan loop is outer loop: wavedata = np.fromfile(f, dtype=np.int16, count=nchans*nt) wavedata.shape = nchans, nt hpstream = SimpleStream(fname, wavedata, siteloc, rawsampfreq, masterclockfreq, intgain, extgain, shcorrect=True, tsfversion=version) lpstream = None # no lowpass data in this version # not all .tsf files have ground truth data at end: pos = f.tell() groundtruth = f.read() if groundtruth == b'': # reached EOF nbytes = f.tell() f.close() print('Read %d bytes, %s is %d bytes long' % (pos, fname, nbytes)) return hpstream, lpstream else: f.seek(pos) # go back and parse ground truth data truth = core.EmptyClass() # something to do with how spikes were seeded vertically in space: truth.vspacing, = unpack('i', f.read(4)) truth.nspikes, = unpack('i', f.read(4)) # sample index of each spike: spiketis = np.fromfile(f, dtype=np.uint32, count=truth.nspikes) sids = spiketis.argsort() # indices that sort spikes in time truth.spikets = spiketis[sids] * hpstream.rawtres # in us truth.nids = np.fromfile(f, dtype=np.uint32, count=truth.nspikes)[sids] truth.chans = np.fromfile(f, dtype=np.uint32, count=truth.nspikes)[sids] assert truth.chans.min() >= 1 # NVS stores these as 1-based truth.chans -= 1 # convert to proper 0-based maxchan ids self.renumber_tsf_truth(truth, hpstream) hpstream.truth = truth pos = f.tell() f.seek(0, 2) nbytes = f.tell() f.close() print('Read %d bytes, %s is %d bytes long' % (pos, fname, nbytes)) return hpstream, lpstream def renumber_tsf_truth(self, truth, stream): """Renumber .tsf ground truth nids according to vertical spatial order of their max chan, similar to what's done in .sort. Differences in labelling can still arise because in a .sort, nids are ordered by the mean vertically modelled position of each neuron's member spikes, not strictly by the maxchan of its mean template""" oldnid2sids = {} nids = truth.nids oldunids = np.unique(nids) nnids = len(oldunids) oldchans = np.zeros(nnids, dtype=truth.chans.dtype) assert (oldunids == np.arange(1, nnids+1)).all() # find maxchan of each nid, store in oldchans: for chani, oldnid in enumerate(oldunids): sids = nids == oldnid oldnid2sids[oldnid] = sids # save these for next loop chans = truth.chans[sids] chan = chans[0] assert (chans == chan).all() # check for surprises oldchans[chani] = chan # convert maxchans to y positions: ypos = np.asarray([ stream.probe.SiteLoc[chan][1] for chan in oldchans ]) # as in sort.on_actionRenumberClusters_triggered(), this is a bit confusing: # find indices that would sort old ids by y pos, but then what you really want # is to find the y pos *rank* of each old id, so you need to take argsort again: sortiis = ypos.argsort().argsort() newunids = oldunids[sortiis] # sorted by vertical position for oldnid, newnid in zip(oldunids, newunids): sids = oldnid2sids[oldnid] nids[sids] = newnid # overwrite old nid values with new ones def OpenEventWavesFile(self, fname): """Open and import the data in an .eventwaves.zip file, containing event times, channels and waveforms, plus some other data. fname is assumed to be relative to self.eventspath""" if self.hpstream != None: self.CloseStream() # in case a stream is open self.DeleteSort() # delete any existing Sort fullfname = os.path.join(self.eventspath, fname) with open(fullfname, 'rb') as f: d = dict(np.load(f)) # convert to an actual dict to use d.get() method print('Done opening .eventswave.zip file') print('.eventswave.zip file was %d bytes long' % f.tell()) chan = d.get('chan') # array of maxchans, one per event chanpos = d.get('chanpos') # array of (x, y) coords, in channel order chans = d.get('chans') # set of incl. chans, each of length nchans, one per event nchans = d.get('nchans') # count of included chans, one per event sampfreq = d.get('sampfreq') # sampling rate, Hz t = d.get('t') # even timestamps, us uVperAD = d.get('uVperAD') # uV per AD value in wavedata # event waveform data (nevents x maxnchans x nt), treated as AD values: wavedata = d.get('wavedata') # check for mandatory fields: if sampfreq is None: raise ValueError('Missing sampfreq') if uVperAD is None: raise ValueError('Missing uVperAD') if wavedata is None: raise ValueError('Missing wavedata') # pull singleton values out of numpy array: sampfreq = float(sampfreq) uVperAD = float(uVperAD) nevents, maxnchans, nt = wavedata.shape # maxnchans is per event print('wavedata.shape:', wavedata.shape) # handle optional fields: if chanpos is None: if maxnchans > 1: raise ValueError('Multiple chans per event, chanpos should be specified') chanpos = np.array([[0, 0]]) # treat events as single channel if t is None: # create artificial event timestamps at 1 ms intervals t = np.arange(nevents) * 1000 # us if chan is None: # maxchan chan = np.zeros(nevents) if nchans is None: nchans = np.ones(nevents) if chans is None: chans = np.asarray([chan]) # (1, nevents) assert len(chans) is maxnchans # create fake stream, create sort, populate spikes array: tres = 1 / sampfreq * 1000000 # us halfdt = nt * tres / 2 self.spiketw = -halfdt, halfdt # treat this source .eventwaves.zip file as a fake stream: fakestream = stream.FakeStream() fakestream.fname = fname fakestream.tres = tres fakestream.probe = probes.findprobe(chanpos) fakestream.converter = None self.hpstream = fakestream sort = self.CreateNewSort() # create a new sort, with bound stream det = Detector(sort=sort) SPIKEDTYPE = calc_SPIKEDTYPE(maxnchans) sort.detector = det sort.converter = core.SimpleConverter(uVperAD) spikes = np.zeros(nevents, SPIKEDTYPE) spikes['id'] = np.arange(nevents) spikes['t'] = t spikes['t0'], spikes['t1'] = t-halfdt, t+halfdt spikes['chan'] = chan spikes['nchans'] = nchans spikes['chans'] = chans.T # (nevents, 1) sort.spikes = spikes sort.wavedata = wavedata # hack: self.uVperum = 20 self.usperum = 125 sort.update_usids() # required for self.on_plotButton_clicked() # lock down filtmeth, car, sampfreq and shcorrect attribs: #sort.filtmeth = sort.stream.filtmeth #sort.car = sort.stream.car #sort.sampfreq = sort.stream.sampfreq #sort.shcorrect = sort.stream.shcorrect self.ui.progressBar.setFormat("%d spikes" % sort.nspikes) self.EnableSortWidgets(True) sw = self.OpenWindow('Sort') # ensure it's open if sort.nspikes > 0: self.on_plotButton_clicked() self.SPIKEWINDOWWIDTH = sort.probe.ncols * SPIKEWINDOWWIDTHPERCOLUMN self.updateTitle() self.updateRecentFiles(fullfname) # start with all events in a single non-junk cluster 1: oldclusters = [] sids = spikes['id'] nids = np.ones(nevents) self.apply_clustering(oldclusters, sids, nids, verb='initial eventwaves split') def OpenEventsFile(self, fname): """Open and import the data in an .events.zip file, containing spike times, channels, and neuron ids. fname is assumed to be relative to self.eventspath. Spike waveforms are extracted from the currently open stream""" if self.hpstream is None: raise RuntimeError("Need an open raw data stream before loading an events.zip " "file") self.DeleteSort() # delete any existing Sort fullfname = os.path.join(self.eventspath, fname) with open(fullfname, 'rb') as f: d = dict(np.load(f)) # convert to an actual dict to use d.get() method print('Done opening .events.zip file') print('.events.zip file was %d bytes long' % f.tell()) spikets = d.get('spikets') # spike times, us maxchans = d.get('maxchans') # maxchans nids = d.get('nids') # neuron IDs # check for mandatory fields: if spikets is None: raise ValueError('Missing spikets') if maxchans is None: raise ValueError('Missing maxchans') if nids is None: raise ValueError('Missing nids') assert len(spikets) == len(maxchans) == len(nids) nspikes = len(spikets) # check that maxchans are a subset of enabled chans in stream: umaxchans = np.unique(maxchans) if not np.isin(umaxchans, self.hpstream.chans).all(): raise RuntimeError("maxchans in %r are not a subset of currently enabled stream " "chans. Was the .events.zip file generated from a different " "set of enabled channels?\n" "maxchans: %s\n" "enabled chans: %s\n" % (fname, umaxchans, self.hpstream.chans)) # create sort: print('Creating new sort') sort = self.CreateNewSort() # create a new sort, with bound stream # create detector and run Detector.predetect(), so that things initialize: self.get_detector() det = sort.detector assert det.extractparamsondetect == True self.init_extractor() # init the Extractor det.predetect(logpath=self.eventspath) # manually set detection results: print('Allocating and filling spikes array') spikes = np.zeros(nspikes, det.SPIKEDTYPE) spikes['id'] = np.arange(nspikes) spikes['t'] = spikets spikes['t0'], spikes['t1'] = spikets+sort.tw[0], spikets+sort.tw[1] spikes['chan'] = maxchans # one maxchan per spike # convert inclnbhdi to inclnbhd, taking chan and returning inclchans instead of taking # chani and returning inclchanis: inclnbhd = {} for chani, inclchanis in det.inclnbhdi.items(): chan = det.chans[chani] inclchans = det.chans[inclchanis] inclnbhd[chan] = inclchans for s, maxchan in zip(spikes, maxchans): inclchans = inclnbhd[maxchan] nchans = len(inclchans) s['nchans'] = nchans s['chans'][:nchans] = inclchans s['chani'], = np.where(inclchans == maxchan) # index into spike's chan list # bind to self: sort.spikes = spikes det.nspikes = nspikes # init wavedata: print('Allocating wavedata array') sort.wavedata = np.zeros((nspikes, det.maxnchansperspike, det.maxnt), dtype=np.int16) # Linux has lazy physical memory allocation. See https://stackoverflow.com/a/27582592. # This forces physical memory allocation, though strangely, doesn't seem to speed # up loading of wavedata. It will fail immediately if physical memory can't be # allocated, which is desirable: sort.wavedata[:] = 0 print('wavedata.shape:', sort.wavedata.shape) print('wavedata.nbytes: %.3f GiB' % (sort.wavedata.nbytes / 1024**3)) # "re"load spike wavedata based on imported events: sort.reload_spikes(spikes['id']) sort.update_usids() # required for self.on_plotButton_clicked() # lock down filtmeth, car, sampfreq and shcorrect attribs: sort.filtmeth = sort.stream.filtmeth sort.car = sort.stream.car sort.sampfreq = sort.stream.sampfreq sort.shcorrect = sort.stream.shcorrect self.ui.progressBar.setFormat("%d spikes" % sort.nspikes) self.EnableSortWidgets(True) sw = self.OpenWindow('Sort') # ensure it's open if sort.nspikes > 0: self.on_plotButton_clicked() self.SPIKEWINDOWWIDTH = sort.probe.ncols * SPIKEWINDOWWIDTHPERCOLUMN self.updateTitle() self.updateRecentFiles(fullfname) # set nids using apply_clustering(): oldclusters = [] sids = spikes['id'] self.apply_clustering(oldclusters, sids, nids, verb='initial .events.zip split') # no longer valid, loaded nids may have had gaps that were removed by # apply_clustering(): del nids sort.init_spike_alignment() # perform spatial localization on all spikes in sort: nreject = sort.spatially_localize_spikes(sw) # spatial localization is done, reset fit objects for clean jsonpickle: sort.extractor.set_fit_objects() print() # newline preject = nreject / nspikes * 100 print('Rejected %d/%d spikes (%.1f %%), set as unclustered' % (nreject, nspikes, preject)) # remove any empty neurons due to all their spikes being rejected: nneurons, nnreject = len(sort.neurons), 0 for neuron in sort.neurons.values(): if len(neuron.sids) == 0: sw.RemoveNeuron(neuron, update=False) nnreject += 1 preject = nnreject / nneurons * 100 print('Removed %d/%d (%.1f %%) empty neurons' % (nnreject, nneurons, preject)) self.UpdateClustersGUI() # update mean cluster positions, so they can be sorted by y0: for cluster in sort.clusters.values(): cluster.update_pos() print('Done importing events from %r' % fullfname) def convert_kilosort2npy2eventszip(self, path): """Read relevant Kilosort2 .npy results files in path, process them slightly, and save them with standard spyke variable names to an ".events.zip" npz file. Kilosort2 .npy results are assumed to correspond to currently open stream.""" s = self.hpstream assert s != None # build file names: chansfname = os.path.join(path, 'channel_map.npy') spiketisfname = os.path.join(path, 'spike_times.npy') nidsfname = os.path.join(path, 'spike_clusters.npy') templatesfname = os.path.join(path, 'templates.npy') outputfname = os.path.join(path, s.fname + '.events.zip') print('Converting Kilosort2 events to:\n%r' % outputfname) # load relevant Kilosort2 .npy results files: chanis = np.load(chansfname).ravel() # 0-based indices of chans that ks2 didn't ignore # ensure that `chanis` are a subset of 0-based indices of chans enabled in the stream: streamchanis = np.arange(s.nchans) assert (np.isin(chanis, streamchanis)).all() chans = s.chans[chanis] # dereference, chans that Kilosort2 didn't ignore if len(chans) < s.nchans: # Kilosort2 has ignored some chans that are enabled in the stream ignoredchans = np.setdiff1d(s.chans, chans) print('*** NOTE: Kilosort2 ignored channels %s because they have a spike rate\n' ' that is too low, yet these channels are currently enabled in\n' ' the open stream. Consider disabling those channels in the open\n' ' stream to save some space in the sort' % ignoredchans) # spike times, sample point integers relative to start of .dat file: spiketis = np.load(spiketisfname).ravel() nids = np.load(nidsfname).ravel() # 0-based neuron IDs, one per spike templates = np.load(templatesfname) # ntemplates, nt, nchans, Fortran contiguous # reshape to ntemplates, nchans, nt by swapping axes (can't just assign new shape!): templates = np.swapaxes(templates, 1, 2) templates = np.ascontiguousarray(templates) # make C contiguous ntemplates, nchans, nt = templates.shape if nchans != len(chans): raise RuntimeError("Number of chans in 'templates.npy' (%d) doesn't match " "number of non-ignored chans in 'channel_map.npy' (%d)" % (nchans, len(chans))) # calculate spike times to nearest int64 us, assume Kilosort2 was run on # raw uninterpolated data, and that gaps=True during the export, i.e. that # gaps between streams in the data were excluded and not zero-padded: print('Assuming that Kilosort2 was run on raw uninterpolated data, ' 'and that gaps=True during the export (if any) to .dat') rawts = [] rawtres = s.rawtres if s.is_multi(): # MultiStream streams = s.streams else: # it's a single Stream streams = [s] tranges = s.tranges # exists for both Stream and MultiStream # iterate over absolute time ranges of Streams relative to start of MultiStream: for stream, trange in zip(streams, tranges): nt = stream.f.nt # get nt from its lower level File object t0, t1 = trange # should be same as taking difference of end-inclusive tranges, # dividing by rawtres, and adding 1: streamnt = intround((t1 - t0)/rawtres) + 1 # end inclusive assert nt == streamnt streamrawts = np.linspace(t0, t0+(nt-1)*rawtres, nt) # end inclusive rawts.append(streamrawts) # pack raw timestamps into a single contiguous array, # convert to nearest int64 us (as in SPIKEDTYPE): rawts = intround(np.concatenate(rawts)) spikets = rawts[spiketis] # us # shift Kilosort2 spike times: print('Shifting Kilosort2 spike times by %g us for better positioning in sort window' % KILOSORT2SHIFTCORRECT) spikets = spikets + KILOSORT2SHIFTCORRECT # find maxchan for each template: find max along time axis of each chan of each # template, then find argmax along chan axis of each template: templatemaxchanis = abs(templates).max(axis=2).argmax(axis=1) # one per template # get dereferenced maxchan IDs: templatemaxchans = chans[templatemaxchanis] # one per template maxchans = templatemaxchans[nids] # one per spike # check limits, convert maxchans to uint8: assert maxchans.min() >= np.iinfo(np.uint8).min assert maxchans.max() <= np.iinfo(np.uint8).max maxchans = np.uint8(maxchans) # save space, use same dtype as in SPIKEDTYPE # convert to 1-based neuron IDs, reserve 0 for unclustered spikes. Note that # Kilosort2's 0-based neuron IDs might have gaps, i.e., they don't necessarily span # the range 0..nneurons-1: nids += 1 # check limits, convert nids to int16: assert nids.min() >= np.iinfo(np.int16).min assert nids.max() <=
np.iinfo(np.int16)
numpy.iinfo
import argparse import os import numpy as np from PIL import Image import torch from torch.autograd import Variable import torchvision.transforms as transforms #import torchvision.transforms as standard_transforms #from sklearn.preprocessing import minmax_scale,StandardScaler from skimage import img_as_ubyte import torch.nn as nn #from util import is_image_file, load_img, save_img from skimage.io import imread, imsave from skimage import io from glob import glob #import SimpleITK as sitk #import nibabel as nib from math import log10 import h5py os.environ["CUDA_VISIBLE_DEVICES"] = "0,1" # Testing settings parser = argparse.ArgumentParser(description='pix2pix-PyTorch-implementation') parser.add_argument('--batchSize', type=int, default=4, help='training batch size') parser.add_argument('--testBatchSize', type=int, default=1, help='testing batch size') parser.add_argument('--nEpochs', type=int, default=200, help='number of epochs to train for') parser.add_argument('--input_nc', type=int, default=16, help='input image channels') parser.add_argument('--output_nc', type=int, default=1, help='output image channels') parser.add_argument('--ngf', type=int, default=64, help='generator filters in first conv layer') parser.add_argument('--ndf', type=int, default=64, help='discriminator filters in first conv layer') parser.add_argument('--lr', type=float, default=0.0002, help='Learning Rate. Default=0.002') parser.add_argument('--beta1', type=float, default=0.5, help='beta1 for adam. default=0.5') parser.add_argument('--threads', type=int, default=4, help='number of threads for data loader to use') parser.add_argument('--seed', type=int, default=123, help='random seed to use. Default=123') parser.add_argument('--lamb', type=int, default=10, help='weight on L1 term in objective') parser.add_argument('--dataset', default=True, help='DEEP-TFM-l1loss') parser.add_argument('--model', type=str, default='checkpoint/DEEP-TFM-l1loss/netG_model_epoch_50.pth.tar', help='model file to use') parser.add_argument('--cuda', default=True, help='use cuda') opt = parser.parse_args(args=[]) max_im = 100 max_gt = 741 criterionMSE = nn.MSELoss() img_dir = open('train.txt','r') avg_mse = 0 avg_psnr = 0 h5_dir = '/n/holyscratch01/wadduwage_lab/uom_bme/ForwardModel_matlab/_cnn_synthTrData/03-Jun-2020/cells_tr_data_6sls_03-Jun-2020.h5' for epochs in range(12,13): my_model = '/n/holyscratch01/wadduwage_lab/uom_bme/2020_static/Data_02Apr2020/unetscse/depth_6/checkpoint/DEEP-TFM-lr-0.001/netG_model_epoch_' + str(epochs) + '.pth.tar' netG = torch.load(my_model) netG.eval() p = 0 for line in img_dir: print(line) id_ = int(line) with h5py.File(h5_dir, 'r') as db: modalities = db['input'][id_] GT_ = db['gt'][id_] depth = modalities.shape[2] predicted_im = np.zeros((160,160,1)) if np.min(np.array(GT_))==np.max(np.array(GT_)): print('Yes') GT = torch.from_numpy(np.divide(GT_,max_gt)) img = torch.from_numpy(np.divide(modalities,max_im)[None, :, :]).float() netG = netG.cuda() input = img.cuda() out = netG(input) print(out.max()) out = out.cpu() out_img = out.data[0] out_img =
np.squeeze(out_img)
numpy.squeeze
# -*- coding: utf-8 -*- ########################################################################## # pySAP - Copyright (C) CEA, 2017 - 2018 # Distributed under the terms of the CeCILL-B license, as published by # the CEA-CNRS-INRIA. Refer to the LICENSE file or to # http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html # for details. ########################################################################## # System import import unittest import numpy as np from itertools import product # Package import from mri.operators import FFT, NonCartesianFFT, Stacked3DNFFT from mri.operators.utils import convert_mask_to_locations, \ convert_locations_to_mask, normalize_frequency_locations, \ discard_frequency_outliers, get_stacks_fourier import time class TestAdjointOperatorFourierTransform(unittest.TestCase): """ Test the adjoint operator of the Fourier in both for 2D and 3D. """ def setUp(self): """ Set the number of iterations. """ self.N = 64 self.max_iter = 10 self.num_channels = [1, 2] def test_normalize_frequency_locations_2D(self): """Test the output of the normalize frequency methods and check that it is indeed within [-0.5; 0.5[ """ for _ in range(10): samples = np.random.randn(128*128, 2) normalized_samples = normalize_frequency_locations(samples) self.assertTrue((normalized_samples < 0.5).all() and (normalized_samples >= -0.5).all()) print(" Test normalization function for 2D input passes") def test_normalize_frequency_locations_3D(self): """Test the output of the normalize frequency methods and check that it is indeed within [-0.5; 0.5[ """ for _ in range(10): samples = np.random.randn(128*128, 3) normalized_samples = normalize_frequency_locations(samples) self.assertTrue((normalized_samples < 0.5).all() and (normalized_samples >= -0.5).all()) print(" Test normalization function for 3D input passes") def test_discard_frequency_outliers_2D(self): """Test the output of the discard frequency methods, checking that locations are within [-0.5; 0.5[ and that locations and samples are similarly discarded. """ for _ in range(10): kspace_loc = np.random.randn(128*128, 2) kspace_data = np.random.randn(1, 128*128, 2) reduced_loc, reduced_data = discard_frequency_outliers(kspace_loc, kspace_data) self.assertTrue((reduced_loc < 0.5).all() and (reduced_loc >= -0.5).all()) self.assertEqual(reduced_loc.shape[0], reduced_data.shape[1]) print(" Test location discarding function for 2D input passes") def test_discard_frequency_outliers_3D(self): """Test the output of the discard frequency methods, checking that locations are within [-0.5; 0.5[ and that locations and samples are similarly discarded. """ for _ in range(10): kspace_loc = np.random.randn(128*128, 3) kspace_data = np.random.randn(1, 128*128, 3) reduced_loc, reduced_data = discard_frequency_outliers(kspace_loc, kspace_data) self.assertTrue((reduced_loc < 0.5).all() and (reduced_loc >= -0.5).all()) self.assertEqual(reduced_loc.shape[0], reduced_data.shape[1]) print(" Test location discarding function for 3D input passes") def test_sampling_converters(self): """Test the adjoint operator for the 2D non-Cartesian Fourier transform """ for i in range(self.max_iter): print("Process test convert mask to samples test '{0}'...", i) Nx = np.random.randint(8, 512) Ny = np.random.randint(8, 512) mask = np.random.randint(2, size=(Nx, Ny)) samples = convert_mask_to_locations(mask) recovered_mask = convert_locations_to_mask(samples, (Nx, Ny)) self.assertEqual(mask.all(), recovered_mask.all()) mismatch = 0. + (np.mean( np.allclose(mask, recovered_mask))) print(" mismatch = ", mismatch) print(" Test convert mask to samples and it's adjoint passes for", " the 2D cases") def test_sampling_converters_3D(self): """Test the adjoint operator for the 3D non-Cartesian Fourier transform """ for i in range(self.max_iter): print("Process test convert mask to samples test '{0}'...", i) Nx = np.random.randint(8, 512) Ny = np.random.randint(8, 512) Nz = np.random.randint(8, 512) mask =
np.random.randint(2, size=(Nx, Ny, Nz))
numpy.random.randint
# -*- coding: utf-8 -*- """ @author: bokorn """ import numpy as np import cv2 import torch import torchvision.transforms as transforms from se3_distributions.utils import to_np def cropBBox(img, bbox, boarder_width = 10): rows, cols = img.shape[:2] x,y,w,h = bbox y0 = min(max(y - boarder_width, 0), rows) x0 = min(max(x - boarder_width, 0), cols) y1 = min(max(y + h + boarder_width, 0), rows) x1 = min(max(x + w + boarder_width, 0), cols) img_crop = img[y0:y1,x0:x1] return img_crop, (x0, y0) def seg2Mask(segmentation, img_size): mask = np.zeros(img_size[:2] + (1,), dtype=np.uint8) polys = [] for seg in segmentation: polys.append(np.reshape(seg,(-1,2))) cv2.fillPoly(mask, polys, (1)) return mask norm_mean = np.array([0.485, 0.456, 0.406]) #norm_std = np.array([0.229, 0.224, 0.225]) #normalize = transforms.Normalize(mean=norm_mean, std=norm_std) normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) to_tensor = transforms.ToTensor() vgg_mean = torch.tensor([102.9801, 115.9465, 122.7717]) def vggToTensor(img, mean = vgg_mean): return (torch.tensor(img).float() - mean).permute([2,0,1]) def cropAndPad(img, padding_size = 0.1): where = np.array(np.where(img[:,:,3])) x1, y1 = np.amin(where, axis=1) x2, y2 = np.amax(where, axis=1) sub_img = img[x1:(x2+1), y1:(y2+1)] pad_size = int(max(sub_img.shape[:2])*padding_size) pad_img = cv2.copyMakeBorder(sub_img, pad_size, pad_size, pad_size, pad_size, cv2.BORDER_CONSTANT,value=0) return pad_img def unprocessImages(imgs, norm_mean = np.array([0.485, 0.456, 0.406]), norm_std = np.array([0.229, 0.224, 0.225])): imgs = np.transpose(to_np(imgs), (0,2,3,1)) imgs = np.minimum(np.maximum(imgs*norm_std + norm_mean, 0.0), 1.0)*255 return imgs def preprocessImages(imgs, img_size, normalize_tensors = False, background = None, background_filenames = None, crop_percent = None, remove_mask = True, vgg_normalize = False): p_imgs = [] for image in imgs: if(background is None and background_filenames is not None): bg_idx = np.random.randint(0, len(background_filenames)) background = cv2.imread(background_filenames[bg_idx]) if (len(image.shape) == 2): image = np.expand_dims(image, axis=2) if(image.shape[2] == 4): image = transparentOverlay(image, background, remove_mask=remove_mask) if(crop_percent is not None): image = cropAndResize(image, img_size, crop_percent) else: if(type(background) in [int, float]): padColor = background else: padColor = 255.0 image = resizeAndPad(image, img_size, padColor=padColor) image = image.astype(np.uint8) if(normalize_tensors): if(vgg_normalize): if(remove_mask): image = vggToTensor(image[:,:,:3]) else: image = torch.cat([vggToTensor(image[:,:,:3]), vggToTensor(image[:,:,3:], mean=0)]) else: if(remove_mask): image = normalize(to_tensor(image[:,:,:3])) else: image = torch.cat([normalize(to_tensor(image[:,:,:3])), to_tensor(image[:,:,3:])]) p_imgs.append(image) if(normalize_tensors): p_imgs = torch.stack(p_imgs) return p_imgs def resizeAndPad(img, size, padColor=255.0): h, w = img.shape[:2] sh, sw = size # interpolation method if h > sh or w > sw: # shrinking image interp = cv2.INTER_AREA else: # stretching image interp = cv2.INTER_CUBIC # aspect ratio of image aspect = w/h # compute scaling and pad sizing if aspect > 1: # horizontal image new_w = sw new_h = np.round(new_w/aspect).astype(int) pad_vert = (sh-new_h)/2 pad_top, pad_bot = np.floor(pad_vert).astype(int), np.ceil(pad_vert).astype(int) pad_left, pad_right = 0, 0 elif aspect < 1: # vertical image new_h = sh new_w = np.round(new_h*aspect).astype(int) pad_horz = (sw-new_w)/2 pad_left, pad_right = np.floor(pad_horz).astype(int), np.ceil(pad_horz).astype(int) pad_top, pad_bot = 0, 0 else: # square image new_h, new_w = sh, sw pad_left, pad_right, pad_top, pad_bot = 0, 0, 0, 0 # set pad color if len(img.shape) is 3 and not isinstance(padColor, (list, tuple, np.ndarray)): # color image but only one color provided padColor = [padColor]*3 # scale and pad scaled_img = cv2.resize(img, (new_w, new_h), interpolation=interp) scaled_img = cv2.copyMakeBorder(scaled_img, pad_top, pad_bot, pad_left, pad_right, borderType=cv2.BORDER_CONSTANT, value=padColor) return scaled_img def cropAndResize(img, size, crop_percent): h, w = img.shape[:2] sh, sw = size ch = crop_percent*h cw = crop_percent*w if(ch/sh > cw/sw): ch = cw*sh/sw else: cw = ch*sw/sh ch = int(ch) cw = int(cw) r0 = int(h/2-ch/2) r1 = r0 + ch c0 = int(w/2-cw/2) c1 = c0 + cw cropped_img = img[r0:r1, c0:c1] # interpolation method if ch > sh or cw > sw: # shrinking image interp = cv2.INTER_AREA else: # stretching image interp = cv2.INTER_CUBIC scaled_img = cv2.resize(cropped_img, (sw, sh), interpolation=interp) return scaled_img def transparentOverlay(foreground, background=None, remove_mask = True, pos=(0,0),scale = 1): """ :param foreground: transparent Image (BGRA) :param background: Input Color Background Image :param pos: position where the image to be blit. :param scale : scale factor of transparent image. :return: Overlayed image """ if(scale != 1): foreground = cv2.resize(foreground, None,fx=scale,fy=scale) alpha = foreground[:,:,3:].astype(float)/255 if(background is None): background = 255.0 if(type(background) in [int, float]): img = alpha*foreground[:,:,:3] + background*(1.0-alpha) if(not remove_mask): img = np.concatenate([img, foreground[:,:,3:]], axis=2) else: h,w,_ = foreground.shape rows,cols,_ = background.shape y0,x0 = pos[0],pos[1] y1 = min(y0+h, rows) x1 = min(x0+w, cols) img = background.copy() img[y0:y1,x0:x1,:] = alpha*foreground[:,:,:3] + (1.0-alpha)*background[y0:y1,x0:x1,:] if(not remove_mask): img = np.concatenate([img,
np.zeros((rows,cols,1))
numpy.zeros
# this tells python to act as if though We are one folder up import sys sys.path.insert(0,'..') import pandas as pd import FixedEffectModelPyHDFE.api as FEM from FixedEffectModelPyHDFE.DemeanDataframe import get_np_columns #import FixedEffectModel.api as FEM import numpy as np from patsy import dmatrices import statsmodels.formula.api as smf import statsmodels.api as sm from fastreg import linear from datetime import datetime import unittest from math import isclose NLS_WORK = "./../data/test_dropped_na.dta" CEREAL = "./../data/cereal.dta" AUTO = "./../data/auto_drop_na.dta" TOLERANCE = 0.01 class FixedEffectsModelTestsVSfastreg(unittest.TestCase): def setup(self, data_directory, target, regressors, absorb, cluster): print(self._testMethodName) print("target: ", target) print("regressors: ", regressors) print("absorb: ", absorb) print("cluster: ", cluster) df = pd.read_stata(data_directory) df.reset_index(drop=True, inplace=True) fem_start = datetime.now() self.result = FEM.ols_high_d_category(df, regressors, target, absorb, cluster, formula=None, robust=False, epsilon = 1e-8, max_iter = 1e6) fem_end = datetime.now() print("FEM time taken: " + str(fem_end-fem_start)) self.result.summary() print() if absorb[0] == '0': absorb=None fastreg_start = datetime.now() fastreg = linear.ols(y=target[0], x=regressors, absorb=absorb, cluster=cluster, data=df) fastreg_end = datetime.now() print(fastreg) print("fastreg time taken: " + str(fastreg_end - fastreg_start)) print("\n\n\n\n\n") ######################################################################### ######################################################################### def test_just_absorb_nls_work_dataset(self): self.setup(NLS_WORK, target=['ttl_exp'], regressors=['wks_ue', 'tenure'], absorb=['idcode', 'birth_yr', 'fifty_clusts', 'sixty_clusts'], cluster=[]) def test_no_absorb_cluster_nls_work_dataset(self): self.setup(NLS_WORK, target=['ttl_exp'], regressors=['wks_ue', 'tenure'], absorb=['0'], cluster=['idcode', 'birth_yr', 'fifty_clusts', 'sixty_clusts']) # comparing fvalue def test_clustering_single_variable_no_absorb2_nls_work_dataset(self): self.setup(NLS_WORK, target=['ttl_exp'], regressors=['wks_ue', 'tenure'], absorb=['0'], cluster=['race']) # comparing fvalue assert(np.isclose(self.result.fvalue, 127593.72, atol=TOLERANCE)) # comparing standard errors assert(np.all(np.isclose(self.result.bse, np.asarray([.148934, .0065111, .0113615]), atol=TOLERANCE))) # comparing tvalues assert(np.all(np.isclose(self.result.tvalues, np.asarray([27.75, 2.32, 66.61]), atol=TOLERANCE))) def test_clustering_single_variable_no_absorb_nls_work_dataset(self): self.setup(NLS_WORK, target=['ttl_exp'], regressors=['wks_ue', 'tenure'], absorb=['0'], cluster=['fifty_clusts']) assert(np.isclose(self.result.fvalue, 10230.63, atol=TOLERANCE)) assert(np.all(np.isclose(self.result.bse, np.asarray([.048274, .0044294, .0052923]), atol=TOLERANCE))) assert(np.all(np.isclose(self.result.tvalues, np.asarray([85.60, 3.42, 143.00]), atol=TOLERANCE))) def test_clustering_two_variables_no_absorb_nls_work_dataset(self): self.setup(NLS_WORK, target=['ttl_exp'], regressors=['wks_ue', 'tenure'], absorb=['0'], cluster=['fifty_clusts', 'sixty_clusts']) assert(np.isclose(self.result.fvalue, 12347.24, atol=TOLERANCE)) assert(np.all(np.isclose(self.result.bse, np.asarray([.0518019, .0048228, .00492]), atol=TOLERANCE))) assert(np.all(np.isclose(self.result.tvalues, np.asarray([79.77, 3.14, 153.82]), atol=TOLERANCE))) def test_clustering_many_variables_no_absorb_nls_work_dataset(self): self.setup(NLS_WORK, target=['ttl_exp'], regressors=['wks_ue', 'tenure'], absorb=['0'], cluster=['fifty_clusts', 'sixty_clusts', 'birth_yr', 'idcode']) assert(np.isclose(self.result.fvalue, 4664.62, atol=TOLERANCE)) assert(np.all(np.isclose(self.result.bse, np.asarray([.0551555, .0080815, .007881]), atol=TOLERANCE))) assert(np.all(np.isclose(self.result.tvalues, np.asarray([74.92, 1.87, 96.03]), atol=TOLERANCE))) def test_just_absorb_nls_work_dataset(self): self.setup(NLS_WORK, target=['ttl_exp'], regressors=['wks_ue', 'tenure'], absorb=['fifty_clusts', 'sixty_clusts', 'birth_yr', 'idcode'], cluster=[]) assert(np.isclose(self.result.fvalue, 3891.51, atol=TOLERANCE)) assert(np.all(np.isclose(self.result.bse, np.asarray([.0047052, .0096448]), atol=TOLERANCE))) assert(np.all(np.isclose(self.result.tvalues, np.asarray([6.48, 88.22]), atol=TOLERANCE))) def test_cluster_1_absorb_1_nls_work_dataset(self): self.setup(NLS_WORK, target=['ttl_exp'], regressors=['wks_ue', 'tenure'], absorb=['fifty_clusts'], cluster=['sixty_clusts']) assert(np.isclose(self.result.fvalue, 9884.24, atol=TOLERANCE)) assert(np.all(np.isclose(self.result.bse, np.asarray([.004654, .0055812]), atol=TOLERANCE))) assert(np.all(np.isclose(self.result.tvalues, np.asarray([3.18, 135.54]), atol=TOLERANCE))) def test_cluster_1_absorb_1_2_nls_work_dataset(self): self.setup(NLS_WORK, target=['ttl_exp'], regressors=['wks_ue', 'tenure'], absorb=['fifty_clusts'], cluster=['fifty_clusts']) assert(np.isclose(self.result.fvalue, 10100.50, atol=TOLERANCE)) assert(np.all(np.isclose(self.result.bse, np.asarray([.0044538, .005324]), atol=TOLERANCE))) assert(np.all(np.isclose(self.result.tvalues, np.asarray([3.33, 142.09]), atol=TOLERANCE))) def test_cluster_many_absorb_1_nls_work_dataset(self): self.setup(NLS_WORK, target=['ttl_exp'], regressors=['wks_ue', 'tenure'], absorb=['fifty_clusts'], cluster=['fifty_clusts', 'sixty_clusts', 'idcode', 'year']) assert(np.isclose(self.result.fvalue, 86.89, atol=TOLERANCE)) assert(np.all(np.isclose(self.result.bse, np.asarray([.0189465, .0574001]), atol=TOLERANCE))) assert(np.all(np.isclose(self.result.tvalues, np.asarray([0.78, 13.18]), atol=TOLERANCE))) def test_cluster_3_absorb_3_nls_work_dataset(self): self.setup(NLS_WORK, target=['ttl_exp'], regressors=['wks_ue', 'tenure'], absorb=['fifty_clusts', 'sixty_clusts', 'ind_code'], cluster=['idcode', 'year', 'grade']) assert(np.isclose(self.result.fvalue, 113.61, atol=TOLERANCE)) assert(np.all(np.isclose(self.result.bse, np.asarray([.0168144, .0501467]), atol=TOLERANCE))) assert(np.all(np.isclose(self.result.tvalues, np.asarray([0.93, 15.03]), atol=TOLERANCE))) def test_cluster_3_absorb_3_2_nls_work_dataset(self): self.setup(NLS_WORK, target=['ttl_exp'], regressors=['wks_ue', 'tenure'], absorb=['fifty_clusts', 'sixty_clusts', 'ind_code'], cluster=['fifty_clusts', 'sixty_clusts', 'ind_code']) assert(np.isclose(self.result.fvalue, 2525.34, atol=TOLERANCE)) assert(np.all(np.isclose(self.result.bse, np.asarray([.004604, .0106474]), atol=TOLERANCE))) assert(np.all(np.isclose(self.result.tvalues, np.asarray([3.41, 70.78]), atol=TOLERANCE))) def test_cluster_4_absorb_4_nls_work_dataset(self): self.setup(NLS_WORK, target=['ttl_exp'], regressors=['wks_ue', 'tenure'], absorb=['fifty_clusts', 'sixty_clusts', 'ind_code', 'idcode'], cluster=['fifty_clusts', 'sixty_clusts', 'ind_code', 'idcode']) assert(np.isclose(self.result.fvalue, 3191.76, atol=TOLERANCE)) assert(np.all(np.isclose(self.result.bse, np.asarray([.00498, .010914]), atol=TOLERANCE))) assert(np.all(np.isclose(self.result.tvalues, np.asarray([6.17, 77.85]), atol=TOLERANCE))) ######################################################################### ######################################################################### # Boston auto dataset def test_pure_regression_boston_auto_dataset(self): self.setup(AUTO, target=['price'], regressors=['weight', 'length', 'turn'], absorb=['0'], cluster=[]) # comparing fvalue assert(np.isclose(self.result.fvalue, 14.78, atol=TOLERANCE)) # comparing standard errors assert(np.all(np.isclose(self.result.bse, np.asarray([4667.441, 1.143408, 40.13139, 128.8455]), atol=TOLERANCE))) # comparing tvalues assert(np.all(np.isclose(self.result.tvalues, np.asarray([3.19, 4.67, -1.75, -2.28]), atol=TOLERANCE))) def test_clustering_one_variable_no_absorb_auto_dataset(self): self.setup(AUTO, target=['price'], regressors=['weight', 'length', 'turn'], absorb=['0'], cluster=['rep78']) # comparing fvalue assert(np.isclose(self.result.fvalue, 17.17, atol=TOLERANCE)) # comparing standard errors assert(np.all(np.isclose(self.result.bse, np.asarray([6132.17, .8258151, 24.15393, 191.4521]), atol=TOLERANCE))) # comparing tvalues assert(np.all(np.isclose(self.result.tvalues, np.asarray([2.42, 6.46, -2.91, -1.53]), atol=TOLERANCE))) def test_clustering_two_variables_no_absorb_auto_dataset(self): self.setup(AUTO, target=['price'], regressors=['weight', 'length', 'turn'], absorb=['0'], cluster=['rep78', 'headroom']) # comparing fvalue assert(np.isclose(self.result.fvalue, 27.03, atol=TOLERANCE)) # comparing standard errors assert(np.all(np.isclose(self.result.bse, np.asarray([6037.897, 1.210828, 44.88812, 183.8683]), atol=TOLERANCE))) # comparing tvalues assert(np.all(np.isclose(self.result.tvalues, np.asarray([2.46, 4.41, -1.57, -1.60]), atol=TOLERANCE))) def test_clustering_two_variables_no_absorb_auto_dataset(self): self.setup(AUTO, target=['price'], regressors=['weight', 'length', 'turn'], absorb=['0'], cluster=['rep78', 'headroom']) # comparing fvalue assert(np.isclose(self.result.fvalue, 27.03, atol=TOLERANCE)) # comparing standard errors assert(np.all(np.isclose(self.result.bse, np.asarray([6037.897, 1.210828, 44.88812, 183.8683]), atol=TOLERANCE))) # comparing tvalues assert(np.all(np.isclose(self.result.tvalues, np.asarray([2.46, 4.41, -1.57, -1.60]), atol=TOLERANCE))) def test_clustering_3_absorb_3_variables_auto_dataset(self): self.setup(AUTO, target=['price'], regressors=['weight', 'length'], absorb=['rep78', 'headroom', 'turn'], cluster=['rep78', 'headroom', 'turn']) # comparing fvalue assert(
np.isclose(self.result.fvalue, 21.46, atol=TOLERANCE)
numpy.isclose
#!/usr/bin/env python # coding: utf-8 """ run consensus analysis to identify overall pattern analysis method developed by <NAME> and <NAME> """ import os import sys import glob import numpy import nibabel import nilearn.plotting import nilearn.input_data import matplotlib.pyplot as plt from statsmodels.stats.multitest import multipletests import scipy.stats from narps import Narps, hypnums, hypotheses from narps import NarpsDirs # noqa, flake8 issue from utils import log_to_file def t_corr(y, res_mean=None, res_var=None, Q=None): """ perform a one-sample t-test on correlated data y = data (n observations X n vars) res_mean = Common mean over voxels and results res_var = Common variance over voxels and results Q = "known" correlation across observations - (use empirical correlation based on maps) """ npts = y.shape[0] X = numpy.ones((npts, 1)) if res_mean is None: res_mean = 0 if res_var is None: res_var = 1 if Q is None: Q = numpy.eye(npts) VarMean = res_var * X.T.dot(Q).dot(X) / npts**2 # T = mean(y,0)/s-hat-2 # use diag to get s_hat2 for each variable T = (
numpy.mean(y, 0)
numpy.mean
#%% from kdg import kdf from kdg.utils import get_ece import openml from kdg.utils import sparse_parity import multiprocessing from joblib import Parallel, delayed import numpy as np import pandas as pd from sklearn.model_selection import StratifiedKFold from sklearn.ensemble import RandomForestClassifier as rf from sklearn.metrics import cohen_kappa_score import os from kdg.utils import generate_gaussian_parity, pdf, hellinger # %% reps = 100 n_estimators = 500 sample_size = np.logspace( np.log10(10), np.log10(5000), num=10, endpoint=True, dtype=int ) #%% def experiment_kdf(sample, n_estimators=500): X, y = sparse_parity(sample, p_star=2, p=2) X_test, y_test = sparse_parity(1000, p_star=2, p=2) p = np.arange(-1,1,step=0.006) q = np.arange(-1,1,step=0.006) xx, yy = np.meshgrid(p,q) grid_samples = np.concatenate( ( xx.reshape(-1,1), yy.reshape(-1,1) ), axis=1 ) model_kdf = kdf(kwargs={'n_estimators':n_estimators}) model_kdf.fit(X, y) proba_kdf = model_kdf.predict_proba(grid_samples) true_pdf_class1 = np.array([np.sum(grid_samples>0, axis=1)%2]).reshape(-1,1) true_pdf = np.concatenate([1-true_pdf_class1, true_pdf_class1], axis = 1) error = 1 - np.mean(model_kdf.predict(X_test)==y_test) return hellinger(proba_kdf, true_pdf), error def experiment_rf(sample, n_estimators=500): X, y = sparse_parity(sample, p_star=2, p=2) X_test, y_test = sparse_parity(1000, p_star=2, p=2) p = np.arange(-1,1,step=0.006) q = np.arange(-1,1,step=0.006) xx, yy = np.meshgrid(p,q) grid_samples = np.concatenate( ( xx.reshape(-1,1), yy.reshape(-1,1) ), axis=1 ) model_rf = rf(n_estimators=n_estimators).fit(X, y) proba_rf = model_rf.predict_proba(grid_samples) true_pdf_class1 = np.array([np.sum(grid_samples>0, axis=1)%2]).reshape(-1,1) true_pdf =
np.concatenate([1-true_pdf_class1, true_pdf_class1], axis = 1)
numpy.concatenate
# coding: utf-8 """ This module implements utility functions to compute several geometric properties. """ import numpy as np __author__ = "<NAME>" __copyright__ = "University of Pau and Pays Adour" __email__ = "<EMAIL>" __all__ = ["center_of_mass", "circum_center", "get_plane", "get_dihedral"] def center_of_mass(coords, masses=None): r"""Compute the center of mass of the points at coordinates `coords` with masses `masses`. Args: coords (np.ndarray): (N, 3) matrix of the points in :math:`\mathbb{R}^3` masses (np.ndarray): vector of length N with the masses Returns: The center of mass as a vector in :math:`\mathbb{R}^3` """ # check coord array try: coords = np.array(coords, dtype=np.float64) coords = coords.reshape(coords.size // 3, 3) except ValueError: print("coords = ", coords) raise ValueError("Cannot convert coords in a numpy array of floats" " with a shape (N, 3).") # check masses if masses is None: masses = np.ones(coords.shape[0]) else: try: masses = np.array(masses, dtype=np.float64) masses = masses.reshape(coords.shape[0]) except ValueError: print("masses = ", masses) raise ValueError("Cannot convert masses in a numpy array of " "floats with length coords.shape[0].") if masses is None: masses = np.ones(coords.shape[0]) return np.sum(coords * masses[:, np.newaxis], axis=0) / masses.sum() def circum_center(coords): r"""Compute the coordinates of the center of the circumscribed circle from three points A, B and C in :math:`\mathbb{R}^3`. Args: coords (ndarray): (3x3) cartesian coordinates of points A, B and C. Returns The coordinates of the center of the cicumscribed circle """ try: coords = np.array(coords, dtype=np.float64).reshape(3, 3) except ValueError: print("coords = ", coords) raise ValueError("Cannot convert coords in a numpy array of floats" " with a shape (3, 3).") # get coords of poins A, B and C a, b, c = coords # normal vector to ABC plane ABvAC = np.cross(b - a, c - a) # matrix M and vector B M = np.array([b - a, c - a, ABvAC]) B = np.array([np.dot(b - a, (b + a) / 2), np.dot(c - a, (c + a) / 2), np.dot(ABvAC, a)]) # solve linear system and return coordinates return np.dot(np.linalg.inv(M), B) def get_plane(coords, masses=None): r"""Given a set of N points in :math:`\mathbb{R}^3`, compute an orthonormal basis of vectors, the first two belonging to the plane and the third one being normal to the plane. In the particular case where N equal 3, there is an exact definition of the plane as the three points define an unique plan. If N = 3, use a gram-schmidt orthonormalization to compute the vectors. If N > 3, the orthonormal basis is obtained from SVD. Args: coords (np.ndarray): (N, 3) matrix of the points in :math:`\mathbb{R}^3` masses (np.ndarray): vector of length N with the masses Returns: Returns the orthonormal basis (vecx, vecy, n_a), vector n_a being normal to the plane. """ # check coord array try: coords =
np.array(coords, dtype=np.float64)
numpy.array
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # =========================================================================== # # Project : ML Studio # # Version : 0.1.0 # # File : test_data_management.py # # Python : 3.8.2 # # -------------------------------------------------------------------------- # # Author : <NAME> # # Company : DecisionScients # # Email : <EMAIL> # # URL : https://github.com/decisionscients/MLStudio # # -------------------------------------------------------------------------- # # Created : Monday, May 11th 2020, 8:33:38 pm # # Last Modified : Monday, May 11th 2020, 8:33:38 pm # # Modified By : <NAME> (<EMAIL>) # # -------------------------------------------------------------------------- # # License : BSD # # Copyright (c) 2020 DecisionScients # # =========================================================================== # """Tests data management utilities.""" #%% import numpy as np import pytest from pytest import mark from scipy.sparse import csr_matrix from sklearn.datasets import make_classification from mlstudio.utils.data_manager import MinMaxScaler, DataSplitter, GradientScaler from mlstudio.utils.data_manager import DataShuffler from mlstudio.utils.data_manager import AddBiasTerm, ZeroBiasTerm, unpack_parameters from mlstudio.utils.data_manager import LabelEncoder, OneHotLabelEncoder # -------------------------------------------------------------------------- # # TEST ADD BIAS TERM TRANSFORMER # # -------------------------------------------------------------------------- # @mark.utils @mark.data_manager @mark.add_bias_term def test_add_bias_term_np(): X = np.random.rand(5,5) xformer = AddBiasTerm() X = xformer.fit_transform(X) assert X.shape[1] == 6, "Bias term not added." assert np.all(X[:,0] == 1.0), "Column zero not ones." # Inverse transform X = xformer.inverse_transform(X) assert X.shape[1] == 5, "Bias term not removed." @mark.utils @mark.data_manager @mark.add_bias_term def test_add_bias_term_csr(): X = np.random.rand(5,5) X = csr_matrix(X) xformer = AddBiasTerm() X = xformer.fit_transform(X) assert X.shape[1] == 6, "Bias term not added." assert np.all(X.toarray()[:,0] == 1.0), "Column zero not ones." # Inverse transform X = xformer.inverse_transform(X) assert X.shape[1] == 5, "Bias term not removed." # -------------------------------------------------------------------------- # # TEST ZERO BIAS TERM TRANSFORMER # # -------------------------------------------------------------------------- # @mark.utils @mark.data_manager @mark.zero_bias_term def test_zero_bias_term(): X =
np.random.rand(5)
numpy.random.rand
# = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = import numpy as np import os import datetime import sys import astropy from astropy import wcs from astropy import units from astropy import convolution import astropy.convolution as ac # convolve, convolve_fft, Moffat2DKernel, Gaussian2DKernel import astropy.io.fits as afits from astropy.coordinates import SkyCoord from astropy import units as u from astropy.modeling.models import Sersic1D from astropy.modeling.models import Sersic2D from astropy.nddata import Cutout2D import subprocess import glob import shutil import scipy.ndimage import scipy.special import scipy.integrate as integrate import tdose_utilities as tu import tdose_model_FoV as tmf from scipy.stats import multivariate_normal import matplotlib as mpl from matplotlib.colors import LogNorm mpl.use('Agg') # prevent pyplot from opening window; enables closing ssh session with detached screen running TDOSE import matplotlib.pylab as plt import pdb # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = def load_setup(setupfile='./tdose_setup_template.txt',verbose=True): """ Return dictionary with the setups found in 'setupfile' (both TDOSE run and modification setup files can be loaded) --- INPUT --- setupfile The name of the txt file containing the TDOSE setup to load Template for relevant setup files can be generated with tdose_load_setup.generate_setup_template() or tdose_load_setup.generate_setup_template_modify() verbose Toggle verbosity --- EXAMPLE OF USE --- import tdose_utilities as tu setup = tu.load_setup(setupfile='./tdose_setup_template.txt') setup_modify = tu.load_setup(setupfile='./tdose_setup_template_modify.txt') """ if verbose: print(' --- tdose_utilities.load_setup() --- ') #------------------------------------------------------------------------------------------------------ if verbose: print((' - Loading setup for TDOSE in '+setupfile)) setup_arr = np.genfromtxt(setupfile,dtype=None,names=None) setup_dic = {} for ii in np.arange(int(setup_arr.shape[0])): paramname = setup_arr[ii,0].astype(str) if paramname in list(setup_dic.keys()): sys.exit(' Setup parameter "'+paramname+'" appears multiple times in the setup file\n '+ setupfile) try: val = float(setup_arr[ii,1].astype(str)) except: val = setup_arr[ii,1].astype(str) # - - - treatment of individual paramters - - - if ('extension' in paramname) & (type(val) == float): val = int(val) if (type(val) == str) or (type(val) == np.str_): if val.lower() == 'none': val = None elif val.lower() == 'true': val = True elif val.lower() == 'false': val = False if (type(val) == str) or (type(val) == np.str_): dirs = ['sources_to_extract','model_cube_layers','cutout_sizes'] if (paramname in dirs) & ('/' in str(val)): val = val setup_dic[paramname] = val continue lists = ['modify_sources_list','nondetections','model_cube_layers','sources_to_extract','plot_1Dspec_xrange','plot_1Dspec_yrange', 'plot_S2Nspec_xrange','plot_S2Nspec_yrange','cutout_sizes','aperture_size'] if (paramname in lists) & (val != 'all') & (val.lower() != 'none') & (val[0] == '['): val = [float(vv) for vv in val.split('[')[-1].split(']')[0].split(',')] setup_dic[paramname] = val continue if ('psf_sigma' in paramname): if '/' in val: sigmasplit = val.split('/') if len(sigmasplit) != 2: pass else: val = float(sigmasplit[0]) / float(sigmasplit[1]) setup_dic[paramname] = val continue setup_dic[paramname] = val if verbose: print(' - Checking main keys are available; if not, adding them with None values') checkkeys = ['nondetections','gauss_guess'] for ck in checkkeys: if ck not in list(setup_dic.keys()): setup_dic[ck] = None if verbose: print(' - Returning dictionary containing setup parameters') return setup_dic # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = def generate_setup_template(outputfile='./tdose_setup_template.txt',clobber=False,verbose=True): """ Generate setup text file template --- INPUT --- outputfile The name of the output which will contain the TDOSE setup template clobber Overwrite files if they exist verbose Toggle verbosity --- EXAMPLE OF USE --- import tdose_utilities as tu filename = './tdose_setup_template_new.txt' tu.generate_setup_template(outputfile=filename,clobber=False) setup = tu.load_setup(setupfile=filename) """ if verbose: print(' --- tdose_utilities.generate_setup_template() --- ') #------------------------------------------------------------------------------------------------------ if os.path.isfile(outputfile) & (clobber == False): sys.exit(' ---> Outputfile already exists and clobber=False ') else: if verbose: print((' - Will store setup template in '+outputfile)) if os.path.isfile(outputfile) & (clobber == True): if verbose: print(' - Output already exists but clobber=True so overwriting it ') setuptemplate = """ #-------------------------------------------------START OF TDOSE SETUP------------------------------------------------- # # Template for Three Dimensional Optimal Spectral Extracion (TDOSE, http://github.com/kasperschmidt/TDOSE) setup file # Template was generated with tdose_utilities.generate_setup_template() on %s # Setup file can be run with tdose.perform_extraction() or tdose.perform_extractions_in_parallel() # # - - - - - - - - - - - - - - - - - - - - - - - - - - DATA INPUT - - - - - - - - - - - - - - - - - - - - - - - - - - - data_cube /path/datacube.fits # Path and name of fits file containing data cube to extract spectra from cube_extension DATA_DCBGC # Name or number of fits extension containing data cube variance_cube /path/variancecube.fits # Path and name of fits file containing variance cube to use for extraction variance_extension VARCUBE # Name or number of fits extension containing noise cube ref_image /path/referenceimage.fits # Path and name of fits file containing image to use as reference when creating source model img_extension 0 # Name or number of fits extension containing reference image wht_image /path/refimage_wht.fits # Path and name of fits file containing weight map of reference image (only cut out; useful for galfit modeling) wht_extension 0 # Name or number of fits extension containing weight map source_catalog /path/tdose_sourcecat.fits # Path and name of source catalog containing sources to extract spectra for sourcecat_IDcol id # Column containing source IDs in source_catalog sourcecat_xposcol x_image # Column containing x pixel position in source_catalog sourcecat_yposcol y_image # Column containing y pixel position in source_catalog sourcecat_racol ra # Column containing ra position in source_catalog (used to position cutouts if model_cutouts = True) sourcecat_deccol dec # Column containing dec position in source_catalog (used to position cutouts if model_cutouts = True) sourcecat_fluxcol fluxscale # Column containing a flux scale used for the modeling if no gauss_guess is provided sourcecat_parentIDcol None # Column containing parent source IDs grouping source IDs into objects. Set to None to used id column # corresponding to assigning each source to a single object # if not None the parentid is used to group source models when storing 1D spectra. All models keep sources separate. # - - - - - - - - - - - - - - - - - - - - - - - - OUTPUT DIRECTORIES - - - - - - - - - - - - - - - - - - - - - - - - - models_directory /path/tdose_models/ # Directory to store the modeling output from TDOSE in cutout_directory /path/tdose_cutouts/ # Directory to store image and cube cutouts in if model_cutouts=True spec1D_directory /path/tdose_spectra/ # Output directory to store spectra in. # - - - - - - - - - - - - - - - - - - - - - - - - - - CUTOUT SETUP - - - - - - - - - - - - - - - - - - - - - - - - - - model_cutouts True # Perform modeling and spectral extraction on small cutouts of the cube and images to reduce run-time cutout_sizes /path/tdose_setup_cutoutsizes.txt # Size of cutouts [ra,dec] in arcsec around each source to model. # To use source-specific cutouts provide ascii file containing ID xsize[arcsec] and ysize[arcsec]. # - - - - - - - - - - - - - - - - - - - - - - - - SOURCE MODEL SETUP - - - - - - - - - - - - - - - - - - - - - - - - - model_image_ext tdose_modelimage # Name extension of fits file containing reference image model. To ignored use None model_param_reg tdose_modelimage_ds9 # Name extension of DS9 region file for reference image model. To ignored use None model_image_cube_ext tdose_modelimage_cubeWCS # Name extension of fits file containing model image after conversion to cube WCS. To ignored use None. source_model gauss # The source model to use for sources. Choices are: # gauss Each source is modeled as a multivariate gaussian using the source_catalog input as starting point # galfit The sources in the field-of-view are defined based on GALFIT header parameters; if all components are # Not enabled yet # Gaussians an analytical convolution is performed. Otherwise numerical convolution is used. # Not enabled yet # modelimg A model image exists, e.g., obtained with Galfit, in modelimg_directory. To disentangle/de-blend individual # components, a model cube and parent_ids should be provided (see comments to modelimg_directory). If a model # image is provded, TDOSE assumes it to represent the 1 object in the field-of-view. # If the model image is not found a gaussian model of the FoV (source_model=gauss) is performed instead. # aperture A simple aperture extraction on the datacubes is performed, i.e., no modeling of sources. # - - - - - - - - - - - - - - - - - - - - - - - - GAUSS MODEL SETUP - - - - - - - - - - - - - - - - - - - - - - - - - - gauss_guess /path/sextractoroutput.fits # To base initial guess of gaussian parameters on a SExtractor output provide SExtractor output fits file here # If gauss_initguess=None the positions and flux scale provided in source_catalog will be used. gauss_guess_idcol ID # Column of IDs in gauss_guess SExtractor file gauss_guess_racol RA # Column of RAs in gauss_guess SExtractor file gauss_guess_deccol DEC # Column of Decs in gauss_guess SExtractor file gauss_guess_aimg A_IMAGE # Column of major axis in gauss_guess SExtractor file gauss_guess_bimg B_IMAGE # Column of minor axis in gauss_guess SExtractor file gauss_guess_angle THETA_IMAGE # Column of angle in gauss_guess SExtractor file gauss_guess_fluxscale ACS_F814W_FLUX # Column of flux in gauss_guess SExtractor file to us for scaling gauss_guess_fluxfactor 3 # Factor to apply to flux scale in initial Gauss parameter guess gauss_guess_Nsigma 1 # Number of sigmas to include in initial Gauss parameter guess max_centroid_shift 10 # The maximum shift of the centroid of each source allowed in the gaussian modeling. Given in pixels to # set bounds ypix_centroid +/- max_centroid_shift and xpix_centroid +/- max_centroid_shift # If none, no bounds are put on the centroid position of the sources. # - - - - - - - - - - - - - - - - - - - - - - - - GALFIT MODEL SETUP - - - - - - - - - - - - - - - - - - - - - - - - - galfit_directory /path/models_galfit/ # If source_model = galfit provide path to directory containing galfit models. # TDOSE will look for galfit_*ref_image*_output.fits (incl. the cutout string if model_cutouts=True) # If no model is found a source_model=gauss run on the object will be performed instead. galfit_model_extension 2 # Fits extension containing galfit model with model parameters of each source in header. # - - - - - - - - - - - - - - - - - - - - - - - - MODEL IMAGE SETUP - - - - - - - - - - - - - - - - - - - - - - - - - modelimg_directory /path/models_cutouts/ # If source_model = modelimg provide the path to directory containing the individual source models # TDOSE will look for model_*ref_image*.fits (incl. the cutout string if model_cutouts=True). If no model is found the object is skipped # If a model image named model_*ref_image*_cube.fits is found, TDOSE assumes this file contains a cube with the individual model # components isolated in individual layers of the cube. TDOSE will use this model instead of one generated within TDOSE. # Parent IDs in the source catalog can be used to define what components belong to the object of interest (i.e., to extract a spectrum for) # GALFIT models can be converted to TDOSE-suited model-cubes with tdose_utilities.galfit_convertmodel2cube() # A TDOSE-suited model-cube can be build from individual 2D models with tdose_utilities.build_modelcube_from_modelimages() modelimg_extension 0 # Fits extension containing model # - - - - - - - - - - - - - - - - - - - - - - - - APERTURE MODEL SETUP - - - - - - - - - - - - - - - - - - - - - - - - aperture_size 1.5 # Radius of apertures (float or list) to use given in arc seconds. For longer list of # object-specific apertures provide ascii file containing ID and aperturesize[arcsec]. # - - - - - - - - - - - - - - - - - - - - - - - - - PSF MODEL SETUP - - - - - - - - - - - - - - - - - - - - - - - - - - psf_type gauss # Select PSF model to build. Choices are: # gauss Model the PSF as a symmetric Gaussian with sigma = FWHM/2.35482 # kernel_gauss An astropy.convolution.Gaussian2DKernel() used for numerical convolution # Not enabled yet # kernel_moffat An astropy.convolution.Moffat2DKernel() used for numerical convolution # Not enabled yet psf_FWHM_evolve linear # Evolution of the FWHM from blue to red end of data cube. Choices are: # linear FWHM wavelength dependence described as FWHM(lambda) = p0[''] + p1[''/A] * (lambda - p2[A]) psf_FWHMp0 0.940 # p0 parameter to use when determining wavelength dependence of PSF psf_FWHMp1 -3.182e-5 # p1 parameter to use when determining wavelength dependence of PSF psf_FWHMp2 7050 # p2 parameter to use when determining wavelength dependence of PSF psf_savecube True # To save fits file containing the PSF cube set psf_savecube = True # This cube is used for the "source_model = modelimg" numerical PSF convolution # - - - - - - - - - - - - - - - - - - - - - - - - - - - NON_DETECTIONS - - - - - - - - - - - - - - - - - - - - - - - - nondetections None # List of IDs of sources in source_catalog that are not detected in the reference image or which # have low flux levels in which cases the Gaussian modeling is likely to be inaccurate. # For long list of objects provide ascii file containing ids. # If source_model = gauss then sources will be extracted by replacing models within ignore_radius # with a single point source in the reference image model, which will then # be convolved with the PSF specified when extracting, as usual. # If source_model = modelimg TDOSE assumes that the input model already represents the desired extraction model # of the non-detection. I.e., if the object should be extracted as a (PSF # convolved) point source, the model image should include a point source. # Hence, for source_model = modelimg the keyword nondetections is ignored. ignore_radius 0.3 # Models within a radius of ignore_radius [arcsec] of the non-detection location will be replaced with a # point source for extractions with source_model = gauss before convolving with the PSF and adjusting the flux # leves in each model cube layer. # - - - - - - - - - - - - - - - - - - - - - - - - - CUBE MODEL SETUP - - - - - - - - - - - - - - - - - - - - - - - - - model_cube_layers all # Layers of data cube to model [both end layers included]. If 'all' the full cube will be modeled. # To model source-specific layers provide ascii file containing ID layerlow and layerhigh. # If layerlow=all and layerhigh=all all layers will be modeled for particular source model_cube_optimizer matrix # The optimizer to use when matching flux levels in cube layers: # matrix Optimize fluxes analytically using matrix algebra to minimize chi squared of # the equation set comparing model and data in each layer. # nnls Optimize fluxes using Scipy's non-negative least squares solver restricting # flux scales to >= 0 (assuming source models are non-negative too). # curvefit Optimize fluxes numerically using least square fitting from scipy.optimize.curve_fit(). # Only enabled for analytic convolution of Gaussian source models. # lstsq Optimize fluxes analytically using scipy.linalg.lstsq(). model_cube_ext tdose_modelcube # Name extension of fits file containing model data cube. residual_cube_ext tdose_modelcube_residual # Name extension of fits file containing residual between model data cube and data. To ignored use None. source_model_cube_ext tdose_source_modelcube # Name extension of fits file containing source model cube (used to modify data cube). # - - - - - - - - - - - - - - - - - - - - - - - - SPECTRAL EXTRACTION - - - - - - - - - - - - - - - - - - - - - - - - - sources_to_extract [8685,9262,10195,29743] # Sources in source_catalog to extract 1D spectra for. # If sourcecat_parentIDcol is not None all associated spectra are included in stored object spectra # If set to 'all', 1D spectra for all sources in source_catalog is produced (without grouping according to parents). # For long list of objects provide ascii file containing containing ids (here parent grouping will be performed) spec1D_name tdose_spectrum # Name extension to use for extracted 1D spectra # - - - - - - - - - - - - - - - - - - - - - - - - - - - PLOTTING - - - - - - - - - - - - - - - - - - - - - - - - - - - plot_generate True # Indicate whether to generate plots or not plot_1Dspec_ext fluxplot # Name extension of pdf file containing plot of 1D spectrum plot_1Dspec_xrange [4800,9300] # Range of x-axes (wavelength) for plot of 1D spectra plot_1Dspec_yrange [-100,1500] # Range of y-axes (flux) for plot of 1D spectra plot_1Dspec_shownoise True # Indicate whether to show the noise envelope in plot or not plot_S2Nspec_ext S2Nplot # Name extension of pdf file containing plot of S/N spectrum plot_S2Nspec_xrange [4800,9300] # Range of x-axes (wavelength) for plot of S2N spectra plot_S2Nspec_yrange [-1,15] # Range of y-axes (S2N) for plot of S2N spectra #--------------------------------------------------END OF TDOSE SETUP-------------------------------------------------- """ % (tu.get_now_string()) fout = open(outputfile,'w') fout.write(setuptemplate) fout.close() # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = def generate_setup_template_modify(outputfile='./tdose_setup_template_modify.txt',clobber=False,verbose=True): """ Generate setup text file template for modifying data cubes --- INPUT --- outputfile The name of the output which will contain the TDOSE setup template clobber Overwrite files if they exist verbose Toggle verbosity --- EXAMPLE OF USE --- import tdose_utilities as tu filename = './tdose_setup_template_modify_new.txt' tu.generate_setup_template_modify(outputfile=filename,clobber=True) setup = tu.load_setup(setupfile=filename) """ if verbose: print(' --- tdose_utilities.generate_setup_template_modify() --- ') #------------------------------------------------------------------------------------------------------ if os.path.isfile(outputfile) & (clobber == False): sys.exit(' ---> Outputfile already exists and clobber=False ') else: if verbose: print((' - Will store setup template in '+outputfile)) if os.path.isfile(outputfile) & (clobber == True): if verbose: print(' - Output already exists but clobber=True so overwriting it ') setuptemplate = """ #---------------------------------------------START OF TDOSE MODIFY SETUP--------------------------------------------- # # Template for TDOSE (http://github.com/kasperschmidt/TDOSE) setup file for modifying data cubes. # Generated with tdose_utilities.generate_setup_template_modify() on %s # Cube modifications are performed with tdose_modify_cube.perform_modification(setupfile=setup_file_modify) # # - - - - - - - - - - - - - - - - - - - - - - - - - MODIFYING CUBE - - - - - - - - - - - - - - - - - - - - - - - - - - data_cube /path/datacube.fits # Path and name of fits file containing data cube to modify cube_extension DATA_DCBGC # Name or number of fits extension containing data cube source_model_cube /path/tdose_source_modelcube.fits # Path and name of fits file containing source model cube source_extension DATA_DCBGC # Name or number of fits extension containing source model cube modified_cube_dir /path/to/output/ # Path of output directory to store modified cube in modified_cube tdose_modified_datacube # Name extension of file containing modified data cube. modify_sources_list [1,2,5] # List of IDs of sources to remove from data cube using source model cube. # Corresponds to indices of source model cube so expects [0,Nmodelcomp-1] # For long list of IDs provide path and name of file containing IDs (only) sources_action remove # Indicate how to modify the data cube. Chose between: # 'remove' Sources in modify_sources_list are removed from data cube # 'keep' All sources except the sources in modify_sources_list are removed from data cube #----------------------------------------------END OF TDOSE MODIFY SETUP---------------------------------------------- """ % (tu.get_now_string()) fout = open(outputfile,'w') fout.write(setuptemplate) fout.close() # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = def duplicate_setup_template(outputdirectory,infofile,infohdr=2,infofmt="S250", loopcols=['data_cube','cube_extension'], namebase='MUSEWide_tdose_setup',clobber=False,verbose=True): """ Take a setup template generated with generate_setup_template() and duplicate it filling it with information from a provided infofile, e.g., fill update PSF info, field names, image names, source lists, etc. --- INPUT --- outputdirectory Directory to store setup templates in infofile File containing info to replace values in template setup with infohdr Number of header (comment) lines in infofile before the expected list of column names infofmt Format of columns in infofile (format for all columns are needed; not just loopcols) If just a single format string is provided, this will be used for all columns. loopcols The name of the columns in the loopcols to perform replacements for. The columns should correspond to keywords in the TDOSE setup file. The first column of the file should be named 'setupname' and will be used to name the duplicated setup file (appending it to namebase). if 'all', all columns in infofile will be attempted replaced. namebase Name base to use for the setup templates clobber Overwrite files if they exist verbose Toggle verbosity --- EXAMPLE OF USE --- import tdose_utilities as tu outputdir = '/Users/kschmidt/work/TDOSE/muse_tdose_setups/' infofile = outputdir+'musewide_infofile.txt' tu.duplicate_setup_template(outputdir,infofile,namebase='MUSEWide_tdose_setup',clobber=False,loopcols=['setupname','data_cube','cube_extension']) """ if verbose: print(' --- tdose_utilities.duplicate_setup_template_MUSEWide() --- ') filename = outputdirectory+namebase+'.txt' tu.generate_setup_template(outputfile=filename,clobber=clobber) if ',' not in infofmt: #if a single common format is given count columns in infofile copen = np.genfromtxt(infofile,skip_header=infohdr,names=True) Ncol = len(copen[0]) infofmt = ','.join([infofmt]*Ncol) copen = np.genfromtxt(infofile,skip_header=infohdr,names=True,dtype=infofmt) if loopcols == 'all': if verbose: print(' - loopcals="all" so will attempt replacement of all columns in infofile') loopcols = np.asarray(copen.dtype.names).tolist() Nfiles = len(copen[loopcols[0]]) if verbose: print((' - Performing replacements and generating the '+str(Nfiles)+' TDOSE setup templates ' \ 'described in \n '+infofile)) for setupnumber in np.arange(int(Nfiles)): replacements = copen[setupnumber] newsetup = outputdirectory+namebase+'_'+replacements['setupname'].astype(str)+'.txt' if os.path.isfile(newsetup) & (clobber == False): if verbose: print(' - File '+newsetup+' already exists and clobber = False so moving on to next duplication ') continue else: fout = open(newsetup,'w') with open(filename,'r') as fsetup: for setupline in fsetup: if setupline.startswith('#'): if "Generated with tdose_utilities.generate_setup_template()" in setupline: nowstring = tu.get_now_string() fout.write("# Generated with tdose_utilities.duplicate_setup_template() on "+nowstring+' \n') else: fout.write(setupline) elif setupline == '\n': fout.write(setupline) else: vals = setupline.split() if vals[0] in loopcols: replaceline = setupline.replace(' '+vals[1]+' ',' '+copen[vals[0]][setupnumber].astype(str)+' ') else: replaceline = setupline.replace(' '+vals[1]+' ',' NO_REPLACEMENT ') newline = replaceline.split('#')[0]+'#'+\ '#'.join(setupline.split('#')[1:]) # don't include comment replacements fout.write(newline) fout.close() # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = def build_2D_cov_matrix(sigmax,sigmay,angle,verbose=True): """ Build a covariance matrix for a 2D multivariate Gaussian --- INPUT --- sigmax Standard deviation of the x-compoent of the multivariate Gaussian sigmay Standard deviation of the y-compoent of the multivariate Gaussian angle Angle to rotate matrix by in degrees (clockwise) to populate covariance cross terms verbose Toggle verbosity --- EXAMPLE OF USE --- import tdose_utilities as tu covmatrix = tu.build_2D_cov_matrix(3,1,35) """ if verbose: print((' - Build 2D covariance matrix with varinaces (x,y)=('+str(sigmax)+','+str(sigmay)+\ ') and then rotated '+str(angle)+' degrees')) cov_orig = np.zeros([2,2]) cov_orig[0,0] = sigmay**2.0 cov_orig[1,1] = sigmax**2.0 angle_rad = (180.0-angle) * np.pi/180.0 # The (90-angle) makes sure the same convention as DS9 is used c, s = np.cos(angle_rad), np.sin(angle_rad) rotmatrix = np.matrix([[c, -s], [s, c]]) cov_rot = np.dot(np.dot(rotmatrix,cov_orig),np.transpose(rotmatrix)) # performing rot * cov * rot^T return cov_rot # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = def normalize_2D_cov_matrix(covmatrix,verbose=True): """ Calculate the normalization foctor for a multivariate gaussian from it's covariance matrix However, not that gaussian returned by tu.gen_2Dgauss() is normalized for scale=1 --- INPUT --- covmatrix covariance matrix to normaliz verbose Toggle verbosity """ detcov = np.linalg.det(covmatrix) normfac = 1.0 / (2.0 * np.pi * np.sqrt(detcov) ) return normfac # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = def gen_noisy_cube(cube,type='poisson',gauss_std=0.5,verbose=True): """ Generate noisy cube based on input cube. --- INPUT --- cube Data cube to be smoothed type Type of noise to generate poisson Generates poissonian (integer) noise gauss Generates gaussian noise for a gaussian with standard deviation gauss_std=0.5 gauss_std Standard deviation of noise if type='gauss' verbose Toggle verbosity --- EXAMPLE OF USE --- import tdose_utilities as tu datacube = np.ones(([3,3,3])); datacube[0,1,1]=5; datacube[1,1,1]=6; datacube[2,1,1]=8 cube_with_noise = tu.gen_noisy_cube(datacube,type='gauss',gauss_std='0.5') """ if verbose: print((' - Generating "'+str(type)+'" noise on data cube')) if type == 'poisson': cube_with_noise = np.random.poisson(lam=cube, size=None) elif type == 'gauss': cube_with_noise = cube + np.random.normal(loc=np.zeros(cube.shape),scale=gauss_std, size=None) else: sys.exit(' ---> type="'+type+'" is not valid in call to mock_cube_sources.generate_cube_noise() ') return cube_with_noise # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = def gen_psfed_cube(cube,type='gauss',type_param=[0.5,1.0],use_fftconvolution=False,verbose=True): """ Smooth cube with a 2D kernel provided by 'type', i.e., applying a model PSF smoothing to cube --- INPUT --- cube Data cube to be smoothed type Type of smoothing kernel to apply gauss Use 2D gaussian smoothing kernel type_param expected: [stdev,(stdev_wave_scale)] moffat Use a 2D moffat profile to represent the PSF type_param expected: [gamma,alpha,(gamma_wave_scale,alpha_wave_scale)] NB: If *wave_scale inputs are provided a list of scales to apply at each wavelength layer (z-direction) of data cube is expected, hence, adding a wavelength dependence to the kernels. type_param List of parameters for the smoothing kernel. For expected paramters see notes in description of "type" keyword above. use_fftconvolution Perform convolution in Foruire space with FFT verbose Toggle verbosity --- EXAMPLE OF USE --- import tdose_utilities as tu datacube = np.ones(([3,3,3])); datacube[0,1,1]=5; datacube[1,1,1]=6; datacube[2,1,1]=8 cube_smoothed = tu.gen_psfed_cube(datacube,type='gauss',type_param=[10.0,[1.1,1.3,1.5]]) --- EXAMPLE OF USE --- """ if verbose: print((' - Applying a '+type+' PSF to data cube')) Nparam = len(type_param) Nlayers = cube.shape[0] # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - if type == 'gauss': if Nparam == 1: if verbose: print(' No wavelength dependence; duplicating kernel for all layers') kernel = ac.Gaussian2DKernel(type_param[0]) kernels = [kernel]*Nlayers elif Nparam == 2: if verbose: print(' Wavelength dependence; looping over layers to generate kernels') if Nlayers != len(type_param[1]): sys.exit(' ---> The number of wavelength scalings provided ('+str(len(type_param[1]))+ ') is different from the number of layers in cube ('+str(Nlayers)+')') kernels = [] for ll in np.arange(int(Nlayers)): kernel = ac.Gaussian2DKernel(type_param[0]*type_param[1][ll]) kernels.append(kernel) else: sys.exit(' ---> Invalid number of paramters provided ('+str(Nparam)+')') # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - elif type == 'moffat': if Nparam == 2: if verbose: print(' No wavelength dependence; duplicating kernel for all layers') kernel = ac.Moffat2DKernel(type_param[0],type_param[1]) kernels = [kernel]*Nlayers elif Nparam == 4: if verbose: print(' Wavelength dependence; looping over layers to generate kernels') if (Nlayers != len(type_param[2])) or (Nlayers != len(type_param[3])): sys.exit(' ---> The number of wavelength scalings provided ('+str(len(type_param[2]))+ ' and '+str(len(type_param[3]))+ ') are different from the number of layers in cube ('+str(Nlayers)+')') kernels = [] for ll in np.arange(int(Nlayers)): kernel = ac.Moffat2DKernel(type_param[0]*type_param[2][ll],type_param[1]*type_param[3][ll]) kernels.append(kernel) else: sys.exit(' ---> Invalid number of paramters provided ('+str(Nparam)+')') # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - else: sys.exit(' ---> type="'+type+'" is not valid in call to mock_cube_sources.gen_smoothed_cube() ') # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - if verbose: print((' - Applying convolution kernel ('+type+') to each wavelength layer ')) cube_psfed = tu.perform_2Dconvolution(cube,kernels,use_fftconvolution=use_fftconvolution,verbose=True) return cube_psfed # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = def perform_2Dconvolution(cube,kernels,use_fftconvolution=False,verbose=True): """ Perform 2D convolution in data cube layer by layer --- INPUT --- cube Data cube to convolve kernels List of (astropy) kernels to apply on each (z/wavelengt)layer of the cube use_fftconvolution To convolve in FFT space set this keyword to True verbose Toggle verbosity --- EXAMPLE OF USE --- # see tdose_utilities.gen_psfed_cube() """ csh = cube.shape cube_convolved = np.zeros(csh) for zz in np.arange(int(csh[0])): # looping over wavelength layers of cube layer = cube[zz,:,:] if use_fftconvolution: layer_convolved = ac.convolve_fft(layer, kernels[zz], boundary='fill') else: layer_convolved = ac.convolve(layer, kernels[zz], boundary='fill') cube_convolved[zz,:,:] = layer_convolved return cube_convolved # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = def gen_aperture(imgsize,ypos,xpos,radius,pixval=1,showaperture=False,verbose=True): """ Generating an aperture image --- INPUT --- imgsize The dimensions of the array to return. Expects [y-size,x-size]. The aperture will be positioned in the center of a (+/-x-size/2., +/-y-size/2) sized array ypos Pixel position in the y direction xpos Pixel position in the x direction radius Radius of aperture in pixels showaperture Display image of generated aperture verbose Toggle verbosity --- EXAMPLE OF USE --- import tdose_utilities as tu apertureimg = tu.gen_aperture([20,40],10,5,10,showaperture=True) apertureimg = tu.gen_aperture([2000,4000],900,1700,150,showaperture=True) """ if verbose: print(' - Generating aperture in image (2D array)') y , x = np.ogrid[-ypos+1.:imgsize[0]-ypos+1., -xpos+1.:imgsize[1]-xpos+1.] # +1s make sure pixel indication starts at pixel 1,1 mask = x*x + y*y <= radius**2. aperture = np.zeros(imgsize) if verbose: print((' - Assigning pixel value '+str(pixval)+' to aperture')) aperture[mask] = pixval if showaperture: if verbose: print(' - Displaying resulting image of aperture (added background noise)') noisimg = np.random.normal(0,pixval/5.,imgsize) noisimg[mask] = pixval plt.imshow(noisimg,interpolation='none') plt.grid() plt.title('Generated aperture') plt.show() plt.ion() return aperture # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = def gen_2Dgauss(size,cov,scale,method='scipy',show2Dgauss=False,savefits=False,verbose=True): """ Generating a 2D gaussian with specified parameters --- INPUT --- size The dimensions of the array to return. Expects [ysize,xsize]. The 2D gauss will be positioned in the center of the array cov Covariance matrix of gaussian, i.e., variances and rotation Can be build with cov = build_2D_cov_matrix(stdx,stdy,angle) scale Scaling the 2D gaussian. By default scale = 1 returns normalized 2D Gaussian. I.e., np.trapz(np.trapz(gauss2D,axis=0),axis=0) = 1 method Method to use for generating 2D gaussian: 'scipy' Using the class multivariate_normal from the scipy.stats library 'matrix' Use direct matrix expression for PDF of 2D gaussian (slow!) show2Dgauss Save plot of generated 2D gaussian savefits Save generated profile to fits file verbose Toggler verbosity --- EXAMPLE OF USE --- import tdose_utilities as tu covmatrix = tu.build_2D_cov_matrix(4,1,5) gauss2Dimg = tu.gen_2Dgauss([20,40],covmatrix,5,show2Dgauss=True) gauss2Dimg = tu.gen_2Dgauss([9,9],covmatrix,1,show2Dgauss=True) sigmax = 3.2 sigmay = 1.5 covmatrix = tu.build_2D_cov_matrix(sigmax,sigmay,0) scale = 1 # returns normalized gaussian Nsigwidth = 15 gauss2DimgNorm = tu.gen_2Dgauss([sigmay*Nsigwidth,sigmax*Nsigwidth],covmatrix,scale,show2Dgauss=True,savefits=True) covmatrix = tu.build_2D_cov_matrix(4,2,45) scale = 1 # returns normalized gaussian gauss2DimgNorm = tu.gen_2Dgauss([33,33],covmatrix,scale,show2Dgauss=True,savefits=True) """ if verbose: print(' - Generating multivariate_normal object for generating 2D gauss using ') if method == 'scipy': if verbose: print(' scipy.stats.multivariate_normal.pdf() ') mvn = multivariate_normal([0, 0], cov) if verbose: print(' - Setting up grid to populate with 2D gauss PDF') #x, y = np.mgrid[-np.ceil(size[0]/2.):np.floor(size[0]/2.):1.0, -np.ceil(size[1]/2.):np.floor(size[1]/2.):1.0] #LT170707 x, y = np.mgrid[-np.floor(size[0]/2.):np.ceil(size[0]/2.):1.0, -np.floor(size[1]/2.):np.ceil(size[1]/2.):1.0] pos = np.zeros(x.shape + (2,)) pos[:, :, 0] = x; pos[:, :, 1] = y gauss2D = mvn.pdf(pos) elif method == 'matrix': if verbose: print(' loop over matrix expression ') gauss2D = np.zeros([np.int(np.ceil(size[0])),np.int(np.ceil(size[1]))]) mean = np.array([np.floor(size[0]/2.),np.floor(size[1]/2.)]) norm = 1/np.linalg.det(np.sqrt(cov))/2.0/np.pi for xpix in np.arange(size[1]): for ypix in np.arange(size[0]): coordMmean = np.array([int(ypix),int(xpix)]) - mean MTXexpr = np.dot(np.dot(np.transpose(coordMmean),np.linalg.inv(cov)),coordMmean) gauss2D[int(ypix),int(xpix)] = norm * np.exp(-0.5 * MTXexpr) if float(size[0]/2.) - float(int(size[0]/2.)) == 0.0: ypos = np.asarray(size[0])/2.0-1.0 else: ypos = np.floor(np.asarray(size[0])/2.0) if float(size[1]/2.) - float(int(size[1]/2.)) == 0.0: xpos = np.asarray(size[1])/2.0-1.0 else: xpos = np.floor(np.asarray(size[1])/2.0) gauss2D = tu.shift_2Dprofile(gauss2D,[ypos,xpos],showprofiles=False,origin=0) if verbose: print((' - Scaling 2D gaussian by a factor '+str(scale))) gauss2D = gauss2D*scale if show2Dgauss: savename = './Generated2Dgauss.pdf' if verbose: print((' - Saving resulting image of 2D gaussian to '+savename)) plt.clf() centerdot = gauss2D*0.0 center = [int(gauss2D.shape[0]/2.),int(gauss2D.shape[1]/2.)] centerdot[center[1],center[0]] = 2.0*np.max(gauss2D) print((' - Center of gaussian (pixelized - marked in plot):'+str(center))) print((' - Center of gaussian (subpixel) :'+str([ypos,xpos]))) plt.imshow(gauss2D-centerdot,interpolation=None,origin='lower') plt.colorbar() plt.title('Generated 2D Gauss') plt.savefig(savename) plt.clf() if savefits: fitsname = './Generated2Dgauss.fits' hduimg = afits.PrimaryHDU(gauss2D) hdus = [hduimg] hdulist = afits.HDUList(hdus) # turn header into to hdulist hdulist.writeto(fitsname,overwrite=True) # write fits file if verbose: print((' - Saved image of shifted profile to '+fitsname)) return gauss2D # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = def gen_2Dsersic(size,parameters,normalize=False,show2Dsersic=False,savefits=False,verbose=True): """ Generating a 2D sersic with specified parameters using astropy's generator --- INPUT --- size The dimensions of the array to return. Expects [ysize,xsize]. The 2D gauss will be positioned in the center of the array parameters List of the sersic parameters. Expects [amplitude,effective radius, Sersic index,ellipticity,rotation angle] The amplitude is the central surface brightness within the effective radius (Ftot/2 is within r_eff) The rotation angle should be in degrees, counterclockwise from the positive x-axis. normalize Normalize the profile so sum(profile img) = 1. show2Dsersic Save plot of generated 2D Sersic savefits Save generated profile to fits file verbose Toggler verbosity --- EXAMPLE OF USE --- import tdose_utilities as tu size = [30,40] size = [31,41] parameters = [1,6.7,1.7,1.0-0.67,17.76-90] sersic2D = tu.gen_2Dsersic(size,parameters,show2Dsersic=True,savefits=True) size = [30,30] size = [31,31] parameters = [1,5,1.7,0.5,45] sersic2D = tu.gen_2Dsersic(size,parameters,show2Dsersic=True,savefits=True) """ x, y = np.meshgrid(np.arange(size[1]), np.arange(size[0])) if float(size[0]/2.) - float(int(size[0]/2.)) == 0.0: ypos = np.asarray(size[0])/2.0-0.5 else: ypos = np.floor(np.asarray(size[0])/2.0) if float(size[1]/2.) - float(int(size[1]/2.)) == 0.0: xpos = np.asarray(size[1])/2.0-0.5 else: xpos = np.floor(np.asarray(size[1])/2.0) model = Sersic2D(amplitude=parameters[0], r_eff=parameters[1], n=parameters[2], ellip=parameters[3], theta=parameters[4]*np.pi/180., x_0=xpos, y_0=ypos) sersic2D = model(x, y) if normalize: sersic2D = sersic2D / np.sum(sersic2D) if show2Dsersic: plt.clf() savename = './Generated2Dsersic.pdf' if verbose: print((' - Displaying resulting image of 2D sersic in '+savename)) centerdot = sersic2D*0.0 center = [int(sersic2D.shape[0]/2.),int(sersic2D.shape[1]/2.)] # centerdot[center[1],center[0]] = 2.0*np.max(sersic2D) print((' - Center of Sersic (pixelized - marked in plot): '+str(center))) plt.imshow(sersic2D,interpolation=None,origin='lower') plt.colorbar() plt.title('Generated 2D Sersic') plt.savefig(savename) plt.clf() if savefits: fitsname = './Generated2Dsersic.fits' hduimg = afits.PrimaryHDU(sersic2D) hdus = [hduimg] hdulist = afits.HDUList(hdus) # turn header into to hdulist hdulist.writeto(fitsname,overwrite=True) # write fits file if verbose: print((' - Saved image of shifted profile to '+fitsname)) return sersic2D # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = def get_2DsersicIeff(value,reff,sersicindex,axisratio,boxiness=0.0,returnFtot=False): """ Get the surface brightness value at the effective radius of a 2D sersic profile (given GALFIT Sersic parameters). Ieff is calculated using ewuations (4) and (5) in Peng et al. (2010), AJ 139:2097. This Ieff is what is referred to as 'amplitude' in astropy.modeling.models.Sersic2D used in tdose_utilities.gen_2Dsersic() --- INPUT --- value If returnFtot=False "value" corresponds to Ftot of the profile (total flux for profile integrated til r=infty) and Ieff will be returned. If instead returnFtot=True "value" should provide Ieff so Ftot can be returned reff Effective radius sersicindex Sersic index of profile axisratio Ratio between the minor and major axis (0<axisratio<1) boxiness The boxiness of the profile returnFtot If Ftot is not known, but Ieff is, set returnFtot=True to return Ftot instead (providing Ieff to "value") --- EXAMPLE OF USE --- Ieff = 1.0 reff = 25.0 sersicindex = 4.0 axisratio = 1.0 Ftot_calc = tu.get_2DsersicIeff(Ieff,reff,sersicindex,axisratio,returnFtot=True) Ieff_calc = tu.get_2DsersicIeff(Ftot_calc,reff,sersicindex,axisratio) size = 1000 x,y = np.meshgrid(np.arange(size), np.arange(size)) mod = Sersic2D(amplitude = Ieff, r_eff = reff, n=sersicindex, x_0=size/2.0, y_0=size/2.0, ellip=1-axisratio, theta=-1) img = mod(x, y) hducube = afits.PrimaryHDU(img) hdus = [hducube] hdulist = afits.HDUList(hdus) hdulist.writeto('/Volumes/DATABCKUP2/TDOSEextractions/models_cutouts/model_sersic_spherical.fits',clobber=True) """ gam2n = scipy.special.gamma(2.0*sersicindex) kappa = scipy.special.gammaincinv(2.0*sersicindex,0.5) Rfct = np.pi * (boxiness + 2.) / (4. * scipy.special.beta(1./(boxiness+2.),1.+1./(boxiness+2.)) ) factor = 2.0 * np.pi * reff**2.0 * np.exp(kappa) * sersicindex * kappa**(-2*sersicindex) * gam2n * axisratio / Rfct if returnFtot: Ftot = value * factor return Ftot else: Ieff = value / factor return Ieff # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = def shift_2Dprofile(profile,position,padvalue=0.0,showprofiles=False,origin=1,splineorder=3,savefits=False,verbose=True): """ Shift 2D profile to given position in array by rolling it in x and y. Can move by sub-pixel amount using interpolation --- INPUT --- profile profile to shift position position to move center of image (profile) to: [ypos,xpos] padvalue the values to padd the images with when shifting profile origin The orging of the position values. If 0-based pixels postions the center calculation is updated to refelect this. showprofiles Save plot of profile when shifted? splineorder Order of spline interpolation to use when shifting savefits Save a fitsfile of the shifted profile verbose Toggle verbosity --- EXAMPLE OF USE --- profile = np.ones([35,35]) profile[17,17] = 5.0 fitsname = './Shifted2Dprofile_initial.fits' hduimg = afits.PrimaryHDU(profile) hdus = [hduimg] hdulist = afits.HDUList(hdus) hdulist.writeto(fitsname,clobber=True) profile_shifted = tu.shift_2Dprofile(profile,[20.5,20.5],padvalue=0.0,showprofiles=False,origin=1,splineorder=3,savefits=True) """ profile_dim = profile.shape yposition = np.asarray(position[0]) xposition = np.asarray(position[1]) if origin == 1: yposition = yposition - 1.0 xposition = xposition - 1.0 ycenter_img = profile_dim[0]/2.-0.5 # sub-pixel center to use as reference when estimating shift xcenter_img = profile_dim[1]/2.-0.5 # sub-pixel center to use as reference when estimating shift yshift = np.float(yposition)-ycenter_img xshift = np.float(xposition)-xcenter_img profile_shifted = scipy.ndimage.interpolation.shift(profile, [yshift,xshift], output=None, order=splineorder, mode='nearest', cval=0.0, prefilter=True) if showprofiles: plt.clf() savename = './Shifted2Dprofile.pdf' vmaxval = np.max(profile_shifted) plt.imshow(profile_shifted,interpolation=None,origin='lower') # ,vmin=-vmaxval, vmax=vmaxval plt.colorbar() plt.title('Positioned Source') plt.savefig(savename) plt.clf() if verbose: print((' - Saved image of shifted profile to '+savename)) if savefits: fitsname = './Shifted2Dprofile.fits' hduimg = afits.PrimaryHDU(profile_shifted) hdus = [hduimg] hdulist = afits.HDUList(hdus) # turn header into to hdulist hdulist.writeto(fitsname,overwrite=True) # write fits file if verbose: print((' - Saved image of shifted profile to '+fitsname)) return profile_shifted # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = def roll_2Dprofile(profile,position,padvalue=0.0,showprofiles=False): """ Move 2D profile to given position in array by rolling it in x and y. Note that the roll does not handle sub-pixel moves. tu.shift_2Dprofile() does this using interpolation --- INPUT --- profile profile to shift position position to move center of image (profile) to: [ypos,xpos] padvalue the values to padd the images with when shifting profile showprofiles Show profile when shifted? --- EXAMPLE OF USE --- tu.roll_2Dprofile(gauss2D,) """ profile_dim = profile.shape yroll = np.int(np.round(position[0]-profile_dim[0]/2.)) xroll = np.int(np.round(position[1]-profile_dim[1]/2.)) profile_shifted = np.roll(np.roll(profile,yroll,axis=0),xroll,axis=1) if showprofiles: vmaxval = np.max(profile_shifted) plt.imshow(profile_shifted,interpolation='none',vmin=-vmaxval, vmax=vmaxval) plt.title('Positioned Source') plt.show() if yroll < 0: profile_shifted[yroll:,:] = padvalue else: profile_shifted[:yroll,:] = padvalue if xroll < 0: profile_shifted[:,xroll:] = padvalue else: profile_shifted[:,:xroll] = padvalue if showprofiles: plt.imshow(profile_shifted,interpolation='none',vmin=-vmaxval, vmax=vmaxval) plt.title('Positioned Source with 0s inserted') plt.show() return profile_shifted # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = def get_now_string(withseconds=False): """ Retruning a string containing a formated version of the current data and time --- INPUNT --- withseconds To include seconds in the outputted string set this keyword to True """ if withseconds: nowstr = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f") else: nowstr = datetime.datetime.now().strftime("%Y-%m-%d %H:%M") return nowstr # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = def gen_gridcomponents(imgsize): """ Generate grid compoents, i.e. x and y indecese for a given image size --- INPUT --- imgsize size of image to generate grid points for (y,x) """ x = np.linspace(0, imgsize[1]-1, imgsize[1]) y = np.linspace(0, imgsize[0]-1, imgsize[0]) x,y = np.meshgrid(x, y) return x,y # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = def analytic_convolution_gaussian(mu1,covar1,mu2,covar2): """ The analytic vconvolution of two Gaussians is simply the sum of the two mean vectors and the two convariance matrixes --- INPUT --- mu1 The mean of the first gaussian covar1 The covariance matrix of of the first gaussian mu2 The mean of the second gaussian covar2 The covariance matrix of of the second gaussian """ muconv = mu1+mu2 covarconv = covar1+covar2 return muconv, covarconv # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = def numerical_convolution_image(imgarray,kerneltype,saveimg=False,clobber=False,imgmask=None,fill_value=0.0, norm_kernel=False,convolveFFT=False,use_scipy_conv=False,verbose=True): """ Perform numerical convolution on numpy array (image) --- INPUT --- imgarray numpy array containing image to convolve kerneltype Provide either a numpy array containing the kernel or an astropy kernel to use for the convolution. E.g., astropy.convolution.Moffat2DKernel() astropy.convolution.Gaussian2DKernel() saveimg Save image of convolved imgarray clobber Overwrite existing files? imgmask Mask of image array to apply during convolution fill_value Fill value to use in convolution norm_kernel To normalize the convolution kernel set this keyword to True convolveFFT To convolve the image in fourier space set convolveFFT=True use_scipy_conv Whenever the kernel and imgarray has odd dimensions, default is to use the Astropy convolution where NaNs are treated with interpolation. To force a scipy.ndimage convolution set use_scipy_conv=True (this is the convolution used if any of the kernel (and imgarray) dimensions are even). verbose Toggle verbosity """ if (type(kerneltype) is np.ndarray): kernel = kerneltype kernelstr = 'numpy array' else: kernel = kerneltype kernelstr = 'astropy Guass/Moffat' if verbose: print((' - Convolving image with a '+kernelstr+' kernel using astropy convolution routines')) if (np.float(imgarray.shape[0]/2.0)-np.int(imgarray.shape[0]/2.0) == 0) or \ (np.float(imgarray.shape[0]/2.0)-np.int(imgarray.shape[0]/2.0) == 0) or \ (np.float(kernel.shape[0]/2.0)-np.int(kernel.shape[0]/2.0) == 0) or \ (np.float(kernel.shape[1]/2.0)-np.int(kernel.shape[1]/2.0) == 0) or \ use_scipy_conv: if verbose: print(' - Convolving using scipy.ndimage.filters.convolve() as at least one dimension of kernel or image is even; ' \ 'no interpolation over NaN values') if norm_kernel & (np.sum(kernel) != 1.0): kernel = kernel/np.sum(kernel) # shift to sub-pixel center for even dimensions intpixcen = [kernel.shape[0]/2.0-0.5,kernel.shape[1]/2.0-0.5] kernel = tu.shift_2Dprofile(kernel,intpixcen,showprofiles=False,origin=0) img_conv = scipy.ndimage.filters.convolve(imgarray,kernel,cval=fill_value,origin=0) else: if (kernel.shape[0] < imgarray.shape[0]) or (kernel.shape[1] < imgarray.shape[1]): sys.exit(' ---> Astropy convolution requires kernel to have same size as image (but at least one size is smaller)') if (kernel.shape[0] > imgarray.shape[0]) or (kernel.shape[1] > imgarray.shape[1]): if verbose: print(' - Astropy convolution requires kernel to have same size as image (but it is larger); ') if verbose: print(' Extracting center of kernel to use for convolution') kernel_use = tu.get_kernelcenter(imgarray.shape,kernel,useMaxAsCenter=True,verbose=False) else: kernel_use = kernel if convolveFFT: if verbose: print(' - Convolving using astropy.convolution.convolve_fft(); interpolation over NaN values') img_conv = convolution.convolve_fft(imgarray, kernel_use, boundary='fill', fill_value=fill_value,normalize_kernel=norm_kernel, mask=imgmask, crop=True, return_fft=False, fft_pad=None, psf_pad=None, interpolate_nan=False, quiet=False, ignore_edge_zeros=False, min_wt=0.0) else: if verbose: print(' - Convolving using astropy.convolution.convolve(); interpolation over NaN values') img_conv = convolution.convolve(imgarray, kernel_use, boundary='fill', fill_value=fill_value, normalize_kernel=norm_kernel, mask=imgmask) if saveimg: hdulist = afits.PrimaryHDU(data=img_conv) hdulist.writeto(saveimg,overwrite=clobber) return img_conv # = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = def get_kernelcenter(shape,kernel,useMaxAsCenter=False,verbose=True): """ Cutting out kernel center (with a given shape). Used to ensure that kernels have the right size for numerical convolution where they are required to have the same shape as the image to be convolved. NB! Assumes that the kernel is _larger_ than the image. In the other case, e.g., add zeros around kernel to grow it's size --- INFO --- shape Shape of center of kernel to cut out kernel Kernel to extract central region from useMaxAsCenter The default is to extract kernel around center of kjernelshape. To use the maximum value of the kernel to define the extraction center set useMaxAsCenter=True verbose Toggle verbosity --- EXAMPLE OF USE --- import tdose_utilities as tu img = np.ones([61,61]) kernel = np.ones([121,121]) kernel[60,60] = 10.0 kcenter = tu.get_kernelcenter(img.shape,kernel,useMaxAsCenter=True) img = np.ones([40,30]) kernel = np.ones([190,190]) kernel[60,60] = 10.0 kcenter = tu.get_kernelcenter(img.shape,kernel,useMaxAsCenter=True) """ if useMaxAsCenter: cenpix = np.where(kernel == np.max(kernel)) if len(cenpix[0]) > 1: print((' WARNING: '+str(len(cenpix[0]))+' pixels with value max(Kernel). Using the first as center')) xcen = cenpix[1][0] ycen = cenpix[0][0] else: xcen = np.floor(kernel.shape[1]/2.) ycen = np.floor(kernel.shape[0]/2.) dx = np.floor(shape[1]/2.) dy = np.floor(shape[0]/2.) if (np.floor(shape[0]/2.) != shape[0]/2.) & (np.floor(shape[1]/2.) != shape[1]/2.): kernelcen = kernel[int(ycen)-int(dy):int(ycen)+int(dy)+1, int(xcen)-int(dx):int(xcen)+int(dx)+1] elif (np.floor(shape[0]/2.) != shape[0]/2.) & (np.floor(shape[1]/2.) == shape[1]/2.): kernelcen = kernel[int(ycen)-int(dy):int(ycen)+int(dy)+1, int(xcen)-int(dx):int(xcen)+int(dx)] elif (np.floor(shape[0]/2.) == shape[0]/2.) & (np.floor(shape[1]/2.) != shape[1]/2.): kernelcen = kernel[int(ycen)-int(dy):int(ycen)+int(dy), int(xcen)-int(dx):int(xcen)+int(dx)+1] elif (np.floor(shape[0]/2.) == shape[0]/2.) & (np.floor(shape[1]/2.) == shape[1]/2.): kernelcen = kernel[int(ycen)-int(dy):int(ycen)+int(dy), int(xcen)-int(dx):int(xcen)+int(dx)] else: kernelcen = None if verbose: print((' - Input kernel shape: '+str(kernel.shape))) if verbose: print((' - Returned kernel center shape: '+str(kernelcen.shape))) if verbose: print((' - Max value of input kernel: '+str(np.max(kernel)))) if verbose: print((' - Max value of returned kernel center: '+str(np.max(kernelcen)))) if verbose: print((' - Location of max value in input kernel: '+str(np.where(kernel == np.max(kernel))))) if verbose: print((' - Location of max value in kernel center: '+str(np.where(kernelcen ==
np.max(kernelcen)
numpy.max
import numpy as np import tensorflow as tf def logistic_logpdf(*, x, mean, logscale): """ log density of logistic distribution this operates elementwise """ z = (x - mean) * tf.exp(-logscale) return z - logscale - 2 * tf.nn.softplus(z) def logistic_logcdf(*, x, mean, logscale): """ log cdf of logistic distribution this operates elementwise """ z = (x - mean) * tf.exp(-logscale) return tf.log_sigmoid(z) def test_logistic(): import scipy.stats # TF graph for logistic pdf computation tf.reset_default_graph() in_x = tf.placeholder(tf.float64, [None]) in_means = tf.placeholder(tf.float64, [None]) in_logscales = tf.placeholder(tf.float64, [None]) out_logpdf = logistic_logpdf(x=in_x, mean=in_means, logscale=in_logscales) out_logcdf = logistic_logcdf(x=in_x, mean=in_means, logscale=in_logscales) # Evaluate log pdf at these points n = 100 xs = np.linspace(-5, 5, n) with tf.Session() as sess: # Test against scipy for loc in np.linspace(-1, 2, 5): for scale in np.linspace(.01, 3, 5): true_logpdfs = scipy.stats.logistic.logpdf(xs, loc, scale) true_logcdfs = scipy.stats.logistic.logcdf(xs, loc, scale) logpdfs, logcdfs = sess.run([out_logpdf, out_logcdf], { in_x: xs, in_means: [loc] * n, in_logscales:
np.log([scale] * n)
numpy.log
import pickle import numpy as np import random import tensorflow as tf import csv import cv2 import glob # import matplotlib.image as mpimg # import matplotlib.pyplot as plt from keras import optimizers from keras.models import Sequential from keras.layers.core import Dense, Activation, Flatten, Dropout, Lambda from keras.layers import Cropping2D from keras.layers.convolutional import Conv2D from keras.layers.pooling import MaxPooling2D from sklearn.utils import shuffle from sklearn.model_selection import train_test_split def preprocess_image(images, measurements, to_flip = 0): X_train, y_train = images, measurements if to_flip == 1: flip_measurements = -1.0*measurements flip_images = [] for image in images: flip_images += [cv2.flip(image, 1)] X_train = np.concatenate((X_train, flip_images), axis = 0) y_train = np.concatenate((y_train, flip_measurements), axis = 0) return X_train, y_train def generator(samples, batch_size = 32, is_validation = 0, include_side = 0, to_flip = 0, sample_size = 2000): samples = random.sample(samples, k=sample_size) if is_validation == 0 else shuffle(samples) num_samples = sample_size while True: shuffle(samples) for offset in range(0, num_samples, batch_size): batch_samples = samples[offset:offset+batch_size] center_images, left_images, right_images = [], [], [] center_measurements = [] for batch_sample in batch_samples: center_images += [cv2.imread('./data/IMG/'+batch_sample[0].split('IMG/')[-1])] center_measurements += [float(batch_sample[3])] if include_side == 1: left_images += [cv2.imread('./data/IMG/'+batch_sample[1].split('IMG/')[-1])] right_images += [cv2.imread('./data/IMG/'+batch_sample[2].split('IMG/')[-1])] images = np.array(center_images) measurements = np.array(center_measurements) if include_side == 1: images = np.concatenate((images, left_images, right_images), axis = 0) measurements = np.concatenate((measurements, measurements + 0.23, measurements - 0.23), axis = 0) if is_validation == 0: X_train, y_train = preprocess_image(images, measurements, to_flip = to_flip) else: X_train, y_train = images, measurements yield shuffle(X_train, y_train) def model_LeNet(X_train, y_train): model = Sequential() model.add(Lambda(lambda x: (x / 255.0) - 0.5, input_shape=(160,320,3))) model.add(Conv2D(10,5, activation='relu')) model.add(MaxPooling2D()) model.add(Conv2D(20,5, activation='relu')) model.add(MaxPooling2D()) model.add(Flatten()) model.add(Dense(500)) model.add(Dense(240)) model.add(Dense(120)) model.add(Dense(40)) model.add(Dense(1)) model.compile(loss='mse', optimizer='adam', metrics=['accuracy']) model.fit(X_train, y_train, validation_split = 0.2, shuffle = True, epochs = 5, batch_size = 16) model.save('model_lenet.h5') def model_nvidia(train_samples, validation_samples): batch_size = 32 sample_size = 3000 train_generator = generator(train_samples, batch_size = batch_size, is_validation = 0, include_side = 1, to_flip = 1, sample_size = sample_size) validation_generator = generator(validation_samples, batch_size = batch_size, is_validation = 1, include_side = 0) model = Sequential() model.add(Lambda(lambda x: (x/255.0) - 0.5, input_shape=(160,320,3))) model.add(Cropping2D(cropping=((70,25),(0,0)))) model.add(Conv2D(24, 5, strides = (2,2), activation='relu')) model.add(Dropout(0.5)) model.add(Conv2D(36, 5, strides = (2,2), activation='relu')) model.add(Dropout(0.5)) model.add(Conv2D(48, 5, strides = (2,2), activation='relu')) model.add(Conv2D(64, 3, activation='relu')) model.add(Conv2D(64, 3, activation='relu')) model.add(Flatten()) model.add(Dense(100)) model.add(Dense(50)) model.add(Dense(10)) model.add(Dense(1)) opt = optimizers.Adam(lr=0.001) model.compile(loss='mse', optimizer=opt, metrics=['accuracy']) model.fit_generator(train_generator, steps_per_epoch = sample_size//batch_size, validation_data = validation_generator, validation_steps = len(validation_samples)//batch_size, epochs = 15, verbose = 1) model.save('model_nvidia.h5') def make_uniform(samples): no_bins = 25 augmented_samples = [] count_thresh = int(len(samples)/no_bins)*2 samples_arr = np.array(samples) angles = np.array(list(map(float, samples_arr[:,3]))) angle_bins = np.linspace(-1., 1.01, no_bins + 1) print(len(angles)) for i in range(no_bins): idx = np.where((angles>=angle_bins[i]) & (angles<angle_bins[i+1]))[0] if len(idx) < count_thresh and len(idx) > 0: idx_sel = np.random.choice(idx, count_thresh - len(idx)) samples = samples + samples_arr[idx_sel].tolist() samples_arr =
np.array(samples)
numpy.array
#!/usr/bin/env py.test from __future__ import print_function, division import math from copy import deepcopy import numpy as np from numpy.random import RandomState from numpy.testing import assert_allclose, assert_approx_equal import pytest import itertools try: from numpy.random import choice HAVE_CHOICE = True except ImportError: HAVE_CHOICE = False import nestle SQRTEPS = math.sqrt(float(np.finfo(np.float64).eps)) # testing closeness to 1 NMAX = 20 # many tests are run for dimensions 1 to NMAX inclusive def test_vol_prefactor(): assert nestle.vol_prefactor(1) == 2. assert nestle.vol_prefactor(2) == math.pi assert nestle.vol_prefactor(3) == 4./3. * math.pi assert nestle.vol_prefactor(4) == 1./2. * math.pi**2 assert nestle.vol_prefactor(5) == 8./15. * math.pi**2 assert nestle.vol_prefactor(9) == 32./945. * math.pi**4 def test_rstate_kwarg(): """Test that rstate keyword argument works as expected.""" rstate = RandomState(123) a = nestle.randsphere(10, rstate=rstate) np.random.seed(123) b = nestle.randsphere(10) assert np.all(a == b) # TODO: test that points are uniform def test_randsphere(): """Draw a lot of points and check that they're within a unit sphere. """ rstate = RandomState(0) npoints = 1000 for n in range(1, NMAX+1): for i in range(npoints): x = nestle.randsphere(n, rstate=rstate) r = np.sum(x**2) assert r < 1.0 @pytest.mark.skipif("not HAVE_CHOICE") def test_random_choice(): """nestle.random_choice() is designed to mimic np.random.choice(), for numpy < v1.7.0. In cases where we have both, test that they agree. """ rstate = RandomState(0) p = rstate.rand(10) p /= p.sum() for seed in range(10): rstate.seed(seed) i = rstate.choice(10, p=p) rstate.seed(seed) j = nestle.random_choice(10, p=p, rstate=rstate) assert i == j def test_random_choice_error(): """random_choice should raise an error when probabilities do not sum to one.""" rstate = RandomState(0) p = rstate.rand(10) p /= p.sum() p *= 1.001 with pytest.raises(ValueError): nestle.random_choice(10, p=p, rstate=rstate) def test_ellipsoid_sphere(): """Test that Ellipsoid works like a sphere when ``a`` is proportional to the identity matrix.""" scale = 5. for n in range(1, NMAX+1): ctr = 2.0 * scale * np.ones(n) # arbitrary non-zero center a = 1.0 / scale**2 *
np.identity(n)
numpy.identity
import numpy as np from sklearn import datasets from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import train_test_split from sklearn.model_selection import StratifiedKFold from sklearn.model_selection import cross_validate from NiaPy.algorithms.modified import HybridBatAlgorithm import pygal KNN_WEIGHT_FUNCTIONS = [ 'uniform', 'distance' ] KNN_ALGORITHMS = [ 'ball_tree', 'kd_tree', 'brute' ] # map from real number [0, 1] to integer ranging [5, 15] def swap_n_neighbors(val): return int(val * 10 + 5) # map from real number [0, 1] to integer ranging [0, 1] def swap_weights(val): if val > 0.5: return 1 return 0 # map from real number [0, 1] to integer ranging [1, 3] def swap_algorithm(val): if val == 1: return 3 return int(val * 3 + 1) # map from real number [0, 1] to integer ranging [10, 50] def swap_leaf_size(val): return int(val * 10 + 40) class KNNBreastCancerBenchmark(object): def __init__(self): self.Lower = 0 self.Upper = 1 def function(self): # our definition of fitness function def evaluate(D, solution): n_neighbors = swap_n_neighbors(solution[0]) weights = KNN_WEIGHT_FUNCTIONS[(swap_weights(solution[1]) - 1)] algorithm = KNN_ALGORITHMS[(swap_algorithm(solution[2]) - 1)] leaf_size = swap_leaf_size(solution[3]) fitness = 1 - KNNBreastCancerClassifier(1234).evaluate(n_neighbors, weights, algorithm, leaf_size) scores.append([fitness, n_neighbors, weights, algorithm, leaf_size]) return fitness return evaluate class KNNBreastCancerClassifier(object): def __init__(self, seed=1234): self.seed = seed self.ten_fold_scores = {} self.default_ten_fold_scores = {} np.random.seed(self.seed) dataset = datasets.load_breast_cancer() self.X = dataset.data self.y = dataset.target self.X_search, self.X_validate, self.y_search, self.y_validate = train_test_split(self.X, self.y, test_size=0.8, random_state=self.seed) self.X_search_train, self.X_search_test, self.y_search_train, self.y_search_test = train_test_split(self.X_search, self.y_search, test_size=0.8, random_state=self.seed) def evaluate(self, n_neighbors, weights, algorithm, leaf_size): model = KNeighborsClassifier(n_neighbors=n_neighbors, weights=weights, algorithm=algorithm, leaf_size=leaf_size) model.fit(self.X_search_train, self.y_search_train) return model.score(self.X_search_test, self.y_search_test) def run_10_fold(self, solution=None): if solution is None: estimator = KNeighborsClassifier() kfold = StratifiedKFold(n_splits=10, shuffle=True, random_state=self.seed) self.default_ten_fold_scores = cross_validate(estimator, self.X, self.y, cv=kfold, scoring=['accuracy']) else: estimator = KNeighborsClassifier(n_neighbors=solution[1], weights=solution[2], algorithm=solution[3], leaf_size=solution[4]) kfold = StratifiedKFold(n_splits=10, shuffle=True, random_state=self.seed) self.ten_fold_scores = cross_validate(estimator, self.X_validate, self.y_validate, cv=kfold, scoring=['accuracy']) scores = [] algorithm = HybridBatAlgorithm(4, 40, 100, 0.9, 0.1, 0.001, 0.9, 0.0, 2.0, KNNBreastCancerBenchmark()) best = algorithm.run() print('Optimal KNN parameters are:') best_solution = [] for score in scores: if score[0] == best: best_solution = score print(best_solution) model = KNNBreastCancerClassifier() model.run_10_fold(solution=best_solution) model.run_10_fold() print('best model mean test accuracy: ' + str(np.mean(model.ten_fold_scores['test_accuracy']))) print('default model mean test accuracy: ' + str(
np.mean(model.default_ten_fold_scores['test_accuracy'])
numpy.mean
from math import isclose import numpy as np import pandas as pd import pytest from freqtrade.data.dataprovider import DataProvider from freqtrade.strategy import (merge_informative_pair, stoploss_from_absolute, stoploss_from_open, timeframe_to_minutes) def generate_test_data(timeframe: str, size: int): np.random.seed(42) tf_mins = timeframe_to_minutes(timeframe) base = np.random.normal(20, 2, size=size) date = pd.period_range('2020-07-05', periods=size, freq=f'{tf_mins}min').to_timestamp() df = pd.DataFrame({ 'date': date, 'open': base, 'high': base + np.random.normal(2, 1, size=size), 'low': base - np.random.normal(2, 1, size=size), 'close': base + np.random.normal(0, 1, size=size), 'volume': np.random.normal(200, size=size) } ) df = df.dropna() return df def test_merge_informative_pair(): data = generate_test_data('15m', 40) informative = generate_test_data('1h', 40) result = merge_informative_pair(data, informative, '15m', '1h', ffill=True) assert isinstance(result, pd.DataFrame) assert len(result) == len(data) assert 'date' in result.columns assert result['date'].equals(data['date']) assert 'date_1h' in result.columns assert 'open' in result.columns assert 'open_1h' in result.columns assert result['open'].equals(data['open']) assert 'close' in result.columns assert 'close_1h' in result.columns assert result['close'].equals(data['close']) assert 'volume' in result.columns assert 'volume_1h' in result.columns assert result['volume'].equals(data['volume']) # First 3 rows are empty assert result.iloc[0]['date_1h'] is pd.NaT assert result.iloc[1]['date_1h'] is pd.NaT assert result.iloc[2]['date_1h'] is pd.NaT # Next 4 rows contain the starting date (0:00) assert result.iloc[3]['date_1h'] == result.iloc[0]['date'] assert result.iloc[4]['date_1h'] == result.iloc[0]['date'] assert result.iloc[5]['date_1h'] == result.iloc[0]['date'] assert result.iloc[6]['date_1h'] == result.iloc[0]['date'] # Next 4 rows contain the next Hourly date original date row 4 assert result.iloc[7]['date_1h'] == result.iloc[4]['date'] assert result.iloc[8]['date_1h'] == result.iloc[4]['date'] def test_merge_informative_pair_same(): data = generate_test_data('15m', 40) informative = generate_test_data('15m', 40) result = merge_informative_pair(data, informative, '15m', '15m', ffill=True) assert isinstance(result, pd.DataFrame) assert len(result) == len(data) assert 'date' in result.columns assert result['date'].equals(data['date']) assert 'date_15m' in result.columns assert 'open' in result.columns assert 'open_15m' in result.columns assert result['open'].equals(data['open']) assert 'close' in result.columns assert 'close_15m' in result.columns assert result['close'].equals(data['close']) assert 'volume' in result.columns assert 'volume_15m' in result.columns assert result['volume'].equals(data['volume']) # Dates match 1:1 assert result['date_15m'].equals(result['date']) def test_merge_informative_pair_lower(): data = generate_test_data('1h', 40) informative = generate_test_data('15m', 40) with pytest.raises(ValueError, match=r"Tried to merge a faster timeframe .*"): merge_informative_pair(data, informative, '1h', '15m', ffill=True) def test_stoploss_from_open(): open_price_ranges = [ [0.01, 1.00, 30], [1, 100, 30], [100, 10000, 30], ] current_profit_range = [-0.99, 2, 30] desired_stop_range = [-0.50, 0.50, 30] for open_range in open_price_ranges: for open_price in
np.linspace(*open_range)
numpy.linspace
import numpy as np import keras.backend as K from keras.models import Model from keras.layers import Input, Embedding, Dot, Lambda, Conv2D from keras.layers import MaxPooling2D, Flatten, Concatenate, Dense from keras.layers import Activation, BatchNormalization, Dropout def semantic_match(X, Y, A, window): """Computing semantic match in direction X -> Y shape X: (s,n,d), Y: (s,m,d), A: (s, n, m) """ # shape Pivot, lower_lim, upper_lim: (s,n,1) Pivot = np.expand_dims(np.argmax(A, axis=-1), axis=-1) lower_lim = np.maximum(0, Pivot-window) upper_lim = np.minimum(A.shape[-1], Pivot+window) # shape indices: (s,n,m) # indices = np.tile(np.arange(A.shape[2]), (A.shape[0], A.shape[1] ,1)) indices = np.tile(np.arange(A.shape[-1]), A.shape[:-1]+(1,)) # NOTE: To replicate "mcrisc" implementation in github use: indices < upper_lim mask = ((indices >= lower_lim) & (indices <= upper_lim)).astype(np.float32) # shape X_hat: (n,d) X_hat = np.matmul(A*mask, Y) return X_hat def decompose(X, X_hat, method="linear"): """Decompose a dataset with regards to its semantic match version shape X, X_hat: (s,n,d) """ assert method in ("linear", "orthogonal") if method == "linear": # shape alpha: (s,n,1) denom = (np.linalg.norm(X, axis=-1, keepdims=True) * np.linalg.norm(X_hat, axis=-1, keepdims=True)) alpha = np.divide(np.sum(X * X_hat, axis=-1, keepdims=True), denom, where=denom!=0) # shape X_pos, X_neg: (s,n,d) X_pos = alpha * X X_neg = (1 - alpha) * X elif method == "orthogonal": # shape X_pos, X_neg: (s,n,d) denom = np.sum(X_hat * X_hat, axis=-1, keepdims=True) X_pos = np.divide(np.sum(X * X_hat, axis=-1, keepdims=True), denom, where=denom!=0) * X_hat X_neg = X - X_pos X_pos = np.expand_dims(X_pos, axis=-1) X_neg = np.expand_dims(X_neg, axis=-1) # shape X_decomp: (s,n,d,2) X_decomp = np.concatenate([X_pos, X_neg], axis=-1) return X_decomp def decompose_data(X, Y, window=3, method="linear"): """Decompose datasets X, Y into positive and negative channels with regards to each other shape X: (s,n,d), Y: (s,m,d) """ # Cosine similarity # shape A: (s,n,m) norm_X =
np.linalg.norm(X, axis=-1, keepdims=True)
numpy.linalg.norm
## Source : https://github.com/naokishibuya/car-behavioral-cloning/blob/master/utils.py import os import cv2 import sklearn import math import csv import numpy as np from scipy.ndimage import rotate from scipy.stats import bernoulli IMAGE_HEIGHT, IMAGE_WIDTH, IMAGE_CHANNELS = 66, 200, 3 INPUT_SHAPE = (IMAGE_HEIGHT, IMAGE_WIDTH, IMAGE_CHANNELS) #IMG_file="/home/workspace/CarND-Behavioral-Cloning-P3/data/IMG/" IMG_file="/opt/carnd_p3/data/data/IMG/" def random_rotation(image, steering_angle, rotation_amount=15): angle = np.random.uniform(-rotation_amount, rotation_amount + 1) rad = (np.pi / 180.0) * angle return rotate(image, angle, reshape=False), steering_angle + (-1) * rad def random_translate(image, steering_angle, range_x=100, range_y=10): """ Randomly shift the image virtially and horizontally (translation). """ trans_x = range_x * (np.random.rand() - 0.5) trans_y = range_y * (np.random.rand() - 0.5) steering_angle += trans_x * 0.002 trans_m = np.float32([[1, 0, trans_x], [0, 1, trans_y]]) height, width = image.shape[:2] image = cv2.warpAffine(image, trans_m, (width, height)) return image, steering_angle def random_shadow(image): """ Generates and adds random shadow """ # (x1, y1) and (x2, y2) forms a line # xm, ym gives all the locations of the image x1, y1 = IMAGE_WIDTH * np.random.rand(), 0 x2, y2 = IMAGE_WIDTH * np.random.rand(), IMAGE_HEIGHT xm, ym = np.mgrid[0:IMAGE_HEIGHT, 0:IMAGE_WIDTH] # mathematically speaking, we want to set 1 below the line and zero otherwise # Our coordinate is up side down. So, the above the line: # (ym-y1)/(xm-x1) > (y2-y1)/(x2-x1) # as x2 == x1 causes zero-division problem, we'll write it in the below form: # (ym-y1)*(x2-x1) - (y2-y1)*(xm-x1) > 0 mask = np.zeros_like(image[:, :, 1]) mask[(ym - y1) * (x2 - x1) - (y2 - y1) * (xm - x1) > 0] = 1 # choose which side should have shadow and adjust saturation cond = mask == np.random.randint(2) s_ratio = np.random.uniform(low=0.2, high=0.5) # adjust Saturation in HLS(Hue, Light, Saturation) hls = cv2.cvtColor(image, cv2.COLOR_RGB2HLS) hls[:, :, 1][cond] = hls[:, :, 1][cond] * s_ratio return cv2.cvtColor(hls, cv2.COLOR_HLS2RGB) def random_brightness(image): """ Randomly adjust brightness of the image. """ # HSV (Hue, Saturation, Value) is also called HSB ('B' for Brightness). hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV) ratio = 1.0 + 0.4 * (np.random.rand() - 0.5) hsv[:,:,2] = hsv[:,:,2] * ratio return cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB) def flipper(image,angle): return cv2.flip(image,1),(-angle)#np.fliplr(image) def preproces(image): image = image[60:-25, :, :] image = cv2.resize(image, (IMAGE_WIDTH, IMAGE_HEIGHT), cv2.INTER_AREA) image = cv2.cvtColor(image, cv2.COLOR_RGB2YUV) return image def augumentation(image,angle,aug_num): image = preproces(image) if aug_num == 0: #image = preproces(image) return image,angle if aug_num == 1: image,angle = random_rotation(image, angle, rotation_amount=10) if aug_num == 2: image, angle = flipper(image, angle) if aug_num == 3: image, angle = random_translate(image, angle, range_x=100, range_y=10) if aug_num == 4: image = random_shadow(image) image = random_brightness(image) image, angle = flipper(image, angle) return image,angle def generator(samples, batch_size=16,is_training=True): num_samples = len(samples) while 1: # Loop forever so the generator never terminates sklearn.utils.shuffle(samples) for offset in range(0, num_samples, (batch_size)): batch_samples = samples[offset:offset+batch_size] images = [] angles = [] for batch_sample in batch_samples: name_center = IMG_file+batch_sample[0].split('\\')[-1] name_left = IMG_file+batch_sample[1].split('\\')[-1] name_right = IMG_file+batch_sample[2].split('\\')[-1] center_image = cv2.imread(name_center) left_image = cv2.imread(name_left) right_image = cv2.imread(name_right) center_angle = float(batch_sample[3]) left_angle = center_angle+0.009#*(1.005) right_angle = center_angle-0.009#*(0.995) if not is_training: center_image1,center_angle1 = augumentation(center_image,center_angle,0) left_image1,left_angle1 = augumentation(center_image,center_angle,0) right_image1,right_angle1 = augumentation(center_image,center_angle,0) images.append(center_image1) images.append(left_image1) images.append(right_image1) angles.append(center_angle1) angles.append(left_angle1) angles.append(right_angle1) else: for i in range(5): center_image1,center_angle1 = augumentation(center_image,center_angle,i) left_image1,left_angle1 = augumentation(center_image,center_angle,i) right_image1,right_angle1 = augumentation(center_image,center_angle,i) #center_image1 = preproces(center_image1) #left_image1 = preproces(left_image1) #ight_image1 = preproces(right_image1) images.append(center_image1) images.append(left_image1) images.append(right_image1) angles.append(center_angle1) angles.append(left_angle1) angles.append(right_angle1) # trim image to only see section with road X_train = np.array(images) y_train =
np.array(angles)
numpy.array
#!/usr/bin/env python # Copyright 2014-2018 The PySCF Developers. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import time import numpy as np from pyscf import lib from pyscf import scf from pyscf.lib import logger from pyscf.cc import ccsd from pyscf.cc import uccsd from pyscf.cc import eom_rccsd from pyscf.cc import eom_gccsd from pyscf.cc import addons ######################################## # EOM-IP-CCSD ######################################## class EOMIP(eom_gccsd.EOMIP): def __init__(self, cc): gcc = addons.convert_to_gccsd(cc) eom_gccsd.EOMIP.__init__(self, gcc) ######################################## # EOM-EA-CCSD ######################################## class EOMEA(eom_gccsd.EOMEA): def __init__(self, cc): gcc = addons.convert_to_gccsd(cc) eom_gccsd.EOMEA.__init__(self, gcc) ######################################## # EOM-EE-CCSD ######################################## def eeccsd(eom, nroots=1, koopmans=False, guess=None, eris=None, imds=None): '''Calculate N-electron neutral excitations via EOM-EE-CCSD. Kwargs: nroots : int Number of roots (eigenvalues) requested koopmans : bool Calculate Koopmans'-like (1p1h) excitations only, targeting via overlap. guess : list of ndarray List of guess vectors to use for targeting via overlap. ''' if eris is None: eris = eom._cc.ao2mo() if imds is None: imds = eom.make_imds(eris) spinvec_size = eom.vector_size() nroots = min(nroots, spinvec_size) diag_ee, diag_sf = eom.get_diag(imds) guess_ee = [] guess_sf = [] if guess and guess[0].size == spinvec_size: raise NotImplementedError #TODO: initial guess from GCCSD EOM amplitudes #orbspin = scf.addons.get_ghf_orbspin(eris.mo_coeff) #nmo = np.sum(eom.nmo) #nocc = np.sum(eom.nocc) #for g in guess: # r1, r2 = eom_gccsd.vector_to_amplitudes_ee(g, nmo, nocc) # r1aa = r1[orbspin==0][:,orbspin==0] # r1ab = r1[orbspin==0][:,orbspin==1] # if abs(r1aa).max() > 1e-7: # r1 = addons.spin2spatial(r1, orbspin) # r2 = addons.spin2spatial(r2, orbspin) # guess_ee.append(eom.amplitudes_to_vector(r1, r2)) # else: # r1 = spin2spatial_eomsf(r1, orbspin) # r2 = spin2spatial_eomsf(r2, orbspin) # guess_sf.append(amplitudes_to_vector_eomsf(r1, r2)) # r1 = r2 = r1aa = r1ab = g = None #nroots_ee = len(guess_ee) #nroots_sf = len(guess_sf) elif guess: for g in guess: if g.size == diag_ee.size: guess_ee.append(g) else: guess_sf.append(g) nroots_ee = len(guess_ee) nroots_sf = len(guess_sf) else: dee = np.sort(diag_ee)[:nroots] dsf = np.sort(diag_sf)[:nroots] dmax = np.sort(np.hstack([dee,dsf]))[nroots-1] nroots_ee = np.count_nonzero(dee <= dmax) nroots_sf = np.count_nonzero(dsf <= dmax) guess_ee = guess_sf = None def eomee_sub(cls, nroots, guess, diag): ee_sub = cls(eom._cc) ee_sub.__dict__.update(eom.__dict__) e, v = ee_sub.kernel(nroots, koopmans, guess, eris, imds, diag=diag) if nroots == 1: e, v = [e], [v] ee_sub.converged = [ee_sub.converged] return list(ee_sub.converged), list(e), list(v) e0 = e1 = [] v0 = v1 = [] conv0 = conv1 = [] if nroots_ee > 0: conv0, e0, v0 = eomee_sub(EOMEESpinKeep, nroots_ee, guess_ee, diag_ee) if nroots_sf > 0: conv1, e1, v1 = eomee_sub(EOMEESpinFlip, nroots_sf, guess_sf, diag_sf) e = np.hstack([e0,e1]) idx = e.argsort() e = e[idx] conv = conv0 + conv1 conv = [conv[x] for x in idx] v = v0 + v1 v = [v[x] for x in idx] if nroots == 1: conv = conv[0] e = e[0] v = v[0] eom.converged = conv eom.e = e eom.v = v return eom.e, eom.v def eomee_ccsd(eom, nroots=1, koopmans=False, guess=None, eris=None, imds=None, diag=None): if eris is None: eris = eom._cc.ao2mo() if imds is None: imds = eom.make_imds(eris) eom.converged, eom.e, eom.v \ = eom_rccsd.kernel(eom, nroots, koopmans, guess, imds=imds, diag=diag) return eom.e, eom.v def eomsf_ccsd(eom, nroots=1, koopmans=False, guess=None, eris=None, imds=None, diag=None): '''Spin flip EOM-EE-CCSD ''' return eomee_ccsd(eom, nroots, koopmans, guess, eris, imds, diag) amplitudes_to_vector_ee = uccsd.amplitudes_to_vector vector_to_amplitudes_ee = uccsd.vector_to_amplitudes def amplitudes_to_vector_eomsf(t1, t2, out=None): t1ab, t1ba = t1 t2baaa, t2aaba, t2abbb, t2bbab = t2 nocca, nvirb = t1ab.shape noccb, nvira = t1ba.shape otrila = np.tril_indices(nocca, k=-1) otrilb = np.tril_indices(noccb, k=-1) vtrila = np.tril_indices(nvira, k=-1) vtrilb = np.tril_indices(nvirb, k=-1) baaa = np.take(t2baaa.reshape(noccb*nocca,nvira*nvira), vtrila[0]*nvira+vtrila[1], axis=1) abbb = np.take(t2abbb.reshape(nocca*noccb,nvirb*nvirb), vtrilb[0]*nvirb+vtrilb[1], axis=1) vector = np.hstack((t1ab.ravel(), t1ba.ravel(), baaa.ravel(), t2aaba[otrila].ravel(), abbb.ravel(), t2bbab[otrilb].ravel())) return vector def vector_to_amplitudes_eomsf(vector, nmo, nocc): nocca, noccb = nocc nmoa, nmob = nmo nvira, nvirb = nmoa-nocca, nmob-noccb t1ab = vector[:nocca*nvirb].reshape(nocca,nvirb).copy() t1ba = vector[nocca*nvirb:nocca*nvirb+noccb*nvira].reshape(noccb,nvira).copy() pvec = vector[t1ab.size+t1ba.size:] nbaaa = noccb*nocca*nvira*(nvira-1)//2 naaba = nocca*(nocca-1)//2*nvirb*nvira nabbb = nocca*noccb*nvirb*(nvirb-1)//2 nbbab = noccb*(noccb-1)//2*nvira*nvirb t2baaa = np.zeros((noccb*nocca,nvira*nvira), dtype=vector.dtype) t2aaba = np.zeros((nocca*nocca,nvirb*nvira), dtype=vector.dtype) t2abbb = np.zeros((nocca*noccb,nvirb*nvirb), dtype=vector.dtype) t2bbab = np.zeros((noccb*noccb,nvira*nvirb), dtype=vector.dtype) otrila = np.tril_indices(nocca, k=-1) otrilb = np.tril_indices(noccb, k=-1) vtrila = np.tril_indices(nvira, k=-1) vtrilb = np.tril_indices(nvirb, k=-1) oidxab = np.arange(nocca*noccb, dtype=np.int32) vidxab = np.arange(nvira*nvirb, dtype=np.int32) v = pvec[:nbaaa].reshape(noccb*nocca,-1) lib.takebak_2d(t2baaa, v, oidxab, vtrila[0]*nvira+vtrila[1]) lib.takebak_2d(t2baaa,-v, oidxab, vtrila[1]*nvira+vtrila[0]) v = pvec[nbaaa:nbaaa+naaba].reshape(-1,nvirb*nvira) lib.takebak_2d(t2aaba, v, otrila[0]*nocca+otrila[1], vidxab) lib.takebak_2d(t2aaba,-v, otrila[1]*nocca+otrila[0], vidxab) v = pvec[nbaaa+naaba:nbaaa+naaba+nabbb].reshape(nocca*noccb,-1) lib.takebak_2d(t2abbb, v, oidxab, vtrilb[0]*nvirb+vtrilb[1]) lib.takebak_2d(t2abbb,-v, oidxab, vtrilb[1]*nvirb+vtrilb[0]) v = pvec[nbaaa+naaba+nabbb:].reshape(-1,nvira*nvirb) lib.takebak_2d(t2bbab, v, otrilb[0]*noccb+otrilb[1], vidxab) lib.takebak_2d(t2bbab,-v, otrilb[1]*noccb+otrilb[0], vidxab) t2baaa = t2baaa.reshape(noccb,nocca,nvira,nvira) t2aaba = t2aaba.reshape(nocca,nocca,nvirb,nvira) t2abbb = t2abbb.reshape(nocca,noccb,nvirb,nvirb) t2bbab = t2bbab.reshape(noccb,noccb,nvira,nvirb) return (t1ab,t1ba), (t2baaa, t2aaba, t2abbb, t2bbab) def spatial2spin_eomsf(rx, orbspin): '''Convert EOM spatial R1,R2 to spin-orbital R1,R2''' if len(rx) == 2: # r1 r1ab, r1ba = rx nocca, nvirb = r1ab.shape noccb, nvira = r1ba.shape else: r2baaa,r2aaba,r2abbb,r2bbab = rx noccb, nocca, nvira = r2baaa.shape[:3] nvirb = r2aaba.shape[2] nocc = nocca + noccb nvir = nvira + nvirb idxoa = np.where(orbspin[:nocc] == 0)[0] idxob = np.where(orbspin[:nocc] == 1)[0] idxva = np.where(orbspin[nocc:] == 0)[0] idxvb = np.where(orbspin[nocc:] == 1)[0] if len(rx) == 2: # r1 r1 = np.zeros((nocc,nvir), dtype=r1ab.dtype) lib.takebak_2d(r1, r1ab, idxoa, idxvb) lib.takebak_2d(r1, r1ba, idxob, idxva) return r1 else: r2 = np.zeros((nocc**2,nvir**2), dtype=r2aaba.dtype) idxoaa = idxoa[:,None] * nocc + idxoa idxoab = idxoa[:,None] * nocc + idxob idxoba = idxob[:,None] * nocc + idxoa idxobb = idxob[:,None] * nocc + idxob idxvaa = idxva[:,None] * nvir + idxva idxvab = idxva[:,None] * nvir + idxvb idxvba = idxvb[:,None] * nvir + idxva idxvbb = idxvb[:,None] * nvir + idxvb r2baaa = r2baaa.reshape(noccb*nocca,nvira*nvira) r2aaba = r2aaba.reshape(nocca*nocca,nvirb*nvira) r2abbb = r2abbb.reshape(nocca*noccb,nvirb*nvirb) r2bbab = r2bbab.reshape(noccb*noccb,nvira*nvirb) lib.takebak_2d(r2, r2baaa, idxoba.ravel(), idxvaa.ravel()) lib.takebak_2d(r2, r2aaba, idxoaa.ravel(), idxvba.ravel()) lib.takebak_2d(r2, r2abbb, idxoab.ravel(), idxvbb.ravel()) lib.takebak_2d(r2, r2bbab, idxobb.ravel(), idxvab.ravel()) lib.takebak_2d(r2, r2baaa, idxoab.T.ravel(), idxvaa.T.ravel()) lib.takebak_2d(r2, r2aaba, idxoaa.T.ravel(), idxvab.T.ravel()) lib.takebak_2d(r2, r2abbb, idxoba.T.ravel(), idxvbb.T.ravel()) lib.takebak_2d(r2, r2bbab, idxobb.T.ravel(), idxvba.T.ravel()) return r2.reshape(nocc,nocc,nvir,nvir) def spin2spatial_eomsf(rx, orbspin): '''Convert EOM spin-orbital R1,R2 to spatial R1,R2''' if rx.ndim == 2: # r1 nocc, nvir = rx.shape else: nocc, nvir = rx.shape[1:3] idxoa = np.where(orbspin[:nocc] == 0)[0] idxob = np.where(orbspin[:nocc] == 1)[0] idxva = np.where(orbspin[nocc:] == 0)[0] idxvb = np.where(orbspin[nocc:] == 1)[0] nocca = len(idxoa) noccb = len(idxob) nvira = len(idxva) nvirb = len(idxvb) if rx.ndim == 2: r1ab = lib.take_2d(rx, idxoa, idxvb) r1ba = lib.take_2d(rx, idxob, idxva) return r1ab, r1ba else: idxoaa = idxoa[:,None] * nocc + idxoa idxoab = idxoa[:,None] * nocc + idxob idxoba = idxob[:,None] * nocc + idxoa idxobb = idxob[:,None] * nocc + idxob idxvaa = idxva[:,None] * nvir + idxva idxvab = idxva[:,None] * nvir + idxvb idxvba = idxvb[:,None] * nvir + idxva idxvbb = idxvb[:,None] * nvir + idxvb r2 = rx.reshape(nocc**2,nvir**2) r2baaa = lib.take_2d(r2, idxoba.ravel(), idxvaa.ravel()) r2aaba = lib.take_2d(r2, idxoaa.ravel(), idxvba.ravel()) r2abbb = lib.take_2d(r2, idxoab.ravel(), idxvbb.ravel()) r2bbab = lib.take_2d(r2, idxobb.ravel(), idxvab.ravel()) r2baaa = r2baaa.reshape(noccb,nocca,nvira,nvira) r2aaba = r2aaba.reshape(nocca,nocca,nvirb,nvira) r2abbb = r2abbb.reshape(nocca,noccb,nvirb,nvirb) r2bbab = r2bbab.reshape(noccb,noccb,nvira,nvirb) return r2baaa,r2aaba,r2abbb,r2bbab # Ref: <NAME>, and <NAME>. Chem. Theory Comput. 10, 5567 (2014) Eqs.(9)-(10) # Note: Last line in Eq. (10) is superfluous. # See, e.g. Gwaltney, Nooijen, and Barlett, Chem. Phys. Lett. 248, 189 (1996) def eomee_ccsd_matvec(eom, vector, imds=None): if imds is None: imds = eom.make_imds() t1, t2, eris = imds.t1, imds.t2, imds.eris t1a, t1b = t1 t2aa, t2ab, t2bb = t2 nocca, noccb, nvira, nvirb = t2ab.shape nmoa, nmob = nocca+nvira, noccb+nvirb r1, r2 = vector_to_amplitudes_ee(vector, (nmoa,nmob), (nocca,noccb)) r1a, r1b = r1 r2aa, r2ab, r2bb = r2 #:eris_vvvv = ao2mo.restore(1, np.asarray(eris.vvvv), nvirb) #:eris_VVVV = ao2mo.restore(1, np.asarray(eris.VVVV), nvirb) #:eris_vvVV = _restore(np.asarray(eris.vvVV), nvira, nvirb) #:Hr2aa += lib.einsum('ijef,aebf->ijab', tau2aa, eris_vvvv) * .5 #:Hr2bb += lib.einsum('ijef,aebf->ijab', tau2bb, eris_VVVV) * .5 #:Hr2ab += lib.einsum('iJeF,aeBF->iJaB', tau2ab, eris_vvVV) tau2aa, tau2ab, tau2bb = uccsd.make_tau(r2, r1, t1, 2) Hr2aa, Hr2ab, Hr2bb = eom._cc._add_vvvv(None, (tau2aa,tau2ab,tau2bb), eris) Hr2aa *= .5 Hr2bb *= .5 tau2aa = tau2ab = tau2bb = None Hr1a = lib.einsum('ae,ie->ia', imds.Fvva, r1a) Hr1a -= lib.einsum('mi,ma->ia', imds.Fooa, r1a) Hr1a += np.einsum('me,imae->ia',imds.Fova, r2aa) Hr1a += np.einsum('ME,iMaE->ia',imds.Fovb, r2ab) Hr1b = lib.einsum('ae,ie->ia', imds.Fvvb, r1b) Hr1b -= lib.einsum('mi,ma->ia', imds.Foob, r1b) Hr1b += np.einsum('me,imae->ia',imds.Fovb, r2bb) Hr1b += np.einsum('me,mIeA->IA',imds.Fova, r2ab) Hr2aa += lib.einsum('mnij,mnab->ijab', imds.woooo, r2aa) * .25 Hr2bb += lib.einsum('mnij,mnab->ijab', imds.wOOOO, r2bb) * .25 Hr2ab += lib.einsum('mNiJ,mNaB->iJaB', imds.woOoO, r2ab) Hr2aa += lib.einsum('be,ijae->ijab', imds.Fvva, r2aa) Hr2bb += lib.einsum('be,ijae->ijab', imds.Fvvb, r2bb) Hr2ab += lib.einsum('BE,iJaE->iJaB', imds.Fvvb, r2ab) Hr2ab += lib.einsum('be,iJeA->iJbA', imds.Fvva, r2ab) Hr2aa -= lib.einsum('mj,imab->ijab', imds.Fooa, r2aa) Hr2bb -= lib.einsum('mj,imab->ijab', imds.Foob, r2bb) Hr2ab -= lib.einsum('MJ,iMaB->iJaB', imds.Foob, r2ab) Hr2ab -= lib.einsum('mj,mIaB->jIaB', imds.Fooa, r2ab) #:tau2aa, tau2ab, tau2bb = uccsd.make_tau(r2, r1, t1, 2) #:eris_ovvv = lib.unpack_tril(np.asarray(eris.ovvv).reshape(nocca*nvira,-1)).reshape(nocca,nvira,nvira,nvira) #:eris_ovVV = lib.unpack_tril(np.asarray(eris.ovVV).reshape(nocca*nvira,-1)).reshape(nocca,nvira,nvirb,nvirb) #:eris_OVvv = lib.unpack_tril(np.asarray(eris.OVvv).reshape(noccb*nvirb,-1)).reshape(noccb,nvirb,nvira,nvira) #:eris_OVVV = lib.unpack_tril(np.asarray(eris.OVVV).reshape(noccb*nvirb,-1)).reshape(noccb,nvirb,nvirb,nvirb) #:Hr1a += lib.einsum('mfae,imef->ia', eris_ovvv, r2aa) #:tmpaa = lib.einsum('meaf,ijef->maij', eris_ovvv, tau2aa) #:Hr2aa+= lib.einsum('mb,maij->ijab', t1a, tmpaa) #:tmpa = lib.einsum('mfae,me->af', eris_ovvv, r1a) #:tmpa-= lib.einsum('meaf,me->af', eris_ovvv, r1a) #:Hr1b += lib.einsum('mfae,imef->ia', eris_OVVV, r2bb) #:tmpbb = lib.einsum('meaf,ijef->maij', eris_OVVV, tau2bb) #:Hr2bb+= lib.einsum('mb,maij->ijab', t1b, tmpbb) #:tmpb = lib.einsum('mfae,me->af', eris_OVVV, r1b) #:tmpb-= lib.einsum('meaf,me->af', eris_OVVV, r1b) #:Hr1b += lib.einsum('mfAE,mIfE->IA', eris_ovVV, r2ab) #:tmpab = lib.einsum('meAF,iJeF->mAiJ', eris_ovVV, tau2ab) #:Hr2ab-= lib.einsum('mb,mAiJ->iJbA', t1a, tmpab) #:tmpb-= lib.einsum('meAF,me->AF', eris_ovVV, r1a) #:Hr1a += lib.einsum('MFae,iMeF->ia', eris_OVvv, r2ab) #:tmpba =-lib.einsum('MEaf,iJfE->MaiJ', eris_OVvv, tau2ab) #:Hr2ab+= lib.einsum('MB,MaiJ->iJaB', t1b, tmpba) #:tmpa-= lib.einsum('MEaf,ME->af', eris_OVvv, r1b) tau2aa = uccsd.make_tau_aa(r2aa, r1a, t1a, 2) mem_now = lib.current_memory()[0] max_memory = max(0, eom.max_memory - mem_now) tmpa = np.zeros((nvira,nvira)) tmpb = np.zeros((nvirb,nvirb)) blksize = min(nocca, max(ccsd.BLKMIN, int(max_memory*1e6/8/(nvira**3*3)))) for p0, p1 in lib.prange(0, nocca, blksize): ovvv = eris.get_ovvv(slice(p0,p1)) # ovvv = eris.ovvv[p0:p1] Hr1a += lib.einsum('mfae,imef->ia', ovvv, r2aa[:,p0:p1]) tmpaa = lib.einsum('meaf,ijef->maij', ovvv, tau2aa) Hr2aa+= lib.einsum('mb,maij->ijab', t1a[p0:p1], tmpaa) tmpa+= lib.einsum('mfae,me->af', ovvv, r1a[p0:p1]) tmpa-= lib.einsum('meaf,me->af', ovvv, r1a[p0:p1]) ovvv = tmpaa = None tau2aa = None tau2bb = uccsd.make_tau_aa(r2bb, r1b, t1b, 2) blksize = min(noccb, max(ccsd.BLKMIN, int(max_memory*1e6/8/(nvirb**3*3)))) for p0, p1 in lib.prange(0, noccb, blksize): OVVV = eris.get_OVVV(slice(p0,p1)) # OVVV = eris.OVVV[p0:p1] Hr1b += lib.einsum('mfae,imef->ia', OVVV, r2bb[:,p0:p1]) tmpbb = lib.einsum('meaf,ijef->maij', OVVV, tau2bb) Hr2bb+= lib.einsum('mb,maij->ijab', t1b[p0:p1], tmpbb) tmpb+= lib.einsum('mfae,me->af', OVVV, r1b[p0:p1]) tmpb-= lib.einsum('meaf,me->af', OVVV, r1b[p0:p1]) OVVV = tmpbb = None tau2bb = None tau2ab = uccsd.make_tau_ab(r2ab, r1 , t1 , 2) blksize = min(nocca, max(ccsd.BLKMIN, int(max_memory*1e6/8/(nvira*nvirb**2*3)))) for p0, p1 in lib.prange(0, nocca, blksize): ovVV = eris.get_ovVV(slice(p0,p1)) # ovVV = eris.ovVV[p0:p1] Hr1b += lib.einsum('mfAE,mIfE->IA', ovVV, r2ab[p0:p1]) tmpab = lib.einsum('meAF,iJeF->mAiJ', ovVV, tau2ab) Hr2ab-= lib.einsum('mb,mAiJ->iJbA', t1a[p0:p1], tmpab) tmpb-= lib.einsum('meAF,me->AF', ovVV, r1a[p0:p1]) ovVV = tmpab = None blksize = min(noccb, max(ccsd.BLKMIN, int(max_memory*1e6/8/(nvirb*nvira**2*3)))) for p0, p1 in lib.prange(0, noccb, blksize): OVvv = eris.get_OVvv(slice(p0,p1)) # OVvv = eris.OVvv[p0:p1] Hr1a += lib.einsum('MFae,iMeF->ia', OVvv, r2ab[:,p0:p1]) tmpba = lib.einsum('MEaf,iJfE->MaiJ', OVvv, tau2ab) Hr2ab-= lib.einsum('MB,MaiJ->iJaB', t1b[p0:p1], tmpba) tmpa-= lib.einsum('MEaf,ME->af', OVvv, r1b[p0:p1]) OVvv = tmpba = None tau2ab = None Hr2aa-= lib.einsum('af,ijfb->ijab', tmpa, t2aa) Hr2bb-= lib.einsum('af,ijfb->ijab', tmpb, t2bb) Hr2ab-= lib.einsum('af,iJfB->iJaB', tmpa, t2ab) Hr2ab-= lib.einsum('AF,iJbF->iJbA', tmpb, t2ab) eris_ovov = np.asarray(eris.ovov) eris_OVOV = np.asarray(eris.OVOV) eris_ovOV = np.asarray(eris.ovOV) tau2aa = uccsd.make_tau_aa(r2aa, r1a, t1a, 2) tauaa = uccsd.make_tau_aa(t2aa, t1a, t1a) tmpaa = lib.einsum('menf,ijef->mnij', eris_ovov, tau2aa) Hr2aa += lib.einsum('mnij,mnab->ijab', tmpaa, tauaa) * 0.25 tau2aa = tauaa = None tau2bb = uccsd.make_tau_aa(r2bb, r1b, t1b, 2) taubb = uccsd.make_tau_aa(t2bb, t1b, t1b) tmpbb = lib.einsum('menf,ijef->mnij', eris_OVOV, tau2bb) Hr2bb += lib.einsum('mnij,mnab->ijab', tmpbb, taubb) * 0.25 tau2bb = taubb = None tau2ab = uccsd.make_tau_ab(r2ab, r1 , t1 , 2) tauab = uccsd.make_tau_ab(t2ab, t1 , t1) tmpab = lib.einsum('meNF,iJeF->mNiJ', eris_ovOV, tau2ab) Hr2ab += lib.einsum('mNiJ,mNaB->iJaB', tmpab, tauab) tau2ab = tauab = None tmpa = lib.einsum('menf,imef->ni', eris_ovov, r2aa) tmpa-= lib.einsum('neMF,iMeF->ni', eris_ovOV, r2ab) tmpb = lib.einsum('menf,imef->ni', eris_OVOV, r2bb) tmpb-= lib.einsum('mfNE,mIfE->NI', eris_ovOV, r2ab) Hr1a += lib.einsum('na,ni->ia', t1a, tmpa) Hr1b += lib.einsum('na,ni->ia', t1b, tmpb) Hr2aa+= lib.einsum('mj,imab->ijab', tmpa, t2aa) Hr2bb+= lib.einsum('mj,imab->ijab', tmpb, t2bb) Hr2ab+= lib.einsum('MJ,iMaB->iJaB', tmpb, t2ab) Hr2ab+= lib.einsum('mj,mIaB->jIaB', tmpa, t2ab) tmp1a = np.einsum('menf,mf->en', eris_ovov, r1a) tmp1a-= np.einsum('mfne,mf->en', eris_ovov, r1a) tmp1a-= np.einsum('neMF,MF->en', eris_ovOV, r1b) tmp1b = np.einsum('menf,mf->en', eris_OVOV, r1b) tmp1b-=
np.einsum('mfne,mf->en', eris_OVOV, r1b)
numpy.einsum
import numpy as np from itertools import permutations # calculating some special moore-penrose-defined resistances for directed graphs class network: def __init__(self, A): # A is the adjacency matrix; it must be square self.A = A if (A.shape[0] != A.shape[1]): raise Exception("SquareMatrixError") else: self.n = A.shape[0] self.L = np.zeros((self.n,self.n)) # L is out-Laplacian self.M = np.zeros((self.n,self.n)) # M is in-Laplacian self.Li = np.zeros((self.n, self.n)) # Li & Mi are pseudoinverses self.Mi = np.zeros((self.n, self.n)) self.makeLaps() def makeLaps(self): # generates the laplacians one = np.ones((self.n,1)) self.L = np.diagflat(np.matmul(A, one)) - A self.M = np.diagflat(np.matmul(
np.transpose(A)
numpy.transpose
#!/usr/bin/env python u""" calc_voronoi_harmonics.py by <NAME> Read the voronoi regions produced by "create_voronoi_regions.py" and create harmonic representations of mascons Last Update 12/2020 """ #-- load required modules import os import sys import pickle import numpy as np from scipy.spatial import SphericalVoronoi,geometric_slerp #-- import pygplates (https://www.gplates.org/docs/pygplates/pygplates_getting_started.html#installation) import pygplates #-- also import gravity toolkit modules from gravity_toolkit.gen_stokes import gen_stokes from gravity_toolkit.ncdf_stokes import ncdf_stokes from gravity_toolkit.ncdf_write import ncdf_write from gravity_toolkit.ncdf_read_stokes import ncdf_read_stokes from gravity_toolkit.read_love_numbers import read_love_numbers from gravity_toolkit.harmonic_summation import harmonic_summation from gravity_toolkit.plm_mohlenkamp import plm_mohlenkamp #------------------------------------------------------------------------------ #-- create harmonics for given voronoi regions #------------------------------------------------------------------------------ def calc_harmonics(parameters): #-- input file for voronoi regions input_file = os.path.expanduser(parameters['VORONOI_FILE']) with open(input_file, 'rb') as in_file: sv = pickle.load(in_file) #-- read grid parameters DDEG_RASTER = float(parameters['DDEG_RASTER']) #-- read harmonic parameters LMAX = int(parameters['LMAX']) MMAX = int(parameters['MMAX']) LMIN = int(parameters['LMIN']) #-- read love numbers from file in parameter file love_file = os.path.expanduser(parameters['LOVE_FILE']) hl,kl,ll = read_love_numbers(love_file,REFERENCE='CF') #-- get output directory and create it if it doesn't exist out_dir = os.path.expanduser(parameters['HARMONIC_DIRECTORY']) if not os.path.exists(out_dir): os.mkdir(out_dir) #----------------------------------------------------------------------------- #-- Now we make a grid so we can rasterize the polygons onto a grid #----------------------------------------------------------------------------- lons = np.arange(-180,180+DDEG_RASTER,DDEG_RASTER) lats = np.arange(-90,90+DDEG_RASTER,DDEG_RASTER) glat,glon = np.meshgrid(lats,lons) #-- flatten the grid for easier processing glon = glon.flatten() glat = glat.flatten() #-- create Legendre polynomials th = (90.0 - lats)*np.pi/180.0 plm = plm_mohlenkamp(LMAX, np.cos(th)) #----------------------------------------------------------------------------- #-- Convert voronoi regions into harmonics and savbe to file #----------------------------------------------------------------------------- if parameters['MAKE_HARMONICS'] in ['Y','y']: index_fid = open(os.path.join(out_dir,'mascon_Ylms_index_L{0:02d}_{1:.2f}deg.txt'.format(LMAX,DDEG_RASTER)),'w') Ylms = {} for i,region in enumerate(sv.regions): #-- intitialize mascon data as all zeros (no mass) mass = np.zeros(len(glon)) #-- get vertices of region reg_vert = sv.vertices[region] #-- create polygon from vertices on surface of sphere poly = pygplates.PolygonOnSphere(reg_vert) #-- loop through grid points to identify which lie inside polygon for j in range(len(mass)): if poly.is_point_in_polygon((glat[j],glon[j])): mass[j] = 1 #-- now convert the mass field to its harmonic representation Ylms[i] = gen_stokes(mass.reshape(len(lons),len(lats)),lons,lats,LMIN=LMIN,LMAX=LMAX,MMAX=MMAX,UNITS=1,PLM=plm,LOVE=(hl,kl,ll)) #-- save harmonics to file outfile = os.path.join(out_dir,'mascon_{0:d}_Ylms_L{1:02d}_{2:.2f}deg.nc'.format(i,LMAX,DDEG_RASTER)) ncdf_stokes(np.array(Ylms[i].clm),np.array(Ylms[i].slm),np.arange(LMAX+1),
np.arange(LMAX+1)
numpy.arange
''' Collection of algorithms for transforming coordinates commoly used in Geophysics. Glossary: --------- Geocentric Geodetic Coordinates (GGC) Geocentric Geodetic System (GGS) Geocentric Cartesian Coordinates (GCC) Geocentric Cartesian System (GCS) Geocentric Spherical Coordinates (GSC) Geocentric Spherical System (GSS) Topocentric Cartesian Coordinates (TCC) Topocentric Cartesian System (TCS) ''' import numpy as np from . import utils def GGC2GCC(height, latitude, longitude, major_semiaxis, minor_semiaxis): ''' Transform GGC into GCC. Parameters: ----------- height: numpy array 1D Vector containing the geometric height (in meters). latitude: numpy array 1D Vector containing the latitude (in degrees). longitude: numpy array 1D Vector containing the longitude (in degrees). major_semiaxis: float Major semiaxis of the reference ellipsoid (in meters). minor_semiaxis: float Minor semiaxis of the reference ellipsoid (in meters). Returns: -------- X: numpy array 1D Vector containing the X component of the Cartesian coordinates (in meters). Y: numpy array 1D Vector containing the X component of the Cartesian coordinates (in meters). Z: numpy array 1D Vector containing the Z component of the Cartesian coordinates (in meters). ''' h = np.asarray(height) lat = np.asarray(latitude) lon = np.asarray(longitude) assert (h.size == lat.size == lon.size), 'height, latitude \ and longitude must have the same number of elements' assert (major_semiaxis > minor_semiaxis), 'major_semiaxis must be greater \ than the minor_semiaxis' #Prime vertical radius of curvature N = utils.prime_vertical_curv(major_semiaxis, minor_semiaxis, lat) # convert degrees to radians lat = np.deg2rad(lat) lon = np.deg2rad(lon) aux = N + height # squared first eccentricity e2 = (major_semiaxis**2. - minor_semiaxis**2.)/(major_semiaxis**2.) clat = np.cos(lat) slat = np.sin(lat) clon = np.cos(lon) slon = np.sin(lon) X = aux*clat*clon Y = aux*clat*slon Z = (N*(1 - e2) + height)*slat return X, Y, Z def GCC2GGC(X, Y, Z, major_semiaxis, minor_semiaxis, itmax = 5): ''' Convert GCC into GGC by using the Hirvonen-Moritz algorithm (Hofmann-Wellenhof and Moritz, 2005, p. 193). Parameters: ----------- X: numpy array 1D or float Vector containing the x component of the Cartesian coordinates (in meters). Y: numpy array 1D or float Vector containing the y component of the Cartesian coordinates (in meters). Z: numpy array 1D or float Vector containing the z component of the Cartesian coordinates (in meters). major_semiaxis: float Major semiaxis of the reference ellipsoid (in meters). minor_semiaxis: float Minor semiaxis of the reference ellipsoid (in meters). itmax: int Maximum number of iterations in the Hirvonen-Moritz algorithm. Default is 5. Returns: -------- height: numpy array 1D Vector containing the geometric height (in meters). latitude: numpy array 1D Vector containing the latitude (in degrees). longitude: numpy array 1D Vector containing the longitude (in degrees). ''' x = np.asarray(X) y = np.asarray(Y) z = np.asarray(Z) assert (x.size == y.size == z.size), \ 'x, y and z must have the same number of elements' assert (major_semiaxis > minor_semiaxis), 'major_semiaxis must be greater \ than the minor_semiaxis' # horizontal distance p = np.sqrt(x**2. + y**2.) # null and non-null horizontal distances p_non_null = (p >= 1e-8) p_null = np.logical_not(p_non_null) lon = np.zeros_like(x) lat = np.zeros_like(x) height = np.zeros_like(x) # squared first eccentricity e2 = (major_semiaxis**2. - minor_semiaxis**2.)/(major_semiaxis**2.) aux1 = z[p_non_null]/p[p_non_null] aux2 = 1.- e2 # define the coordinates for null horizontal distances lon[p_null] = 0. height[p_null] = np.abs(z[p_null]) - minor_semiaxis lat[p_null] = np.sign(z[p_null])*np.pi*0.5 # first iteration lat[p_non_null] = np.arctan(aux1/aux2) sinlat = np.sin(lat[p_non_null]) N = major_semiaxis/np.sqrt(1 - e2*sinlat*sinlat) height[p_non_null] = p[p_non_null]/np.cos(lat[p_non_null]) - N for i in range(itmax): aux3 = e2*N/(N + height[p_non_null]) lat[p_non_null] = np.arctan(aux1/(1.-aux3)) sinlat = np.sin(lat[p_non_null]) N = major_semiaxis/np.sqrt(1 - e2*sinlat*sinlat) height[p_non_null] = p[p_non_null]/np.cos(lat[p_non_null]) - N lon[p_non_null] = np.arctan2(y[p_non_null], x[p_non_null]) # convert latitude and longitude from radians to degrees latitude = np.rad2deg(lat) longitude = np.rad2deg(lon) return height, latitude, longitude def GCC2GGC_approx(X, Y, Z, major_semiaxis, minor_semiaxis): ''' Convert GCC into GGC by using an approximated formula (Hofmann-Wellenhof and Moritz, 2005, p. 196). Parameters: ----------- X: numpy array 1D or float Vector containing the x component of the Cartesian coordinates (in meters). Y: numpy array 1D or float Vector containing the y component of the Cartesian coordinates (in meters). Z: numpy array 1D or float Vector containing the z component of the Cartesian coordinates (in meters). major_semiaxis: float Major semiaxis of the reference ellipsoid (in meters). minor_semiaxis: float Minor semiaxis of the reference ellipsoid (in meters). Returns: -------- height: numpy array 1D Vector containing the geometric height (in meters). latitude: numpy array 1D Vector containing the latitude (in degrees). longitude: numpy array 1D Vector containing the longitude (in degrees). ''' x = np.asarray(X) y = np.asarray(Y) z = np.asarray(Z) assert (x.size == y.size == z.size), \ 'x, y and z must have the same number of elements' assert (major_semiaxis > minor_semiaxis), 'major_semiaxis must be greater \ than the minor_semiaxis' # horizontal distance p = np.sqrt(x**2. + y**2.) # null and non-null horizontal distances p_non_null = (p >= 1e-8) p_null = np.logical_not(p_non_null) lon = np.zeros_like(x) lat = np.zeros_like(x) height = np.zeros_like(x) # define the coordinates for null horizontal distances lon[p_null] = 0. height[p_null] = np.abs(z[p_null]) - minor_semiaxis lat[p_null] = np.sign(z[p_null])*np.pi*0.5 # squared first eccentricity e2 = (major_semiaxis**2. - minor_semiaxis**2.)/(major_semiaxis**2.) # squared second eccentricity elinha2 = (major_semiaxis**2. - minor_semiaxis**2.)/(minor_semiaxis**2.) # auxiliary variable theta = np.arctan( z[p_non_null]*major_semiaxis/(p[p_non_null]*minor_semiaxis) ) sintheta = np.sin(theta) costheta = np.cos(theta) aux1 = z[p_non_null] + elinha2*minor_semiaxis*sintheta*sintheta*sintheta aux2 = p[p_non_null] - e2*major_semiaxis*costheta*costheta*costheta #lat[p_non_null] = np.arctan(aux1/aux2) lat[p_non_null] = np.arctan2(aux1, aux2) #lon[p_non_null] = np.arctan(y[p_non_null]/x[p_non_null]) lon[p_non_null] = np.arctan2(y[p_non_null], x[p_non_null]) sinlat = np.sin(lat[p_non_null]) N = major_semiaxis/np.sqrt(1 - e2*sinlat*sinlat) height[p_non_null] = p[p_non_null]/np.cos(lat[p_non_null]) - N # convert latitude and longitude from radians to degrees latitude = np.rad2deg(lat) longitude = np.rad2deg(lon) return height, latitude, longitude def GCC2TCC(X, Y, Z, X0, Y0, Z0, latitude_0, longitude_0): ''' Convert GCC into TCC with origin at a point Q = (X0, Y0, Z0). The point Q has latitude and longitude given by latitude_0 and longitude_0, respectively. This TCS has axis x pointing to north, axis z pointing to the inward normal and axis y completing the right-handed system. If latitude_0 is geodetic, then the computed normal is defined with respect to the referrence elipsoid. If latitude_0 is spherical, then the normal is defined with respect to a sphere. The transformation is computed as follows: x = vX*(X - X0) + vY*(Y - Y0) + vZ*(Z - Z0) y = wX*(X - X0) + wY*(Y - Y0) z = -uX*(X - X0) - uY*(Y - Y0) - uZ*(Z - Z0) where uX, uY, uZ, vX, vY, vZ, wX, and wy are components of the unit vectors (referred to the GCS) pointing to the orthogonal directions of the GGS at the point Q. Parameters: ----------- X, Y, Z: numpy arrays 1D Vectors containing the coordinates x, y and z (in meters), respectively, of the points referred to the GCS. X0, Y0, Z0: floats Coordinates of the origin in the GCS. latitude_0: float Latitude (in degrees) of the origin Q. longitude_0: float Longitude (in degrees) of the origin Q. Returns: -------- x: numpy array 1D Vector containing the x component of TCC (in meters). y: numpy array 1D Vector containing the y component of TCC (in meters). z: numpy array 1D Vector containing the z component of TCC (in meters). ''' X = np.asarray(X) Y = np.asarray(Y) Z = np.asarray(Z) assert (X.shape == Y.shape == Z.shape), 'X, Y and Z must have the same \ shape' assert np.isscalar(X0), 'X0 must be a scalar' assert np.isscalar(Y0), 'Y0 must be a scalar' assert np.isscalar(Z0), 'Z0 must be a scalar' assert
np.isscalar(latitude_0)
numpy.isscalar
""" Unit-testing module for weighted_npairs_s_mu """ from __future__ import absolute_import, division, print_function, unicode_literals import pytest import numpy as np from astropy.utils.misc import NumpyRNGContext from ..npairs_s_mu import npairs_s_mu from ..weighted_npairs_s_mu import weighted_npairs_s_mu __all__ = ('test1', ) fixed_seed = 43 def test1(): """ """ Npts = 1000 with NumpyRNGContext(fixed_seed): random_sample = np.random.random((Npts, 3)) period = np.array([1.0, 1.0, 1.0]) # define bins s_bins = np.array([0.0, 0.1, 0.2, 0.3]) N_mu_bins = 100 mu_bins = np.linspace(0, 1.0, N_mu_bins) Npts = len(random_sample) weights1 = np.ones(Npts) weights2 = np.ones(Npts) # count pairs using optimized double tree pair counter unweighted_counts1 = npairs_s_mu(random_sample, random_sample, s_bins, mu_bins, period=period) unweighted_counts2, weighted_counts = weighted_npairs_s_mu(random_sample, random_sample, weights1, weights2, s_bins, mu_bins, period=period) assert np.all(unweighted_counts1 == unweighted_counts2) assert np.all(unweighted_counts1 == weighted_counts) def test2(): """ """ Npts = 1000 with NumpyRNGContext(fixed_seed+1): random_sample = np.random.random((Npts, 3)) weights1 = np.random.rand(Npts) weights2 = np.random.rand(Npts) period = np.array([1.0, 1.0, 1.0]) # define bins s_bins = np.array([0.0, 0.1, 0.2, 0.3]) N_mu_bins = 100 mu_bins = np.linspace(0, 1.0, N_mu_bins) Npts = len(random_sample) # count pairs using optimized double tree pair counter unweighted_counts1 = npairs_s_mu(random_sample, random_sample, s_bins, mu_bins, period=period) unweighted_counts2, weighted_counts = weighted_npairs_s_mu(random_sample, random_sample, weights1, weights2, s_bins, mu_bins, period=period) assert np.all(unweighted_counts1 == unweighted_counts2) assert np.all(unweighted_counts1 != weighted_counts) def test_weight_consistency(): """ """ Npts = 1000 with NumpyRNGContext(fixed_seed): random_sample =
np.random.random((Npts, 3))
numpy.random.random
import math import numpy as np class Atom: def __init__(self, atom_string): self.id = int(atom_string[6:11]) self.name = atom_string[11:16].strip() self.alt = atom_string[16] self.resn = atom_string[17:20].strip() self.chain = atom_string[21] self.resi = int(atom_string[22:26]) self.x = float(atom_string[30:38]) self.y = float(atom_string[38:46]) self.z = float(atom_string[46:54]) self.pos = np.array([self.x,self.y,self.z]) self.occ = float(atom_string[54:60]) self.temp_factor = float(atom_string[60:66]) if len(atom_string)>=78: self.elem = atom_string[76:78].strip() def __str__(self): return self.name+"_"+str(self.resi) def __repr__(self): return 'Atom("ATOM %5d%5s %3s %c%4d %8.3f%8.3f%8.3f")' % (self.id, self.name, self.resn, self.chain, self.resi, self.x, self.y, self.z) def pdbString(self): return 'ATOM %5d%5s %3s %c%4d %8.3f%8.3f%8.3f' % (self.id, self.name, self.resn, self.chain, self.resi, self.x, self.y, self.z) def __sub__(self, other): return np.array([self.x-other.x, self.y-other.y, self.z-other.z]) def __add__(self, other): return np.array([self.x+other.x, self.y+other.y, self.z+other.z]) def distance(self, a): return math.sqrt((self.x-a.x)**2 + (self.y-a.y)**2 + (self.z-a.z)**2) def distanceSquared(self, a): return (self.x-a.x)**2 + (self.y-a.y)**2 + (self.z-a.z)**2 class PDBFile: """ A representation of a PDB-file """ def pdbDownload(self,pdb_id): hostname="ftp.wwpdb.org" directory="/pub/pdb/data/structures/all/pdb/" prefix="pdb" suffix=".ent.gz" import os, sys, ftplib, shutil, gzip # Log into server #print "Downloading %s from %s ..." % (pdb_id, hostname) ftp = ftplib.FTP() ftp.connect(hostname) ftp.login() # Download all files in file_list to_get = "%s/%s%s%s" % (directory,prefix,pdb_id.lower(),suffix) to_write = "%s%s" % (pdb_id,suffix) final_name = "%s.pdb" % to_write[:to_write.index(".")] try: ftp.retrbinary("RETR %s" % to_get,open(to_write,"wb").write) f = gzip.open(to_write,'r') g = open(final_name,'w') g.writelines(f.readlines()) f.close() g.close() os.remove(to_write) except ftplib.error_perm: os.remove(to_write) print("ERROR! %s could not be retrieved from PDB!" % to_get) ftp.quit() return None # Log out ftp.quit() return final_name def __init__(self, pdb): """ Initialize a PDBFile object using a PDB-file or PDB-id. If pdb is 4 characters long its assumed to be a PDB-id and the corresponding PDB-file will be downloaded and used. """ self.file_name = pdb self.models = [] cur_model = None if len(pdb)==4: self.file_name = self.pdbDownload(pdb) if self.file_name.endswith(".gz"): import gzip f = gzip.open(self.file_name, "r") lines = map(lambda l: l.decode('ascii'), f.readlines()) else: f = open(self.file_name,'r') lines = f.readlines() for line in lines: if line[0:4] == "ATOM": if cur_model==None: cur_model = [] cur_model.append(Atom(line)) if (line[0:6] == "ENDMDL" or line[0:5] == "MODEL") and cur_model!=None: self.models.append(cur_model) cur_model = None if cur_model!=None: self.models.append(cur_model) f.close() def removeResidues(self, residues): for model in range(len(self.models)): self.models[model] = [ a for a in self.models[model] if not a.resi in residues ] def getAtom(self, res_number, atom_name, model_number = 0): for atom in self.models[model_number]: if atom.resi==res_number and atom.name==atom_name: return atom def getAtomById(self, atom_id): for model in self.models: for atom in model: if atom.id==atom_id: return atom def getAtoms(self, model_number = 0): return self.models[model_number] def getAtomsInResi(self, resi, model_number = 0): ret = [] for atom in self.models[model_number]: if atom.resi==resi: ret.append(atom) return ret def getResidues(self, model_number = 0): ''' Return a sorted list of all residue numbers in this structure ''' ret = set() for atom in self.models[model_number]: ret.add(atom.resi) return sorted(list(ret)) def getResidueIDsandNames(self, model_number = 0): ''' Return a sorted list of all residue numbers and names in this structure ''' ret = set() for atom in self.models[model_number]: ret.add((atom.resi,atom.resn)) return sorted(list(ret)) def getChains(self, model_number = 0): ''' Return a set of unique chain identifiers ''' return set(map(lambda a: a.chain, self.models[model_number])) def getSequence(self, model_number = 0): ''' Get the sequence of this structure. Currently only works for RNA (single-char resn) ''' protresnmap={'ALA':'A','ARG':'R','ASN':'N','ASP':'D','ASX':'B','CYS':'C','GLU':'E','GLN':'Q','GLX':'Z','GLY':'G','HIS':'H','ILE':'I','LEU':'L','LYS':'K','MET':'M','PHE':'F','PRO':'P','SER':'S','THR':'T','TRP':'W','TYR':'Y','VAL':'V'} ret = '' prevResi = -1000 for atom in self.models[model_number]: if prevResi==-1000 or prevResi+1==atom.resi: if len(atom.resn)==1: #Its RNA/DNA: Just use the resn ret+=atom.resn else: #Its probably protein. Use the resn map if atom.resn in protresnmap: ret+=protresnmap[atom.resn] else: ret+='?' prevResi=atom.resi else: while prevResi<atom.resi: ret+='_' prevResi+=1 return ret def bFactorList(self, model_number = 0, names=["C4'","CA"],resis=None): """ Get a list of b-factors number of atoms with one of the specified names, an optional list of residues that can limit b factors to specified residues only, useful for comparison across non-identical sequences or with missing loops. """ ret =[] for atom in self.models[model_number]: if names and atom.name not in names: continue if resis and atom.resi not in resis: continue ret.append(atom.temp_factor) return ret def coordMatrix(self, model_number = 0, names=["C4'","CA"],resis=None): """ Get a coordinate-matrix of shape (a, 3) where a is the number of atoms with one of the specified names. New: an optional list of residues can limit the coordinate Matrix to specified residues only, useful for comparison across non-identical sequences or with missing loops. """ ret = np.zeros( shape=( len(self.models[model_number]) , 3 ) ) a = 0 for atom in self.models[model_number]: if names and atom.name not in names: continue if resis and atom.resi not in resis: continue ret[a][0] = atom.x ret[a][1] = atom.y ret[a][2] = atom.z a+=1 ret.resize(a,3) return ret def rmsd(self, pdbFile, model1=0, model2=0, names=None): """ Return the smallest root-mean-square-deviation between coordinates in self and pdbFile. If names is None, then all atoms are used. """ crds1 = self.coordMatrix(model1, names=names) crds2 = pdbFile.coordMatrix(model2, names=names) assert(crds1.shape[1] == 3) if crds1.shape[0] != crds2.shape[0]: print("Structure 1 size does not match structure 2 (", crds1.shape[0], "vs", crds2.shape[0], ")") assert(crds1.shape == crds2.shape) n = np.shape(crds1)[0] # Move crds1 to origo avg1 = np.zeros(3) for c1 in crds1: avg1 += c1 avg1 /= n for c1 in crds1: c1 -= avg1 # Move crds2 to origo avg2 = np.zeros(3) for c2 in crds2: avg2 += c2 avg2 /= n for c2 in crds2: c2 -= avg2 # Get optimal rotation # From http://boscoh.com/protein/rmsd-root-mean-square-deviation.html correlation_matrix = np.dot(np.transpose(crds1), crds2) u, s, v_tr = np.linalg.svd(correlation_matrix) r = np.dot(u, v_tr) r_det = np.linalg.det(r) if r_det < 0: # print 'WARNING: MIRRORING' u[:,-1] = -u[:,-1] r = np.dot(u, v_tr) # is_reflection = (np.linalg.det(u) * np.linalg.det(v_tr)) # if is_reflection: # u[:,-1] = -u[:,-1] # Apply rotation and find rmsd import itertools rms = 0. for c1, c2 in itertools.izip(crds1, crds2): c2_r = np.dot(r, c2) #rotate centroid-shifted coordinates #compute optimal RMSD tmp = c1-c2_r rms +=
np.dot(tmp, tmp)
numpy.dot
import numpy as np from sklearn.metrics import confusion_matrix, accuracy_score from sklearn.datasets import load_digits from sklearn.model_selection import train_test_split digits = load_digits() X = np.round(digits.data / 16.) y_classed = digits.target target_arr = digits.target_names X, X_test, y, y_test = train_test_split(X, y_classed, test_size=0.33, random_state=42) m = X.shape[0] n = X.shape[1] N = target_arr.shape[0] m_test = X_test.shape[1] theta = np.zeros((n, N)) for k in range(N): theta[:, k] = np.sum(X[y == k], axis=0) / len(X[y == k]) unique, counts = np.unique(y, return_counts=True) priors = np.array([x / np.sum(counts) for x in counts]) class_probs = np.zeros((m, N)) for i, x in enumerate(X): for k in range(N): prior = priors[k] lklhd = np.prod(theta[:, k] ** x * (1 - theta[:, k]) ** (1 - x)) pstrr_k = prior * lklhd class_probs[i, k] = pstrr_k class_probs /= np.sum(class_probs, axis=1, keepdims=True) y_pred_train = np.argmax(class_probs, axis=1) cm_train = confusion_matrix(y_pred_train, y) # print(cm_train) # print(r) train_accuracy = accuracy_score(y, y_pred_train) print('training accuracy: {}, trying to beat 0.913549459684123'.format( train_accuracy)) class_probs_test = np.zeros((m, N)) for i, xt in enumerate(X_test): for k in range(N): prior = priors[k] lklhd = np.prod(theta[:, k] ** xt * (1 - theta[:, k]) ** (1 - xt)) pstrr_k = prior * lklhd class_probs_test[i, k] = pstrr_k class_probs_test /=
np.sum(class_probs_test, axis=1, keepdims=True)
numpy.sum
# -*- coding: utf-8 -*- """ Merge two X/y. Takes care of reading two feature/label files, merges them and shuffels them and writes them to new output directory. Of course, I could also generalize to two lists of X and ys, respectively but this might lead to even worse practices. One big approximation of all of this is that all data fits into memory in once. But it should not be hard to wrap it in Dask if this is not the case. """ import os import pickle import click import numpy as np from sklearn.utils import shuffle from oximachine_featurizer.utils import read_pickle RANDOM_SEED = 1234 class Merger: """Class to merge two featrue sets""" def __init__( # pylint:disable=too-many-arguments self, features0, features1, labels0, labels1, names0, names1, outdir_features, outdir_labels, outdir_names, ): self.features0 = features0 self.features1 = features1 # make sure that they have the same number of features assert self.features0.shape[1] == self.features1.shape[1] self.labels0 = labels0 self.labels1 = labels1 self.names0 = names0 self.names1 = names1 # make sure labels have the same number of columns (one) and the same length as the corresponding features assert len(self.features0) == len(self.labels0) assert len(self.features1) == len(self.labels1) assert len(self.labels0) == len(self.names0) assert len(self.labels1) == len(self.labels1) # set the outdir self.outdir_features = outdir_features self.outdir_labels = outdir_labels self.outdir_names = outdir_names @staticmethod def stack_arrays(features0, features1, labels0, labels1, names0, names1): """Perform the actual merging""" X = np.vstack([features0, features1]) # pylint:disable=invalid-name y = np.array(list(labels0) + list(labels1)) # pylint:disable=invalid-name names = names0 + names1 return X, y, names @classmethod def from_files( # pylint:disable=too-many-arguments cls, features0path, features1path, labels0path, labels1path, names0path, names1path, outdir_features, outdir_labels, outdir_names, ): """Construct class from filepaths""" features0 = np.load(features0path) features1 = np.load(features1path) labels0 =
np.load(labels0path)
numpy.load