prompt
stringlengths
19
879k
completion
stringlengths
3
53.8k
api
stringlengths
8
59
import h5py import numpy as np import numpy.ma as ma import numpy.lib.recfunctions as rfn import logging ref_region_dtype = np.dtype([('start','i8'), ('stop','i8')]) def print_ref(grp): ''' Print out all references in file (or group) ''' l = list() grp.visititems(lambda n,d: l.append((n,d))\ if n.endswith('/ref') and isinstance(d,h5py.Dataset) else None ) if not len(l): return max_length = max([len(n) for n,d in l]) for n,d in l: print(n+' '*(max_length-len(n))+' '+str(d)) def print_data(grp): ''' Print out all datasets in file (or group) ''' l = list() grp.visititems(lambda n,d: l.append((n,d))\ if n.endswith('/data') and isinstance(d,h5py.Dataset) else None ) if not len(l): return max_length = max([len(n) for n,d in l]) for n,d in l: print(n+' '*(max_length-len(n))+' '+str(d)) def print_attr(grp): ''' Print out all attributes in file (or group) ''' l = list() grp.visititems(lambda n,d: l.append((n,d.attrs))\ if len(d.attrs) and not (n.endswith('/ref') or n.endswith('/ref_region'))\ else None ) if not len(l): return max_length = max([len(k) for n,d in l for k in d]) for n,d in l: print(n) for k,v in d.items(): print('\t'+k+':'+' '*(max_length-len(k))+' '+str(v)) def dereference_chain(sel, refs, data=None, regions=None, mask=None, ref_directions=None, indices_only=False): ''' Load a "chain" of references. Allows traversal of multiple layers of references, e.g. for three datasets ``A``, ``B``, and ``C`` linked ``A->B->C``. One can use a selection in ``A`` and load the ``C`` data associated with it. Example usage:: sel = slice(0,100) refs = [f['A/ref/B/ref'], f['C/ref/B/ref']] ref_dirs = [(0,1), (1,0)] data = f['C/data'] regions = [f['A/ref/B/ref_region'], f['B/ref/C/ref_region']] mask = np.r_[sel] > 50 c_data = dereference_chain(sel, refs, data, regions=regions, mask=mask, ref_directions=ref_dirs) c_data.shape # (100, max_a2b_assoc, max_b2c_assoc) :param sel: iterable of indices, a slice, or an integer, see ``sel`` argument in ``dereference`` :param refs: a list of reference datasets to load, in order, see ``ref`` argument in ``dereference`` :param data: a dataset to load dereferenced data from, optional if ``indices_only=True`` :param regions: lookup table into ``refs`` for each selection, see ``region`` argument in ``dereference`` :param mask: a boolean mask into the first selection, true will not load the entry :param ref_directions: intepretation of reference datasets, see ``ref_direction`` argument in ``dereference`` :param indices_only: flag to skip loading the data and instead just return indices into the final dataset ''' sel = np.r_[sel] mask = np.zeros_like(sel, dtype=bool) | (mask if mask is not None else False) sel = ma.array(sel, mask=mask, shrink=False) shape = (len(sel),) dref = None nsteps = len(refs) for i in range(nsteps): dset = data if i == nsteps-1 else None ref = refs[i] ref_dir = ref_directions[i] if ref_directions else (0,1) # default to (0,1) reg = regions[i] if regions else None dref = dereference(sel.data.ravel(), ref, data=dset, region=reg, mask=mask.ravel(), ref_direction=ref_dir, indices_only=True if i != nsteps-1 else indices_only) shape += dref.shape[-1:] mask = np.expand_dims(mask, axis=-1) | \ (rfn.structured_to_unstructured(dref.mask).any(axis=-1).reshape(shape) \ if dref.mask.dtype.kind == 'V' else dref.mask.reshape(shape)) dref = ma.array(dref.data.reshape(shape), mask=mask, shrink=False) if i != nsteps-1: sel = dref return dref def dereference(sel, ref, data=None, region=None, mask=None, ref_direction=(0,1), indices_only=False, as_masked=True): ''' Load ``data`` referred to by ``ref`` that corresponds to the desired positions specified in ``sel``. :param sel: iterable of indices, an index, or a ``slice`` to match against ``ref[:,ref_direction[0]]``. Return value will have same first dimension as ``sel``, e.g. ``dereference(slice(100), ref, data).shape[0] == 100`` :param ref: a shape (N,2) ``h5py.Dataset`` or array of pairs of indices linking ``sel`` and ``data`` :param data: a ``h5py.Dataset`` or array to load dereferenced data from, can be omitted if ``indices_only==True`` :param region: a 1D ``h5py.Dataset`` or array with a structured array type of [('start','i8'), ('stop','i8')]; 'start' defines the earliest index within the ``ref`` dataset for each value in ``sel``, and 'stop' defines the last index + 1 within the ``ref`` dataset (optional). If a ``h5py.Dataset`` is used, the ``sel`` spec will be used to load data from the dataset (i.e. ``region[sel]``), otherwise ``len(sel) == len(region)`` and a 1:1 correspondence is assumed :param mask: mask off specific items in selection (boolean, True == don't dereference selection), len(mask) == len(np.r_[sel]) :param ref_direction: defines how to interpret second dimension of ``ref``. ``ref[:,ref_direction[0]]`` are matched against items in ``sel``, and ``ref[:,ref_direction[1]]`` are indices into the ``data`` array (``default=(0,1)``). So for a simple example: ``dereference([0,1,2], [[1,0], [2,1]], ['A','B','C','D'], ref_direction=(0,1))`` returns an array equivalent to ``[[],['A'],['B']]`` and ``dereference([0,1,2], [[1,0], [2,1]], ['A','B','C','D'], ref_direction=(1,0))`` returns an array equivalent to ``[['B'],['C'],[]]`` :param indices_only: if ``True``, only returns the indices into ``data``, does not fetch data from ``data`` :returns: ``numpy`` masked array (or if ``as_masked=False`` a ``list``) of length equivalent to ``sel`` ''' # set up selection sel_mask = mask sel_idcs = np.r_[sel][~sel_mask] if sel_mask is not None else np.r_[sel] n_elem = len(sel_idcs) if sel_mask is None else len(sel_mask) return_dtype = data.dtype if not indices_only else ref.dtype if not len(sel_idcs) and n_elem: # special case for if there is nothing selected in the mask if as_masked: return ma.array(np.empty((n_elem,1), dtype=return_dtype), mask=True, shrink=False) else: return [np.empty(0, data.dtype) for _ in range(n_elem)] elif not len(sel_idcs): if as_masked: return ma.array(np.empty((0,1), dtype=return_dtype), mask=True, shrink=False) else: return [] # load fast region lookup if region is not None: if isinstance(region, h5py.Dataset): if isinstance(sel, slice): region = region[sel] # load parent reference region information else: region_offset = np.min(sel_idcs) region_sel = slice(region_offset, int(np.max(sel_idcs)+1)) region = region[region_sel][sel_idcs - region_offset] else: region = region[sel_idcs] # load relevant references region_valid = region['start'] != region['stop'] if region is not None else None if not region is None and np.count_nonzero(region_valid) == 0: # special case for if there are no valid references if as_masked: return ma.array(
np.empty((n_elem,1), dtype=return_dtype)
numpy.empty
import numpy as np from numpy.linalg import det, inv import matplotlib.pyplot as plt from scipy.special import gamma, digamma from gaussian import simpleGaussian pca_dim = 23 class factorAnalyzer(): def __init__(self, mean, covariance, phi, K): self.mean = mean self.covariance = covariance self.phi = phi self.K = K self.D = pca_dim self.E_h = np.zeros((1000,self.K, self.D)) self.E_h_T = np.zeros((1000,self.K, self.K)) def pdf(self, i, X): # Effective covariance of the distribution sigma = np.matmul(self.phi, self.phi.T) + self.covariance x = X[:,i].reshape(-1,1) - self.mean temp = np.matmul(x.T, inv(self.covariance)) numerator = np.exp(-0.5*np.matmul(temp,x)) det_sigma =
det(sigma)
numpy.linalg.det
import collections import logging import numpy as np import os import torch import torch.nn as nn import torch.nn.functional as F import torch.backends.cudnn as cudnn import torch.cuda.random as trandom import torch.optim as optim from torch.utils.data import DataLoader from torch.utils.data.sampler import RandomSampler, WeightedRandomSampler from tqdm import tqdm import constants as c import loss_bank as lb import model_bank as mb import optimizer_bank as ob import util from dataset import CellDataset, PairDataset, SubimageDataset, SubimageControlDataset, DataPrefetcher cudnn.benchmark = True cudnn.deterministic = False def _get_plate_group(g2rna, id_codes, prediction): plate_group = dict() for id_code, pred in zip(id_codes, prediction): exp = id_code.split('_')[0] plate = int(id_code.split('_')[1]) key = (exp, plate) if key not in plate_group: plate_group[key] = [0, 0, 0, 0] sirna = np.argmax(pred) for i in range(4): if sirna in g2rna[i]: plate_group[key][i] += 1 break return plate_group def get_plate_postprocessing(id_codes, prediction): g2rna, masks = util.get_g2rna() plate_group = _get_plate_group(g2rna, id_codes, prediction) for i, id_code in enumerate(id_codes): exp = id_code.split('_')[0] plate = int(id_code.split('_')[1]) key = (exp, plate) group = np.argmax(plate_group[key]) prediction[i, masks[group]] = -np.inf if prediction.shape[1] > c.N_CLASS: prediction[:, c.N_CLASS:] = -np.inf return prediction def _balancing_label(prob): idxs = np.dstack(np.unravel_index(np.argsort(prob.ravel()), prob.shape))[0][::-1] pred = -np.ones(prob.shape[0]) used_idx = np.zeros(prob.shape[0]) used_rna = np.zeros(prob.shape[1]) for idx in idxs: if used_idx[idx[0]] == 0 and used_rna[idx[1]] == 0: pred[idx[0]] = idx[1] used_idx[idx[0]] = 1 used_rna[idx[1]] = 1 return pred def balancing_class_prediction(id_codes, prediction): # at most 1 instance each class prediction = get_plate_postprocessing(id_codes, prediction) plates = set() for id_code in id_codes: plate = '_'.join(id_code.split('_')[:2]) plates.add(plate) plates = sorted(plates) y_pred = np.zeros(len(id_codes)) for plate in plates: idx = [i for i, x in enumerate(id_codes) if x.startswith(plate)] y_pred_i = _balancing_label(prediction[idx]) y_pred[idx] = y_pred_i return y_pred class Model: def __init__(self, model_name='resnet', ckpt_path=None, ckpt_epoch=None, ckpt_full_path=None, output_ckpt_path=None, cell_type=None, criterion='cross_entropy', train_transform=list(), progress_func=tqdm, lr=0.0001, load_optimizer=True, freeze_eval=True, precision=16, plate_group=None, train_control=False, optimizer='adam', training=True, gaussian_sigma=0): assert torch.cuda.is_available() torch.manual_seed(c.SEED) trandom.manual_seed_all(c.SEED) self.freeze_eval = freeze_eval self.device = torch.device('cuda') self.progress_func = progress_func self.train_transform = train_transform self.eval_transform = [] self.cell_type = cell_type self.plate_group = plate_group self.criterion = criterion self.train_control = train_control self.gaussian_sigma = gaussian_sigma if train_control: n_class = c.N_CLASS + c.N_CLASS_CONTROL else: n_class = c.N_CLASS if model_name.startswith('resnet2in2out'): self.model = mb.Resnet2in2out(int(model_name[13:]), n_class) elif model_name.startswith('resnet'): self.model = mb.Resnet(int(model_name[6:]), n_class) elif model_name.startswith('arcresnet'): self.model = mb.Resnet(int(model_name[9:]), n_class) elif model_name.startswith('resnext'): self.model = mb.Resnet(int(model_name[7:]), n_class) elif model_name.startswith('densenet'): self.model = mb.Densenet(int(model_name[8:]), n_class) elif model_name.startswith('efficientnet'): if training: self.model = mb.EfficientNet(model_name, n_class, nn.BatchNorm2d, mb.mish_efficientnet.swish) else: self.model = mb.EfficientNet(model_name, n_class, mb.mish_efficientnet.MovingBatchNorm2d, mb.mish_efficientnet.swish) elif model_name.startswith('mishefficientnet'): if training: self.model = mb.EfficientNet(model_name, n_class, nn.BatchNorm2d, mb.mish_efficientnet.mish) else: self.model = mb.EfficientNet(model_name, n_class, mb.mish_efficientnet.MovingBatchNorm2d, mb.mish_efficientnet.mish) elif model_name.startswith('arcefficientnet'): self.model = mb.ArcEfficientNet(model_name[3:], n_class, nn.BatchNorm2d, mb.mish_efficientnet.swish) else: return self.model.cuda() # fixme: should be double - 64 bits, float - 32 bits, half - 16 bits if precision == 32: self.model.double() elif precision == 16: self.model.float() elif precision == 8: self.model.half() else: raise Exception('Precision %d not in (8, 16, 32)' % precision) self.precision = precision # training_params = [] # for name, param in self.model.named_parameters(): # if 'fc' not in name: # param.requires_grad = False # training_params.append(param) if optimizer.lower().startswith('adam'): self.optimizer = optim.Adam(self.model.parameters(), lr=lr) elif optimizer.lower().startswith('ranger'): self.optimizer = ob.Ranger(self.model.parameters(), lr=lr) elif optimizer.lower().startswith('sgd'): self.optimizer = optim.SGD(self.model.parameters(), lr=lr, weight_decay=lr * 0.05, momentum=0.9) self.start_epoch = 0 self.loss_history = {'train': [], 'valid': [], 'test': []} self.acc_history = {'train': [], 'valid': [], 'test': []} self.pp_acc_history = {'train': [], 'valid': []} self.ckpt_path = ckpt_path self.ckpt_full_path = ckpt_full_path self.ckpt_epoch = None self.output_ckpt_path = output_ckpt_path if output_ckpt_path: os.makedirs(output_ckpt_path, exist_ok=True) self._load_ckpt(ckpt_full_path, ckpt_path, ckpt_epoch, load_optimizer) if self.start_epoch == 0: logging.info('No checkpoint loaded.') if optimizer.endswith('swa'): self.optimizer = ob.StochasticWeightAverage(self.optimizer, swa_start=1, swa_freq=1, swa_lr=lr) g2rna, masks = util.get_g2rna() self.label2mask = [] for i in range(c.N_CLASS): for j in range(4): if i in g2rna[j]: self.label2mask.append(masks[j]) break assert len(self.label2mask) == c.N_CLASS def _load_ckpt(self, ckpt_full_path, ckpt_path, ckpt_epoch, load_optimizer=True): if ckpt_full_path is not None: path = ckpt_full_path elif ckpt_path is not None: cell_str = self.cell_type + '_' if self.cell_type else '' group_str = str(self.plate_group) + '_' if self.plate_group is not None else '' epoch_str = str(ckpt_epoch) if ckpt_epoch else 'best' path = os.path.join(ckpt_path, '%s%s%s.tar' % (cell_str, group_str, epoch_str)) if not os.path.exists(path): path = os.path.join(ckpt_path, '%s%s.tar' % (cell_str, epoch_str)) else: return False if os.path.exists(path): model_ckpt = torch.load(path) try: self.model.load_state_dict(model_ckpt['model']) except RuntimeError: weights = model_ckpt['model'] new_weights = collections.OrderedDict() for k, v in weights.items(): new_weights['model.' + k] = v self.model.load_state_dict(new_weights) if load_optimizer: self.optimizer.load_state_dict(model_ckpt['optimizer']) self.start_epoch = model_ckpt['epoch'] + 1 self.ckpt_epoch = model_ckpt['epoch'] self.loss_history = model_ckpt['loss'] self.acc_history = model_ckpt['acc'] if 'pp_acc' in model_ckpt: self.pp_acc_history = model_ckpt['pp_acc'] logging.info('Check point %s loaded', path) return True elif ckpt_path is not None: os.makedirs(ckpt_path, exist_ok=True) return False def _save_ckpt(self, path, epoch): torch.save({ 'epoch': epoch, 'model': self.model.state_dict(), 'optimizer': self.optimizer.state_dict(), 'loss': self.loss_history, 'acc': self.acc_history, 'pp_acc': self.pp_acc_history, }, path) def _forward_batch(self, images, labels): if len(images.size()) == 5: B, T, C, H, W = images.size() outputs = self.model(images.view(-1, C, H, W)) if labels is not None: labels = labels.view(-1) else: T = 1 outputs = self.model(images) return outputs, labels, T def _predict_batch(self, images): if len(images.size()) == 5: B, T, C, H, W = images.size() outputs = self.model(images.view(-1, C, H, W)) outputs = outputs.view(B, T, -1) outputs = outputs.mean(dim=1) else: outputs = self.model(images) return outputs def _train_epoch(self, dataloader, criterion): running_loss = 0.0 running_corrects = 0 self.model.train() prefetcher = DataPrefetcher(dataloader) images, labels = prefetcher.next() for _ in self.progress_func(range(len(dataloader))): # zero the parameter gradients self.optimizer.zero_grad() with torch.set_grad_enabled(True): outputs, labels, T = self._forward_batch(images, labels) loss = criterion(outputs, labels) _, preds = torch.max(outputs, 1) # backward + optimize only if in training phase loss.backward() self.optimizer.step() # statistics running_loss += loss.item() * labels.size(0) / T running_corrects += torch.sum(preds == labels).cpu().numpy() / T images, labels = prefetcher.next() assert images is None epoch_loss = running_loss / len(dataloader.dataset) epoch_acc = running_corrects / len(dataloader.dataset) return epoch_loss, epoch_acc def _eval_epoch(self, dataloader, criterion): running_loss = 0.0 running_corrects = 0 running_pp_corrects = 0 if self.freeze_eval: self.model.eval() prefetcher = DataPrefetcher(dataloader) images, labels = prefetcher.next() for _ in self.progress_func(range(len(dataloader))): # forward with torch.set_grad_enabled(False): outputs = self._predict_batch(images) loss = criterion(outputs, labels) outputs = outputs.cpu().numpy() labels = labels.cpu().numpy() preds = np.argmax(outputs, axis=1) # statistics running_loss += loss.item() * labels.shape[0] running_corrects += np.sum(preds == labels) for i, l in enumerate(labels): # do not eval control data in eval_epoch for consistency if l < c.N_CLASS: outputs[i, self.label2mask[l]] = -np.inf preds = np.argmax(outputs, axis=1) running_pp_corrects += np.sum(preds == labels) images, labels = prefetcher.next() assert images is None epoch_loss = running_loss / len(dataloader.dataset) epoch_acc = running_corrects / len(dataloader.dataset) epoch_pp_acc = running_pp_corrects / len(dataloader.dataset) return epoch_loss, epoch_acc, epoch_pp_acc def _eval_kld_epoch(self, dataloader, criterion): running_loss = 0.0 running_kld_loss = 0.0 running_corrects = 0 running_pp_corrects = 0 if self.freeze_eval: self.model.eval() for images1, images2, labels, masks in self.progress_func(dataloader): images1 = images1.to(self.device) images2 = images2.to(self.device) labels = labels.to(self.device) # forward with torch.set_grad_enabled(False): outputs1 = self._predict_batch(images1) outputs2 = self._predict_batch(images2) outputs = ((outputs1 + outputs2) / 2) loss = criterion(outputs, labels) for i, mask in enumerate(masks): outputs1[i, mask] = -np.inf outputs2[i, mask] = -np.inf kld_loss = nn.KLDivLoss(reduction='batchmean')(F.log_softmax(outputs1, dim=1), F.softmax(outputs2, dim=1)) kld_loss += nn.KLDivLoss(reduction='batchmean')(F.log_softmax(outputs2, dim=1), F.softmax(outputs1, dim=1)) kld_loss /= 2 outputs = outputs.cpu().numpy() labels = labels.cpu().numpy() preds = np.argmax(outputs, axis=1) # statistics running_loss += loss.item() * labels.shape[0] running_kld_loss += kld_loss.item() * labels.shape[0] running_corrects += np.sum(preds == labels) for i, l in enumerate(labels): # do not eval control data in eval_epoch for consistency if l < c.N_CLASS: outputs[i, self.label2mask[l]] = -np.inf preds = np.argmax(outputs, axis=1) running_pp_corrects += np.sum(preds == labels) epoch_loss = running_loss / len(dataloader.dataset) epoch_kld_loss = running_kld_loss / len(dataloader.dataset) epoch_acc = running_corrects / len(dataloader.dataset) epoch_pp_acc = running_pp_corrects / len(dataloader.dataset) return epoch_loss, epoch_kld_loss, epoch_acc, epoch_pp_acc @staticmethod def _get_instance_weight(train_files): exp_count = dict() for f in train_files: exp_now = '' for exp in c.EXPS: if exp in f: exp_now = exp break if exp_now not in exp_count: exp_count[exp_now] = 0 exp_count[exp_now] += 1 weights = [] for f in train_files: exp_now = '' for exp in c.EXPS: if exp in f: exp_now = exp break weights.append(1 / exp_count[exp_now]) return weights def get_best_epoch(self, valid_exps): best_epoch = [-1] * len(valid_exps) best_loss = [np.inf] * len(valid_exps) for i, loss_dict in enumerate(self.loss_history['valid']): for j, exp in enumerate(valid_exps): if isinstance(loss_dict, dict): loss = loss_dict[exp] else: loss = loss_dict if loss < best_loss[j]: best_loss[j] = loss best_epoch[j] = i return best_loss, best_epoch def train(self, train_files, train_labels, train_stats, valid_files, valid_labels, valid_stats, test_files, test_labels, test_stats, epochs=10, patient=5, batch_size=32, num_workers=6, valid_exps=c.EXPS, dataset_class=CellDataset, balance_exp=False, eval_batch_size=32, eval_bn_batch_size=0, restore_loss=True): tw = 0 for exp in valid_exps: tw += c.TEST_COUNT[exp] if restore_loss: best_loss, best_epoch = self.get_best_epoch(valid_exps) else: best_epoch = [-1] * len(valid_exps) best_loss = [np.inf] * len(valid_exps) train_dataset = dataset_class(train_files, train_labels, train_stats, self.train_transform, 'train', gaussian_sigma=self.gaussian_sigma) if balance_exp: sampler = WeightedRandomSampler(Model._get_instance_weight(train_dataset.files), len(train_dataset)) else: sampler = RandomSampler(train_dataset) train_loader = DataLoader(train_dataset, batch_size=batch_size, num_workers=num_workers, sampler=sampler, pin_memory=True) valid_loaders = dict() test_loaders = dict() bn_loaders = dict() for exp in valid_exps: idx = util.get_exp_index(exp, valid_files) valid_loaders[exp] = DataLoader( dataset_class(valid_files[idx], valid_labels[idx], np.array(valid_stats)[idx], self.eval_transform, 'valid', gaussian_sigma=self.gaussian_sigma), batch_size=eval_batch_size, shuffle=False, num_workers=num_workers, pin_memory=True) if eval_bn_batch_size > 0: bn_loaders[exp] = DataLoader( dataset_class(valid_files[idx], valid_labels[idx], np.array(valid_stats)[idx], self.eval_transform, 'valid', gaussian_sigma=self.gaussian_sigma), batch_size=eval_bn_batch_size, shuffle=False, num_workers=num_workers, pin_memory=True) idx = util.get_exp_index(exp, test_files) test_loaders[exp] = DataLoader( dataset_class(test_files[idx], test_labels[idx], np.array(test_stats)[idx], self.eval_transform, 'valid', gaussian_sigma=self.gaussian_sigma), batch_size=eval_batch_size, shuffle=False, num_workers=num_workers, pin_memory=True) # start swa after {swa_start_epoch} epochs swa_start_epoch = 5 if isinstance(self.optimizer, ob.StochasticWeightAverage): epoch_steps = int(np.ceil(len(train_dataset) / batch_size)) self.optimizer.set_swa_param(epoch_steps * swa_start_epoch, epoch_steps) criterion = lb.get_criterion(self.criterion) for epoch in range(self.start_epoch, self.start_epoch + epochs): train_loss, train_acc = self._train_epoch(train_loader, criterion) valid_loss_dict = dict() valid_acc_dict = dict() valid_pp_acc_dict = dict() test_loss_dict = dict() test_acc_dict = dict() if isinstance(self.optimizer, ob.StochasticWeightAverage) and epoch - self.start_epoch >= swa_start_epoch: logging.info('Update for SWA') self.optimizer.update_swa() if isinstance(self.optimizer, ob.StochasticWeightAverage) and self.optimizer.has_swa(): logging.info('Swap SWA') self.optimizer.swap_swa_sgd() if self.freeze_eval: logging.info('Update SWA BN params') self.optimizer.bn_update(train_loader, self.model, device=self.device) for exp in valid_exps: valid_loss, valid_acc, valid_pp_acc = self._eval_epoch(valid_loaders[exp], criterion) valid_loss_dict[exp] = valid_loss valid_acc_dict[exp] = valid_acc valid_pp_acc_dict[exp] = valid_pp_acc if self.train_control: self.model.eval() test_loss, test_acc, test_pp_acc = self._eval_epoch(test_loaders[exp], criterion) test_loss_dict[exp] = test_loss test_acc_dict[exp] = test_acc valid_loss = np.sum([valid_loss_dict[exp] * c.TEST_COUNT[exp] / tw for exp in valid_exps]) valid_acc = np.sum([valid_acc_dict[exp] * c.TEST_COUNT[exp] / tw for exp in valid_exps]) valid_pp_acc = np.sum([valid_pp_acc_dict[exp] * c.TEST_COUNT[exp] / tw for exp in valid_exps]) if self.train_control: test_loss = np.sum([test_loss_dict[exp] * c.TEST_COUNT[exp] / tw for exp in valid_exps]) test_acc = np.sum([test_acc_dict[exp] * c.TEST_COUNT[exp] / tw for exp in valid_exps]) logging.info('Epoch {} - Train / Valid / Test Loss: {:.6f} / {:.6f} / {:.6f}'.format(epoch, train_loss, valid_loss, test_loss)) logging.info( 'Epoch {} - Train / Valid / Valid Plate / Test Acc: {:.4f}% / {:.4f}% / {:.4f}% / {:.4f}%'.format( epoch, train_acc * 100, valid_acc * 100, valid_pp_acc * 100, test_acc * 100)) else: logging.info('Epoch {} - Train / Valid Loss: {:.6f} / {:.6f}'.format(epoch, train_loss, valid_loss)) logging.info( 'Epoch {} - Train / Valid / Valid Plate Acc: {:.4f}% / {:.4f}% / {:.4f}%'.format( epoch, train_acc * 100, valid_acc * 100, valid_pp_acc * 100)) for exp in valid_exps: logging.info('Epoch {} - {} Valid Loss / Acc / Plate Acc: {:.6f} / {:.4f}% / {:.4f}%'.format(epoch, exp, valid_loss_dict[ exp], valid_acc_dict[ exp] * 100, valid_pp_acc_dict[ exp] * 100)) if self.train_control: for exp in valid_exps: logging.info( 'Epoch {} - {} Test Loss / Acc: {:.6f} / {:.4f}%'.format(epoch, exp, test_loss_dict[exp], test_acc_dict[exp] * 100)) self.loss_history['train'].append(train_loss) self.acc_history['train'].append(train_acc) self.loss_history['valid'].append(valid_loss_dict) self.acc_history['valid'].append(valid_acc_dict) self.pp_acc_history['valid'].append(valid_pp_acc_dict) if self.train_control: self.loss_history['test'].append(test_loss_dict) self.acc_history['test'].append(test_acc_dict) # save best model if self.cell_type and self.output_ckpt_path: group_str = str(self.plate_group) + '_' if self.plate_group is not None else '' tar_name = os.path.join(self.output_ckpt_path, '%s_%s%d.tar' % (self.cell_type, group_str, epoch)) else: tar_name = os.path.join(self.ckpt_path, '%d.tar' % epoch) self._save_ckpt(tar_name, epoch) best_loss_sum = np.sum([best_loss[i] * c.TEST_COUNT[exp] / tw for i, exp in enumerate(valid_exps)]) if best_loss_sum > valid_loss: if self.cell_type and self.output_ckpt_path: group_str = str(self.plate_group) + '_' if self.plate_group is not None else '' tar_name = os.path.join(self.output_ckpt_path, '%s_%sbest.tar' % (self.cell_type, group_str)) else: tar_name = os.path.join(self.ckpt_path, 'best.tar') self._save_ckpt(tar_name, epoch) if isinstance(self.optimizer, ob.StochasticWeightAverage) and self.optimizer.has_swa(): logging.info('Swap SWA') self.optimizer.swap_swa_sgd() if train_loss >= 2: _patient = patient * 2 else: _patient = patient for i, exp in enumerate(valid_exps): if best_loss[i] > valid_loss_dict[exp]: best_loss[i] = valid_loss_dict[exp] best_epoch[i] = epoch logging.info('%s best epoch %d loss %f', exp, epoch, valid_loss_dict[exp]) if epoch - max(best_epoch) >= _patient: logging.info('Loss not improving for %d epochs! Break.', epoch - max(best_epoch)) break return best_loss def get_swa_from_ckpts(self, train_files, train_labels, train_stats, valid_files, valid_labels, valid_stats, ckpt_prefix, cell_type, first_epoch, last_epoch, epoch_step=5, batch_size=32, num_workers=6, dataset_class=CellDataset, eval_batch_size=32): train_dataset = dataset_class(train_files, train_labels, train_stats, self.train_transform, 'train', gaussian_sigma=self.gaussian_sigma) train_loader = DataLoader(train_dataset, batch_size=batch_size, num_workers=num_workers, shuffle=False, pin_memory=True) valid_loader = DataLoader(dataset_class(valid_files, valid_labels, np.array(valid_stats), self.eval_transform, 'valid', gaussian_sigma=self.gaussian_sigma), batch_size=eval_batch_size, shuffle=False, num_workers=num_workers, pin_memory=True) best_loss = np.inf criterion = lb.get_criterion(self.criterion) swa_optimizer = ob.StochasticWeightAverage(self.optimizer, swa_start=1, swa_freq=1, swa_lr=1) for epoch in range(first_epoch, last_epoch + 1, epoch_step): ckpt_path = os.path.join('%s' % ckpt_prefix, '%s_%d.tar' % (cell_type, epoch)) self._load_ckpt(ckpt_path, None, -1, False) swa_optimizer.update_swa() if self.freeze_eval: logging.info('Update SWA BN params') swa_optimizer.bn_update(train_loader, self.model, device=self.device) swa_optimizer.swap_swa_sgd() train_loss, train_acc, train_pp_acc = self._eval_epoch(train_loader, criterion) valid_loss, valid_acc, valid_pp_acc = self._eval_epoch(valid_loader, criterion) logging.info('Epoch {} - Train / Valid Loss: {:.6f} / {:.6f}'.format(epoch, train_loss, valid_loss)) logging.info('Epoch {} - Train / Valid / Valid Plate Acc: {:.4f}% / {:.4f}% / {:.4f}%'.format( epoch, train_acc * 100, valid_acc * 100, valid_pp_acc * 100)) self.loss_history['train'].append(train_loss) self.acc_history['train'].append(train_acc) self.loss_history['valid'].append({cell_type: valid_loss}) self.acc_history['valid'].append({cell_type: valid_acc}) self.pp_acc_history['valid'].append({cell_type: valid_pp_acc}) if self.cell_type and self.output_ckpt_path: group_str = str(self.plate_group) + '_' if self.plate_group is not None else '' tar_name = os.path.join(self.output_ckpt_path, '%s_%s%d.tar' % (self.cell_type, group_str, epoch)) else: tar_name = os.path.join(self.ckpt_path, '%d.tar' % epoch) self._save_ckpt(tar_name, epoch) if valid_loss < best_loss: best_loss = valid_loss if self.cell_type and self.output_ckpt_path: group_str = str(self.plate_group) + '_' if self.plate_group is not None else '' tar_name = os.path.join(self.output_ckpt_path, '%s_%sbest.tar' % (self.cell_type, group_str)) else: tar_name = os.path.join(self.ckpt_path, 'best.tar') self._save_ckpt(tar_name, epoch) swa_optimizer.swap_swa_sgd() return best_loss def eval_kld(self, files, stats, labels=None, batch_size=32): valid_loader = DataLoader(PairDataset(files, labels, stats, self.eval_transform, 'valid'), batch_size=batch_size, shuffle=False, num_workers=6) criterion = lb.get_criterion(self.criterion) loss, kld_loss, acc, pp_acc = self._eval_kld_epoch(valid_loader, criterion) logging.info('loss: %.6f', loss) logging.info('KLD loss: %.6f', kld_loss) logging.info('accuracy: %.4f%%', acc * 100) logging.info('pp accuracy: %.4f%%', pp_acc * 100) def predict(self, files, stats, labels=None, dataset='test', dataset_class=CellDataset, batch_size=32, eval_bn_batch_size=0, tta=(True, True, True, True)): dataloader = DataLoader(dataset_class(files, labels, stats, self.eval_transform, dataset, tta=tta), batch_size=batch_size, shuffle=False, num_workers=6) if self.freeze_eval: self.model.eval() prediction = [] labels = np.array([]) for images, label in tqdm(dataloader): images = images.to(self.device) if self.precision == 8: images = images.half() with torch.set_grad_enabled(False): outputs = self._predict_batch(images) prediction.append(outputs.cpu().numpy()) labels = np.concatenate((labels, label)) return np.vstack(prediction), labels def saliency_map(self, files, stats, labels, output_dir, batch_size=32, dataset_class=SubimageDataset): dataloader = DataLoader(dataset_class(files, labels, stats, self.eval_transform, 'valid'), batch_size=batch_size, shuffle=False, num_workers=6) i = 0 corrects = 0.0 self.model.eval() for images, label in tqdm(dataloader): images = images.to(self.device) label = label.to(self.device) if self.precision == 8: images = images.half() images.requires_grad = True B, T, C, H, W = images.size() images_flatten = images.view(-1, C, H, W) outputs = self.model(images_flatten) preds = outputs.detach().view(B, T, -1).mean(dim=1).cpu().numpy() raw_preds = outputs.detach().view(B, T, -1).cpu().numpy() label_flatten = label.repeat_interleave(T) outputs = outputs.gather(1, label_flatten.view(-1, 1)).squeeze() outputs.backward(torch.ones_like(outputs)) for k, l in enumerate(label): # do not eval control data in eval_epoch for consistency if l < c.N_CLASS: preds[k, self.label2mask[l]] = -np.inf preds = np.argmax(preds, axis=1) corrects += np.sum(preds == label.cpu().numpy()) # save gradient image file_name = files[i:i + label.size(0)] # B, T, C, H, W to B, T, H, W, C grad_images = np.transpose(images.grad.cpu().numpy(), axes=(0, 1, 3, 4, 2)) for j in range(label.size(0)): for idx in range(8): path_i = file_name[j][idx // 4].replace('./data/train', output_dir).replace('//', '/')\ .replace('s%d' % (idx // 4 + 1), 's%d_%d' % (idx // 4 + 1, idx)) dir_i = path_i.rsplit('/', 1)[0] os.makedirs(dir_i, exist_ok=True) np.save(path_i, grad_images[j][idx]) for idx in range(2): path_i = file_name[j][idx].replace('./data/train', output_dir).replace('//', '/') \ .replace('s%d' % (idx + 1), 's%d_prob' % (idx + 1)) raw_pred_i = raw_preds[idx * 4:(idx + 1) * 4]
np.save(path_i, raw_pred_i)
numpy.save
import os,sys import igraph as ig import numpy as np import matplotlib.pyplot as plt import plotly.offline as py import math import random import matplotlib.pyplot as plt import feather import pandas as pd import pygeos as pyg import logging from codetiming import Timer import geopandas as gpd from timeit import default_timer as timer from tqdm import tqdm from pathlib import Path from plotly.graph_objs import * import traceback from numpy import inf from numpy.ma import masked from population_OD import create_bbox,create_grid data_path = Path(__file__).resolve().parents[2].joinpath('data','percolation') code_timer = Timer("time_code", text="Time spent: {:.2f}") from pathos.multiprocessing import Pool,cpu_count from itertools import repeat from functools import reduce import operator #import warnings #warnings.filterwarnings("ignore") def metrics(graph): """This method prints some basic network metrics of an iGraph Args: graph (iGraph.Graph object): Returns: m: """ g = graph return pd.DataFrame([[g.ecount(),g.vcount(),g.density(),g.omega(),g.average_path_length(directed=False),g.assortativity_degree(False),g.diameter(directed=False),g.edge_connectivity(),g.maxdegree(),np.sum(g.es['distance'])]],columns=["Edge_No","Node_No","Density","Clique_No", "Ave_Path_Length", "Assortativity","Diameter","Edge_Connectivity","Max_Degree","Total_Edge_Length"]) def metrics_Print(graph): """This method prints some basic network metrics of an iGraph Args: graph (iGraph.Graph object): Returns: m: """ g = graph m = [] print("Number of edges: ", g.ecount()) print("Number of nodes: ", g.vcount()) print("Density: ", g.density()) print("Number of cliques: ", g.omega())#omega or g.clique_number() print("Average path length: ", g.average_path_length(directed=False)) print("Assortativity: ", g.assortativity_degree(False)) print("Diameter: ",g.diameter(directed=False)) print("Edge Connectivity: ", g.edge_connectivity()) print("Maximum degree: ", g.maxdegree()) print("Total Edge length ", np.sum(g.es['distance'])) #Creates a graph def graph_load(edges): """Creates Args: edges (pandas.DataFrame) : containing road network edges, with from and to ids, and distance / time columns Returns: igraph.Graph (object) : a graph with distance and time attributes """ #return ig.Graph.TupleList(gdfNet.edges[['from_id','to_id','distance']].itertuples(index=False),edge_attrs=['distance']) edges = edges.reindex(['from_id','to_id'] + [x for x in list(edges.columns) if x not in ['from_id','to_id']],axis=1) graph = ig.Graph.TupleList(edges.itertuples(index=False), edge_attrs=list(edges.columns)[2:],directed=False) graph.vs['id'] = graph.vs['name'] # graph = ig.Graph(directed=False) # max_node_id = max(max(edges.from_id),max(edges.to_id)) # graph.add_vertices(max_node_id+1) # edge_tuples = zip(edges.from_id,edges.to_id) # graph.add_edges(edge_tuples) # graph.es['distance'] = edges.distance # graph.es['time'] = edges.time return graph def graph_load_largest(edges): """Returns the largest component of a graph given an edge dataframe Args: edges (pandas.DataFrame): A dataframe containing from, to ids; time and distance attributes for each edge Returns: igraph.Graph (object) : a graph with distance and time attributes """ graph = graph_load(gdfNet) return graph.clusters().giant() def largest_component_df(edges,nodes): """Returns the largest component of a network object (network.edges pd and network.nodes pd) with reset ids. Uses igraphs built in function, while adding ids as attributes Args: edges (pandas.DataFrame): A dataframe containing from and to ids nodes (pandas.DataFrame): A dataframe containing node ids Returns: edges, nodes (pandas.DataFrame) : 2 dataframes containing only those edges and nodes belonging to the giant component """ edges = edges nodes = nodes edge_tuples = zip(edges['from_id'],edges['to_id']) graph = ig.Graph(directed=False) graph.add_vertices(len(nodes)) graph.vs['id'] = nodes['id'] graph.add_edges(edge_tuples) graph.es['id'] = edges['id'] graph = graph.clusters().giant() edges_giant = edges.loc[edges.id.isin(graph.es()['id'])] nodes_giant = nodes.loc[nodes.id.isin(graph.vs()['id'])] return reset_ids(edges_giant,nodes_giant) def create_demand(OD_nodes, OD_orig, node_pop): """This function creates a demand matrix from the equation: Demand_a,b = Population_a * Population_b * e^ [-p * Distance_a,b] -p is set to 1, populations represent the grid square of the origin, Args: OD_nodes (list): a list of nodes to use for the OD, a,b OD_orig (np.matrix): A shortest path matrix used for the distance calculation node_pop (list): population per OD node Returns: demand (np.ndarray) : A matrix with demand calculations for each OD pair """ demand = np.zeros((len(OD_nodes), len(OD_nodes))) dist_decay = 1 maxtrips = 100 for o in range(0, len(OD_nodes)): for d in range(0, len(OD_nodes)): if o == d: demand[o][d] = 0 else: normalized_dist = OD_orig[o,d] / OD_orig.max() demand[o][d] = ((node_pop[o] * node_pop[d]) * np.exp(-1 * dist_decay * normalized_dist)) demand = ((demand / demand.max()) * maxtrips) demand = np.ceil(demand).astype(int) return demand def choose_OD(pos_OD, OD_no): """Chooses nodes for OD matrix according to their population size stochastically and probabilistically Args: pos_OD (list): a list of tuples representing the nodes and their population OD_no (int): Number of OD pairs to create Returns: OD_nodes [list]: The nodes chosen for the OD mapped_pops [list]: Population for nodes chosen """ #creates 2 tuples of the node ids and their total representative population node_ids, tot_pops = zip(*pos_OD) #Assigns a probability by population size pop_probs = [x/sum(tot_pops) for x in tot_pops] #OD nodes chosen OD_nodes = list(np.random.choice(node_ids, size=OD_no, replace = False, p=pop_probs)) #Population counts in a mapped list node_positions = [node_ids.index(i) for i in OD_nodes] mapped_pops = [tot_pops[j] for j in node_positions] #returns the nodes, and their populations, should this be zipped? return OD_nodes, mapped_pops def prepare_possible_OD(gridDF, nodes, tolerance = 1): """Returns an array of tuples, with the first value the node ID to consider, and the second value the total population associated with this node. The tolerance is the size of the bounding box to search for nodes within Args: gridDF (pandas.DataFrame): A dataframe with the grid centroids and their population nodes (pandas.DataFrame): A dataframe of the road network nodes tolerance (float, optional): size of the bounding box . Defaults to 0.1. Returns: final_possible_pop (list): a list of tuples representing the nodes and their population """ nodeIDs = [] sindex = pyg.STRtree(nodes['geometry']) pos_OD_nodes = [] pos_tot_pop = [] for i in gridDF.itertuples(): ID = nearest(i.geometry, nodes, sindex, tolerance) #If a node was found if ID > -1: pos_OD_nodes.append(ID) pos_tot_pop.append(i.tot_pop) a = nodes.loc[nodes.id.isin(pos_OD_nodes)] #Create a geopackage of the possible ODs #with Geopackage('nodyBGR.gpkg', 'w') as out: # out.add_layer(a, name='finanod', crs='EPSG:4326') nodes = np.array([pos_OD_nodes]) node_unique = np.unique(nodes) count = np.array([pos_tot_pop]) #List comprehension to add total populations of recurring nodes final_possible_pop = [(i, count[nodes==i].sum()) for i in node_unique] return final_possible_pop def nearest(geom, gdf,sindex, tolerance): """Finds the nearest node Args: geom (pygeos.Geometry) : Geometry to find nearest gdf (pandas.index): Node dataframe to provide possible nodes sindex (pygeos.Sindex): Spatial index for faster lookup tolerance (float): Size of buffer to use to find nodes Returns: nearest_geom.id [int]: The node id that is closest to the geom """ matches_idx = sindex.query(geom) if not matches_idx.any(): buf = pyg.buffer(geom, tolerance) matches_idx = sindex.query(buf,'contains').tolist() try: nearest_geom = min( [gdf.iloc[match_idx] for match_idx in matches_idx], key=lambda match: pyg.measurement.distance(match.geometry,geom) ) except: #print("Couldn't find node") return -1 return nearest_geom.id def simple_OD_calc(OD, comparisonOD,pos_trip_no): """An alternative OD calculation that counts how many trips exceed threshold length Args: OD ([type]): [description] comparisonOD ([type]): [description] pos_trip_no ([type]): [description] Returns: [type]: [description] """ compare_thresh = np.greater(OD,comparisonOD) over_thresh_no = np.sum(compare_thresh) / 2 return over_thresh_no / pos_trip_no def reset_ids(edges, nodes): """Resets the ids of the nodes and edges, editing the references in edge table using dict masking Args: edges (pandas.DataFrame): edges to re-reference ids nodes (pandas.DataFrame): nodes to re-reference ids Returns: edges, nodes (pandas.DataFrame) : The re-referenced edges and nodes. """ nodes = nodes.copy() edges = edges.copy() to_ids = edges['to_id'].to_numpy() from_ids = edges['from_id'].to_numpy() new_node_ids = range(len(nodes)) #creates a dictionary of the node ids and the actual indices id_dict = dict(zip(nodes.id,new_node_ids)) nt = np.copy(to_ids) nf = np.copy(from_ids) #updates all from and to ids, because many nodes are effected, this #is quite optimal approach for large dataframes for k,v in id_dict.items(): nt[to_ids==k] = v nf[from_ids==k] = v edges.drop(labels=['to_id','from_id'],axis=1,inplace=True) edges['from_id'] = nf edges['to_id'] = nt nodes.drop(labels=['id'],axis=1,inplace=True) nodes['id'] = new_node_ids edges['id'] = range(len(edges)) edges.reset_index(drop=True,inplace=True) nodes.reset_index(drop=True,inplace=True) return edges,nodes def get_metrics_and_split(x): try: data_path = Path(r'/scistor/ivm/data_catalogue/open_street_map/') #data_path = Path(r'C:/data/') if data_path.joinpath("percolation_metrics","{}_0_metrics.csv".format(x)).is_file(): print("{} already finished!".format(x)) return None print(x+' has started!') edges = feather.read_dataframe(data_path.joinpath("road_networks","{}-edges.feather".format(x))) nodes = feather.read_dataframe(data_path.joinpath("road_networks","{}-nodes.feather".format(x))) #edges = edges.drop('geometry',axis=1) edges = edges.reindex(['from_id','to_id'] + [x for x in list(edges.columns) if x not in ['from_id','to_id']],axis=1) graph= ig.Graph.TupleList(edges.itertuples(index=False), edge_attrs=list(edges.columns)[2:],directed=False) graph.vs['id'] = graph.vs['name'] #all_df = metrics(graph) #all_df.to_csv(data_path.joinpath("percolation_metrics","{}_all_metrics.csv".format(x))) cluster_sizes = graph.clusters().sizes() cluster_sizes.sort(reverse=True) cluster_loc = [graph.clusters().sizes().index(x) for x in cluster_sizes[:5]] main_cluster = graph.clusters().giant() main_edges = edges.loc[edges.id.isin(main_cluster.es()['id'])] main_nodes = nodes.loc[nodes.id.isin(main_cluster.vs()['id'])] main_edges, main_nodes = reset_ids(main_edges,main_nodes) feather.write_dataframe(main_edges,data_path.joinpath("percolation_networks","{}_0-edges.feather".format(x))) feather.write_dataframe(main_nodes,data_path.joinpath("percolation_networks","{}_0-nodes.feather".format(x))) main_df = metrics(main_cluster) main_df.to_csv(data_path.joinpath("percolation_metrics","{}_0_metrics.csv".format(x))) skipped_giant = False counter = 1 for y in cluster_loc: if not skipped_giant: skipped_giant=True continue if len(graph.clusters().subgraph(y).vs) < 500: break g = graph.clusters().subgraph(y) g_edges = edges.loc[edges.id.isin(g.es()['id'])] g_nodes = nodes.loc[nodes.id.isin(g.vs()['id'])] if len(g_edges) == len(main_edges) & len(g_nodes) == len(main_nodes): continue g_edges, g_nodes = reset_ids(g_edges,g_nodes) feather.write_dataframe(g_edges,data_path.joinpath("percolation_networks","{}_{}-edges.feather".format(x,str(counter)))) feather.write_dataframe(g_nodes,data_path.joinpath("percolation_networks","{}_{}-nodes.feather".format(x,str(counter)))) g_df = metrics(g) g_df.to_csv("/scistor/ivm/data_catalogue/open_street_map/percolation_metrics/"+x+"_"+str(counter)+"_metrics.csv") counter += 1 print(x+' has finished!') except Exception as e: print(x+" failed because of {}".format(e)) def SummariseOD(OD, fail_value, demand, baseline, GDP_per_capita, frac_counter,distance_disruption, time_disruption): """Function returns the % of total trips between origins and destinations that exceed fail value Almost verbatim from world bank /GOSTnets world_files_criticality_v2.py Args: OD (np.matrix): Current OD matrix times (during percolation) fail_value (int): Came form GOSTNETS , seems just to be a huge int demand (np.ndarray): Demand matrix baseline (np.matrix): OD matrix before percolation GDP_per_capita (int): GDP of relevant area frac_counter (float): Keeps track of current fraction for ease of results storage Returns: frac_counter, pct_isolated, average_time_disruption, pct_thirty_plus, pct_twice_plus, pct_thrice_plus,total_surp_loss_e1, total_pct_surplus_loss_e1, total_surp_loss_e2, total_pct_surplus_loss_e2 """ #adjusted time adj_time = OD-baseline # total trips total_trips = (baseline.shape[0]*baseline.shape[1])-baseline.shape[0] #isolated_trips = np.ma.masked_array(masked_demand,~masked_OD.mask) isolated_trips_sum = OD[OD == fail_value].shape[1] # get percentage of isolated trips pct_isolated = (isolated_trips_sum / total_trips)*100 ## get travel times for remaining trips time_unaffected_trips = OD[OD == baseline] # get unaffected trips travel times if not (np.isnan(np.array(time_unaffected_trips)).all()): unaffected_percentiles = [] unaffected_percentiles.append(np.nanpercentile(np.array(time_unaffected_trips),10)) unaffected_percentiles.append(np.nanpercentile(np.array(time_unaffected_trips),25)) unaffected_percentiles.append(np.nanpercentile(np.array(time_unaffected_trips),50)) unaffected_percentiles.append(np.nanpercentile(np.array(time_unaffected_trips),75)) unaffected_percentiles.append(np.nanpercentile(np.array(time_unaffected_trips),90)) unaffected_percentiles.append(np.nanmean((time_unaffected_trips))) else: unaffected_percentiles = [np.nan,np.nan,np.nan,np.nan,np.nan,np.nan] # save delayed trips travel times delayed_trips_time = adj_time[(OD != baseline) & (np.nan_to_num(np.array(OD),nan=fail_value) != fail_value)] unaffected_trips = np.array(time_unaffected_trips).shape[1] delayed_trips = np.array(delayed_trips_time).shape[1] # save percentage unaffected and delayed pct_unaffected = (unaffected_trips/total_trips)*100 pct_delayed = (delayed_trips/total_trips)*100 # get delayed trips travel times if not (np.isnan(np.array(delayed_trips_time)).all()): delayed_percentiles = [] delayed_percentiles.append(np.nanpercentile(np.array(delayed_trips_time),10)) delayed_percentiles.append(np.nanpercentile(np.array(delayed_trips_time),25)) delayed_percentiles.append(np.nanpercentile(np.array(delayed_trips_time),50)) delayed_percentiles.append(np.nanpercentile(np.array(delayed_trips_time),75)) delayed_percentiles.append(np.nanpercentile(np.array(delayed_trips_time),90)) delayed_percentiles.append(np.nanmean(np.array(delayed_trips_time))) average_time_disruption = np.nanmean(np.array(delayed_trips_time)) else: delayed_percentiles = [np.nan,np.nan,np.nan,np.nan,np.nan,np.nan] average_time_disruption = np.nan # Flexing demand with trip cost def surplus_loss(e, C2, C1, D1): """[summary] Args: e ([type]): [description] C2 ([type]): [description] C1 ([type]): [description] D1 ([type]): [description] Returns: [type]: [description] """ Y_intercept_max_cost = C1 - (e * D1) C2 = np.minimum(C2, Y_intercept_max_cost) delta_cost = C2 - C1 delta_demand = (delta_cost / e) D2 = (D1 + delta_demand) surplus_loss_ans = ((delta_cost * D2) + ((delta_cost * -delta_demand) / 2)) triangle = (D1 * (Y_intercept_max_cost - C1) ) / 2 total_surp_loss = surplus_loss_ans.sum() total_pct_surplus_loss = total_surp_loss / triangle.sum() return total_surp_loss, total_pct_surplus_loss*100 adj_cost = (OD * GDP_per_capita) / (365 * 8 ) #* 3600) time is in hours, so not sure why we do this multiplications with 3600? and minutes would be times 60? baseline_cost = (baseline * GDP_per_capita) / (365 * 8 ) #* 3600) time is in hours, so not sure why we do this multiplications with 3600? and minutes would be times 60? adj_cost = np.nan_to_num(np.array(adj_cost),nan=np.nanmax(adj_cost)) total_surp_loss_e1, total_pct_surplus_loss_e1 = surplus_loss(-0.15, adj_cost, baseline_cost, demand) total_surp_loss_e2, total_pct_surplus_loss_e2 = surplus_loss(-0.36, adj_cost, baseline_cost, demand) return frac_counter, pct_isolated, pct_unaffected, pct_delayed, average_time_disruption, total_surp_loss_e1, total_pct_surplus_loss_e1, total_surp_loss_e2, total_pct_surplus_loss_e2, distance_disruption, time_disruption, unaffected_percentiles, delayed_percentiles def percolation_random_attack(edges, del_frac=0.01, OD_list=[], pop_list=[], GDP_per_capita=50000): """Final version of percolation, runs a simulation on the network provided, to give an indication of network resilience. Args: edges (pandas.DataFrame): A dataframe containing edge information: the nodes to and from, the time and distance of the edge del_frac (float): The fraction to increment the percolation. Defaults to 0.01. e.g.0.01 removes 1 percent of edges at each step OD_list (list, optional): OD nodes to use for matrix and calculations. Defaults to []. pop_list (list, optional): Corresponding population sizes for ODs for demand calculations. Defaults to []. GDP_per_capita (int, optional): The GDP of the country/area for surplus cost calculations. Defaults to 50000. Returns: result_df [pandas.DataFrame]: The results! 'frac_counter', 'pct_isolated', 'average_time_disruption', 'pct_thirty_plus', 'pct_twice_plus', 'pct_thrice_plus','total_surp_loss_e1', 'total_pct_surplus_loss_e1', 'total_surp_loss_e2', 'total_pct_surplus_loss_e2' """ edges.geometry = pyg.from_wkb(edges.geometry) result_df = [] g = graph_load(edges) #These if statements allow for an OD and population list to be randomly generated if OD_list == []: OD_nodes = random.sample(range(g.vcount()-1),100) else: OD_nodes = OD_list edge_no = g.ecount() OD_node_no = len(OD_nodes) if pop_list == []: node_pop = random.sample(range(4000), OD_node_no) else: node_pop = pop_list #Creates a matrix of shortest path times between OD nodes base_shortest_paths = g.shortest_paths_dijkstra(source=OD_nodes,target = OD_nodes,weights='time') OD_orig = np.matrix(base_shortest_paths) demand = create_demand(OD_nodes, OD_orig, node_pop) exp_g = g.copy() trips_possible = True frac_counter = 0 tot_edge_length = np.sum(g.es['distance']) tot_edge_time = np.sum(g.es['time']) # add frac 0.00 for better figures and results result_df.append((0.00, 0, 100, 0, 0.0, 0, 0.0, 0, 0.0, 0.0, 0.0, [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0,0.0, 0.0, 0.0, 0.0, 0.0])) while trips_possible: if frac_counter > 0.3 and frac_counter <= 0.5: del_frac = 0.02 if frac_counter > 0.5: del_frac = 0.05 exp_edge_no = exp_g.ecount() #sample_probabilities = np.array(exp_g.es['distance'])/sum(exp_g.es['distance']) #The number of edges to delete no_edge_del = max(1,math.floor(del_frac * edge_no)) try: edges_del = random.sample(range(exp_edge_no),no_edge_del) #edges_del = np.random.choice(range(exp_edge_no), size=no_edge_del, replace = False, p=sample_probabilities) except: edges_del = range(exp_edge_no) exp_g.delete_edges(edges_del) frac_counter += del_frac cur_dis_length = 1 - (np.sum(exp_g.es['distance'])/tot_edge_length) cur_dis_time = 1 - (np.sum(exp_g.es['time'])/tot_edge_time) new_shortest_paths = exp_g.shortest_paths_dijkstra(source=OD_nodes,target = OD_nodes,weights='time') perc_matrix = np.matrix(new_shortest_paths) perc_matrix[perc_matrix == inf] = 99999999999 perc_matrix[perc_matrix == 0] = np.nan results = SummariseOD(perc_matrix, 99999999999, demand, OD_orig, GDP_per_capita,round(frac_counter,3),cur_dis_length,cur_dis_time) result_df.append(results) #If the frac_counter goes past 0.99 if results[0] >= 0.99: break #If there are no edges left to remove if exp_edge_no < 1: break result_df = pd.DataFrame(result_df, columns=['frac_counter', 'pct_isolated','pct_unaffected', 'pct_delayed', 'average_time_disruption','total_surp_loss_e1', 'total_pct_surplus_loss_e1', 'total_surp_loss_e2', 'total_pct_surplus_loss_e2', 'distance_disruption','time_disruption','unaffected_percentiles','delayed_percentiles']) result_df = result_df.replace('--',0) return result_df def percolation_random_attack_od_buffer(edges, nodes,grid_height, del_frac=0.01, OD_list=[], pop_list=[], GDP_per_capita=50000): """Final version of percolation, runs a simulation on the network provided, to give an indication of network resilience. Args: edges (pandas.DataFrame): A dataframe containing edge information: the nodes to and from, the time and distance of the edge del_frac (float): The fraction to increment the percolation. Defaults to 0.01. e.g.0.01 removes 1 percent of edges at each step OD_list (list, optional): OD nodes to use for matrix and calculations. Defaults to []. pop_list (list, optional): Corresponding population sizes for ODs for demand calculations. Defaults to []. GDP_per_capita (int, optional): The GDP of the country/area for surplus cost calculations. Defaults to 50000. Returns: result_df [pandas.DataFrame]: The results! 'frac_counter', 'pct_isolated', 'average_time_disruption', 'pct_thirty_plus', 'pct_twice_plus', 'pct_thrice_plus','total_surp_loss_e1', 'total_pct_surplus_loss_e1', 'total_surp_loss_e2', 'total_pct_surplus_loss_e2' """ nodes.geometry = pyg.from_wkb(nodes.geometry) edges.geometry = pyg.from_wkb(edges.geometry) result_df = [] g = graph_load(edges) #These if statements allow for an OD and population list to be randomly generated if OD_list == []: OD_nodes = random.sample(range(g.vcount()-1),100) else: OD_nodes = OD_list edge_no = g.ecount() OD_node_no = len(OD_nodes) if pop_list == []: node_pop = random.sample(range(4000), OD_node_no) else: node_pop = pop_list buffer_centroids = pyg.buffer(nodes.loc[nodes.id.isin(OD_list)].geometry,grid_height*0.05).values OD_buffers = dict(zip(OD_nodes,buffer_centroids)) edges_per_OD = {} for OD_buffer in OD_buffers: get_list_edges = list(edges.id.loc[pyg.intersects(pyg.make_valid(OD_buffers[OD_buffer]),pyg.make_valid(edges.geometry.values))].values) edges_per_OD[OD_buffer] = get_list_edges,get_list_edges #Creates a matrix of shortest path times between OD nodes base_shortest_paths = g.shortest_paths_dijkstra(source=OD_nodes,target=OD_nodes,weights='time') OD_orig = np.matrix(base_shortest_paths) OD_thresh = OD_orig * 10 demand = create_demand(OD_nodes, OD_orig, node_pop) exp_g = g.copy() trips_possible = True pos_trip_no = (((OD_node_no**2) - OD_node_no) / 2) - ((np.count_nonzero(np.isinf(OD_orig)))/2) counter = 0 frac_counter = 0 tot_edge_length =
np.sum(g.es['distance'])
numpy.sum
''' Classes for extracting "decodable features" from various types of neural signal sources. Examples include spike rate estimation, LFP power, and EMG amplitude. ''' import numpy as np import time from scipy.signal import butter, lfilter import math import os import nitime.algorithms as tsa from riglib.ripple.pyns import pyns class FeatureExtractor(object): ''' Parent of all feature extractors, used only for interfacing/type-checking. Feature extractors are objects tha gets the data that it needs (e.g., spike timestamps, LFP voltages, etc.) from the neural data source object and extracts features from it ''' @classmethod def extract_from_file(cls, *args, **kwargs): raise NotImplementedError class DummyExtractor(FeatureExtractor): ''' An extractor which does nothing. Used for tasks which are only pretending to be BMI tasks, e.g., visual feedback tasks ''' feature_type = 'obs' feature_dtype = [('obs', 'f8', (1,))] def __call__(self, *args, **kwargs): return dict(obs=np.array([[np.nan]])) class BinnedSpikeCountsExtractor(FeatureExtractor): ''' Extracts spike counts from spike timestamps separated into rectangular window. This extractor is (currently) the main type of feature extractor in intracortical BMIs ''' feature_type = 'spike_counts' def __init__(self, source, n_subbins=1, units=[]): ''' Constructor for BinnedSpikeCountsExtractor Parameters ---------- source: DataSource instance Source must implement a '.get()' function which returns the appropriate data (appropriateness will change depending on the source) n_subbins: int, optional, default=1 Number of bins into which to divide the observed spike counts units: np.ndarray of shape (N, 2), optional, default=[] Units which need spike binning. Each row of the array corresponds to (channel, unit). By default no units will be binned. Returns ------- BinnedSpikeCountsExtractor instance ''' self.feature_dtype = [('spike_counts', 'u4', (len(units), n_subbins)), ('bin_edges', 'f8', 2)] self.source = source self.n_subbins = n_subbins self.units = units extractor_kwargs = dict() extractor_kwargs['n_subbins'] = self.n_subbins extractor_kwargs['units'] = self.units self.extractor_kwargs = extractor_kwargs self.last_get_spike_counts_time = 0 def set_n_subbins(self, n_subbins): ''' Alter the # of subbins without changing the extractor kwargs of a decoder Parameters ---------- n_subbins : int Number of bins into which to divide the observed spike counts Returns ------- None ''' self.n_subbins = n_subbins self.extractor_kwargs['n_subbins'] = n_subbins self.feature_dtype = [('spike_counts', 'u4', (len(self.units), n_subbins)), ('bin_edges', 'f8', 2)] def get_spike_ts(self, *args, **kwargs): ''' Get the spike timestamps from the neural data source. This function has no type checking, i.e., it is assumed that the Extractor object was created with the proper source Parameters ---------- None are needed (args and kwargs are ignored) Returns ------- numpy record array Spike timestamps in the format of riglib.plexon.Spikes.dtype ''' return self.source.get() def get_bin_edges(self, ts): ''' Determine the first and last spike timestamps to allow HDF files created by the BMI to be semi-synchronized with the neural data file Parameters ---------- ts : numpy record array Must have field 'ts' of spike timestamps in seconds Returns ------- np.ndarray of shape (2,) The smallest and largest timestamps corresponding to the current feature; useful for rough synchronization of the BMI event loop with the neural recording system. ''' if len(ts) == 0: bin_edges = np.array([np.nan, np.nan]) else: min_ind = np.argmin(ts['ts']) max_ind = np.argmax(ts['ts']) bin_edges = np.array([ts[min_ind]['ts'], ts[max_ind]['ts']]) @classmethod def bin_spikes(cls, ts, units, max_units_per_channel=13): ''' Count up the number of BMI spikes in a list of spike timestamps. Parameters ---------- ts : numpy record array Must have field 'ts' of spike timestamps in seconds units : np.ndarray of shape (N, 2) Each row corresponds to the channel index (typically the electrode number) and the unit index (an index to differentiate the possibly many units on the same electrode). These are the units used in the BMI. max_units_per_channel : int, optional, default=13 This int is used to map from a (channel, unit) index to a single 'unit_ind' for faster binning of spike timestamps. Just set to a large number. Returns ------- np.ndarray of shape (N, 1) Column vector of counts of spike events for each of the N units. ''' unit_inds = units[:,0]*max_units_per_channel + units[:,1] edges = np.sort(np.hstack([unit_inds - 0.5, unit_inds + 0.5])) spiking_unit_inds = ts['chan']*max_units_per_channel + ts['unit'] counts, _ = np.histogram(spiking_unit_inds, edges) return counts[::2] def __call__(self, start_time, *args, **kwargs): ''' Main function to retreive new spike data and bin the counts Parameters ---------- start_time : float Absolute time from the task event loop. This is used only to subdivide the spike timestamps into multiple bins, if desired (if the 'n_subbins' attribute is > 1) *args, **kwargs : optional positional/keyword arguments These are passed to the source, or ignored (not needed for this extractor). Returns ------- dict Extracted features to be saved in the task. ''' ts = self.get_spike_ts(*args, **kwargs) if len(ts) == 0: counts = np.zeros([len(self.units), self.n_subbins]) elif self.n_subbins > 1: subbin_edges = np.linspace(self.last_get_spike_counts_time, start_time, self.n_subbins+1) # Decrease the first subbin index to include any spikes that were # delayed in getting to the task layer due to threading issues # An acceptable delay is 1 sec or less. Realistically, most delays should be # on the millisecond order subbin_edges[0] -= 1 subbin_inds = np.digitize(ts['arrival_ts'], subbin_edges) counts = np.vstack([self.bin_spikes(ts[subbin_inds == k], self.units) for k in range(1, self.n_subbins+1)]).T else: counts = self.bin_spikes(ts, self.units).reshape(-1, 1) print("Units", self.units) print("Counts:", counts) counts = np.array(counts, dtype=np.uint32) bin_edges = self.get_bin_edges(ts) self.last_get_spike_counts_time = start_time return dict(spike_counts=counts, bin_edges=bin_edges) @classmethod def extract_from_file(cls, files, neurows, binlen, units, extractor_kwargs, strobe_rate=60.0): ''' Compute binned spike count features Parameters ---------- files : dict Data files used to train the decoder. Should contain exactly one type of neural data file (e.g., Plexon, Blackrock, TDT, Ripple) neurows: np.ndarray of shape (T,) Timestamps in the plexon time reference corresponding to bin boundaries binlen: float Length of time over which to sum spikes from the specified cells units: np.ndarray of shape (N, 2) List of units that the decoder will be trained on. The first column specifies the electrode number and the second specifies the unit on the electrode extractor_kwargs: dict Any additional parameters to be passed to the feature extractor. This function is agnostic to the actual extractor utilized strobe_rate: 60.0 The rate at which the task sends the sync pulse to the neural recording file Returns ------- spike_counts : np.ndarray of shape (N, T) Spike counts binned over the length of the datafile. units : np.ndarray of shape (N, 2) Each row corresponds to the channel index (typically the electrode number) and the unit index (an index to differentiate the possibly many units on the same electrode). These are the units used in the BMI. extractor_kwargs : dict Parameters used to instantiate the feature extractor, to be stored along with the trained decoder so that the exact same feature extractor can be re-created at runtime. ''' if 'plexon' in files: from plexon import plexfile plx = plexfile.openFile(str(files['plexon'])) # interpolate between the rows to 180 Hz if binlen < 1./strobe_rate: interp_rows = [] neurows = np.hstack([neurows[0] - 1./strobe_rate, neurows]) for r1, r2 in zip(neurows[:-1], neurows[1:]): interp_rows += list(np.linspace(r1, r2, 4)[1:]) interp_rows = np.array(interp_rows) else: step = int(binlen/(1./strobe_rate)) # Downsample kinematic data according to decoder bin length (assumes non-overlapping bins) interp_rows = neurows[::step] print(('step: ', step)) from plexon import psth spike_bin_fn = psth.SpikeBin(units, binlen) spike_counts = np.array(list(plx.spikes.bin(interp_rows, spike_bin_fn))) # discard units that never fired at all discard_zero_units = extractor_kwargs.pop('discard_zero_units', True) if discard_zero_units: unit_inds, = np.nonzero(np.sum(spike_counts, axis=0)) units = units[unit_inds,:] spike_counts = spike_counts[:, unit_inds] extractor_kwargs['units'] = units return spike_counts, units, extractor_kwargs elif 'blackrock' in files: nev_fname = [name for name in files['blackrock'] if '.nev' in name][0] # only one of them nev_hdf_fname = [name for name in files['blackrock'] if '.nev' in name and name[-4:]=='.hdf'] nsx_fnames = [name for name in files['blackrock'] if '.ns' in name] # interpolate between the rows to 180 Hz if binlen < 1./strobe_rate: interp_rows = [] neurows = np.hstack([neurows[0] - 1./strobe_rate, neurows]) for r1, r2 in zip(neurows[:-1], neurows[1:]): interp_rows += list(np.linspace(r1, r2, 4)[1:]) interp_rows = np.array(interp_rows) else: step = int(binlen/(1./strobe_rate)) # Downsample kinematic data according to decoder bin length (assumes non-overlapping bins) interp_rows = neurows[::step] if len(nev_hdf_fname) == 0: nev_hdf_fname = nev_fname + '.hdf' if not os.path.isfile(nev_hdf_fname): # convert .nev file to hdf file using Blackrock's n2h5 utility subprocess.call(['n2h5', nev_fname, nev_hdf_fname]) else: nev_hdf_fname = nev_hdf_fname[0] try: nev_hdf = h5py.File(nev_hdf_fname, 'r') open_method = 1 except: import tables nev_hdf = tables.openFile(nev_hdf_fname) open_method = 2 #print 'open method 2' n_bins = len(interp_rows) n_units = units.shape[0] spike_counts = np.zeros((n_bins, n_units)) for i in range(n_units): chan = units[i, 0] # 1-based numbering (comes from web interface) unit = units[i, 1] chan_str = str(chan).zfill(5) path = 'channel/channel%s/spike_set' % chan_str if open_method == 1: ts = nev_hdf.get(path).value['TimeStamp'] # the units corresponding to each timestamp in ts # 0-based numbering (comes from .nev file), so add 1 units_ts = nev_hdf.get(path).value['Unit'] elif open_method == 2: try: grp = nev_hdf.getNode('/'+path) ts = grp[:]['TimeStamp'] units_ts = grp[:]['Unit'] except: print(('no spikes recorded on channel: ', chan_str, ': adding zeros')) ts = [] units_ts = [] # get the ts for this unit, in units of secs fs = 30000. ts = [t/fs for idx, (t, u_t) in enumerate(zip(ts, units_ts)) if u_t == unit] # insert value interp_rows[0]-step to beginning of interp_rows array interp_rows_ = np.insert(interp_rows, 0, interp_rows[0]-step) # use ts to fill in the spike_counts that corresponds to unit i spike_counts[:, i] = np.histogram(ts, interp_rows_)[0] # discard units that never fired at all if 'keep_zero_units' in extractor_kwargs: print('keeping zero firing units') else: unit_inds, = np.nonzero(np.sum(spike_counts, axis=0)) units = units[unit_inds,:] spike_counts = spike_counts[:, unit_inds] extractor_kwargs['units'] = units return spike_counts, units, extractor_kwargs elif 'ripple' in files: nev_fname = [name for name in files['ripple'] if '.nev' in name][0] # only one of them nevfile = pyns.NSFile(nev_fname) # interpolate between the rows to 180 Hz if binlen < 1./strobe_rate: interp_rows = [] neurows = np.hstack([neurows[0] - 1./strobe_rate, neurows]) for r1, r2 in zip(neurows[:-1], neurows[1:]): interp_rows += list(np.linspace(r1, r2, 4)[1:]) interp_rows = np.array(interp_rows) else: step = int(binlen/(1./strobe_rate)) # Downsample kinematic data according to decoder bin length (assumes non-overlapping bins) interp_rows = neurows[::step] electrode_list = units[:,0] # first column is electrode numbers # access spike data for all electrodes indicated in units array spike_entities = [e for e in nevfile.get_entities() if e.entity_type ==3] spike_entities = [e for e in spike_entities if int(e.label[4:]) in electrode_list] print('checkpoint1') print(units) print(units.shape[0]) print(electrode_list) # there is one entity per electrode. now extract spike times and ids to do binning. # spike_counts should be units x time n_bins = len(interp_rows) n_units = units.shape[0] spike_counts = np.zeros((n_bins, n_units)) # insert value interp_rows[0]-step to beginning of interp_rows array interp_rows_ = np.insert(interp_rows, 0, interp_rows[0]-step) i = 0 print('checkpoint2') print(n_bins) print(interp_rows_) for entity in spike_entities: # placeholder matrix: spike count x 2, holds spike time in first column and spike id in second column spike_data = np.zeros((entity.item_count, 2)) elec = int(entity.label[4:]) # electrode number elec_uids = units[units[:,0]==elec,1] # units on this electrode to be included print(entity) print(elec) print(elec_uids) for item in range(0,entity.item_count): spike_data[item,0], data, spike_data[item,1] = entity.get_segment_data(item) # check which spike data will be used for uid in elec_uids: ts = spike_data[spike_data[:,1]==uid,0] print(ts) spike_counts[:, i] = np.histogram(ts, interp_rows_)[0] i += 1 # discard units that never fired at all if 'keep_zero_units' in extractor_kwargs: print('keeping zero firing units') else: print(np.sum(spike_counts, axis=0)) unit_inds, = np.nonzero(np.sum(spike_counts, axis=0)) print(unit_inds) units = units[unit_inds,:] spike_counts = spike_counts[:, unit_inds] extractor_kwargs['units'] = units print('File Extractor.py') print(units) return spike_counts, units, extractor_kwargs elif 'tdt' in files: raise NotImplementedError # bands should be a list of tuples representing ranges # e.g., bands = [(0, 10), (10, 20), (130, 140)] for 0-10, 10-20, and 130-140 Hz start = 0 end = 150 step = 10 default_bands = [] for freq in range(start, end, step): default_bands.append((freq, freq+step)) class LFPMTMPowerExtractor(object): ''' Computes log power of the LFP in different frequency bands (for each channel) in freq-domain using the multi-taper method. ''' feature_type = 'lfp_power' def __init__(self, source, channels=[], bands=default_bands, win_len=0.2, NW=3, fs=1000, **kwargs): ''' Constructor for LFPMTMPowerExtractor, which extracts LFP power using the multi-taper method Parameters ---------- source : riglib.source.Source object Object which yields new data when its 'get' method is called channels : list LFP electrode indices to use for feature extraction bands : list of tuples Each tuple defines a frequency band of interest as (start frequency, end frequency) Returns ------- LFPMTMPowerExtractor instance ''' #self.feature_dtype = ('lfp_power', 'f8', (len(channels)*len(bands), 1)) self.source = source self.channels = channels self.bands = bands self.win_len = win_len self.NW = NW if source is not None: self.fs = source.source.update_freq else: self.fs = fs extractor_kwargs = dict() extractor_kwargs['channels'] = self.channels extractor_kwargs['bands'] = self.bands extractor_kwargs['win_len'] = self.win_len extractor_kwargs['NW'] = self.NW extractor_kwargs['fs'] = self.fs extractor_kwargs['no_log'] = 'no_log' in kwargs and kwargs['no_log']==True #remove log calculation extractor_kwargs['no_mean'] = 'no_mean' in kwargs and kwargs['no_mean']==True #r self.extractor_kwargs = extractor_kwargs self.n_pts = int(self.win_len * self.fs) self.nfft = 2**int(np.ceil(np.log2(self.n_pts))) # nextpow2(self.n_pts) fft_freqs = np.arange(0., fs, float(fs)/self.nfft)[:int(self.nfft/2) + 1] #fft_freqs = np.arange(0., fs, float(fs)/self.nfft)[:self.nfft/2 + 1] self.fft_inds = dict() for band_idx, band in enumerate(bands): self.fft_inds[band_idx] = [freq_idx for freq_idx, freq in enumerate(fft_freqs) if band[0] <= freq < band[1]] extractor_kwargs['fft_inds'] = self.fft_inds extractor_kwargs['fft_freqs'] = fft_freqs self.epsilon = 1e-9 if extractor_kwargs['no_mean']: #Used in lfp 1D control task self.feature_dtype = ('lfp_power', 'f8', (len(channels)*len(fft_freqs), 1)) else: self.feature_dtype = ('lfp_power', 'f8', (len(channels)*len(bands), 1)) def get_cont_samples(self, *args, **kwargs): ''' Retreives the last n_pts number of samples for each LPF channel from the neural data 'source' Parameters ---------- *args, **kwargs : optional arguments Ignored for this extractor (not necessary) Returns ------- np.ndarray of shape ??? ''' return self.source.get(self.n_pts, self.channels) def extract_features(self, cont_samples): ''' Extract spectral features from a block of time series samples Parameters ---------- cont_samples : np.ndarray of shape (n_channels, n_samples) Raw voltage time series (one per channel) from which to extract spectral features Returns ------- lfp_power : np.ndarray of shape (n_channels * n_features, 1) Multi-band power estimates for each channel, for each band specified when the feature extractor was instantiated. ''' psd_est = tsa.multi_taper_psd(cont_samples, Fs=self.fs, NW=self.NW, jackknife=False, low_bias=True, NFFT=self.nfft)[1] if ('no_mean' in self.extractor_kwargs) and (self.extractor_kwargs['no_mean'] is True): return psd_est.reshape(psd_est.shape[0]*psd_est.shape[1], 1) else: # compute average power of each band of interest n_chan = len(self.channels) lfp_power = np.zeros((n_chan * len(self.bands), 1)) for idx, band in enumerate(self.bands): if self.extractor_kwargs['no_log']: lfp_power[idx*n_chan : (idx+1)*n_chan, 0] = np.mean(psd_est[:, self.fft_inds[idx]], axis=1) else: lfp_power[idx*n_chan : (idx+1)*n_chan, 0] = np.mean(np.log10(psd_est[:, self.fft_inds[idx]] + self.epsilon), axis=1) return lfp_power def __call__(self, start_time, *args, **kwargs): ''' Parameters ---------- start_time : float Absolute time from the task event loop. This is unused by LFP extractors in their current implementation and only passed in to ensure that function signatures are the same across extractors. *args, **kwargs : optional positional/keyword arguments These are passed to the source, or ignored (not needed for this extractor). Returns ------- dict Extracted features to be saved in the task. ''' cont_samples = self.get_cont_samples(*args, **kwargs) # dims of channels x time print(cont_samples) lfp_power = self.extract_features(cont_samples['samples']) return dict(lfp_power=lfp_power) @classmethod def extract_from_file(cls, files, neurows, binlen, units, extractor_kwargs, strobe_rate=60.0): ''' Compute binned spike count features Parameters ---------- files : dict Data files used to train the decoder. Should contain exactly one type of neural data file (e.g., Plexon, Blackrock, TDT) neurows: np.ndarray of shape (T,) Timestamps in the plexon time reference corresponding to bin boundaries binlen: float Length of time over which to sum spikes from the specified cells units: np.ndarray of shape (N, 2) List of units that the decoder will be trained on. The first column specifies the electrode number and the second specifies the unit on the electrode extractor_kwargs: dict Any additional parameters to be passed to the feature extractor. This function is agnostic to the actual extractor utilized strobe_rate: 60.0 The rate at which the task sends the sync pulse to the plx file Returns ------- spike_counts : np.ndarray of shape (N, T) Spike counts binned over the length of the datafile. units : Not used by this type of extractor, just passed back from the input argument to make the outputs consistent with spike count extractors extractor_kwargs : dict Parameters used to instantiate the feature extractor, to be stored along with the trained decoder so that the exact same feature extractor can be re-created at runtime. ''' if 'plexon' in files: from plexon import plexfile plx = plexfile.openFile(str(files['plexon'])) # interpolate between the rows to 180 Hz if binlen < 1./strobe_rate: interp_rows = [] neurows = np.hstack([neurows[0] - 1./strobe_rate, neurows]) for r1, r2 in zip(neurows[:-1], neurows[1:]): interp_rows += list(np.linspace(r1, r2, 4)[1:]) interp_rows = np.array(interp_rows) else: step = int(binlen/(1./strobe_rate)) # Downsample kinematic data according to decoder bin length (assumes non-overlapping bins) interp_rows = neurows[::step] # create extractor object f_extractor = LFPMTMPowerExtractor(None, **extractor_kwargs) extractor_kwargs = f_extractor.extractor_kwargs win_len = f_extractor.win_len bands = f_extractor.bands channels = f_extractor.channels fs = f_extractor.fs print(('bands:', bands)) n_itrs = len(interp_rows) n_chan = len(channels) lfp_power = np.zeros((n_itrs, n_chan * len(bands))) # for i, t in enumerate(interp_rows): # cont_samples = plx.lfp[t-win_len:t].data[:, channels-1] # lfp_power[i, :] = f_extractor.extract_features(cont_samples.T).T lfp = plx.lfp[:].data[:, channels-1] n_pts = int(win_len * fs) for i, t in enumerate(interp_rows): try: sample_num = int(t * fs) cont_samples = lfp[sample_num-n_pts:sample_num, :] lfp_power[i, :] = f_extractor.extract_features(cont_samples.T).T except: print("Error with LFP decoder training") print((i, t)) pass # TODO -- discard any channel(s) for which the log power in any frequency # bands was ever equal to -inf (i.e., power was equal to 0) # or, perhaps just add a small epsilon inside the log to avoid this # then, remember to do this: extractor_kwargs['channels'] = channels # and reset the units variable return lfp_power, units, extractor_kwargs elif 'blackrock' in files: raise NotImplementedError elif 'ripple' in files: ns5_fname = [name for name in files['ripple'] if '.ns5' in name][0] # only one of them ns5file = pyns.NSFile(ns5_fname) # interpolate between the rows to 180 Hz if binlen < 1./strobe_rate: interp_rows = [] neurows = np.hstack([neurows[0] - 1./strobe_rate, neurows]) for r1, r2 in zip(neurows[:-1], neurows[1:]): interp_rows += list(np.linspace(r1, r2, 4)[1:]) interp_rows = np.array(interp_rows) else: step = int(binlen/(1./strobe_rate)) # Downsample kinematic data according to decoder bin length (assumes non-overlapping bins) interp_rows = neurows[::step] electrode_list = units[:,0] # first column is electrode numbers # access spike data for all electrodes indicated in units array lfp_entities = [e for e in ns5file.get_entities() if e.entity_type ==2] lfp_entities = [e for e in lfp_entities if (e.label[:3]=='lfp') and (int(e.label.split('\x00')[0][4:]) in electrode_list)] print('checkpoint1') print(units) print(units.shape[0]) print(electrode_list) # create extractor object f_extractor = LFPMTMPowerExtractor(None, **extractor_kwargs) extractor_kwargs = f_extractor.extractor_kwargs win_len = f_extractor.win_len bands = f_extractor.bands channels = f_extractor.channels fs = f_extractor.fs print(('bands:', bands)) n_itrs = len(interp_rows) n_chan = len(channels) lfp_power = np.zeros((n_itrs, n_chan * len(bands))) n_data = lfp_entities[0].item_count lfp = np.zeros((n_data, n_chan)) for i, e in enumerate(lfp_entities): lfp[:, i] = e.get_analog_data() # for i, t in enumerate(interp_rows): # cont_samples = plx.lfp[t-win_len:t].data[:, channels-1] # lfp_power[i, :] = f_extractor.extract_features(cont_samples.T).T #lfp = plx.lfp[:].data[:, channels-1] n_pts = int(win_len * fs) for i, t in enumerate(interp_rows): try: sample_num = int(t * fs) cont_samples = lfp[sample_num-n_pts:sample_num, :] lfp_power[i, :] = f_extractor.extract_features(cont_samples.T).T except: print("Error with LFP decoder training") print((i, t)) pass # TODO -- discard any channel(s) for which the log power in any frequency # bands was ever equal to -inf (i.e., power was equal to 0) # or, perhaps just add a small epsilon inside the log to avoid this # then, remember to do this: extractor_kwargs['channels'] = channels # and reset the units variable return lfp_power, units, extractor_kwargs ######################################################### ##### Reconstruction extractors, used in test cases ##### ######################################################### class ReplaySpikeCountsExtractor(BinnedSpikeCountsExtractor): ''' A "feature extractor" that replays spike counts from an HDF file ''' feature_type = 'spike_counts' def __init__(self, hdf_table, source='spike_counts', cycle_rate=60.0, units=[]): ''' Parameters ---------- hdf_table : HDF table Data table to replay. Usually the 'task' table. source : string, optional, default=spike_counts Column of the HDF table to replay cycle_rate : float, optional, default=60.0 Rate at which the task FSM "cycles", i.e., the rate at which the task will ask for new observations units : iterable, optional, default=[] Names (channel, unit) of the units. If none specified, some fake names are created Returns ------- ReplaySpikeCountsExtractor instance ''' self.idx = 0 self.hdf_table = hdf_table self.source = source self.units = units self.n_subbins = hdf_table[0][source].shape[1] self.last_get_spike_counts_time = 0 self.cycle_rate = cycle_rate n_units = hdf_table[0]['spike_counts'].shape[0] self.feature_dtype = [('spike_counts', 'u4', (n_units, self.n_subbins)), ('bin_edges', 'f8', 2)] def get_spike_ts(self): ''' Make up fake timestamps to go with the spike counts extracted from the HDF file ''' from . import sim_neurons # Get counts from HDF file counts = self.hdf_table[self.idx][self.source] n_subbins = counts.shape[1] # Convert counts to timestamps between (self.idx*1./cycle_rate, (self.idx+1)*1./cycle_rate) # NOTE: this code is mostly copied from riglib.bmi.sim_neurons.CLDASimPointProcessEnsemble ts_data = [] cycle_rate = self.cycle_rate for k in range(n_subbins): fake_time = (self.idx - 1) * 1./cycle_rate + (k + 0.5)*1./cycle_rate*1./n_subbins nonzero_units, = np.nonzero(counts[:,k]) for unit_ind in nonzero_units: n_spikes = counts[unit_ind, k] for m in range(n_spikes): ts = (fake_time, self.units[unit_ind, 0], self.units[unit_ind, 1], fake_time) ts_data.append(ts) ts_dtype_new = sim_neurons.ts_dtype_new return np.array(ts_data, dtype=ts_dtype_new) def get_bin_edges(self, ts): ''' Get the first and last timestamp of spikes in the current "bin" as saved in the HDF file ''' return self.hdf_table[self.idx]['bin_edges'] def __call__(self, *args, **kwargs): ''' See BinnedSpikeCountsExtractor.__call__ for documentation ''' output = super(ReplaySpikeCountsExtractor, self).__call__(*args, **kwargs) if not np.array_equal(output['spike_counts'], self.hdf_table[self.idx][self.source]): print(("spike binning error: ", self.idx)) self.idx += 1 return output class ReplayLFPPowerExtractor(BinnedSpikeCountsExtractor): ''' A "feature extractor" that replays LFP power estimates from an HDF file ''' feature_type = 'lfp_power' def __init__(self, hdf_table, source='lfp_power'): ''' Constructor for ReplayLFPPowerExtractor Parameters ---------- hdf_table : HDF table Data table to replay. Usually the 'task' table. source : string, optional, default=spike_counts Column of the HDF table to replay Returns ------- ReplayLFPPowerExtractor instance ''' self.idx = 0 self.hdf_table = hdf_table self.source = source self.n_subbins = hdf_table[0][source].shape[1] self.last_get_spike_counts_time = 0 n_units = hdf_table[0][source].shape[0] self.feature_dtype = [('lfp_power', 'f8', (n_units, self.n_subbins)), ] def __call__(self, *args, **kwargs): ''' See BinnedSpikeCountsExtractor.__call__ for documentation ''' output = self.hdf_table[self.idx][self.source] self.idx += 1 return dict(lfp_power=output) ################################# ##### Simulation extractors ##### ################################# class SimBinnedSpikeCountsExtractor(BinnedSpikeCountsExtractor): ''' Spike count features are generated by a population of synthetic neurons ''' feature_type = 'spike_counts' def __init__(self, input_device, encoder, n_subbins, units, task=None): ''' Constructor for SimBinnedSpikeCountsExtractor Parameters ---------- input_device: object with a "calc_next_state" method Generate the "intended" next state, e.g., by feedback control policy encoder: callable with 1 argument Maps the "control" input into the spike timestamps of a set of neurons n_subbins: Number of subbins to divide the spike counts into, e.g. 3 are necessary for the PPF units: np.ndarray of shape (N, 2) Each row of the array corresponds to (channel, unit) Returns ------- SimBinnedSpikeCountsExtractor instance ''' self.input_device = input_device print("Yes we go here SimBinnedSpikeCountsExtractor") self.encoder = encoder self.n_subbins = n_subbins self.units = units self.last_get_spike_counts_time = 0 self.feature_dtype = [('spike_counts', 'f8', (len(units), n_subbins)), ('bin_edges', 'f8', 2), ('ctrl_input', 'f8', self.encoder.C.shape[1])] self.task = task self.sim_ctrl = np.zeros((self.encoder.C.shape[1])) def get_spike_ts(self): ''' see BinnedSpikeCountsExtractor.get_spike_ts for docs ''' current_state = self.task.get_current_state() target_state = self.task.get_target_BMI_state() ctrl = self.input_device.calc_next_state(current_state, target_state) #print current_state.T, target_state.T, ctrl.T self.sim_ctrl = ctrl print("Yes we go here SimBinnedSpikeCountsExtractor") ts_data = self.encoder(ctrl) return ts_data class SimDirectObsExtractor(SimBinnedSpikeCountsExtractor): ''' This extractor just passes back the observation vector generated by the encoder ''' def __call__(self, start_time, *args, **kwargs): y_t = self.get_spike_ts(*args, **kwargs) return dict(spike_counts=y_t) ############################################# ##### Feature extractors in development ##### ############################################# class LFPButterBPFPowerExtractor(object): ''' Computes log power of the LFP in different frequency bands (for each channel) in time-domain using Butterworth band-pass filters. ''' feature_type = 'lfp_power' def __init__(self, source, channels=[], bands=default_bands, win_len=0.2, filt_order=5, fs=1000): self.feature_dtype = ('lfp_power', 'u4', (len(channels)*len(bands), 1)) self.source = source self.channels = channels self.bands = bands self.win_len = win_len # secs self.filt_order = filt_order if source is not None: self.fs = source.source.update_freq else: self.fs = fs extractor_kwargs = dict() extractor_kwargs['channels'] = self.channels extractor_kwargs['bands'] = self.bands extractor_kwargs['win_len'] = self.win_len extractor_kwargs['filt_order'] = self.filt_order extractor_kwargs['fs'] = self.fs self.extractor_kwargs = extractor_kwargs self.n_pts = int(self.win_len * self.fs) self.filt_coeffs = dict() for band in bands: nyq = 0.5 * self.fs low = band[0] / nyq high = band[1] / nyq self.filt_coeffs[band] = butter(self.filt_order, [low, high], btype='band') # returns (b, a) self.epsilon = 1e-9 self.last_get_lfp_power_time = 0 # TODO -- is this variable necessary for LFP? def get_cont_samples(self, *args, **kwargs): return self.source.get(self.n_pts, self.channels) def extract_features(self, cont_samples): n_chan = len(self.channels) lfp_power = np.zeros((n_chan * len(self.bands), 1)) for i, band in enumerate(self.bands): b, a = self.filt_coeffs[band] y = lfilter(b, a, cont_samples) lfp_power[i*n_chan:(i+1)*n_chan] = np.log((1. / self.n_pts) * np.sum(y**2, axis=1) + self.epsilon).reshape(-1, 1) return lfp_power def __call__(self, start_time, *args, **kwargs): cont_samples = self.get_cont_samples(*args, **kwargs) # dims of channels x time lfp_power = self.extract_features(cont_samples) self.last_get_lfp_power_time = start_time return dict(lfp_power=lfp_power) @classmethod def extract_from_file(cls, files, neurows, binlen, units, extractor_kwargs, strobe_rate=60.0): '''Compute lfp power features from a blackrock data file.''' nsx_fnames = [name for name in files['blackrock'] if '.ns' in name] # interpolate between the rows to 180 Hz if binlen < 1./strobe_rate: interp_rows = [] neurows = np.hstack([neurows[0] - 1./strobe_rate, neurows]) for r1, r2 in zip(neurows[:-1], neurows[1:]): interp_rows += list(np.linspace(r1, r2, 4)[1:]) interp_rows = np.array(interp_rows) else: step = int(binlen/(1./strobe_rate)) # Downsample kinematic data according to decoder bin length (assumes non-overlapping bins) interp_rows = neurows[::step] # TODO -- for now, use .ns3 or .ns2 file (2 kS/s) nsx_fname = None for fname in nsx_fnames: if '.ns3' in fname: nsx_fname = fname fs_ = 2000 if nsx_fname is None: for fname in nsx_fnames: if '.ns2' in fname: nsx_fname = fname fs_ = 1000 if nsx_fname is None: raise Exception('Need an nsx file --> .ns2 or .ns3 is acceptable. Higher nsx files yield memory errors') extractor_kwargs['fs'] = fs_ # default order of 5 seems to cause problems when fs > 1000 extractor_kwargs['filt_order'] = 3 if nsx_fname[-4:] == '.hdf': nsx_hdf_fname = nsx_fname else: nsx_hdf_fname = nsx_fname + '.hdf' if not os.path.isfile(nsx_hdf_fname): # convert .nsx file to hdf file using Blackrock's n2h5 utility from db.tracker import models models.parse_blackrock_file(None, [nsx_fname], ) import h5py nsx_hdf = h5py.File(nsx_hdf_fname, 'r') # create extractor object f_extractor = LFPButterBPFPowerExtractor(None, **extractor_kwargs) extractor_kwargs = f_extractor.extractor_kwargs win_len = f_extractor.win_len bands = f_extractor.bands channels = f_extractor.channels fs = f_extractor.fs n_itrs = len(interp_rows) n_chan = len(channels) lfp_power = np.zeros((n_itrs, n_chan * len(bands))) n_pts = int(win_len * fs) # for i, t in enumerate(interp_rows): # sample_num = int(t * fs) # # cont_samples = np.zeros((n_chan, n_pts)) # # for j, chan in enumerate(channels): # # chan_str = str(chan).zfill(5) # # path = 'channel/channel%s/continuous_set' % chan_str # # cont_samples[j, :] = nsx_hdf.get(path).value[sample_num-n_pts:sample_num] # cont_samples = abs(np.random.randn(n_chan, n_pts)) # feats = f_extractor.extract_features(cont_samples).T # print feats # lfp_power[i, :] = f_extractor.extract_features(cont_samples).T print(('*' * 40)) print('WARNING: replacing LFP values from .ns3 file with random values!!') print(('*' * 40)) lfp_power = abs(np.random.randn(n_itrs, n_chan * len(bands))) # TODO -- discard any channel(s) for which the log power in any frequency # bands was ever equal to -inf (i.e., power was equal to 0) # or, perhaps just add a small epsilon inside the log to avoid this # then, remember to do this: extractor_kwargs['channels'] = channels # and reset the units variable return lfp_power, units, extractor_kwargs class AIMTMPowerExtractor(LFPMTMPowerExtractor): ''' Multitaper extractor for Plexon analog input channels''' feature_type = 'ai_power' def __init__(self, source, channels=[], bands=default_bands, win_len=0.2, NW=3, fs=1000, **kwargs): #self.feature_dtype = ('lfp_power', 'f8', (len(channels)*len(bands), 1)) self.source = source self.channels = channels self.bands = bands self.win_len = win_len self.NW = NW if source is not None: self.fs = source.source.update_freq else: self.fs = fs extractor_kwargs = dict() extractor_kwargs['channels'] = self.channels extractor_kwargs['bands'] = self.bands extractor_kwargs['win_len'] = self.win_len extractor_kwargs['NW'] = self.NW extractor_kwargs['fs'] = self.fs extractor_kwargs['no_log'] = 'no_log' in kwargs and kwargs['no_log']==True #remove log calculation extractor_kwargs['no_mean'] = 'no_mean' in kwargs and kwargs['no_mean']==True #r self.extractor_kwargs = extractor_kwargs self.n_pts = int(self.win_len * self.fs) self.nfft = 2**int(np.ceil(np.log2(self.n_pts))) # nextpow2(self.n_pts) fft_freqs = np.arange(0., fs, float(fs)/self.nfft)[:self.nfft/2 + 1] self.fft_inds = dict() for band_idx, band in enumerate(bands): self.fft_inds[band_idx] = [freq_idx for freq_idx, freq in enumerate(fft_freqs) if band[0] <= freq < band[1]] extractor_kwargs['fft_inds'] = self.fft_inds extractor_kwargs['fft_freqs'] = fft_freqs self.epsilon = 1e-9 if extractor_kwargs['no_mean']: #Used in lfp 1D control task self.feature_dtype = ('ai_power', 'f8', (len(channels)*len(fft_freqs), 1)) else: #Else: self.feature_dtype = ('ai_power', 'f8', (len(channels)*len(bands), 1)) def __call__(self, start_time, *args, **kwargs): cont_samples = self.get_cont_samples(*args, **kwargs) # dims of channels x time #cont_samples = np.random.randn(len(self.channels), self.n_pts) # change back! lfp_power = self.extract_features(cont_samples) return dict(ai_power=lfp_power) @classmethod def extract_from_file(cls, files, neurows, binlen, units, extractor_kwargs, strobe_rate=60.0): ''' Compute binned spike count features Parameters ---------- plx: neural data file instance neurows: np.ndarray of shape (T,) Timestamps in the plexon time reference corresponding to bin boundaries binlen: float Length of time over which to sum spikes from the specified cells units: np.ndarray of shape (N, 2) List of units that the decoder will be trained on. The first column specifies the electrode number and the second specifies the unit on the electrode extractor_kwargs: dict Any additional parameters to be passed to the feature extractor. This function is agnostic to the actual extractor utilized strobe_rate: 60.0 The rate at which the task sends the sync pulse to the plx file Returns ------- ''' if 'plexon' in files: from plexon import plexfile plx = plexfile.openFile(str(files['plexon'])) # interpolate between the rows to 180 Hz if binlen < 1./strobe_rate: interp_rows = [] neurows = np.hstack([neurows[0] - 1./strobe_rate, neurows]) for r1, r2 in zip(neurows[:-1], neurows[1:]): interp_rows += list(np.linspace(r1, r2, 4)[1:]) interp_rows = np.array(interp_rows) else: step = int(binlen/(1./strobe_rate)) # Downsample kinematic data according to decoder bin length (assumes non-overlapping bins) interp_rows = neurows[::step] # create extractor object f_extractor = AIMTMPowerExtractor(None, **extractor_kwargs) extractor_kwargs = f_extractor.extractor_kwargs win_len = f_extractor.win_len bands = f_extractor.bands channels = f_extractor.channels fs = f_extractor.fs print(('bands:', bands)) n_itrs = len(interp_rows) n_chan = len(channels) lfp_power = np.zeros((n_itrs, n_chan * len(bands))) # for i, t in enumerate(interp_rows): # cont_samples = plx.lfp[t-win_len:t].data[:, channels-1] # lfp_power[i, :] = f_extractor.extract_features(cont_samples.T).T lfp = plx.lfp[:].data[:, channels-1] n_pts = int(win_len * fs) for i, t in enumerate(interp_rows): try: sample_num = int(t * fs) cont_samples = lfp[sample_num-n_pts:sample_num, :] lfp_power[i, :] = f_extractor.extract_features(cont_samples.T).T except: print("Error with LFP decoder training") print((i, t)) pass # TODO -- discard any channel(s) for which the log power in any frequency # bands was ever equal to -inf (i.e., power was equal to 0) # or, perhaps just add a small epsilon inside the log to avoid this # then, remember to do this: extractor_kwargs['channels'] = channels # and reset the units variable return lfp_power, units, extractor_kwargs elif 'blackrock' in files: raise NotImplementedError class AIAmplitudeExtractor(object): ''' Computes the analog input channel amplitude. Out of date... ''' feature_type = 'ai_amplitude' def __init__(self, source, channels=[], win_len=0.1, fs=1000): self.feature_dtype = ('emg_amplitude', 'u4', (len(channels), 1)) self.source = source self.channels = channels self.win_len = win_len if source is not None: self.fs = source.source.update_freq else: self.fs = fs extractor_kwargs = dict() extractor_kwargs['channels'] = self.channels extractor_kwargs['fs'] = self.fs extractor_kwargs['win_len'] = self.win_len self.extractor_kwargs = extractor_kwargs self.n_pts = int(self.win_len * self.fs) def get_cont_samples(self, *args, **kwargs): return self.source.get(self.n_pts, self.channels) def extract_features(self, cont_samples): n_chan = len(self.channels) emg_amplitude = np.mean(cont_samples,axis=1) emg_amplitude = emg_amplitude[:,None] return emg_amplitude def __call__(self, start_time, *args, **kwargs): cont_samples = self.get_cont_samples(*args, **kwargs) # dims of channels x time emg = self.extract_features(cont_samples) return emg, None class WaveformClusterCountExtractor(FeatureExtractor): feature_type = 'cluster_counts' def __init__(self, source, gmm_model_params, n_subbins=1, units=[]): self.feature_dtype = [('cluster_counts', 'f8', (len(units), n_subbins)), ('bin_edges', 'f8', 2)] self.source = source self.gmm_model_params = gmm_model_params self.n_subbins = n_subbins self.units = units self.n_units = len(units) extractor_kwargs = dict() extractor_kwargs['n_subbins'] = self.n_subbins extractor_kwargs['units'] = self.units extractor_kwargs['gmm_model_params'] = gmm_model_params self.extractor_kwargs = extractor_kwargs self.last_get_spike_counts_time = 0 def get_spike_data(self): ''' Get the spike timestamps from the neural data source. This function has no type checking, i.e., it is assumed that the Extractor object was created with the proper source ''' return self.source.get() def get_bin_edges(self, ts): ''' Determine the first and last spike timestamps to allow HDF files created by the BMI to be semi-synchronized with the neural data file ''' if len(ts) == 0: bin_edges = np.array([np.nan, np.nan]) else: min_ind = np.argmin(ts['ts']) max_ind = np.argmax(ts['ts']) bin_edges = np.array([ts[min_ind]['ts'], ts[max_ind]['ts']]) def __call__(self, start_time, *args, **kwargs): spike_data = self.get_spike_data() if len(spike_data) == 0: counts = np.zeros([len(self.units), self.n_subbins]) elif self.n_subbins > 1: subbin_edges = np.linspace(self.last_get_spike_counts_time, start_time, self.n_subbins+1) # Decrease the first subbin index to include any spikes that were # delayed in getting to the task layer due to threading issues # An acceptable delay is 1 sec or less. Realistically, most delays should be # on the millisecond order # subbin_edges[0] -= 1 # subbin_inds = np.digitize(spike_data['arrival_ts'], subbin_edges) # counts = np.vstack([bin_spikes(ts[subbin_inds == k], self.units) for k in range(1, self.n_subbins+1)]).T raise NotImplementedError else: # TODO pull the waveforms waveforms = [] # TODO determine p(class) for each waveform against the model params counts = np.zeros(self.n_units) wf_class_probs = [] for wf in waveforms: raise NotImplementedError # counts = bin_spikes(ts, self.units).reshape(-1, 1) counts = np.array(counts, dtype=np.uint32) bin_edges = self.get_bin_edges(ts) self.last_get_spike_counts_time = start_time return dict(spike_counts=counts, bin_edges=bin_edges) @classmethod def extract_from_file(cls, files, neurows, binlen, units, extractor_kwargs, strobe_rate=60.0): from sklearn.mixture import GMM if 'plexon' in files: from plexon import plexfile plx = plexfile.openFile(str(files['plexon'])) channels = units[:,0] channels = np.unique(channels) np.sort(channels) spike_chans = plx.spikes[:].data['chan'] spike_times = plx.spikes[:].data['ts'] waveforms = plx.spikes[:].waveforms # construct the feature matrix (n_timepoints, n_units) # interpolate between the rows to 180 Hz if binlen < 1./strobe_rate: interp_rows = [] neurows = np.hstack([neurows[0] - 1./strobe_rate, neurows]) for r1, r2 in zip(neurows[:-1], neurows[1:]): interp_rows += list(np.linspace(r1, r2, 4)[1:]) interp_rows = np.array(interp_rows) else: step = int(binlen/(1./strobe_rate)) # Downsample kinematic data according to decoder bin length (assumes non-overlapping bins) interp_rows = neurows[::step] # digitize the spike timestamps into interp_rows spike_bin_ind = np.digitize(spike_times, interp_rows) spike_counts = np.zeros(len(interp_rows), n_units) for ch in channels: ch_waveforms = waveforms[spike_chans == ch] # cluster the waveforms using a GMM # TODO pick the number of components in an unsupervised way! n_components = len(np.nonzero(units[:,0] == ch)[0]) gmm = GMM(n_components=n_components) gmm.fit(ch_waveforms) # store the cluster probabilities back in the same order that the waveforms were extracted wf_probs = gmm.predict_proba(ch_waveforms) ch_spike_bin_inds = spike_bin_ind[spike_chans == ch] ch_inds, = np.nonzero(units[:,0] == ch) # TODO don't assume the units are sorted! for bin_ind, wf_prob in zip(ch_spike_bin_inds, wf_probs): spike_counts[bin_ind, ch_inds] += wf_prob # discard units that never fired at all unit_inds, = np.nonzero(np.sum(spike_counts, axis=0)) units = units[unit_inds,:] spike_counts = spike_counts[:, unit_inds] extractor_kwargs['units'] = units return spike_counts, units, extractor_kwargs else: raise NotImplementedError('Not implemented for blackrock/TDT data yet!') def get_butter_bpf_lfp_power(plx, neurows, binlen, units, extractor_kwargs, strobe_rate=60.0): ''' Compute lfp power features -- corresponds to LFPButterBPFPowerExtractor. ''' # interpolate between the rows to 180 Hz if binlen < 1./strobe_rate: interp_rows = [] neurows = np.hstack([neurows[0] - 1./strobe_rate, neurows]) for r1, r2 in zip(neurows[:-1], neurows[1:]): interp_rows += list(np.linspace(r1, r2, 4)[1:]) interp_rows = np.array(interp_rows) else: step = int(binlen/(1./strobe_rate)) # Downsample kinematic data according to decoder bin length (assumes non-overlapping bins) interp_rows = neurows[::step] # create extractor object f_extractor = extractor.LFPButterBPFPowerExtractor(None, **extractor_kwargs) extractor_kwargs = f_extractor.extractor_kwargs win_len = f_extractor.win_len bands = f_extractor.bands channels = f_extractor.channels fs = f_extractor.fs n_itrs = len(interp_rows) n_chan = len(channels) lfp_power = np.zeros((n_itrs, n_chan * len(bands))) # for i, t in enumerate(interp_rows): # cont_samples = plx.lfp[t-win_len:t].data[:, channels-1] # lfp_power[i, :] = f_extractor.extract_features(cont_samples.T).T lfp = plx.lfp[:].data[:, channels-1] n_pts = int(win_len * fs) for i, t in enumerate(interp_rows): sample_num = int(t * fs) cont_samples = lfp[sample_num-n_pts:sample_num, :] lfp_power[i, :] = f_extractor.extract_features(cont_samples.T).T # TODO -- discard any channel(s) for which the log power in any frequency # bands was ever equal to -inf (i.e., power was equal to 0) # or, perhaps just add a small epsilon inside the log to avoid this # then, remember to do this: extractor_kwargs['channels'] = channels # and reset the units variable return lfp_power, units, extractor_kwargs def get_mtm_lfp_power(plx, neurows, binlen, units, extractor_kwargs, strobe_rate=60.0): ''' Compute lfp power features -- corresponds to LFPMTMPowerExtractor. ''' # interpolate between the rows to 180 Hz if binlen < 1./strobe_rate: interp_rows = [] neurows = np.hstack([neurows[0] - 1./strobe_rate, neurows]) for r1, r2 in zip(neurows[:-1], neurows[1:]): interp_rows += list(np.linspace(r1, r2, 4)[1:]) interp_rows = np.array(interp_rows) else: step = int(binlen/(1./strobe_rate)) # Downsample kinematic data according to decoder bin length (assumes non-overlapping bins) interp_rows = neurows[::step] # create extractor object f_extractor = extractor.LFPMTMPowerExtractor(None, **extractor_kwargs) extractor_kwargs = f_extractor.extractor_kwargs win_len = f_extractor.win_len bands = f_extractor.bands channels = f_extractor.channels fs = f_extractor.fs print(('bands:', bands)) n_itrs = len(interp_rows) n_chan = len(channels) lfp_power = np.zeros((n_itrs, n_chan * len(bands))) # for i, t in enumerate(interp_rows): # cont_samples = plx.lfp[t-win_len:t].data[:, channels-1] # lfp_power[i, :] = f_extractor.extract_features(cont_samples.T).T lfp = plx.lfp[:].data[:, channels-1] n_pts = int(win_len * fs) for i, t in enumerate(interp_rows): sample_num = int(t * fs) cont_samples = lfp[sample_num-n_pts:sample_num, :] lfp_power[i, :] = f_extractor.extract_features(cont_samples.T).T # TODO -- discard any channel(s) for which the log power in any frequency # bands was ever equal to -inf (i.e., power was equal to 0) # or, perhaps just add a small epsilon inside the log to avoid this # then, remember to do this: extractor_kwargs['channels'] = channels # and reset the units variable return lfp_power, units, extractor_kwargs def get_emg_amplitude(plx, neurows, binlen, units, extractor_kwargs, strobe_rate=60.0): ''' Compute EMG features. ''' # interpolate between the rows to 180 Hz if binlen < 1./strobe_rate: interp_rows = [] neurows = np.hstack([neurows[0] - 1./strobe_rate, neurows]) for r1, r2 in zip(neurows[:-1], neurows[1:]): interp_rows += list(np.linspace(r1, r2, 4)[1:]) interp_rows = np.array(interp_rows) else: step = int(binlen/(1./strobe_rate)) # Downsample kinematic data according to decoder bin length (assumes non-overlapping bins) interp_rows = neurows[::step] # create extractor object f_extractor = extractor.EMGAmplitudeExtractor(None, **extractor_kwargs) extractor_kwargs = f_extractor.extractor_kwargs win_len = f_extractor.win_len channels = f_extractor.channels fs = f_extractor.fs n_itrs = len(interp_rows) n_chan = len(channels) emg =
np.zeros((n_itrs, n_chan))
numpy.zeros
import numpy as np import numbers from scipy import sparse from scipy import linalg import scipy.sparse.linalg as spla from mesh import Vertex, Interval, HalfEdge, QuadCell, convert_to_array from function import Map, Nodal, Constant from fem import parse_derivative_info, Basis from inspect import signature import time class GaussRule(): """ Description: ------------ Gaussian Quadrature weights and nodes on reference cell """ def __init__(self, order, element=None, shape=None): """ Constructor Inputs: order: int, order of quadrature rule 1D rule: order in {1,2,3,4,5,6} 2D rule: order in {1,4,9,16,25,36} for quadrilaterals {1,3,7,13} for triangles element: Element object OR shape: str, 'interval', 'triangle', or 'quadrilateral'. """ # # Determine shape of cells # if element is None: # Shape specified directly assert shape is not None, 'Must specify either element or cell shape.' else: # Element given shape = element.cell_type() # Check if shape is supported assert shape in ['interval','triangle','quadrilateral'], \ "Use 'interval', 'triangle', or 'quadrilateral'." # Get dimension dim = 1 if shape=='interval' else 2 # # Tensorize 1D rules if cell is quadrilateral # use_tensor_product_rules = \ ( dim == 1 or shape == 'quadrilateral' ) if use_tensor_product_rules: # # Determine the order of constituent 1D rules # if dim == 1: assert order in [1,2,3,4,5,6], 'Gauss rules in 1D: 1,2,3,4,5,6.' order_1d = order elif dim == 2: assert order in [1,4,9,16,25,36], 'Gauss rules over quads in 2D: 1,4,16,25' order_1d = int(
np.sqrt(order)
numpy.sqrt
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Tests models.parameters """ from __future__ import (absolute_import, division, print_function, unicode_literals) import itertools import pytest import numpy as np from . import irafutil from .. import models, fitting from ..core import Model, FittableModel from ..parameters import Parameter, InputParameterError from ...utils.data import get_pkg_data_filename def setter1(val): return val def setter2(val, model): model.do_something(val) return val * model.p class SetterModel(FittableModel): inputs = ('x', 'y') outputs = ('z',) xc = Parameter(default=1, setter=setter1) yc = Parameter(default=1, setter=setter2) def __init__(self, xc, yc, p): self.p = p # p is a value intended to be used by the setter super(SetterModel, self).__init__() self.xc = xc self.yc = yc def evaluate(self, x, y, xc, yc): return ((x - xc)**2 + (y - yc)**2) def do_something(self, v): pass class TParModel(Model): """ A toy model to test parameters machinery """ coeff = Parameter() e = Parameter() def __init__(self, coeff, e, **kwargs): super(TParModel, self).__init__(coeff=coeff, e=e, **kwargs) @staticmethod def evaluate(coeff, e): pass class MockModel(FittableModel): alpha = Parameter(name='alpha', default=42) @staticmethod def evaluate(*args): pass def test_parameter_properties(): """Test if getting / setting of Parameter properties works.""" m = MockModel() p = m.alpha assert p.name == 'alpha' # Parameter names are immutable with pytest.raises(AttributeError): p.name = 'beta' assert p.fixed is False p.fixed = True assert p.fixed is True assert p.tied is False p.tied = lambda _: 0 p.tied = False assert p.tied is False assert p.min is None p.min = 42 assert p.min == 42 p.min = None assert p.min is None assert p.max is None # TODO: shouldn't setting a max < min give an error? p.max = 41 assert p.max == 41 def test_parameter_operators(): """Test if the parameter arithmetic operators work.""" m = MockModel() par = m.alpha num = 42. val = 3 assert par - val == num - val assert val - par == val - num assert par / val == num / val assert val / par == val / num assert par ** val == num ** val assert val ** par == val ** num assert par < 45 assert par > 41 assert par <= par assert par >= par assert par == par assert -par == -num assert abs(par) == abs(num) class TestParameters(object): def setup_class(self): """ Unit tests for parameters Read an iraf database file created by onedspec.identify. Use the information to create a 1D Chebyshev model and perform the same fit. Create also a gausian model. """ test_file = get_pkg_data_filename('data/idcompspec.fits') f = open(test_file) lines = f.read() reclist = lines.split("begin") f.close() record = irafutil.IdentifyRecord(reclist[1]) self.icoeff = record.coeff order = int(record.fields['order']) self.model = models.Chebyshev1D(order - 1) self.gmodel = models.Gaussian1D(2, mean=3, stddev=4) self.linear_fitter = fitting.LinearLSQFitter() self.x = record.x self.y = record.z self.yy = np.array([record.z, record.z]) def test_set_slice(self): """ Tests updating the parameters attribute with a slice. This is what fitters internally do. """ self.model.parameters[:] = np.array([3, 4, 5, 6, 7]) assert (self.model.parameters == [3., 4., 5., 6., 7.]).all() def test_set_parameters_as_list(self): """Tests updating parameters using a list.""" self.model.parameters = [30, 40, 50, 60, 70] assert (self.model.parameters == [30., 40., 50., 60, 70]).all() def test_set_parameters_as_array(self): """Tests updating parameters using an array.""" self.model.parameters = np.array([3, 4, 5, 6, 7]) assert (self.model.parameters == [3., 4., 5., 6., 7.]).all() def test_set_as_tuple(self): """Tests updating parameters using a tuple.""" self.model.parameters = (1, 2, 3, 4, 5) assert (self.model.parameters == [1, 2, 3, 4, 5]).all() def test_set_model_attr_seq(self): """ Tests updating the parameters attribute when a model's parameter (in this case coeff) is updated. """ self.model.parameters = [0, 0., 0., 0, 0] self.model.c0 = 7 assert (self.model.parameters == [7, 0., 0., 0, 0]).all() def test_set_model_attr_num(self): """Update the parameter list when a model's parameter is updated.""" self.gmodel.amplitude = 7 assert (self.gmodel.parameters == [7, 3, 4]).all() def test_set_item(self): """Update the parameters using indexing.""" self.model.parameters = [1, 2, 3, 4, 5] self.model.parameters[0] = 10. assert (self.model.parameters == [10, 2, 3, 4, 5]).all() assert self.model.c0 == 10 def test_wrong_size1(self): """ Tests raising an error when attempting to reset the parameters using a list of a different size. """ with pytest.raises(InputParameterError): self.model.parameters = [1, 2, 3] def test_wrong_size2(self): """ Tests raising an exception when attempting to update a model's parameter (in this case coeff) with a sequence of the wrong size. """ with pytest.raises(InputParameterError): self.model.c0 = [1, 2, 3] def test_wrong_shape(self): """ Tests raising an exception when attempting to update a model's parameter and the new value has the wrong shape. """ with pytest.raises(InputParameterError): self.gmodel.amplitude = [1, 2] def test_par_against_iraf(self): """ Test the fitter modifies model.parameters. Uses an iraf example. """ new_model = self.linear_fitter(self.model, self.x, self.y) np.testing.assert_allclose( new_model.parameters, np.array([4826.1066602783685, 952.8943813407858, 12.641236013982386, -1.7910672553339604, 0.90252884366711317]), rtol=10 ** (-2)) def testPolynomial1D(self): d = {'c0': 11, 'c1': 12, 'c2': 13, 'c3': 14} p1 = models.Polynomial1D(3, **d) np.testing.assert_equal(p1.parameters, [11, 12, 13, 14]) def test_poly1d_multiple_sets(self): p1 = models.Polynomial1D(3, n_models=3) np.testing.assert_equal(p1.parameters, [0.0, 0.0, 0.0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) np.testing.assert_array_equal(p1.c0, [0, 0, 0]) p1.c0 = [10, 10, 10] np.testing.assert_equal(p1.parameters, [10.0, 10.0, 10.0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) def test_par_slicing(self): """ Test assigning to a parameter slice """ p1 = models.Polynomial1D(3, n_models=3) p1.c0[:2] = [10, 10] np.testing.assert_equal(p1.parameters, [10.0, 10.0, 0.0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) def test_poly2d(self): p2 = models.Polynomial2D(degree=3) p2.c0_0 = 5 np.testing.assert_equal(p2.parameters, [5, 0, 0, 0, 0, 0, 0, 0, 0, 0]) def test_poly2d_multiple_sets(self): kw = {'c0_0': [2, 3], 'c1_0': [1, 2], 'c2_0': [4, 5], 'c0_1': [1, 1], 'c0_2': [2, 2], 'c1_1': [5, 5]} p2 = models.Polynomial2D(2, **kw) np.testing.assert_equal(p2.parameters, [2, 3, 1, 2, 4, 5, 1, 1, 2, 2, 5, 5]) def test_shift_model_parameters1d(self): sh1 = models.Shift(2) sh1.offset = 3 assert sh1.offset == 3 assert sh1.offset.value == 3 def test_scale_model_parametersnd(self): sc1 = models.Scale([2, 2]) sc1.factor = [3, 3] assert np.all(sc1.factor == [3, 3]) np.testing.assert_array_equal(sc1.factor.value, [3, 3]) def test_parameters_wrong_shape(self): sh1 = models.Shift(2) with pytest.raises(InputParameterError): sh1.offset = [3, 3] class TestMultipleParameterSets(object): def setup_class(self): self.x1 = np.arange(1, 10, .1) self.y, self.x = np.mgrid[:10, :7] self.x11 = np.array([self.x1, self.x1]).T self.gmodel = models.Gaussian1D([12, 10], [3.5, 5.2], stddev=[.4, .7], n_models=2) def test_change_par(self): """ Test that a change to one parameter as a set propagates to param_sets. """ self.gmodel.amplitude = [1, 10] np.testing.assert_almost_equal( self.gmodel.param_sets, np.array([[1., 10], [3.5, 5.2], [0.4, 0.7]])) np.all(self.gmodel.parameters == [1.0, 10.0, 3.5, 5.2, 0.4, 0.7]) def test_change_par2(self): """ Test that a change to one single parameter in a set propagates to param_sets. """ self.gmodel.amplitude[0] = 11 np.testing.assert_almost_equal( self.gmodel.param_sets, np.array([[11., 10], [3.5, 5.2], [0.4, 0.7]])) np.all(self.gmodel.parameters == [11.0, 10.0, 3.5, 5.2, 0.4, 0.7]) def test_change_parameters(self): self.gmodel.parameters = [13, 10, 9, 5.2, 0.4, 0.7] np.testing.assert_almost_equal(self.gmodel.amplitude.value, [13., 10.]) np.testing.assert_almost_equal(self.gmodel.mean.value, [9., 5.2]) class TestParameterInitialization(object): """ This suite of tests checks most if not all cases if instantiating a model with parameters of different shapes/sizes and with different numbers of parameter sets. """ def test_single_model_scalar_parameters(self): t = TParModel(10, 1) assert len(t) == 1 assert t.model_set_axis is False assert np.all(t.param_sets == [[10], [1]]) assert np.all(t.parameters == [10, 1]) assert t.coeff.shape == () assert t.e.shape == () def test_single_model_scalar_and_array_parameters(self): t = TParModel(10, [1, 2]) assert len(t) == 1 assert t.model_set_axis is False assert np.issubdtype(t.param_sets.dtype, np.object_) assert len(t.param_sets) == 2 assert np.all(t.param_sets[0] == [10]) assert np.all(t.param_sets[1] == [[1, 2]]) assert np.all(t.parameters == [10, 1, 2]) assert t.coeff.shape == () assert t.e.shape == (2,) def test_single_model_1d_array_parameters(self): t = TParModel([10, 20], [1, 2]) assert len(t) == 1 assert t.model_set_axis is False assert np.all(t.param_sets == [[[10, 20]], [[1, 2]]]) assert np.all(t.parameters == [10, 20, 1, 2]) assert t.coeff.shape == (2,) assert t.e.shape == (2,) def test_single_model_1d_array_different_length_parameters(self): with pytest.raises(InputParameterError): # Not broadcastable t = TParModel([1, 2], [3, 4, 5]) def test_single_model_2d_array_parameters(self): t = TParModel([[10, 20], [30, 40]], [[1, 2], [3, 4]]) assert len(t) == 1 assert t.model_set_axis is False assert np.all(t.param_sets == [[[[10, 20], [30, 40]]], [[[1, 2], [3, 4]]]]) assert np.all(t.parameters == [10, 20, 30, 40, 1, 2, 3, 4]) assert t.coeff.shape == (2, 2) assert t.e.shape == (2, 2) def test_single_model_2d_non_square_parameters(self): coeff = np.array([[10, 20], [30, 40], [50, 60]]) e = np.array([[1, 2], [3, 4], [5, 6]]) t = TParModel(coeff, e) assert len(t) == 1 assert t.model_set_axis is False assert np.all(t.param_sets == [[[[10, 20], [30, 40], [50, 60]]], [[[1, 2], [3, 4], [5, 6]]]]) assert np.all(t.parameters == [10, 20, 30, 40, 50, 60, 1, 2, 3, 4, 5, 6]) assert t.coeff.shape == (3, 2) assert t.e.shape == (3, 2) t2 = TParModel(coeff.T, e.T) assert len(t2) == 1 assert t2.model_set_axis is False assert np.all(t2.param_sets == [[[[10, 30, 50], [20, 40, 60]]], [[[1, 3, 5], [2, 4, 6]]]]) assert np.all(t2.parameters == [10, 30, 50, 20, 40, 60, 1, 3, 5, 2, 4, 6]) assert t2.coeff.shape == (2, 3) assert t2.e.shape == (2, 3) # Not broadcastable with pytest.raises(InputParameterError): TParModel(coeff, e.T) with pytest.raises(InputParameterError): TParModel(coeff.T, e) def test_single_model_2d_broadcastable_parameters(self): t = TParModel([[10, 20, 30], [40, 50, 60]], [1, 2, 3]) assert len(t) == 1 assert t.model_set_axis is False assert len(t.param_sets) == 2 assert np.issubdtype(t.param_sets.dtype, np.object_) assert np.all(t.param_sets[0] == [[[10, 20, 30], [40, 50, 60]]]) assert np.all(t.param_sets[1] == [[1, 2, 3]]) assert np.all(t.parameters == [10, 20, 30, 40, 50, 60, 1, 2, 3]) @pytest.mark.parametrize(('p1', 'p2'), [ (1, 2), (1, [2, 3]), ([1, 2], 3), ([1, 2, 3], [4, 5]), ([1, 2], [3, 4, 5])]) def test_two_model_incorrect_scalar_parameters(self, p1, p2): with pytest.raises(InputParameterError): TParModel(p1, p2, n_models=2) @pytest.mark.parametrize('kwargs', [ {'n_models': 2}, {'model_set_axis': 0}, {'n_models': 2, 'model_set_axis': 0}]) def test_two_model_scalar_parameters(self, kwargs): t = TParModel([10, 20], [1, 2], **kwargs) assert len(t) == 2 assert t.model_set_axis == 0 assert np.all(t.param_sets == [[10, 20], [1, 2]]) assert np.all(t.parameters == [10, 20, 1, 2]) assert t.coeff.shape == () assert t.e.shape == () @pytest.mark.parametrize('kwargs', [ {'n_models': 2}, {'model_set_axis': 0}, {'n_models': 2, 'model_set_axis': 0}]) def test_two_model_scalar_and_array_parameters(self, kwargs): t = TParModel([10, 20], [[1, 2], [3, 4]], **kwargs) assert len(t) == 2 assert t.model_set_axis == 0 assert len(t.param_sets) == 2 assert np.issubdtype(t.param_sets.dtype, np.object_) assert np.all(t.param_sets[0] == [[10], [20]]) assert np.all(t.param_sets[1] == [[1, 2], [3, 4]]) assert np.all(t.parameters == [10, 20, 1, 2, 3, 4]) assert t.coeff.shape == () assert t.e.shape == (2,) def test_two_model_1d_array_parameters(self): t = TParModel([[10, 20], [30, 40]], [[1, 2], [3, 4]], n_models=2) assert len(t) == 2 assert t.model_set_axis == 0 assert np.all(t.param_sets == [[[10, 20], [30, 40]], [[1, 2], [3, 4]]]) assert np.all(t.parameters == [10, 20, 30, 40, 1, 2, 3, 4]) assert t.coeff.shape == (2,) assert t.e.shape == (2,) t2 = TParModel([[10, 20, 30], [40, 50, 60]], [[1, 2, 3], [4, 5, 6]], n_models=2) assert len(t2) == 2 assert t2.model_set_axis == 0 assert np.all(t2.param_sets == [[[10, 20, 30], [40, 50, 60]], [[1, 2, 3], [4, 5, 6]]]) assert np.all(t2.parameters == [10, 20, 30, 40, 50, 60, 1, 2, 3, 4, 5, 6]) assert t2.coeff.shape == (3,) assert t2.e.shape == (3,) def test_two_model_mixed_dimension_array_parameters(self): with pytest.raises(InputParameterError): # Can't broadcast different array shapes TParModel([[[1, 2], [3, 4]], [[5, 6], [7, 8]]], [[9, 10, 11], [12, 13, 14]], n_models=2) t = TParModel([[[10, 20], [30, 40]], [[50, 60], [70, 80]]], [[1, 2], [3, 4]], n_models=2) assert len(t) == 2 assert t.model_set_axis == 0 assert len(t.param_sets) == 2 assert
np.issubdtype(t.param_sets.dtype, np.object_)
numpy.issubdtype
import os import tempfile import numpy as np import scipy.ndimage.measurements as meas from functools import reduce import warnings import sys sys.path.append(os.path.abspath(r'../lib')) import NumCppPy as NumCpp # noqa E402 #################################################################################### def factors(n): return set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))) #################################################################################### def test_seed(): np.random.seed(1) #################################################################################### def test_abs(): randValue = np.random.randint(-100, -1, [1, ]).astype(np.double).item() assert NumCpp.absScaler(randValue) == np.abs(randValue) components = np.random.randint(-100, -1, [2, ]).astype(np.double) value = complex(components[0], components[1]) assert np.round(NumCpp.absScaler(value), 9) == np.round(np.abs(value), 9) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(-100, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.absArray(cArray), np.abs(data)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) data = np.random.randint(-100, 100, [shape.rows, shape.cols]) + \ 1j * np.random.randint(-100, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.absArray(cArray), 9), np.round(np.abs(data), 9)) #################################################################################### def test_add(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArray(shape) data1 = np.random.randint(-100, 100, [shape.rows, shape.cols]) data2 = np.random.randint(-100, 100, [shape.rows, shape.cols]) cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.add(cArray1, cArray2), data1 + data2) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(-100, 100, [shape.rows, shape.cols]) cArray.setArray(data) value = np.random.randint(-100, 100) assert np.array_equal(NumCpp.add(cArray, value), data + value) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(-100, 100, [shape.rows, shape.cols]) cArray.setArray(data) value = np.random.randint(-100, 100) assert np.array_equal(NumCpp.add(value, cArray), data + value) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArrayComplexDouble(shape) cArray2 = NumCpp.NdArrayComplexDouble(shape) real1 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag1 = np.random.randint(1, 100, [shape.rows, shape.cols]) data1 = real1 + 1j * imag1 real2 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag2 = np.random.randint(1, 100, [shape.rows, shape.cols]) data2 = real2 + 1j * imag2 cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.add(cArray1, cArray2), data1 + data2) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) value = np.random.randint(-100, 100) + 1j * np.random.randint(-100, 100) assert np.array_equal(NumCpp.add(cArray, value), data + value) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) value = np.random.randint(-100, 100) + 1j * np.random.randint(-100, 100) assert np.array_equal(NumCpp.add(value, cArray), data + value) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArrayComplexDouble(shape) cArray2 = NumCpp.NdArray(shape) real1 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag1 = np.random.randint(1, 100, [shape.rows, shape.cols]) data1 = real1 + 1j * imag1 data2 = np.random.randint(1, 100, [shape.rows, shape.cols]) cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.add(cArray1, cArray2), data1 + data2) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArrayComplexDouble(shape) data1 = np.random.randint(1, 100, [shape.rows, shape.cols]) real2 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag2 = np.random.randint(1, 100, [shape.rows, shape.cols]) data2 = real2 + 1j * imag2 cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.add(cArray1, cArray2), data1 + data2) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(-100, 100, [shape.rows, shape.cols]) cArray.setArray(data) value = np.random.randint(-100, 100) + 1j * np.random.randint(-100, 100) assert np.array_equal(NumCpp.add(cArray, value), data + value) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(-100, 100, [shape.rows, shape.cols]) cArray.setArray(data) value = np.random.randint(-100, 100) + 1j * np.random.randint(-100, 100) assert np.array_equal(NumCpp.add(value, cArray), data + value) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) value = np.random.randint(-100, 100) assert np.array_equal(NumCpp.add(cArray, value), data + value) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) value = np.random.randint(-100, 100) assert np.array_equal(NumCpp.add(value, cArray), data + value) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArrayComplexDouble(shape) cArray2 = NumCpp.NdArrayComplexDouble(shape) real1 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag1 = np.random.randint(1, 100, [shape.rows, shape.cols]) data1 = real1 + 1j * imag1 real2 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag2 = np.random.randint(1, 100, [shape.rows, shape.cols]) data2 = real2 + 1j * imag2 cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.add(cArray1, cArray2), data1 + data2) #################################################################################### def test_alen(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(-100, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert NumCpp.alen(cArray) == shape.rows #################################################################################### def test_all(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert NumCpp.all(cArray, NumCpp.Axis.NONE).astype(bool).item() == np.all(data).item() shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert NumCpp.all(cArray, NumCpp.Axis.NONE).astype(bool).item() == np.all(data).item() shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.all(cArray, NumCpp.Axis.ROW).flatten().astype(bool), np.all(data, axis=0)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.all(cArray, NumCpp.Axis.ROW).flatten().astype(bool), np.all(data, axis=0)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.all(cArray, NumCpp.Axis.COL).flatten().astype(bool), np.all(data, axis=1)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.all(cArray, NumCpp.Axis.COL).flatten().astype(bool), np.all(data, axis=1)) #################################################################################### def test_allclose(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArray(shape) cArray3 = NumCpp.NdArray(shape) tolerance = 1e-5 data1 = np.random.randn(shape.rows, shape.cols) data2 = data1 + tolerance / 10 data3 = data1 + 1 cArray1.setArray(data1) cArray2.setArray(data2) cArray3.setArray(data3) assert NumCpp.allclose(cArray1, cArray2, tolerance) and not NumCpp.allclose(cArray1, cArray3, tolerance) #################################################################################### def test_amax(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert NumCpp.amax(cArray, NumCpp.Axis.NONE).item() == np.max(data) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert NumCpp.amax(cArray, NumCpp.Axis.NONE).item() == np.max(data) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.amax(cArray, NumCpp.Axis.ROW).flatten(), np.max(data, axis=0)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.amax(cArray, NumCpp.Axis.ROW).flatten(), np.max(data, axis=0)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.amax(cArray, NumCpp.Axis.COL).flatten(), np.max(data, axis=1)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.amax(cArray, NumCpp.Axis.COL).flatten(), np.max(data, axis=1)) #################################################################################### def test_amin(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert NumCpp.amin(cArray, NumCpp.Axis.NONE).item() == np.min(data) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert NumCpp.amin(cArray, NumCpp.Axis.NONE).item() == np.min(data) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.amin(cArray, NumCpp.Axis.ROW).flatten(), np.min(data, axis=0)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.amin(cArray, NumCpp.Axis.ROW).flatten(), np.min(data, axis=0)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.amin(cArray, NumCpp.Axis.COL).flatten(), np.min(data, axis=1)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.amin(cArray, NumCpp.Axis.COL).flatten(), np.min(data, axis=1)) #################################################################################### def test_angle(): components = np.random.randint(-100, -1, [2, ]).astype(np.double) value = complex(components[0], components[1]) assert np.round(NumCpp.angleScaler(value), 9) == np.round(np.angle(value), 9) # noqa shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) data = np.random.randint(-100, 100, [shape.rows, shape.cols]) + \ 1j * np.random.randint(-100, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.angleArray(cArray), 9), np.round(np.angle(data), 9)) #################################################################################### def test_any(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert NumCpp.any(cArray, NumCpp.Axis.NONE).astype(bool).item() == np.any(data).item() shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert NumCpp.any(cArray, NumCpp.Axis.NONE).astype(bool).item() == np.any(data).item() shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.any(cArray, NumCpp.Axis.ROW).flatten().astype(bool), np.any(data, axis=0)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.any(cArray, NumCpp.Axis.ROW).flatten().astype(bool), np.any(data, axis=0)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.any(cArray, NumCpp.Axis.COL).flatten().astype(bool), np.any(data, axis=1)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.any(cArray, NumCpp.Axis.COL).flatten().astype(bool), np.any(data, axis=1)) #################################################################################### def test_append(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArray(shape) data1 = np.random.randint(0, 100, [shape.rows, shape.cols]) data2 = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.append(cArray1, cArray2, NumCpp.Axis.NONE).getNumpyArray().flatten(), np.append(data1, data2)) shapeInput = np.random.randint(20, 100, [2, ]) numRows = np.random.randint(1, 100, [1, ]).item() shape1 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) shape2 = NumCpp.Shape(shapeInput[0].item() + numRows, shapeInput[1].item()) cArray1 = NumCpp.NdArray(shape1) cArray2 = NumCpp.NdArray(shape2) data1 = np.random.randint(0, 100, [shape1.rows, shape1.cols]) data2 = np.random.randint(0, 100, [shape2.rows, shape2.cols]) cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.append(cArray1, cArray2, NumCpp.Axis.ROW).getNumpyArray(), np.append(data1, data2, axis=0)) shapeInput = np.random.randint(20, 100, [2, ]) NumCppols = np.random.randint(1, 100, [1, ]).item() shape1 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) shape2 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item() + NumCppols) cArray1 = NumCpp.NdArray(shape1) cArray2 = NumCpp.NdArray(shape2) data1 = np.random.randint(0, 100, [shape1.rows, shape1.cols]) data2 = np.random.randint(0, 100, [shape2.rows, shape2.cols]) cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.append(cArray1, cArray2, NumCpp.Axis.COL).getNumpyArray(), np.append(data1, data2, axis=1)) #################################################################################### def test_arange(): start = np.random.randn(1).item() stop = np.random.randn(1).item() * 100 step = np.abs(np.random.randn(1).item()) if stop < start: step *= -1 data = np.arange(start, stop, step) assert np.array_equal(np.round(NumCpp.arange(start, stop, step).flatten(), 9), np.round(data, 9)) #################################################################################### def test_arccos(): value = np.abs(np.random.rand(1).item()) assert np.round(NumCpp.arccosScaler(value), 9) == np.round(np.arccos(value), 9) components = np.random.rand(2).astype(np.double) value = complex(components[0], components[1]) assert np.round(NumCpp.arccosScaler(value), 9) == np.round(np.arccos(value), 9) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.rand(shape.rows, shape.cols) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.arccosArray(cArray), 9), np.round(np.arccos(data), 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) data = np.random.rand(shape.rows, shape.cols) + 1j * np.random.rand(shape.rows, shape.cols) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.arccosArray(cArray), 9), np.round(np.arccos(data), 9)) #################################################################################### def test_arccosh(): value = np.abs(np.random.rand(1).item()) + 1 assert np.round(NumCpp.arccoshScaler(value), 9) == np.round(np.arccosh(value), 9) components = np.random.rand(2).astype(np.double) value = complex(components[0], components[1]) assert np.round(NumCpp.arccoshScaler(value), 9) == np.round(np.arccosh(value), 9) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.rand(shape.rows, shape.cols) + 1 cArray.setArray(data) assert np.array_equal(np.round(NumCpp.arccoshArray(cArray), 9), np.round(np.arccosh(data), 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) data = np.random.rand(shape.rows, shape.cols) + 1j * np.random.rand(shape.rows, shape.cols) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.arccoshArray(cArray), 9), np.round(np.arccosh(data), 9)) #################################################################################### def test_arcsin(): value = np.abs(np.random.rand(1).item()) assert np.round(NumCpp.arcsinScaler(value), 9) == np.round(np.arcsin(value), 9) components = np.random.rand(2).astype(np.double) value = complex(components[0], components[1]) assert np.round(NumCpp.arcsinScaler(value), 9) == np.round(np.arcsin(value), 9) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.rand(shape.rows, shape.cols) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.arcsinArray(cArray), 9), np.round(np.arcsin(data), 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) data = np.random.rand(shape.rows, shape.cols) + 1j * np.random.rand(shape.rows, shape.cols) cArray.setArray(data) np.array_equal(np.round(NumCpp.arcsinArray(cArray), 9), np.round(np.arcsin(data), 9)) #################################################################################### def test_arcsinh(): value = np.abs(np.random.rand(1).item()) assert np.round(NumCpp.arcsinhScaler(value), 9) == np.round(np.arcsinh(value), 9) components = np.random.rand(2).astype(np.double) value = complex(components[0], components[1]) assert np.round(NumCpp.arcsinhScaler(value), 9) == np.round(np.arcsinh(value), 9) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.rand(shape.rows, shape.cols) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.arcsinhArray(cArray), 9), np.round(np.arcsinh(data), 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) data = np.random.rand(shape.rows, shape.cols) + 1j * np.random.rand(shape.rows, shape.cols) cArray.setArray(data) np.array_equal(np.round(NumCpp.arcsinhArray(cArray), 9), np.round(np.arcsinh(data), 9)) #################################################################################### def test_arctan(): value = np.abs(np.random.rand(1).item()) assert np.round(NumCpp.arctanScaler(value), 9) == np.round(np.arctan(value), 9) components = np.random.rand(2).astype(np.double) value = complex(components[0], components[1]) assert np.round(NumCpp.arctanScaler(value), 9) == np.round(np.arctan(value), 9) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.rand(shape.rows, shape.cols) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.arctanArray(cArray), 9), np.round(np.arctan(data), 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) data = np.random.rand(shape.rows, shape.cols) + 1j * np.random.rand(shape.rows, shape.cols) cArray.setArray(data) np.array_equal(np.round(NumCpp.arctanArray(cArray), 9), np.round(np.arctan(data), 9)) #################################################################################### def test_arctan2(): xy = np.random.rand(2) * 2 - 1 assert np.round(NumCpp.arctan2Scaler(xy[1], xy[0]), 9) == np.round(np.arctan2(xy[1], xy[0]), 9) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArrayX = NumCpp.NdArray(shape) cArrayY = NumCpp.NdArray(shape) xy = np.random.rand(*shapeInput, 2) * 2 - 1 xData = xy[:, :, 0].reshape(shapeInput) yData = xy[:, :, 1].reshape(shapeInput) cArrayX.setArray(xData) cArrayY.setArray(yData) assert np.array_equal(np.round(NumCpp.arctan2Array(cArrayY, cArrayX), 9), np.round(np.arctan2(yData, xData), 9)) #################################################################################### def test_arctanh(): value = np.abs(np.random.rand(1).item()) assert np.round(NumCpp.arctanhScaler(value), 9) == np.round(np.arctanh(value), 9) components = np.random.rand(2).astype(np.double) value = complex(components[0], components[1]) assert np.round(NumCpp.arctanhScaler(value), 9) == np.round(np.arctanh(value), 9) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.rand(shape.rows, shape.cols) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.arctanhArray(cArray), 9), np.round(np.arctanh(data), 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) data = np.random.rand(shape.rows, shape.cols) + 1j * np.random.rand(shape.rows, shape.cols) cArray.setArray(data) np.array_equal(np.round(NumCpp.arctanhArray(cArray), 9), np.round(np.arctanh(data), 9)) #################################################################################### def test_argmax(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.argmax(cArray, NumCpp.Axis.NONE).item(), np.argmax(data)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.argmax(cArray, NumCpp.Axis.NONE).item(), np.argmax(data)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.argmax(cArray, NumCpp.Axis.ROW).flatten(), np.argmax(data, axis=0)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.argmax(cArray, NumCpp.Axis.ROW).flatten(), np.argmax(data, axis=0)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.argmax(cArray, NumCpp.Axis.COL).flatten(), np.argmax(data, axis=1)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.argmax(cArray, NumCpp.Axis.COL).flatten(), np.argmax(data, axis=1)) #################################################################################### def test_argmin(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.argmin(cArray, NumCpp.Axis.NONE).item(), np.argmin(data)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.argmin(cArray, NumCpp.Axis.NONE).item(), np.argmin(data)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.argmin(cArray, NumCpp.Axis.ROW).flatten(), np.argmin(data, axis=0)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.argmin(cArray, NumCpp.Axis.ROW).flatten(), np.argmin(data, axis=0)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.argmin(cArray, NumCpp.Axis.COL).flatten(), np.argmin(data, axis=1)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.argmin(cArray, NumCpp.Axis.COL).flatten(), np.argmin(data, axis=1)) #################################################################################### def test_argsort(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) dataFlat = data.flatten() assert np.array_equal(dataFlat[NumCpp.argsort(cArray, NumCpp.Axis.NONE).flatten().astype(np.uint32)], dataFlat[np.argsort(data, axis=None)]) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) dataFlat = data.flatten() assert np.array_equal(dataFlat[NumCpp.argsort(cArray, NumCpp.Axis.NONE).flatten().astype(np.uint32)], dataFlat[np.argsort(data, axis=None)]) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) pIdx = np.argsort(data, axis=0) cIdx = NumCpp.argsort(cArray, NumCpp.Axis.ROW).astype(np.uint16) allPass = True for idx, row in enumerate(data.T): if not np.array_equal(row[cIdx[:, idx]], row[pIdx[:, idx]]): allPass = False break assert allPass shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) pIdx = np.argsort(data, axis=0) cIdx = NumCpp.argsort(cArray, NumCpp.Axis.ROW).astype(np.uint16) allPass = True for idx, row in enumerate(data.T): if not np.array_equal(row[cIdx[:, idx]], row[pIdx[:, idx]]): allPass = False break assert allPass shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) pIdx = np.argsort(data, axis=1) cIdx = NumCpp.argsort(cArray, NumCpp.Axis.COL).astype(np.uint16) allPass = True for idx, row in enumerate(data): if not np.array_equal(row[cIdx[idx, :]], row[pIdx[idx, :]]): # noqa allPass = False break assert allPass shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) pIdx = np.argsort(data, axis=1) cIdx = NumCpp.argsort(cArray, NumCpp.Axis.COL).astype(np.uint16) allPass = True for idx, row in enumerate(data): if not np.array_equal(row[cIdx[idx, :]], row[pIdx[idx, :]]): allPass = False break assert allPass #################################################################################### def test_argwhere(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) randValue = np.random.randint(0, 100, [1, ]).item() data2 = data > randValue cArray.setArray(data2) assert np.array_equal(NumCpp.argwhere(cArray).flatten(), np.argwhere(data.flatten() > randValue).flatten()) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag randValue = np.random.randint(0, 100, [1, ]).item() data2 = data > randValue cArray.setArray(data2) assert np.array_equal(NumCpp.argwhere(cArray).flatten(), np.argwhere(data.flatten() > randValue).flatten()) #################################################################################### def test_around(): value = np.abs(np.random.rand(1).item()) * np.random.randint(1, 10, [1, ]).item() numDecimalsRound = np.random.randint(0, 10, [1, ]).astype(np.uint8).item() assert NumCpp.aroundScaler(value, numDecimalsRound) == np.round(value, numDecimalsRound) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.rand(shape.rows, shape.cols) * np.random.randint(1, 10, [1, ]).item() cArray.setArray(data) numDecimalsRound = np.random.randint(0, 10, [1, ]).astype(np.uint8).item() assert np.array_equal(NumCpp.aroundArray(cArray, numDecimalsRound), np.round(data, numDecimalsRound)) #################################################################################### def test_array_equal(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArray(shape) cArray3 = NumCpp.NdArray(shape) data1 = np.random.randint(1, 100, shapeInput) data2 = np.random.randint(1, 100, shapeInput) cArray1.setArray(data1) cArray2.setArray(data1) cArray3.setArray(data2) assert NumCpp.array_equal(cArray1, cArray2) and not NumCpp.array_equal(cArray1, cArray3) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArrayComplexDouble(shape) cArray2 = NumCpp.NdArrayComplexDouble(shape) cArray3 = NumCpp.NdArrayComplexDouble(shape) real1 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag1 = np.random.randint(1, 100, [shape.rows, shape.cols]) data1 = real1 + 1j * imag1 real2 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag2 = np.random.randint(1, 100, [shape.rows, shape.cols]) data2 = real2 + 1j * imag2 cArray1.setArray(data1) cArray2.setArray(data1) cArray3.setArray(data2) assert NumCpp.array_equal(cArray1, cArray2) and not NumCpp.array_equal(cArray1, cArray3) #################################################################################### def test_array_equiv(): shapeInput1 = np.random.randint(1, 100, [2, ]) shapeInput3 = np.random.randint(1, 100, [2, ]) shape1 = NumCpp.Shape(shapeInput1[0].item(), shapeInput1[1].item()) shape2 = NumCpp.Shape(shapeInput1[1].item(), shapeInput1[0].item()) shape3 = NumCpp.Shape(shapeInput3[0].item(), shapeInput3[1].item()) cArray1 = NumCpp.NdArray(shape1) cArray2 = NumCpp.NdArray(shape2) cArray3 = NumCpp.NdArray(shape3) data1 = np.random.randint(1, 100, shapeInput1) data3 = np.random.randint(1, 100, shapeInput3) cArray1.setArray(data1) cArray2.setArray(data1.reshape([shapeInput1[1].item(), shapeInput1[0].item()])) cArray3.setArray(data3) assert NumCpp.array_equiv(cArray1, cArray2) and not NumCpp.array_equiv(cArray1, cArray3) shapeInput1 = np.random.randint(1, 100, [2, ]) shapeInput3 = np.random.randint(1, 100, [2, ]) shape1 = NumCpp.Shape(shapeInput1[0].item(), shapeInput1[1].item()) shape2 = NumCpp.Shape(shapeInput1[1].item(), shapeInput1[0].item()) shape3 = NumCpp.Shape(shapeInput3[0].item(), shapeInput3[1].item()) cArray1 = NumCpp.NdArrayComplexDouble(shape1) cArray2 = NumCpp.NdArrayComplexDouble(shape2) cArray3 = NumCpp.NdArrayComplexDouble(shape3) real1 = np.random.randint(1, 100, [shape1.rows, shape1.cols]) imag1 = np.random.randint(1, 100, [shape1.rows, shape1.cols]) data1 = real1 + 1j * imag1 real3 = np.random.randint(1, 100, [shape3.rows, shape3.cols]) imag3 = np.random.randint(1, 100, [shape3.rows, shape3.cols]) data3 = real3 + 1j * imag3 cArray1.setArray(data1) cArray2.setArray(data1.reshape([shapeInput1[1].item(), shapeInput1[0].item()])) cArray3.setArray(data3) assert NumCpp.array_equiv(cArray1, cArray2) and not NumCpp.array_equiv(cArray1, cArray3) #################################################################################### def test_asarray(): values = np.random.randint(0, 100, [2, ]).astype(np.double) assert np.array_equal(NumCpp.asarrayArray1D(*values).flatten(), values) real = np.random.randint(0, 100, [2, ]).astype(np.double) imag = np.random.randint(0, 100, [2, ]).astype(np.double) values = real + 1j * imag assert np.array_equal(NumCpp.asarrayArray1D(*values).flatten(), values) values = np.random.randint(0, 100, [2, ]).astype(np.double) assert np.array_equal(NumCpp.asarrayArray1DCopy(*values).flatten(), values) real = np.random.randint(0, 100, [2, ]).astype(np.double) imag = np.random.randint(0, 100, [2, ]).astype(np.double) values = real + 1j * imag assert np.array_equal(NumCpp.asarrayArray1DCopy(*values).flatten(), values) values = np.random.randint(0, 100, [2, ]).astype(np.double) data = np.vstack([values, values]) assert np.array_equal(NumCpp.asarrayArray2D(*values), data) real = np.random.randint(0, 100, [2, ]).astype(np.double) imag = np.random.randint(0, 100, [2, ]).astype(np.double) values = real + 1j * imag data = np.vstack([values, values]) assert np.array_equal(NumCpp.asarrayArray2D(*values), data) values = np.random.randint(0, 100, [2, ]).astype(np.double) data = np.vstack([values, values]) assert np.array_equal(NumCpp.asarrayArray2DCopy(*values), data) real = np.random.randint(0, 100, [2, ]).astype(np.double) imag = np.random.randint(0, 100, [2, ]).astype(np.double) values = real + 1j * imag data = np.vstack([values, values]) assert np.array_equal(NumCpp.asarrayArray2DCopy(*values), data) values = np.random.randint(0, 100, [2, ]).astype(np.double) assert np.array_equal(NumCpp.asarrayVector1D(*values).flatten(), values) real = np.random.randint(0, 100, [2, ]).astype(np.double) imag = np.random.randint(0, 100, [2, ]).astype(np.double) values = real + 1j * imag assert np.array_equal(NumCpp.asarrayVector1D(*values).flatten(), values) values = np.random.randint(0, 100, [2, ]).astype(np.double) assert np.array_equal(NumCpp.asarrayVector1DCopy(*values).flatten(), values) real = np.random.randint(0, 100, [2, ]).astype(np.double) imag = np.random.randint(0, 100, [2, ]).astype(np.double) values = real + 1j * imag assert np.array_equal(NumCpp.asarrayVector1DCopy(*values).flatten(), values) values = np.random.randint(0, 100, [2, ]).astype(np.double) data = np.vstack([values, values]) assert np.array_equal(NumCpp.asarrayVector2D(*values), data) real = np.random.randint(0, 100, [2, ]).astype(np.double) imag = np.random.randint(0, 100, [2, ]).astype(np.double) values = real + 1j * imag data = np.vstack([values, values]) assert np.array_equal(NumCpp.asarrayVector2D(*values), data) values = np.random.randint(0, 100, [2, ]).astype(np.double) data = np.vstack([values, values]) assert np.array_equal(NumCpp.asarrayVectorArray2D(*values), data) real = np.random.randint(0, 100, [2, ]).astype(np.double) imag = np.random.randint(0, 100, [2, ]).astype(np.double) values = real + 1j * imag data = np.vstack([values, values]) assert np.array_equal(NumCpp.asarrayVectorArray2D(*values), data) values = np.random.randint(0, 100, [2, ]).astype(np.double) data = np.vstack([values, values]) assert np.array_equal(NumCpp.asarrayVectorArray2DCopy(*values), data) real = np.random.randint(0, 100, [2, ]).astype(np.double) imag = np.random.randint(0, 100, [2, ]).astype(np.double) values = real + 1j * imag data = np.vstack([values, values]) assert np.array_equal(NumCpp.asarrayVectorArray2DCopy(*values), data) values = np.random.randint(0, 100, [2, ]).astype(np.double) assert np.array_equal(NumCpp.asarrayDeque1D(*values).flatten(), values) real = np.random.randint(0, 100, [2, ]).astype(np.double) imag = np.random.randint(0, 100, [2, ]).astype(np.double) values = real + 1j * imag assert np.array_equal(NumCpp.asarrayDeque1D(*values).flatten(), values) values = np.random.randint(0, 100, [2, ]).astype(np.double) data = np.vstack([values, values]) assert np.array_equal(NumCpp.asarrayDeque2D(*values), data) real = np.random.randint(0, 100, [2, ]).astype(np.double) imag = np.random.randint(0, 100, [2, ]).astype(np.double) values = real + 1j * imag data = np.vstack([values, values]) assert np.array_equal(NumCpp.asarrayDeque2D(*values), data) values = np.random.randint(0, 100, [2, ]).astype(np.double) assert np.array_equal(NumCpp.asarrayList(*values).flatten(), values) real = np.random.randint(0, 100, [2, ]).astype(np.double) imag = np.random.randint(0, 100, [2, ]).astype(np.double) values = real + 1j * imag assert np.array_equal(NumCpp.asarrayList(*values).flatten(), values) values = np.random.randint(0, 100, [2, ]).astype(np.double) assert np.array_equal(NumCpp.asarrayIterators(*values).flatten(), values) real = np.random.randint(0, 100, [2, ]).astype(np.double) imag = np.random.randint(0, 100, [2, ]).astype(np.double) values = real + 1j * imag assert np.array_equal(NumCpp.asarrayIterators(*values).flatten(), values) values = np.random.randint(0, 100, [2, ]).astype(np.double) assert np.array_equal(NumCpp.asarrayPointerIterators(*values).flatten(), values) real = np.random.randint(0, 100, [2, ]).astype(np.double) imag = np.random.randint(0, 100, [2, ]).astype(np.double) values = real + 1j * imag assert np.array_equal(NumCpp.asarrayPointerIterators(*values).flatten(), values) values = np.random.randint(0, 100, [2, ]).astype(np.double) assert np.array_equal(NumCpp.asarrayPointer(*values).flatten(), values) real = np.random.randint(0, 100, [2, ]).astype(np.double) imag = np.random.randint(0, 100, [2, ]).astype(np.double) values = real + 1j * imag assert np.array_equal(NumCpp.asarrayPointer(*values).flatten(), values) values = np.random.randint(0, 100, [2, ]).astype(np.double) data = np.vstack([values, values]) assert np.array_equal(NumCpp.asarrayPointer2D(*values), data) real = np.random.randint(0, 100, [2, ]).astype(np.double) imag = np.random.randint(0, 100, [2, ]).astype(np.double) values = real + 1j * imag data = np.vstack([values, values]) assert np.array_equal(NumCpp.asarrayPointer2D(*values), data) values = np.random.randint(0, 100, [2, ]).astype(np.double) assert np.array_equal(NumCpp.asarrayPointerShell(*values).flatten(), values) real = np.random.randint(0, 100, [2, ]).astype(np.double) imag = np.random.randint(0, 100, [2, ]).astype(np.double) values = real + 1j * imag assert np.array_equal(NumCpp.asarrayPointerShell(*values).flatten(), values) values = np.random.randint(0, 100, [2, ]).astype(np.double) data = np.vstack([values, values]) assert np.array_equal(NumCpp.asarrayPointerShell2D(*values), data) real = np.random.randint(0, 100, [2, ]).astype(np.double) imag = np.random.randint(0, 100, [2, ]).astype(np.double) values = real + 1j * imag data = np.vstack([values, values]) assert np.array_equal(NumCpp.asarrayPointerShell2D(*values), data) values = np.random.randint(0, 100, [2, ]).astype(np.double) assert np.array_equal(NumCpp.asarrayPointerShellTakeOwnership(*values).flatten(), values) real = np.random.randint(0, 100, [2, ]).astype(np.double) imag = np.random.randint(0, 100, [2, ]).astype(np.double) values = real + 1j * imag assert np.array_equal(NumCpp.asarrayPointerShellTakeOwnership(*values).flatten(), values) values = np.random.randint(0, 100, [2, ]).astype(np.double) data = np.vstack([values, values]) assert np.array_equal(NumCpp.asarrayPointerShell2DTakeOwnership(*values), data) real = np.random.randint(0, 100, [2, ]).astype(np.double) imag = np.random.randint(0, 100, [2, ]).astype(np.double) values = real + 1j * imag data = np.vstack([values, values]) assert np.array_equal(NumCpp.asarrayPointerShell2DTakeOwnership(*values), data) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) cArrayCast = NumCpp.astypeDoubleToUint32(cArray).getNumpyArray() assert np.array_equal(cArrayCast, data.astype(np.uint32)) assert cArrayCast.dtype == np.uint32 shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) cArrayCast = NumCpp.astypeDoubleToComplex(cArray).getNumpyArray() assert np.array_equal(cArrayCast, data.astype(np.complex128)) assert cArrayCast.dtype == np.complex128 shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) cArrayCast = NumCpp.astypeComplexToComplex(cArray).getNumpyArray() assert np.array_equal(cArrayCast, data.astype(np.complex64)) assert cArrayCast.dtype == np.complex64 shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) cArrayCast = NumCpp.astypeComplexToDouble(cArray).getNumpyArray() warnings.filterwarnings('ignore', category=np.ComplexWarning) assert np.array_equal(cArrayCast, data.astype(np.double)) warnings.filters.pop() # noqa assert cArrayCast.dtype == np.double #################################################################################### def test_average(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.round(NumCpp.average(cArray, NumCpp.Axis.NONE).item(), 9) == np.round(np.average(data), 9) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.round(NumCpp.average(cArray, NumCpp.Axis.NONE).item(), 9) == np.round(np.average(data), 9) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.average(cArray, NumCpp.Axis.ROW).flatten(), 9), np.round(np.average(data, axis=0), 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(np.round(NumCpp.average(cArray, NumCpp.Axis.ROW).flatten(), 9), np.round(np.average(data, axis=0), 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.average(cArray, NumCpp.Axis.COL).flatten(), 9), np.round(np.average(data, axis=1), 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(np.round(NumCpp.average(cArray, NumCpp.Axis.COL).flatten(), 9), np.round(np.average(data, axis=1), 9)) #################################################################################### def test_averageWeighted(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) cWeights = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) weights = np.random.randint(1, 5, [shape.rows, shape.cols]) cArray.setArray(data) cWeights.setArray(weights) assert np.round(NumCpp.averageWeighted(cArray, cWeights, NumCpp.Axis.NONE).item(), 9) == \ np.round(np.average(data, weights=weights), 9) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) cWeights = NumCpp.NdArray(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag weights = np.random.randint(1, 5, [shape.rows, shape.cols]) cArray.setArray(data) cWeights.setArray(weights) assert np.round(NumCpp.averageWeighted(cArray, cWeights, NumCpp.Axis.NONE).item(), 9) == \ np.round(np.average(data, weights=weights), 9) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) cWeights = NumCpp.NdArray(1, shape.cols) data = np.random.randint(0, 100, [shape.rows, shape.cols]) weights = np.random.randint(1, 5, [1, shape.rows]) cArray.setArray(data) cWeights.setArray(weights) assert np.array_equal(np.round(NumCpp.averageWeighted(cArray, cWeights, NumCpp.Axis.ROW).flatten(), 9), np.round(np.average(data, weights=weights.flatten(), axis=0), 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) cWeights = NumCpp.NdArray(1, shape.cols) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag weights = np.random.randint(1, 5, [1, shape.rows]) cArray.setArray(data) cWeights.setArray(weights) assert np.array_equal(np.round(NumCpp.averageWeighted(cArray, cWeights, NumCpp.Axis.ROW).flatten(), 9), np.round(np.average(data, weights=weights.flatten(), axis=0), 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) cWeights = NumCpp.NdArray(1, shape.rows) data = np.random.randint(0, 100, [shape.rows, shape.cols]) weights = np.random.randint(1, 5, [1, shape.cols]) cWeights.setArray(weights) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.averageWeighted(cArray, cWeights, NumCpp.Axis.COL).flatten(), 9), np.round(np.average(data, weights=weights.flatten(), axis=1), 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) cWeights = NumCpp.NdArray(1, shape.rows) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag weights = np.random.randint(1, 5, [1, shape.cols]) cWeights.setArray(weights) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.averageWeighted(cArray, cWeights, NumCpp.Axis.COL).flatten(), 9), np.round(np.average(data, weights=weights.flatten(), axis=1), 9)) #################################################################################### def test_binaryRepr(): value = np.random.randint(0, np.iinfo(np.uint64).max, [1, ], dtype=np.uint64).item() assert NumCpp.binaryRepr(np.uint64(value)) == np.binary_repr(value, np.iinfo(np.uint64).bits) #################################################################################### def test_bincount(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayUInt32(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.uint16) cArray.setArray(data) assert np.array_equal(NumCpp.bincount(cArray, 0).flatten(), np.bincount(data.flatten(), minlength=0)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayUInt32(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.uint16) cArray.setArray(data) minLength = int(np.max(data) + 10) assert np.array_equal(NumCpp.bincount(cArray, minLength).flatten(), np.bincount(data.flatten(), minlength=minLength)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayUInt32(shape) cWeights = NumCpp.NdArrayUInt32(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.uint16) weights = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.uint16) cArray.setArray(data) cWeights.setArray(weights) assert np.array_equal(NumCpp.bincountWeighted(cArray, cWeights, 0).flatten(), np.bincount(data.flatten(), minlength=0, weights=weights.flatten())) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayUInt32(shape) cWeights = NumCpp.NdArrayUInt32(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.uint16) weights = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.uint16) cArray.setArray(data) cWeights.setArray(weights) minLength = int(np.max(data) + 10) assert np.array_equal(NumCpp.bincountWeighted(cArray, cWeights, minLength).flatten(), np.bincount(data.flatten(), minlength=minLength, weights=weights.flatten())) #################################################################################### def test_bitwise_and(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArrayUInt64(shape) cArray2 = NumCpp.NdArrayUInt64(shape) data1 = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.uint64) data2 = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.uint64) cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.bitwise_and(cArray1, cArray2), np.bitwise_and(data1, data2)) #################################################################################### def test_bitwise_not(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayUInt64(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.uint64) cArray.setArray(data) assert np.array_equal(NumCpp.bitwise_not(cArray), np.bitwise_not(data)) #################################################################################### def test_bitwise_or(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArrayUInt64(shape) cArray2 = NumCpp.NdArrayUInt64(shape) data1 = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.uint64) data2 = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.uint64) cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.bitwise_or(cArray1, cArray2), np.bitwise_or(data1, data2)) #################################################################################### def test_bitwise_xor(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArrayUInt64(shape) cArray2 = NumCpp.NdArrayUInt64(shape) data1 = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.uint64) data2 = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.uint64) cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.bitwise_xor(cArray1, cArray2), np.bitwise_xor(data1, data2)) #################################################################################### def test_byteswap(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayUInt64(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.uint64) cArray.setArray(data) assert np.array_equal(NumCpp.byteswap(cArray).shape, shapeInput) #################################################################################### def test_cbrt(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.double) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.cbrtArray(cArray), 9), np.round(np.cbrt(data), 9)) #################################################################################### def test_ceil(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randn(shape.rows, shape.cols).astype(np.double) * 1000 cArray.setArray(data) assert np.array_equal(np.round(NumCpp.ceilArray(cArray), 9), np.round(np.ceil(data), 9)) #################################################################################### def test_center_of_mass(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randn(shape.rows, shape.cols).astype(np.double) * 1000 cArray.setArray(data) assert np.array_equal(np.round(NumCpp.centerOfMass(cArray, NumCpp.Axis.NONE).flatten(), 9), np.round(meas.center_of_mass(data), 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randn(shape.rows, shape.cols).astype(np.double) * 1000 cArray.setArray(data) coms = list() for col in range(data.shape[1]): coms.append(np.round(meas.center_of_mass(data[:, col])[0], 9)) assert np.array_equal(np.round(NumCpp.centerOfMass(cArray, NumCpp.Axis.ROW).flatten(), 9), np.round(coms, 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randn(shape.rows, shape.cols).astype(np.double) * 1000 cArray.setArray(data) coms = list() for row in range(data.shape[0]): coms.append(np.round(meas.center_of_mass(data[row, :])[0], 9)) assert np.array_equal(np.round(NumCpp.centerOfMass(cArray, NumCpp.Axis.COL).flatten(), 9), np.round(coms, 9)) #################################################################################### def test_clip(): value = np.random.randint(0, 100, [1, ]).item() minValue = np.random.randint(0, 10, [1, ]).item() maxValue = np.random.randint(90, 100, [1, ]).item() assert NumCpp.clipScaler(value, minValue, maxValue) == np.clip(value, minValue, maxValue) value = np.random.randint(0, 100, [1, ]).item() + 1j * np.random.randint(0, 100, [1, ]).item() minValue = np.random.randint(0, 10, [1, ]).item() + 1j * np.random.randint(0, 10, [1, ]).item() maxValue = np.random.randint(90, 100, [1, ]).item() + 1j * np.random.randint(0, 100, [1, ]).item() assert NumCpp.clipScaler(value, minValue, maxValue) == np.clip(value, minValue, maxValue) # noqa shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) minValue = np.random.randint(0, 10, [1, ]).item() maxValue = np.random.randint(90, 100, [1, ]).item() assert np.array_equal(NumCpp.clipArray(cArray, minValue, maxValue), np.clip(data, minValue, maxValue)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) minValue = np.random.randint(0, 10, [1, ]).item() + 1j * np.random.randint(0, 10, [1, ]).item() maxValue = np.random.randint(90, 100, [1, ]).item() + 1j * np.random.randint(0, 100, [1, ]).item() assert np.array_equal(NumCpp.clipArray(cArray, minValue, maxValue), np.clip(data, minValue, maxValue)) # noqa #################################################################################### def test_column_stack(): shapeInput = np.random.randint(20, 100, [2, ]) shape1 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) shape2 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item() + np.random.randint(1, 10, [1, ]).item()) shape3 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item() + np.random.randint(1, 10, [1, ]).item()) shape4 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item() + np.random.randint(1, 10, [1, ]).item()) cArray1 = NumCpp.NdArray(shape1) cArray2 = NumCpp.NdArray(shape2) cArray3 = NumCpp.NdArray(shape3) cArray4 = NumCpp.NdArray(shape4) data1 = np.random.randint(1, 100, [shape1.rows, shape1.cols]) data2 = np.random.randint(1, 100, [shape2.rows, shape2.cols]) data3 = np.random.randint(1, 100, [shape3.rows, shape3.cols]) data4 = np.random.randint(1, 100, [shape4.rows, shape4.cols]) cArray1.setArray(data1) cArray2.setArray(data2) cArray3.setArray(data3) cArray4.setArray(data4) assert np.array_equal(NumCpp.column_stack(cArray1, cArray2, cArray3, cArray4), np.column_stack([data1, data2, data3, data4])) #################################################################################### def test_complex(): real = np.random.rand(1).astype(np.double).item() value = complex(real) assert np.round(NumCpp.complexScaler(real), 9) == np.round(value, 9) components = np.random.rand(2).astype(np.double) value = complex(components[0], components[1]) assert np.round(NumCpp.complexScaler(components[0], components[1]), 9) == np.round(value, 9) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) realArray = NumCpp.NdArray(shape) real = np.random.rand(shape.rows, shape.cols) realArray.setArray(real) assert np.array_equal(np.round(NumCpp.complexArray(realArray), 9), np.round(real + 1j * np.zeros_like(real), 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) realArray = NumCpp.NdArray(shape) imagArray = NumCpp.NdArray(shape) real = np.random.rand(shape.rows, shape.cols) imag = np.random.rand(shape.rows, shape.cols) realArray.setArray(real) imagArray.setArray(imag) assert np.array_equal(np.round(NumCpp.complexArray(realArray, imagArray), 9), np.round(real + 1j * imag, 9)) #################################################################################### def test_concatenate(): shapeInput = np.random.randint(20, 100, [2, ]) shape1 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) shape2 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item() + np.random.randint(1, 10, [1, ]).item()) shape3 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item() + np.random.randint(1, 10, [1, ]).item()) shape4 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item() + np.random.randint(1, 10, [1, ]).item()) cArray1 = NumCpp.NdArray(shape1) cArray2 = NumCpp.NdArray(shape2) cArray3 = NumCpp.NdArray(shape3) cArray4 = NumCpp.NdArray(shape4) data1 = np.random.randint(1, 100, [shape1.rows, shape1.cols]) data2 = np.random.randint(1, 100, [shape2.rows, shape2.cols]) data3 = np.random.randint(1, 100, [shape3.rows, shape3.cols]) data4 = np.random.randint(1, 100, [shape4.rows, shape4.cols]) cArray1.setArray(data1) cArray2.setArray(data2) cArray3.setArray(data3) cArray4.setArray(data4) assert np.array_equal(NumCpp.concatenate(cArray1, cArray2, cArray3, cArray4, NumCpp.Axis.NONE).flatten(), np.concatenate([data1.flatten(), data2.flatten(), data3.flatten(), data4.flatten()])) shapeInput = np.random.randint(20, 100, [2, ]) shape1 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) shape2 = NumCpp.Shape(shapeInput[0].item() + np.random.randint(1, 10, [1, ]).item(), shapeInput[1].item()) shape3 = NumCpp.Shape(shapeInput[0].item() + np.random.randint(1, 10, [1, ]).item(), shapeInput[1].item()) shape4 = NumCpp.Shape(shapeInput[0].item() + np.random.randint(1, 10, [1, ]).item(), shapeInput[1].item()) cArray1 = NumCpp.NdArray(shape1) cArray2 = NumCpp.NdArray(shape2) cArray3 = NumCpp.NdArray(shape3) cArray4 = NumCpp.NdArray(shape4) data1 = np.random.randint(1, 100, [shape1.rows, shape1.cols]) data2 = np.random.randint(1, 100, [shape2.rows, shape2.cols]) data3 = np.random.randint(1, 100, [shape3.rows, shape3.cols]) data4 = np.random.randint(1, 100, [shape4.rows, shape4.cols]) cArray1.setArray(data1) cArray2.setArray(data2) cArray3.setArray(data3) cArray4.setArray(data4) assert np.array_equal(NumCpp.concatenate(cArray1, cArray2, cArray3, cArray4, NumCpp.Axis.ROW), np.concatenate([data1, data2, data3, data4], axis=0)) shapeInput = np.random.randint(20, 100, [2, ]) shape1 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) shape2 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item() + np.random.randint(1, 10, [1, ]).item()) shape3 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item() + np.random.randint(1, 10, [1, ]).item()) shape4 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item() + np.random.randint(1, 10, [1, ]).item()) cArray1 = NumCpp.NdArray(shape1) cArray2 = NumCpp.NdArray(shape2) cArray3 = NumCpp.NdArray(shape3) cArray4 = NumCpp.NdArray(shape4) data1 = np.random.randint(1, 100, [shape1.rows, shape1.cols]) data2 = np.random.randint(1, 100, [shape2.rows, shape2.cols]) data3 = np.random.randint(1, 100, [shape3.rows, shape3.cols]) data4 = np.random.randint(1, 100, [shape4.rows, shape4.cols]) cArray1.setArray(data1) cArray2.setArray(data2) cArray3.setArray(data3) cArray4.setArray(data4) assert np.array_equal(NumCpp.concatenate(cArray1, cArray2, cArray3, cArray4, NumCpp.Axis.COL), np.concatenate([data1, data2, data3, data4], axis=1)) #################################################################################### def test_conj(): components = np.random.rand(2).astype(np.double) value = complex(components[0], components[1]) assert np.round(NumCpp.conjScaler(value), 9) == np.round(np.conj(value), 9) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) data = np.random.rand(shape.rows, shape.cols) + 1j * np.random.rand(shape.rows, shape.cols) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.conjArray(cArray), 9), np.round(np.conj(data), 9)) #################################################################################### def test_contains(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) value = np.random.randint(0, 100, [1, ]).item() cArray.setArray(data) assert NumCpp.contains(cArray, value, NumCpp.Axis.NONE).getNumpyArray().item() == (value in data) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag value = np.random.randint(0, 100, [1, ]).item() + 1j * np.random.randint(0, 100, [1, ]).item() cArray.setArray(data) assert NumCpp.contains(cArray, value, NumCpp.Axis.NONE).getNumpyArray().item() == (value in data) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) value = np.random.randint(0, 100, [1, ]).item() cArray.setArray(data) truth = list() for row in data: truth.append(value in row) assert np.array_equal(NumCpp.contains(cArray, value, NumCpp.Axis.COL).getNumpyArray().flatten(), np.asarray(truth)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag value = np.random.randint(0, 100, [1, ]).item() + 1j * np.random.randint(0, 100, [1, ]).item() cArray.setArray(data) truth = list() for row in data: truth.append(value in row) assert np.array_equal(NumCpp.contains(cArray, value, NumCpp.Axis.COL).getNumpyArray().flatten(), np.asarray(truth)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) value = np.random.randint(0, 100, [1, ]).item() cArray.setArray(data) truth = list() for row in data.T: truth.append(value in row) assert np.array_equal(NumCpp.contains(cArray, value, NumCpp.Axis.ROW).getNumpyArray().flatten(), np.asarray(truth)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag value = np.random.randint(0, 100, [1, ]).item() + 1j * np.random.randint(0, 100, [1, ]).item() cArray.setArray(data) truth = list() for row in data.T: truth.append(value in row) assert np.array_equal(NumCpp.contains(cArray, value, NumCpp.Axis.ROW).getNumpyArray().flatten(), np.asarray(truth)) #################################################################################### def test_copy(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.copy(cArray), data) #################################################################################### def test_copysign(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArray(shape) data1 = np.random.randint(-100, 100, [shape.rows, shape.cols]) data2 = np.random.randint(-100, 100, [shape.rows, shape.cols]) cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.copysign(cArray1, cArray2), np.copysign(data1, data2)) #################################################################################### def test_copyto(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArray() data1 = np.random.randint(-100, 100, [shape.rows, shape.cols]) cArray1.setArray(data1) assert np.array_equal(NumCpp.copyto(cArray2, cArray1), data1) #################################################################################### def test_cos(): value = np.abs(np.random.rand(1).item()) assert np.round(NumCpp.cosScaler(value), 9) == np.round(np.cos(value), 9) components = np.random.rand(2).astype(np.double) value = complex(components[0], components[1]) assert np.round(NumCpp.cosScaler(value), 9) == np.round(np.cos(value), 9) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.rand(shape.rows, shape.cols) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.cosArray(cArray), 9), np.round(np.cos(data), 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) data = np.random.rand(shape.rows, shape.cols) + 1j * np.random.rand(shape.rows, shape.cols) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.cosArray(cArray), 9), np.round(np.cos(data), 9)) #################################################################################### def test_cosh(): value = np.abs(np.random.rand(1).item()) assert np.round(NumCpp.coshScaler(value), 9) == np.round(np.cosh(value), 9) components = np.random.rand(2).astype(np.double) value = complex(components[0], components[1]) assert np.round(NumCpp.coshScaler(value), 9) == np.round(np.cosh(value), 9) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.rand(shape.rows, shape.cols) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.coshArray(cArray), 9), np.round(np.cosh(data), 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) data = np.random.rand(shape.rows, shape.cols) + 1j * np.random.rand(shape.rows, shape.cols) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.coshArray(cArray), 9), np.round(np.cosh(data), 9)) #################################################################################### def test_count_nonzero(): shapeInput = np.random.randint(1, 50, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 3, [shape.rows, shape.cols], dtype=np.uint32) cArray.setArray(data) assert NumCpp.count_nonzero(cArray, NumCpp.Axis.NONE) == np.count_nonzero(data) shapeInput = np.random.randint(1, 50, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 3, [shape.rows, shape.cols]) imag = np.random.randint(1, 3, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert NumCpp.count_nonzero(cArray, NumCpp.Axis.NONE) == np.count_nonzero(data) shapeInput = np.random.randint(1, 50, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 3, [shape.rows, shape.cols], dtype=np.uint32) cArray.setArray(data) assert np.array_equal(NumCpp.count_nonzero(cArray, NumCpp.Axis.ROW).flatten(), np.count_nonzero(data, axis=0)) shapeInput = np.random.randint(1, 50, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 3, [shape.rows, shape.cols]) imag = np.random.randint(1, 3, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.count_nonzero(cArray, NumCpp.Axis.ROW).flatten(), np.count_nonzero(data, axis=0)) shapeInput = np.random.randint(1, 50, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 3, [shape.rows, shape.cols], dtype=np.uint32) cArray.setArray(data) assert np.array_equal(NumCpp.count_nonzero(cArray, NumCpp.Axis.COL).flatten(), np.count_nonzero(data, axis=1)) shapeInput = np.random.randint(1, 50, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 3, [shape.rows, shape.cols]) imag = np.random.randint(1, 3, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.count_nonzero(cArray, NumCpp.Axis.COL).flatten(), np.count_nonzero(data, axis=1)) #################################################################################### def test_cross(): shape = NumCpp.Shape(1, 2) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArray(shape) data1 = np.random.randint(1, 10, [shape.rows, shape.cols]).astype(np.double) data2 = np.random.randint(1, 10, [shape.rows, shape.cols]).astype(np.double) cArray1.setArray(data1) cArray2.setArray(data2) assert NumCpp.cross(cArray1, cArray2, NumCpp.Axis.NONE).item() == np.cross(data1, data2).item() shape = NumCpp.Shape(1, 2) cArray1 = NumCpp.NdArrayComplexDouble(shape) cArray2 = NumCpp.NdArrayComplexDouble(shape) real1 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag1 = np.random.randint(1, 100, [shape.rows, shape.cols]) data1 = real1 + 1j * imag1 real2 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag2 = np.random.randint(1, 100, [shape.rows, shape.cols]) data2 = real2 + 1j * imag2 cArray1.setArray(data1) cArray2.setArray(data2) assert NumCpp.cross(cArray1, cArray2, NumCpp.Axis.NONE).item() == np.cross(data1, data2).item() shape = NumCpp.Shape(2, np.random.randint(1, 100, [1, ]).item()) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArray(shape) data1 = np.random.randint(1, 10, [shape.rows, shape.cols]).astype(np.double) data2 = np.random.randint(1, 10, [shape.rows, shape.cols]).astype(np.double) cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.cross(cArray1, cArray2, NumCpp.Axis.ROW).getNumpyArray().flatten(), np.cross(data1, data2, axis=0)) shape = NumCpp.Shape(2, np.random.randint(1, 100, [1, ]).item()) cArray1 = NumCpp.NdArrayComplexDouble(shape) cArray2 = NumCpp.NdArrayComplexDouble(shape) real1 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag1 = np.random.randint(1, 100, [shape.rows, shape.cols]) data1 = real1 + 1j * imag1 real2 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag2 = np.random.randint(1, 100, [shape.rows, shape.cols]) data2 = real2 + 1j * imag2 cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.cross(cArray1, cArray2, NumCpp.Axis.ROW).getNumpyArray().flatten(), np.cross(data1, data2, axis=0)) shape = NumCpp.Shape(np.random.randint(1, 100, [1, ]).item(), 2) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArray(shape) data1 = np.random.randint(1, 10, [shape.rows, shape.cols]).astype(np.double) data2 = np.random.randint(1, 10, [shape.rows, shape.cols]).astype(np.double) cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.cross(cArray1, cArray2, NumCpp.Axis.COL).getNumpyArray().flatten(), np.cross(data1, data2, axis=1)) shape = NumCpp.Shape(np.random.randint(1, 100, [1, ]).item(), 2) cArray1 = NumCpp.NdArrayComplexDouble(shape) cArray2 = NumCpp.NdArrayComplexDouble(shape) real1 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag1 = np.random.randint(1, 100, [shape.rows, shape.cols]) data1 = real1 + 1j * imag1 real2 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag2 = np.random.randint(1, 100, [shape.rows, shape.cols]) data2 = real2 + 1j * imag2 cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.cross(cArray1, cArray2, NumCpp.Axis.COL).getNumpyArray().flatten(), np.cross(data1, data2, axis=1)) shape = NumCpp.Shape(1, 3) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArray(shape) data1 = np.random.randint(1, 10, [shape.rows, shape.cols]).astype(np.double) data2 = np.random.randint(1, 10, [shape.rows, shape.cols]).astype(np.double) cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.cross(cArray1, cArray2, NumCpp.Axis.NONE).getNumpyArray().flatten(), np.cross(data1, data2).flatten()) shape = NumCpp.Shape(1, 3) cArray1 = NumCpp.NdArrayComplexDouble(shape) cArray2 = NumCpp.NdArrayComplexDouble(shape) real1 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag1 = np.random.randint(1, 100, [shape.rows, shape.cols]) data1 = real1 + 1j * imag1 real2 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag2 = np.random.randint(1, 100, [shape.rows, shape.cols]) data2 = real2 + 1j * imag2 cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.cross(cArray1, cArray2, NumCpp.Axis.NONE).getNumpyArray().flatten(), np.cross(data1, data2).flatten()) shape = NumCpp.Shape(3, np.random.randint(1, 100, [1, ]).item()) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArray(shape) data1 = np.random.randint(1, 10, [shape.rows, shape.cols]).astype(np.double) data2 = np.random.randint(1, 10, [shape.rows, shape.cols]).astype(np.double) cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.cross(cArray1, cArray2, NumCpp.Axis.ROW).getNumpyArray(), np.cross(data1, data2, axis=0)) shape = NumCpp.Shape(3, np.random.randint(1, 100, [1, ]).item()) cArray1 = NumCpp.NdArrayComplexDouble(shape) cArray2 = NumCpp.NdArrayComplexDouble(shape) real1 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag1 = np.random.randint(1, 100, [shape.rows, shape.cols]) data1 = real1 + 1j * imag1 real2 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag2 = np.random.randint(1, 100, [shape.rows, shape.cols]) data2 = real2 + 1j * imag2 cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.cross(cArray1, cArray2, NumCpp.Axis.ROW).getNumpyArray(), np.cross(data1, data2, axis=0)) shape = NumCpp.Shape(np.random.randint(1, 100, [1, ]).item(), 3) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArray(shape) data1 = np.random.randint(1, 10, [shape.rows, shape.cols]).astype(np.double) data2 = np.random.randint(1, 10, [shape.rows, shape.cols]).astype(np.double) cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.cross(cArray1, cArray2, NumCpp.Axis.COL).getNumpyArray(), np.cross(data1, data2, axis=1)) shape = NumCpp.Shape(np.random.randint(1, 100, [1, ]).item(), 3) cArray1 = NumCpp.NdArrayComplexDouble(shape) cArray2 = NumCpp.NdArrayComplexDouble(shape) real1 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag1 = np.random.randint(1, 100, [shape.rows, shape.cols]) data1 = real1 + 1j * imag1 real2 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag2 = np.random.randint(1, 100, [shape.rows, shape.cols]) data2 = real2 + 1j * imag2 cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.cross(cArray1, cArray2, NumCpp.Axis.COL).getNumpyArray(), np.cross(data1, data2, axis=1)) #################################################################################### def test_cube(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.rand(shape.rows, shape.cols) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.cube(cArray), 9), np.round(data * data * data, 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(np.round(NumCpp.cube(cArray), 9), np.round(data * data * data, 9)) #################################################################################### def test_cumprod(): shapeInput = np.random.randint(1, 5, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 4, [shape.rows, shape.cols], dtype=np.uint32) cArray.setArray(data) assert np.array_equal(NumCpp.cumprod(cArray, NumCpp.Axis.NONE).flatten(), data.cumprod()) shapeInput = np.random.randint(1, 5, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 4, [shape.rows, shape.cols]) imag = np.random.randint(1, 4, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.cumprod(cArray, NumCpp.Axis.NONE).flatten(), data.cumprod()) shapeInput = np.random.randint(1, 5, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 4, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.cumprod(cArray, NumCpp.Axis.ROW), data.cumprod(axis=0)) shapeInput = np.random.randint(1, 5, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 4, [shape.rows, shape.cols]) imag = np.random.randint(1, 4, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.cumprod(cArray, NumCpp.Axis.ROW), data.cumprod(axis=0)) shapeInput = np.random.randint(1, 5, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 4, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.cumprod(cArray, NumCpp.Axis.COL), data.cumprod(axis=1)) shapeInput = np.random.randint(1, 5, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 4, [shape.rows, shape.cols]) imag = np.random.randint(1, 4, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.cumprod(cArray, NumCpp.Axis.COL), data.cumprod(axis=1)) #################################################################################### def test_cumsum(): shapeInput = np.random.randint(1, 50, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 50, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.cumsum(cArray, NumCpp.Axis.NONE).flatten(), data.cumsum()) shapeInput = np.random.randint(1, 50, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 50, [shape.rows, shape.cols]) imag = np.random.randint(1, 50, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.cumsum(cArray, NumCpp.Axis.NONE).flatten(), data.cumsum()) shapeInput = np.random.randint(1, 50, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 50, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.cumsum(cArray, NumCpp.Axis.ROW), data.cumsum(axis=0)) shapeInput = np.random.randint(1, 50, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 50, [shape.rows, shape.cols]) imag = np.random.randint(1, 50, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.cumsum(cArray, NumCpp.Axis.ROW), data.cumsum(axis=0)) shapeInput = np.random.randint(1, 50, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 50, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.cumsum(cArray, NumCpp.Axis.COL), data.cumsum(axis=1)) shapeInput = np.random.randint(1, 50, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 50, [shape.rows, shape.cols]) imag = np.random.randint(1, 50, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.cumsum(cArray, NumCpp.Axis.COL), data.cumsum(axis=1)) #################################################################################### def test_deg2rad(): value = np.abs(np.random.rand(1).item()) * 360 assert np.round(NumCpp.deg2radScaler(value), 9) == np.round(np.deg2rad(value), 9) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.rand(shape.rows, shape.cols) * 360 cArray.setArray(data) assert np.array_equal(np.round(NumCpp.deg2radArray(cArray), 9), np.round(np.deg2rad(data), 9)) #################################################################################### def test_degrees(): value = np.abs(np.random.rand(1).item()) * 2 * np.pi assert np.round(NumCpp.degreesScaler(value), 9) == np.round(np.degrees(value), 9) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.rand(shape.rows, shape.cols) * 2 * np.pi cArray.setArray(data) assert np.array_equal(np.round(NumCpp.degreesArray(cArray), 9), np.round(np.degrees(data), 9)) #################################################################################### def test_deleteIndices(): shapeInput = np.asarray([100, 100]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 100, [shape.rows, shape.cols]) indices = NumCpp.Slice(0, 100, 4) indicesPy = slice(0, 99, 4) cArray.setArray(data) assert np.array_equal(NumCpp.deleteIndicesSlice(cArray, indices, NumCpp.Axis.NONE).flatten(), np.delete(data, indicesPy, axis=None)) shapeInput = np.asarray([100, 100]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 100, [shape.rows, shape.cols]) indices = NumCpp.Slice(0, 100, 4) indicesPy = slice(0, 99, 4) cArray.setArray(data) assert np.array_equal(NumCpp.deleteIndicesSlice(cArray, indices, NumCpp.Axis.ROW), np.delete(data, indicesPy, axis=0)) shapeInput = np.asarray([100, 100]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 100, [shape.rows, shape.cols]) indices = NumCpp.Slice(0, 100, 4) indicesPy = slice(0, 99, 4) cArray.setArray(data) assert np.array_equal(NumCpp.deleteIndicesSlice(cArray, indices, NumCpp.Axis.COL), np.delete(data, indicesPy, axis=1)) shapeInput = np.asarray([100, 100]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 100, [shape.rows, shape.cols]) index = np.random.randint(0, shape.size(), [1, ]).item() cArray.setArray(data) assert np.array_equal(NumCpp.deleteIndicesScaler(cArray, index, NumCpp.Axis.NONE).flatten(), np.delete(data, index, axis=None)) shapeInput = np.asarray([100, 100]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 100, [shape.rows, shape.cols]) index = np.random.randint(0, 100, [1, ]).item() cArray.setArray(data) assert np.array_equal(NumCpp.deleteIndicesScaler(cArray, index, NumCpp.Axis.ROW), np.delete(data, index, axis=0)) shapeInput = np.asarray([100, 100]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 100, [shape.rows, shape.cols]) index = np.random.randint(0, 100, [1, ]).item() cArray.setArray(data) assert np.array_equal(NumCpp.deleteIndicesScaler(cArray, index, NumCpp.Axis.COL), np.delete(data, index, axis=1)) #################################################################################### def test_diag(): shapeInput = np.random.randint(2, 25, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) k = np.random.randint(0, np.min(shapeInput), [1, ]).item() elements = np.random.randint(1, 100, shapeInput) cElements = NumCpp.NdArray(shape) cElements.setArray(elements) assert np.array_equal(NumCpp.diag(cElements, k).flatten(), np.diag(elements, k)) shapeInput = np.random.randint(2, 25, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) k = np.random.randint(0, np.min(shapeInput), [1, ]).item() real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) elements = real + 1j * imag cElements = NumCpp.NdArrayComplexDouble(shape) cElements.setArray(elements) assert np.array_equal(NumCpp.diag(cElements, k).flatten(), np.diag(elements, k)) #################################################################################### def test_diagflat(): numElements = np.random.randint(2, 25, [1, ]).item() shape = NumCpp.Shape(1, numElements) k = np.random.randint(0, 10, [1, ]).item() elements = np.random.randint(1, 100, [numElements, ]) cElements = NumCpp.NdArray(shape) cElements.setArray(elements) assert np.array_equal(NumCpp.diagflat(cElements, k), np.diagflat(elements, k)) numElements = np.random.randint(2, 25, [1, ]).item() shape = NumCpp.Shape(1, numElements) k = np.random.randint(0, 10, [1, ]).item() real = np.random.randint(1, 100, [numElements, ]) imag = np.random.randint(1, 100, [numElements, ]) elements = real + 1j * imag cElements = NumCpp.NdArrayComplexDouble(shape) cElements.setArray(elements) assert np.array_equal(NumCpp.diagflat(cElements, k), np.diagflat(elements, k)) numElements = np.random.randint(1, 25, [1, ]).item() shape = NumCpp.Shape(1, numElements) k = np.random.randint(0, 10, [1, ]).item() elements = np.random.randint(1, 100, [numElements, ]) cElements = NumCpp.NdArray(shape) cElements.setArray(elements) assert np.array_equal(NumCpp.diagflat(cElements, k), np.diagflat(elements, k)) numElements = np.random.randint(1, 25, [1, ]).item() shape = NumCpp.Shape(1, numElements) k = np.random.randint(0, 10, [1, ]).item() real = np.random.randint(1, 100, [numElements, ]) imag = np.random.randint(1, 100, [numElements, ]) elements = real + 1j * imag cElements = NumCpp.NdArrayComplexDouble(shape) cElements.setArray(elements) assert np.array_equal(NumCpp.diagflat(cElements, k), np.diagflat(elements, k)) #################################################################################### def test_diagonal(): shapeInput = np.random.randint(1, 50, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 50, [shape.rows, shape.cols]) cArray.setArray(data) offset = np.random.randint(0, min(shape.rows, shape.cols), [1, ]).item() assert np.array_equal(NumCpp.diagonal(cArray, offset, NumCpp.Axis.ROW).flatten(), np.diagonal(data, offset, axis1=0, axis2=1)) shapeInput = np.random.randint(1, 50, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 50, [shape.rows, shape.cols]) imag = np.random.randint(1, 50, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) offset = np.random.randint(0, min(shape.rows, shape.cols), [1, ]).item() assert np.array_equal(NumCpp.diagonal(cArray, offset, NumCpp.Axis.ROW).flatten(), np.diagonal(data, offset, axis1=0, axis2=1)) shapeInput = np.random.randint(1, 50, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 50, [shape.rows, shape.cols]) cArray.setArray(data) offset = np.random.randint(0, min(shape.rows, shape.cols), [1, ]).item() assert np.array_equal(NumCpp.diagonal(cArray, offset, NumCpp.Axis.COL).flatten(), np.diagonal(data, offset, axis1=1, axis2=0)) shapeInput = np.random.randint(1, 50, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 50, [shape.rows, shape.cols]) imag = np.random.randint(1, 50, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) offset = np.random.randint(0, min(shape.rows, shape.cols), [1, ]).item() assert np.array_equal(NumCpp.diagonal(cArray, offset, NumCpp.Axis.COL).flatten(), np.diagonal(data, offset, axis1=1, axis2=0)) #################################################################################### def test_diff(): shapeInput = np.random.randint(10, 50, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 50, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.diff(cArray, NumCpp.Axis.NONE).flatten(), np.diff(data.flatten())) shapeInput = np.random.randint(10, 50, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 50, [shape.rows, shape.cols]) imag = np.random.randint(1, 50, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.diff(cArray, NumCpp.Axis.NONE).flatten(), np.diff(data.flatten())) shapeInput = np.random.randint(10, 50, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 50, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.diff(cArray, NumCpp.Axis.ROW), np.diff(data, axis=0)) shapeInput = np.random.randint(10, 50, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 50, [shape.rows, shape.cols]) imag = np.random.randint(1, 50, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.diff(cArray, NumCpp.Axis.ROW), np.diff(data, axis=0)) shapeInput = np.random.randint(10, 50, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 50, [shape.rows, shape.cols]).astype(np.uint32) cArray.setArray(data) assert np.array_equal(NumCpp.diff(cArray, NumCpp.Axis.COL).astype(np.uint32), np.diff(data, axis=1)) shapeInput = np.random.randint(10, 50, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 50, [shape.rows, shape.cols]) imag = np.random.randint(1, 50, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.diff(cArray, NumCpp.Axis.COL), np.diff(data, axis=1)) #################################################################################### def test_divide(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArray(shape) data1 = np.random.randint(-100, 100, [shape.rows, shape.cols]) data2 = np.random.randint(-100, 100, [shape.rows, shape.cols]) data2[data2 == 0] = 1 cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(np.round(NumCpp.divide(cArray1, cArray2), 9), np.round(data1 / data2, 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(-100, 100, [shape.rows, shape.cols]) cArray.setArray(data) value = 0 while value == 0: value = np.random.randint(-100, 100) assert np.array_equal(np.round(NumCpp.divide(cArray, value), 9), np.round(data / value, 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(-100, 100, [shape.rows, shape.cols]) data[data == 0] = 1 cArray.setArray(data) value = np.random.randint(-100, 100) assert np.array_equal(np.round(NumCpp.divide(value, cArray), 9), np.round(value / data, 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArrayComplexDouble(shape) cArray2 = NumCpp.NdArrayComplexDouble(shape) real1 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag1 = np.random.randint(1, 100, [shape.rows, shape.cols]) data1 = real1 + 1j * imag1 real2 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag2 = np.random.randint(1, 100, [shape.rows, shape.cols]) data2 = real2 + 1j * imag2 data2[data2 == complex(0)] = complex(1) cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(np.round(NumCpp.divide(cArray1, cArray2), 9), np.round(data1 / data2, 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) value = 0 while value == complex(0): value = np.random.randint(-100, 100) + 1j * np.random.randint(-100, 100) assert np.array_equal(np.round(NumCpp.divide(cArray, value), 9), np.round(data / value, 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag data[data == complex(0)] = complex(1) cArray.setArray(data) value = np.random.randint(-100, 100) + 1j * np.random.randint(-100, 100) assert np.array_equal(np.round(NumCpp.divide(value, cArray), 9), np.round(value / data, 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArrayComplexDouble(shape) cArray2 = NumCpp.NdArray(shape) real1 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag1 = np.random.randint(1, 100, [shape.rows, shape.cols]) data1 = real1 + 1j * imag1 data2 = np.random.randint(1, 100, [shape.rows, shape.cols]) data2[data2 == 0] = 1 cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(np.round(NumCpp.divide(cArray1, cArray2), 9), np.round(data1 / data2, 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArrayComplexDouble(shape) data1 = np.random.randint(1, 100, [shape.rows, shape.cols]) real2 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag2 = np.random.randint(1, 100, [shape.rows, shape.cols]) data2 = real2 + 1j * imag2 data2[data2 == complex(0)] = complex(1) cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(np.round(NumCpp.divide(cArray1, cArray2), 9), np.round(data1 / data2, 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(-100, 100, [shape.rows, shape.cols]) cArray.setArray(data) while value == complex(0): value = np.random.randint(-100, 100) + 1j * np.random.randint(-100, 100) assert np.array_equal(np.round(NumCpp.divide(cArray, value), 9), np.round(data / value, 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(-100, 100, [shape.rows, shape.cols]) data[data == 0] = 1 cArray.setArray(data) value = np.random.randint(-100, 100) + 1j * np.random.randint(-100, 100) assert np.array_equal(np.round(NumCpp.divide(value, cArray), 9), np.round(value / data, 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) value = 0 while value == 0: value = np.random.randint(-100, 100) assert np.array_equal(np.round(NumCpp.divide(cArray, value), 9), np.round(data / value, 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag data[data == complex(0)] = complex(1) cArray.setArray(data) value = np.random.randint(-100, 100) assert np.array_equal(np.round(NumCpp.divide(value, cArray), 9), np.round(value / data, 9)) #################################################################################### def test_dot(): size = np.random.randint(1, 100, [1, ]).item() shape = NumCpp.Shape(1, size) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArray(shape) data1 = np.random.randint(1, 50, [shape.rows, shape.cols]) data2 = np.random.randint(1, 50, [shape.rows, shape.cols]) cArray1.setArray(data1) cArray2.setArray(data2) assert NumCpp.dot(cArray1, cArray2).item() == np.dot(data1, data2.T).item() size = np.random.randint(1, 100, [1, ]).item() shape = NumCpp.Shape(1, size) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArrayComplexDouble(shape) data1 = np.random.randint(1, 50, [shape.rows, shape.cols]) real2 = np.random.randint(1, 50, [shape.rows, shape.cols]) imag2 = np.random.randint(1, 50, [shape.rows, shape.cols]) data2 = real2 + 1j * imag2 cArray1.setArray(data1) cArray2.setArray(data2) assert NumCpp.dot(cArray1, cArray2).item() == np.dot(data1, data2.T).item() size = np.random.randint(1, 100, [1, ]).item() shape = NumCpp.Shape(1, size) cArray1 = NumCpp.NdArrayComplexDouble(shape) cArray2 = NumCpp.NdArrayComplexDouble(shape) real1 = np.random.randint(1, 50, [shape.rows, shape.cols]) imag1 = np.random.randint(1, 50, [shape.rows, shape.cols]) data1 = real1 + 1j * imag1 real2 = np.random.randint(1, 50, [shape.rows, shape.cols]) imag2 = np.random.randint(1, 50, [shape.rows, shape.cols]) data2 = real2 + 1j * imag2 cArray1.setArray(data1) cArray2.setArray(data2) assert NumCpp.dot(cArray1, cArray2).item() == np.dot(data1, data2.T).item() size = np.random.randint(1, 100, [1, ]).item() shape = NumCpp.Shape(1, size) cArray1 = NumCpp.NdArrayComplexDouble(shape) cArray2 = NumCpp.NdArray(shape) real1 = np.random.randint(1, 50, [shape.rows, shape.cols]) imag1 = np.random.randint(1, 50, [shape.rows, shape.cols]) data1 = real1 + 1j * imag1 data2 = np.random.randint(1, 50, [shape.rows, shape.cols]) cArray1.setArray(data1) cArray2.setArray(data2) assert NumCpp.dot(cArray1, cArray2).item() == np.dot(data1, data2.T).item() shapeInput = np.random.randint(1, 100, [2, ]) shape1 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) shape2 = NumCpp.Shape(shapeInput[1].item(), np.random.randint(1, 100, [1, ]).item()) cArray1 = NumCpp.NdArray(shape1) cArray2 = NumCpp.NdArray(shape2) data1 = np.random.randint(1, 50, [shape1.rows, shape1.cols]) data2 = np.random.randint(1, 50, [shape2.rows, shape2.cols]) cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.dot(cArray1, cArray2), np.dot(data1, data2)) shapeInput = np.random.randint(1, 100, [2, ]) shape1 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) shape2 = NumCpp.Shape(shapeInput[1].item(), np.random.randint(1, 100, [1, ]).item()) cArray1 = NumCpp.NdArrayComplexDouble(shape1) cArray2 = NumCpp.NdArrayComplexDouble(shape2) real1 = np.random.randint(1, 50, [shape1.rows, shape1.cols]) imag1 = np.random.randint(1, 50, [shape1.rows, shape1.cols]) data1 = real1 + 1j * imag1 real2 = np.random.randint(1, 50, [shape2.rows, shape2.cols]) imag2 = np.random.randint(1, 50, [shape2.rows, shape2.cols]) data2 = real2 + 1j * imag2 cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.dot(cArray1, cArray2), np.dot(data1, data2)) #################################################################################### def test_empty(): shapeInput = np.random.randint(1, 100, [2, ]) cArray = NumCpp.emptyRowCol(shapeInput[0].item(), shapeInput[1].item()) assert cArray.shape[0] == shapeInput[0] assert cArray.shape[1] == shapeInput[1] assert cArray.size == shapeInput.prod() shapeInput = np.random.randint(1, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.emptyShape(shape) assert cArray.shape[0] == shape.rows assert cArray.shape[1] == shape.cols assert cArray.size == shapeInput.prod() shapeInput = np.random.randint(1, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.empty_like(cArray1) assert cArray2.shape().rows == shape.rows assert cArray2.shape().cols == shape.cols assert cArray2.size() == shapeInput.prod() #################################################################################### def test_endianess(): shapeInput = np.random.randint(1, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) assert NumCpp.endianess(cArray) == NumCpp.Endian.NATIVE #################################################################################### def test_equal(): shapeInput = np.random.randint(1, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArray(shape) data1 = np.random.randint(0, 10, [shape.rows, shape.cols]) data2 = np.random.randint(0, 10, [shape.rows, shape.cols]) cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.equal(cArray1, cArray2), np.equal(data1, data2)) shapeInput = np.random.randint(1, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArrayComplexDouble(shape) cArray2 = NumCpp.NdArrayComplexDouble(shape) real1 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag1 = np.random.randint(1, 100, [shape.rows, shape.cols]) data1 = real1 + 1j * imag1 real2 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag2 = np.random.randint(1, 100, [shape.rows, shape.cols]) data2 = real2 + 1j * imag2 cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.equal(cArray1, cArray2), np.equal(data1, data2)) #################################################################################### def test_exp2(): value = np.abs(np.random.rand(1).item()) assert np.round(NumCpp.expScaler(value), 9) == np.round(np.exp(value), 9) components = np.random.rand(2).astype(np.double) value = complex(components[0], components[1]) assert np.round(NumCpp.expScaler(value), 9) == np.round(np.exp(value), 9) value = np.abs(np.random.rand(1).item()) assert np.round(NumCpp.exp2Scaler(value), 9) == np.round(np.exp2(value), 9) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.rand(shape.rows, shape.cols) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.exp2Array(cArray), 9), np.round(np.exp2(data), 9)) #################################################################################### def test_exp(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.rand(shape.rows, shape.cols) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.expArray(cArray), 9), np.round(np.exp(data), 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) data = np.random.rand(shape.rows, shape.cols) + 1j * np.random.rand(shape.rows, shape.cols) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.expArray(cArray), 9), np.round(np.exp(data), 9)) value = np.abs(np.random.rand(1).item()) assert np.round(NumCpp.expm1Scaler(value), 9) == np.round(np.expm1(value), 9) components = np.random.rand(2).astype(np.double) value = complex(components[0], components[1]) assert np.round(NumCpp.expm1Scaler(value), 9) == np.round(np.expm1(value), 9) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.rand(shape.rows, shape.cols) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.expm1Array(cArray), 9), np.round(np.expm1(data), 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.rand(shape.rows, shape.cols) imag = np.random.rand(shape.rows, shape.cols) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(np.round(NumCpp.expm1Array(cArray), 9), np.round(np.expm1(data), 9)) #################################################################################### def test_eye(): shapeInput = np.random.randint(1, 100, [1, ]).item() randK = np.random.randint(0, shapeInput, [1, ]).item() assert np.array_equal(NumCpp.eye1D(shapeInput, randK), np.eye(shapeInput, k=randK)) shapeInput = np.random.randint(1, 100, [1, ]).item() randK = np.random.randint(0, shapeInput, [1, ]).item() assert np.array_equal(NumCpp.eye1DComplex(shapeInput, randK), np.eye(shapeInput, k=randK) + 1j * np.zeros([shapeInput, shapeInput])) shapeInput = np.random.randint(10, 100, [2, ]) randK = np.random.randint(0, np.min(shapeInput), [1, ]).item() assert np.array_equal(NumCpp.eye2D(shapeInput[0].item(), shapeInput[1].item(), randK), np.eye(shapeInput[0].item(), shapeInput[1].item(), k=randK)) shapeInput = np.random.randint(10, 100, [2, ]) randK = np.random.randint(0, np.min(shapeInput), [1, ]).item() assert np.array_equal(NumCpp.eye2DComplex(shapeInput[0].item(), shapeInput[1].item(), randK), np.eye(shapeInput[0].item(), shapeInput[1].item(), k=randK) + 1j * np.zeros(shapeInput)) shapeInput = np.random.randint(10, 100, [2, ]) cShape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) randK = np.random.randint(0, np.min(shapeInput), [1, ]).item() assert np.array_equal(NumCpp.eyeShape(cShape, randK), np.eye(shapeInput[0].item(), shapeInput[1].item(), k=randK)) shapeInput = np.random.randint(10, 100, [2, ]) cShape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) randK = np.random.randint(0, np.min(shapeInput), [1, ]).item() assert np.array_equal(NumCpp.eyeShapeComplex(cShape, randK), np.eye(shapeInput[0].item(), shapeInput[1].item(), k=randK) + 1j * np.zeros(shapeInput)) #################################################################################### def test_fill_diagonal(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randn(shape.rows, shape.cols) * 100 cArray.setArray(data) NumCpp.fillDiagonal(cArray, 666) np.fill_diagonal(data, 666) assert np.array_equal(cArray.getNumpyArray(), data) #################################################################################### def test_find(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randn(shape.rows, shape.cols) * 100 cArray.setArray(data) value = data.mean() cMask = NumCpp.operatorGreater(cArray, value) cMaskArray = NumCpp.NdArrayBool(cMask.shape[0], cMask.shape[1]) cMaskArray.setArray(cMask) idxs = NumCpp.find(cMaskArray).astype(np.int64) idxsPy = np.nonzero((data > value).flatten())[0] assert np.array_equal(idxs.flatten(), idxsPy) #################################################################################### def test_findN(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randn(shape.rows, shape.cols) * 100 cArray.setArray(data) value = data.mean() cMask = NumCpp.operatorGreater(cArray, value) cMaskArray = NumCpp.NdArrayBool(cMask.shape[0], cMask.shape[1]) cMaskArray.setArray(cMask) idxs = NumCpp.findN(cMaskArray, 8).astype(np.int64) idxsPy = np.nonzero((data > value).flatten())[0] assert np.array_equal(idxs.flatten(), idxsPy[:8]) #################################################################################### def fix(): value = np.random.randn(1).item() * 100 assert NumCpp.fixScaler(value) == np.fix(value) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randn(shape.rows, shape.cols) * 100 cArray.setArray(data) assert np.array_equal(NumCpp.fixArray(cArray), np.fix(data)) #################################################################################### def test_flatten(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.flatten(cArray).getNumpyArray(), np.resize(data, [1, data.size])) #################################################################################### def test_flatnonzero(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.flatnonzero(cArray).getNumpyArray().flatten(), np.flatnonzero(data)) #################################################################################### def test_flip(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.flip(cArray, NumCpp.Axis.NONE).getNumpyArray(), np.flip(data.reshape(1, data.size), axis=1).reshape(shapeInput)) #################################################################################### def test_fliplr(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.fliplr(cArray).getNumpyArray(), np.fliplr(data)) #################################################################################### def test_flipud(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.flipud(cArray).getNumpyArray(), np.flipud(data)) #################################################################################### def test_floor(): value = np.random.randn(1).item() * 100 assert NumCpp.floorScaler(value) == np.floor(value) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randn(shape.rows, shape.cols) * 100 cArray.setArray(data) assert np.array_equal(NumCpp.floorArray(cArray), np.floor(data)) #################################################################################### def test_floor_divide(): value1 = np.random.randn(1).item() * 100 + 1000 value2 = np.random.randn(1).item() * 100 + 1000 assert NumCpp.floor_divideScaler(value1, value2) == np.floor_divide(value1, value2) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArray(shape) data1 = np.random.randn(shape.rows, shape.cols) * 100 + 1000 data2 = np.random.randn(shape.rows, shape.cols) * 100 + 1000 cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.floor_divideArray(cArray1, cArray2), np.floor_divide(data1, data2)) #################################################################################### def test_fmax(): value1 = np.random.randn(1).item() * 100 + 1000 value2 = np.random.randn(1).item() * 100 + 1000 assert NumCpp.fmaxScaler(value1, value2) == np.fmax(value1, value2) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArray(shape) data1 = np.random.randn(shape.rows, shape.cols) * 100 + 1000 data2 = np.random.randn(shape.rows, shape.cols) * 100 + 1000 cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.fmaxArray(cArray1, cArray2), np.fmax(data1, data2)) #################################################################################### def test_fmin(): value1 = np.random.randn(1).item() * 100 + 1000 value2 = np.random.randn(1).item() * 100 + 1000 assert NumCpp.fminScaler(value1, value2) == np.fmin(value1, value2) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArray(shape) data1 = np.random.randn(shape.rows, shape.cols) * 100 + 1000 data2 = np.random.randn(shape.rows, shape.cols) * 100 + 1000 cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.fminArray(cArray1, cArray2), np.fmin(data1, data2)) #################################################################################### def test_fmod(): value1 = np.random.randint(1, 100, [1, ]).item() * 100 + 1000 value2 = np.random.randint(1, 100, [1, ]).item() * 100 + 1000 assert NumCpp.fmodScaler(value1, value2) == np.fmod(value1, value2) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArrayUInt32(shape) cArray2 = NumCpp.NdArrayUInt32(shape) data1 = np.random.randint(1, 100, [shape.rows, shape.cols], dtype=np.uint32) * 100 + 1000 data2 = np.random.randint(1, 100, [shape.rows, shape.cols], dtype=np.uint32) * 100 + 1000 cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.fmodArray(cArray1, cArray2), np.fmod(data1, data2)) #################################################################################### def test_fromfile(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 50, [shape.rows, shape.cols]).astype(np.double) cArray.setArray(data) tempDir = r'C:\Temp' if not os.path.exists(tempDir): os.mkdir(tempDir) tempFile = os.path.join(tempDir, 'NdArrayDump.bin') NumCpp.dump(cArray, tempFile) assert os.path.isfile(tempFile) data2 = NumCpp.fromfile(tempFile, '').reshape(shape) assert np.array_equal(data, data2) os.remove(tempFile) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 50, [shape.rows, shape.cols]).astype(np.double) cArray.setArray(data) tempDir = tempfile.gettempdir() tempFile = os.path.join(tempDir, 'NdArrayDump') NumCpp.tofile(cArray, tempFile, '\n') assert os.path.exists(tempFile + '.txt') data2 = NumCpp.fromfile(tempFile + '.txt', '\n').reshape(shape) assert np.array_equal(data, data2) os.remove(tempFile + '.txt') #################################################################################### def test_fromiter(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.fromiter(cArray).flatten(), data.flatten()) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.fromiter(cArray).flatten(), data.flatten()) #################################################################################### def test_full(): shapeInput = np.random.randint(1, 100, [1, ]).item() value = np.random.randint(1, 100, [1, ]).item() cArray = NumCpp.fullSquare(shapeInput, value) assert (cArray.shape[0] == shapeInput and cArray.shape[1] == shapeInput and cArray.size == shapeInput**2 and np.all(cArray == value)) shapeInput = np.random.randint(1, 100, [1, ]).item() value = np.random.randint(1, 100, [1, ]).item() + 1j * np.random.randint(1, 100, [1, ]).item() cArray = NumCpp.fullSquareComplex(shapeInput, value) assert (cArray.shape[0] == shapeInput and cArray.shape[1] == shapeInput and cArray.size == shapeInput**2 and np.all(cArray == value)) shapeInput = np.random.randint(1, 100, [2, ]) value = np.random.randint(1, 100, [1, ]).item() cArray = NumCpp.fullRowCol(shapeInput[0].item(), shapeInput[1].item(), value) assert (cArray.shape[0] == shapeInput[0] and cArray.shape[1] == shapeInput[1] and cArray.size == shapeInput.prod() and np.all(cArray == value)) shapeInput = np.random.randint(1, 100, [2, ]) value = np.random.randint(1, 100, [1, ]).item() + 1j * np.random.randint(1, 100, [1, ]).item() cArray = NumCpp.fullRowColComplex(shapeInput[0].item(), shapeInput[1].item(), value) assert (cArray.shape[0] == shapeInput[0] and cArray.shape[1] == shapeInput[1] and cArray.size == shapeInput.prod() and np.all(cArray == value)) shapeInput = np.random.randint(1, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) value = np.random.randint(1, 100, [1, ]).item() cArray = NumCpp.fullShape(shape, value) assert (cArray.shape[0] == shape.rows and cArray.shape[1] == shape.cols and cArray.size == shapeInput.prod() and np.all(cArray == value)) shapeInput = np.random.randint(1, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) value = np.random.randint(1, 100, [1, ]).item() cArray = NumCpp.fullShape(shape, value) assert (cArray.shape[0] == shape.rows and cArray.shape[1] == shape.cols and cArray.size == shapeInput.prod() and np.all(cArray == value)) #################################################################################### def test_full_like(): shapeInput = np.random.randint(1, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArray(shape) value = np.random.randint(1, 100, [1, ]).item() cArray2 = NumCpp.full_like(cArray1, value) assert (cArray2.shape().rows == shape.rows and cArray2.shape().cols == shape.cols and cArray2.size() == shapeInput.prod() and np.all(cArray2.getNumpyArray() == value)) shapeInput = np.random.randint(1, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArrayComplexDouble(shape) value = np.random.randint(1, 100, [1, ]).item() + 1j * np.random.randint(1, 100, [1, ]).item() cArray2 = NumCpp.full_likeComplex(cArray1, value) assert (cArray2.shape().rows == shape.rows and cArray2.shape().cols == shape.cols and cArray2.size() == shapeInput.prod() and np.all(cArray2.getNumpyArray() == value)) #################################################################################### def test_gcd(): if not NumCpp.NUMCPP_NO_USE_BOOST or NumCpp.STL_GCD_LCM: value1 = np.random.randint(1, 1000, [1, ]).item() value2 = np.random.randint(1, 1000, [1, ]).item() assert NumCpp.gcdScaler(value1, value2) == np.gcd(value1, value2) if not NumCpp.NUMCPP_NO_USE_BOOST: size = np.random.randint(20, 100, [1, ]).item() cArray = NumCpp.NdArrayUInt32(1, size) data = np.random.randint(1, 1000, [size, ], dtype=np.uint32) cArray.setArray(data) assert NumCpp.gcdArray(cArray) == np.gcd.reduce(data) # noqa #################################################################################### def test_gradient(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 1000, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.gradient(cArray, NumCpp.Axis.ROW), np.gradient(data, axis=0)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 1000, [shape.rows, shape.cols]) imag = np.random.randint(1, 1000, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.gradient(cArray, NumCpp.Axis.ROW), np.gradient(data, axis=0)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 1000, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.gradient(cArray, NumCpp.Axis.COL), np.gradient(data, axis=1)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 1000, [shape.rows, shape.cols]) imag = np.random.randint(1, 1000, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.gradient(cArray, NumCpp.Axis.COL),
np.gradient(data, axis=1)
numpy.gradient
import numpy as np import collections import argparse import matplotlib.pyplot as plt import matplotlib.animation as anim import copy import random import time from bp94nball.qsr_util import circles from bp94nball.qsr_util import qsr_part_of_characteristic_function from bp94nball.qsr_util import qsr_disconnect_characteristic_function from bp94nball.qsr_util import vec_length from bp94nball.colors import cnames colorList = ['blue', 'green', 'red', 'cyan', 'magenta', 'yellow','black', 'seagreen', 'pink', 'navy','violet', 'crimson'] + list(cnames.keys()) r0=0.05 rock_1 = [np.cos(np.pi / 4), np.sin(np.pi / 4), 10,r0] stone = [np.cos(np.pi / 4 + np.pi / 100), np.sin(np.pi / 4 + np.pi / 100), 10, r0] basalt = [np.cos(np.pi / 4 - np.pi / 200), np.sin(np.pi / 4 - np.pi / 200), 10, r0] material = [np.cos(np.pi / 4 - np.pi / 100), np.sin(np.pi / 4 - np.pi / 100), 10, r0] substance = [np.cos(np.pi / 4 - np.pi / 50), np.sin(np.pi / 4 - np.pi / 50), 10, r0] entity = [np.cos(np.pi / 4- np.pi / 40), np.sin(np.pi / 4- np.pi / 40), 10, r0] rock_2 = [np.cos(np.pi / 4 + np.pi / 30), np.sin(np.pi / 4 + np.pi / 30), 10, r0] pop = [np.cos(np.pi / 4 + np.pi / 50), np.sin(np.pi / 4 + np.pi / 50), 10, r0] jazz = [np.cos(np.pi / 3 - np.pi / 50), np.sin(np.pi / 3 - np.pi / 50), 10, r0] music = [np.cos(np.pi / 4 + np.pi / 15), np.sin(np.pi / 4 + np.pi / 15), 10, r0] communication = [np.cos(np.pi / 3), np.sin(np.pi / 3), 10, r0] event = [np.cos(np.pi / 3 + np.pi / 50), np.sin(np.pi / 3 + np.pi / 50), 10, r0] wDic = { 'rock_1': rock_1, 'stone': stone, 'basalt': basalt, 'material' : material, 'substance' : substance, 'entity': entity, 'rock_2': rock_2, 'pop': pop, 'jazz': jazz, 'music': music, 'communication': communication, 'event': event } kw0 = [ ['rock_1', 'material', 'rock_2'], ['stone', 'material', 'jazz'], ['basalt', 'material', 'communication'], ['material', 'substance', 'event'], ['substance', 'entity', 'music'] ] kw1=[ ['rock_2', 'music', 'material'], ['pop', 'music', 'substance'], ['jazz', 'music', 'basalt'], ['music', 'communication', 'entity'], ['communication', 'event', 'entity'], ] def do_func(funcName="part_of"): fdic = { "part_of": qsr_part_of_characteristic_function, "disconnect": qsr_disconnect_characteristic_function } if funcName in fdic.keys(): return fdic[funcName] else: print("unknown qsr reltion:", funcName) return -1 def energy_2(ball1, ball2, func="part_of"): """ compute the energy of ball1 being part of ball2 ball1 \part_of ball2 = distance :param ball1: :param ball2: :return: """ qsr_func = do_func(funcName=func) assert qsr_func != -1 qsrIndicator = qsr_func(ball1, ball2) if qsrIndicator <= 0: return 0 else: return min(0.999, 2/(1 + np.exp(-qsrIndicator)) - 1) def loss(ball_w, ball_u, negBalls=[], func="part_of", func_neg="disconnect"): """ :param ball_w: :param ball_u: :param negBalls: a list of balls as negative sample :return: """ qsr_func = do_func(funcName=func) qsrIndicator = qsr_func(ball_u, ball_w) if qsrIndicator <= 0: Lw = 0 else: Lw = energy_2(ball_u, ball_w, func=func) for ball_i in negBalls: qsr_func = do_func(funcName=func_neg) qsrIndicator = qsr_func(ball_i, ball_w) if qsrIndicator > 0: Lw += energy_2(ball_i, ball_w, func=func_neg) return Lw def total_loss(klst, wDic, func="part_of", func_neg="disconnect", numNeg=0): value = 0 for piece in klst: value += loss(wDic[piece[1]], wDic[piece[0]], negBalls=[wDic[nball] for nball in piece[2:]][0:numNeg], func=func, func_neg=func_neg) return value def partial_derative_lw(ball_w, ball_u, negBalls=[], func="part_of", func_neg="disconnect"): """ :param ball_w: :param ball_u: :param negBalls: :param func: :return: """ alpha_w, lw, rw = ball_w[:-2], ball_w[-2], ball_w[-1] alpha_u, lu, ru = ball_u[:-2], ball_u[-2], ball_u[-1] hight = np.dot(alpha_w, alpha_u) e1 = energy_2(ball_u, ball_w, func=func) if e1 == 0: result = 0 else: dis2 = lw * lw + lu * lu - np.multiply(2*lu*lw, hight) assert dis2 > 0 result = (2 - 2*e1)* e1 * (lw - np.multiply(lu, hight))\ / np.sqrt(dis2) i = 0 for ball_i in negBalls: # print('neg i', i) i += 1 alpha_i, li, ri = ball_i[:-2], ball_i[-2], ball_i[-1] hight = np.dot(alpha_i, alpha_w) e2 = energy_2(ball_i, ball_w, func=func_neg) if e2 != 0: dis2 = lw * lw + li * li - np.multiply(2*li*lw, hight) assert (dis2 > 0), "lw: {0}, li: {1}, hight: {2}, dis: {3}".format(float(lw), float(li), float(hight), float(dis2)) result -= (2 - 2*e2)* e2 * (lw - np.multiply(li, hight))\ / np.sqrt(dis2) return result def partial_derative_rw(ball_w, ball_u, negBalls=[], func="part_of", func_neg="disconnect"): """ :param ball_w: :param ball_u: :param negBalls: :param func: :return: """ e1 = energy_2(ball_u, ball_w, func=func) result = (2*e1 - 2)*e1 for ball_i in negBalls: e2 = energy_2(ball_i, ball_w, func=func_neg) result += (2 - 2*e2) * e2 return result def partial_derative_lu(ball_w, ball_u, negBalls=[], func="part_of", func_neg="disconnect"): """ :param ball_w: :param ball_u: :param negBalls: :param func: :return: """ alpha_w, lw, rw = ball_w[:-2], ball_w[-2], ball_w[-1] alpha_u, lu, ru = ball_u[:-2], ball_u[-2], ball_u[-1] hight =
np.dot(alpha_w, alpha_u)
numpy.dot
from __future__ import print_function try: import cv2 except ModuleNotFoundError: print("Please install opencv-python module using following command:\npip3 install opencv-python") import stmpy import numpy as np import scipy as sp import matplotlib as mpl import matplotlib.pyplot as plt import scipy.optimize as opt import scipy.ndimage as snd from scipy.interpolate import interp1d, interp2d from skimage import transform as tf from skimage.feature import peak_local_max from pprint import pprint import types ''' REFERENCES: [1] <NAME>, et al. "Picometer registration of zinc impurity states in Bi2Sr2CaCu2O8+d for phase determination in intra-unit-cell Fourier transform STM", New J. Phys. 14, 053017 (2012). [2] <NAME>, PhD thesis (Ch. 3), http://davisgroup.lassp.cornell.edu/theses/Thesis_JamesSlezak.pdf History: 2017-04-28 CREATED BY <NAME> 04/29/2019 RL : Add documents for all functions. Add another method to calculate phasemap. Add inverse FFT method to apply the drift field. 03/25/2021 RL : Change the whole drift corr library to function based library ''' ################################################################################## ######################### Wrapped functions for easy use ######################### ################################################################################## def find_drift_parameter(A, r=None, w=None, mask3=None, cut1=None, cut2=None, bp_angle=None, orient=None, bp_c=None,\ sigma=10, method='lockin', even_out=False, show=True, **kwargs): ''' This method find drift parameters from a 2D map automatically. Input: A - Required : 2D array of topo or LIY in real space. r - Optional : width of the gaussian mask, ratio to the full map size, to remove low-q noise, =r*width Set r=None will disable this mask. w - Optional : width of the mask that filters out noise along qx=0 and qy=0 lines. Set w=None will disable this mask. mask3 - Optional : Tuple for custom-defined mask. mask3 = [n, offset, width], where n is order of symmetry, offset is initial angle, width is the width of the mask. e.g., mask3 = [4, np.pi/4, 5], or mask3 = [6, 0, 10]. Set mask3=None will disable this mask. even_out - Optional : Boolean, if True then Bragg peaks will be rounded to the make sure there are even number of lattice cut1 - Optional : List of length 1 or length 4, specifying how much bad area or area with too large drift to be cut cut2 - Optional : List of length 1 or length 4, specifying after local drift correction how much to crop on the edge angle_offset- Optional : The min offset angle of the Bragg peak to the x-axis, in unit of rad bp_angle - Optional : The angle between neighboring Bragg peaks, if not given, it will be computed based on all Bragg peaks orient - Optional : The orientation of the Bragg peaks with respect to the x-axis bp_c - Optional : The correct Bragg peak position that user wants after the drift correction sigma - Optional : Floating number specifying the size of mask to be used in phasemap() method - Optional : Specifying which method to apply the drift correction "lockin": Interpolate A and then apply it to a new set of coordinates, (x-ux, y-uy) "convolution": Used inversion fft to apply the drift fields show - Optional : Boolean, if True then A and Bragg peaks will be plotted out. **kwargs - Optional : key word arguments for findBraggs function Returns: p : A dict of parameters that can be directly applied to drift correct orther 2D or 3D datasets Usage: p = find_drift(z, sigma=4, cut1=None, cut2=[0,7,0,7], show=True) History: 06/23/2020 - RL : Initial commit. ''' p = {} if cut1 is not None: A = cropedge(A, n=cut1) # find the Bragg peak before the drift correction bp1 = findBraggs(A, r=r, w=w, mask3=mask3, show=show, **kwargs) bp1 = sortBraggs(bp1, s=np.shape(A)) if bp_c is None: # Find the angle between each Bragg peaks if bp_angle is None: N = len(bp1) Q = bp_to_q(bp1, A) angles = [] for i in range(N-1): angles.append(np.arctan2(*Q[i+1]) - np.arctan2(*Q[i])) # Here is the commonly used angles in the real world angle_list = np.array([0, np.pi/6, np.pi/4, np.pi/3, np.pi/2]) offset = np.absolute(np.mean(angles) - angle_list) index = np.argmin(offset) bp_angle = angle_list[index] if orient is None: orient = np.absolute(np.arctan2(*Q[0])) # Calculate the correction position of each Bragg peak bp_c = generate_bp(A, bp1, angle=bp_angle, orient= orient, even_out=even_out) # Find the phasemap thetax, thetay, Q1, Q2 = phasemap(A, bp=bp_c, method=method, sigma=sigma) phix = fixphaseslip(thetax, method='unwrap') phiy = fixphaseslip(thetay, method='unwrap') ux, uy = driftmap(phix, phiy, Q1, Q2, method=method) z_temp = driftcorr(A, ux, uy, method=method, interpolation='cubic') # This part interpolates the drift corrected maps if cut2 is None: z_c = z_temp else: bp3 = findBraggs(z_temp, r=r, w=w, mask3=mask3, **kwargs) z_c = cropedge(z_temp, n=cut2, bp=bp3, force_commen=True) p['bp3'] = bp3 # This part displays the intermediate maps in the process of drift correction if show is True: fig, ax = plt.subplots(1, 2, figsize=[8, 4]) c = np.mean(phix) s = np.std(phix) fig.suptitle('Phasemaps after fixing phase slips:') ax[0].imshow(phix, origin='lower', clim=[c-5*s, c+5*s]) ax[1].imshow(phiy, origin='lower', clim=[c-5*s, c+5*s]) A_fft = stmpy.tools.fft(A, zeroDC=True) B_fft = stmpy.tools.fft(z_c, zeroDC=True) c1 = np.mean(A_fft) s1 = np.std(A_fft) c2 = np.mean(A) s2 = np.std(A) fig, ax = plt.subplots(2, 2, figsize=[8, 8]) fig.suptitle('Maps before and after drift correction:') ax[0,0].imshow(A, cmap=stmpy.cm.blue2, origin='lower', clim=[c2-5*s2, c2+5*s2]) ax[0,1].imshow(A_fft, cmap=stmpy.cm.gray_r, origin='lower', clim=[0, c1+5*s1]) ax[1,0].imshow(z_c, cmap=stmpy.cm.blue2, origin='lower', clim=[c2-5*s2, c2+5*s2]) ax[1,1].imshow(B_fft, cmap=stmpy.cm.gray_r, origin='lower', clim=[0, c1+5*s1]) p['cut1'] = cut1 p['cut2'] = cut2 p['r'] = r p['w'] = w p['mask3'] = mask3 p['sigma'] = sigma p['method'] = method p['even_out'] = even_out p['bp_c'] = bp_c p['bp_angle'] = bp_angle p['orient'] = orient p['bp1'] = bp1 p['phix'] = phix p['phiy'] = phiy p['ux'] = ux p['uy'] = uy return z_c, p def apply_drift_parameter(A, p, **kwargs): ''' Apply the drifr correction parameters p to the 2D or 3D map A. Input: A - Required : 2D or 3D map to be drift corrected p - Required : A collection of parameters to be used in drift correction. Use parameters (those parameters should be generated by find_drift_parameter automatically) cut1 : cut2 : ux : uy : method : bp3 : **kwargs - Optional : Returns: A_c : 2D or 3D map with drift removed. Usage: A_c = apply_drift_parameter(A, p) History: 06/23/2020 - RL : Initial commit. ''' data_c = np.copy(A) if p['cut1'] is None: data_c = data_c else: data_c = cropedge(data_c, n=p['cut1']) data_corr = driftcorr(data_c, ux=p['ux'], uy=p['uy'], method=p['method'], interpolation='cubic') if p['cut2'] is None: data_out = data_corr else: data_out = cropedge(data_corr, bp=p['bp3'], n=p['cut2'], force_commen=True) return data_out ################################################################################## ###################### Basic building blocks for OOD use ######################### ################################################################################## def get_para(A, a0=None, size=None, angle=np.pi/2, orient=np.pi/4, pixels=None, even_out=False, use_a0=False): ''' Get parameters that are useful for the drift correction Input: A - Required : Spy object of topo (2D) or map (3D). a0 - Optional : Lattice constant in the unit of nm. size - Optional : Size of the map in the unit of nm. If not offered, it'll be created automatically from header file. angle - Optional : Angle of the lattice. If the lattice is n-fold symmetry, then angle = 2*pi/n orient - Optional : Angle of the 1st Bragg peak. It's actually the orientation of the scan frame with respect to the Lattice. pixels - Optional : Number of pixels of the topo/map. If not offered, it'll be created automatically from header file. even_out - Optional : Boolean, if True then Bragg peaks will be rounded to the make sure there are even number of lattice Returns: p - Dict, contains necessary information for the Usage: import stmpy.driftcorr as dfc dfc.getAttrs(topo, a0=a0) ''' if size is None: try: size = A.header['scan_range'][-2:] except KeyError: try: #size = float(A.header['Grid settings'].split(";")[-2]) size = [float(k) for k in A.header['Grid settings'].split(";")[-2:]] except: print( "Error: Cannot find map size from header. Please input it manually.") if pixels is None: try: #pixels = int(A.header['scan_pixels'][-1]) pixels = [int(k) for k in A.header['scan_pixels'][-2:]] except KeyError: try: pixels = int(A.header['Grid dim'].split()[-1][:-1]) except: print( "Error: Cannot find number of pixels from header. Please input it manually.") if not isinstance(size, list): sizex, sizey = size, size else: sizex, sizey = size if not isinstance(pixels, list): pixelx, pixely = pixels, pixels else: pixelx, pixely = pixels if a0 is None: use_a0 = False a0 = 1 # parameters related to the map itself A.dfc_para = { 'a0': a0, 'size': np.array([sizex, sizey]), 'pixels': np.array([pixelx, pixely]), 'qmag': np.array([sizex, sizey]) / a0, 'qscale': np.array([pixelx, pixely]) / (2*np.array([sizex, sizey]) / a0), 'angle': angle, 'orient': orient, 'use_a0': use_a0, 'even_out': even_out, } def find_drift(self, A, r=None, w=None, mask3=None, cut1=None, cut2=None, \ sigma=10, method='convolution', even_out=False, show=True, **kwargs): ''' This method find drift field from a 2D map automatically. Input: A - Required : 2D array of topo or LIY in real space. r - Optional : width of the gaussian mask to remove low-q noise, =r*width Set r=None will disable this mask. w - Optional : width of the mask that filters out noise along qx=0 and qy=0 lines. Set w=None will disable this mask. mask3 - Optional : Tuple for custom-defined mask. mask3 = [n, offset, width], where n is order of symmetry, offset is initial angle, width is the width of the mask. e.g., mask3 = [4, np.pi/4, 5], or mask3 = [6, 0, 10] Set mask3=None will disable this mask. even_out - Optional : Boolean, if True then Bragg peaks will be rounded to the make sure there are even number of lattice cut1 - Optional : List of length 1 or length 4, specifying after global shear correction how much to crop on the edge cut2 - Optional : List of length 1 or length 4, specifying after local drift correction how much to crop on the edge sigma - Optional : Floating number specifying the size of mask to be used in phasemap() method - Optional : Specifying which method to apply the drift correction "lockin": Interpolate A and then apply it to a new set of coordinates, (x-ux, y-uy) "convolution": Used inversion fft to apply the drift fields show - Optional : Boolean, if True then A and Bragg peaks will be plotted out. **kwargs - Optional : key word arguments for findBraggs function Returns: coords - (4x2) array contains Bragg peaks in the format of [[x1,y1],[x2,y2],...,[x4,y4]] Usage: t.find_drift(t.z, sigma=4, cut1=None, cut2=[0,7,0,7], show=True) History: 06/09/2020 - RL : Initial commit. ''' if not hasattr(self, 'parameters'): self = getAttrs(self, a0=None, size=None, angle=np.pi/2, orient=np.pi/4, pixels=np.shape(A)[::-1], \ even_out=even_out, use_a0=None) # Find Bragg peaks that will be used in the drift correction part self.dfcPara = { 'cut1': cut1, 'cut2': cut2, 'method': method, 'sigma': sigma, } if cut1 is not None: A = cropedge(A, n=cut1) if not hasattr(self, 'bp_parameters'): self.bp1 = findBraggs(A, r=r, w=w, mask3=mask3, update_obj=True, obj=self, \ show=show, even_out=even_out, **kwargs) else: self.bp1 = findBraggs(A, r=r, w=w, mask3=mask3, update_obj=True, obj=self, \ show=show, even_out=even_out, **kwargs) # self.bp1 = findBraggs(A, obj=self, show=show) self.bp1 = sortBraggs(self.bp1, s=np.shape(A)) if self.parameters['angle'] is None: N = len(self.bp1) Q = bp_to_q(self.bp1, A) angles = [] for i in range(N-1): angles.append(np.arctan2(*Q[i+1]) - np.arctan2(*Q[i])) # Here are the commonly used angles in the real world angle_list = np.array([0, np.pi/6, np.pi/4, np.pi/3, np.pi/2]) offset = np.absolute(np.mean(angles) - angle_list) index = np.argmin(offset) self.parameters['angle'] = angle_list[index] if self.parameters['orient'] is None: orient = np.absolute(np.arctan2(*Q[0])) self.parameters['orient'] = orient # This is the correct value for the Bragg peak self.bp2 = generate_bp(A, self.bp1, angle=self.parameters['angle'], orient= self.parameters['orient'], even_out=self.parameters['even_out'], obj=self) # This part corrects for the drift thetax, thetay, Q1, Q2 = phasemap(A, bp=self.bp2, method=method, sigma=sigma) self.phix = fixphaseslip(thetax, method='unwrap') self.phiy = fixphaseslip(thetay, method='unwrap') self.ux, self.uy = driftmap(self.phix, self.phiy, Q1, Q2, method=method) ztemp = driftcorr(A, self.ux, self.uy, method=method, interpolation='cubic') # This part interpolates the drift corrected maps self.bp3 = findBraggs(ztemp, obj=self) if cut2 is None: cut2 = 0 force_commen = False else: force_commen = True self.zc = cropedge(ztemp, n=cut2, bp=self.bp3, force_commen=force_commen) # This part displays the intermediate maps in the process of drift correction if show is True: fig, ax = plt.subplots(1, 2, figsize=[8, 4]) c = np.mean(self.phix) s = np.std(self.phix) fig.suptitle('Phasemaps after fixing phase slips:') ax[0].imshow(self.phix, origin='lower', clim=[c-5*s, c+5*s]) ax[1].imshow(self.phiy, origin='lower', clim=[c-5*s, c+5*s]) A_fft = stmpy.tools.fft(A, zeroDC=True) B_fft = stmpy.tools.fft(self.zc, zeroDC=True) c1 = np.mean(A_fft) s1 = np.std(A_fft) c2 = np.mean(A) s2 = np.std(A) fig, ax = plt.subplots(2, 2, figsize=[8, 8]) fig.suptitle('Maps before and after drift correction:') ax[0,0].imshow(A, cmap=stmpy.cm.blue2, origin='lower', clim=[c2-5*s2, c2+5*s2]) ax[0,1].imshow(A_fft, cmap=stmpy.cm.gray_r, origin='lower', clim=[0, c1+5*s1]) ax[1,0].imshow(self.zc, cmap=stmpy.cm.blue2, origin='lower', clim=[c2-5*s2, c2+5*s2]) ax[1,1].imshow(B_fft, cmap=stmpy.cm.gray_r, origin='lower', clim=[0, c1+5*s1]) self.bp = findBraggs(self.zc, obj=self) def correct(self, use): ''' Use attributes of object "self" to correc the 3D map use. Input: self - Required : Spy object of topo (2D) or map (3D). use - Required : 3D map to be corrected with attributes of the object. Returns: N/A Usage: d.correct(d.LIY) History: 06/09/2020 - RL : Initial commit. ''' data_c = np.copy(use) if self.dfcPara['cut1'] is None: data_c = data_c else: data_c = cropedge(data_c, n=self.dfcPara['cut1']) data_corr = driftcorr(data_c, ux=self.ux, uy=self.uy, method=self.dfcPara['method'], interpolation='cubic') if self.dfcPara['cut2'] is None: data_out = cropedge(data_corr, bp=self.bp3, n=0, force_commen=False) else: data_out = cropedge(data_corr, bp=self.bp3, n=self.dfcPara['cut2'], force_commen=True) self.liy_c = data_out def __update_parameters(obj, a0=None, bp=None, pixels=None, size=None, use_a0=True): if use_a0 is True: center = (np.array(pixels)-1) // 2 Q = bp - center q1, q2, q3, q4, *_ = Q delta_qx = (np.absolute(q1[0]-q3[0])+np.absolute(q2[0]-q4[0])) / 2 delta_qy = (np.absolute(q1[1]-q3[1])+np.absolute(q2[1]-q4[1])) / 2 sizex = np.absolute( delta_qx / (4 * a0 * np.cos(obj.parameters['angle']))) sizey = np.absolute( delta_qy / (4 * a0 * np.cos(obj.parameters['angle']))) bp_x = np.min(bp[:, 0]) ext_x = pixels[0] / (pixels[0] - 2*bp_x) bp_y = np.min(bp[:, 1]) ext_y = pixels[1] / (pixels[1] - 2*bp_y) obj.parameters['size'] = np.array([sizex, sizey]) obj.parameters['pixels'] = np.array(pixels) obj.parameters['qscale'] = np.array([ext_x, ext_y]) obj.qx = bp[0] - center obj.qy = bp[1] - center else: center = (np.array(pixels)-1) // 2 bp_x = np.min(bp[:, 0]) ext_x = pixels[0] / (pixels[0] - 2*bp_x) bp_y = np.min(bp[:, 1]) ext_y = pixels[1] / (pixels[1] - 2*bp_y) obj.parameters['size'] = np.array( pixels) / obj.parameters['pixels'] * obj.parameters['size'] obj.parameters['pixels'] = np.array(pixels) obj.parameters['qscale'] = np.array([ext_x, ext_y]) obj.qx = bp[0] - center obj.qy = bp[1] - center ################################################################################## ################## Basic building blocks for drift correction #################### ################################################################################## #1 - findBraggs def findBraggs(A, rspace=True, min_dist=5, thres=0.25, r=None, w=None, mask3=None, even_out=False, precise=False, width=10, p0=None, show=False): ''' Find Bragg peaks in the unit of pixels of topo or FT pattern A using peak_local_max. If obj is offered, an attribute of bp will be created for obj. Input: A - Required : 2D array of topo in real space, or FFT in q space. min_dist - Optional : Minimum distance (in pixels) between peaks. Default: 5 thres - Optional : Minimum intensity of Bragg peaks relative to max value. Default: 0.25 rspace - Optional : Boolean indicating if A is real or Fourier space image. Default: True r - Optional : width of the gaussian mask to remove low-q noise, =r*width Set r=None will disable this mask. w - Optional : width of the mask that filters out noise along qx=0 and qy=0 lines. Set w=None will disable this mask. mask3 - Optional : Tuple for custom-defined mask. mask3 = [n, offset, width], where n is order of symmetry, offset is initial angle, width is the width of the mask. e.g., mask3 = [4, np.pi/4, 5], or mask3 = [6, 0, 10] Set mask3=None will disable this mask. even_out - Optional : Boolean, if True then Bragg peaks will be rounded to the make sure there are even number of lattice precise - Optional : Boolean, if True then a 2D Gaussian fit will be used to find the precise location of Bragg peaks width - Optional : Integer, defines how large the 2D Gaussian fit will be performed around each Bragg peaks p0 - Optional : List of initial parameters for fitting. Default: p0 = [amplitude,x0,y0,sigmaX,sigmaY,offset]=[1, width, width, 1, 1, 0] show - Optional : Boolean, if True then data A and Bragg peaks will be plotted. Returns: coords - (4x2) array contains Bragg peaks in the format of [[x1,y1],[x2,y2],...,[x4,y4]] Usage: import stmpy.driftcorr as dfc bp = dfc.findBraggs(A, min_dist=10, thres=0.2, rspace=True, show=True) History: 04/28/2017 JG : Initial commit. 04/29/2019 RL : Add maskon option, add outAll option, and add documents. ''' if rspace is True: F = stmpy.tools.fft(A, zeroDC=True) else: F = np.copy(A) # Remove low-q high intensity data with multiple masks *_, Y, X = np.shape(A) if r is not None: Lx = X * r Ly = Y * r x = np.arange(X) y = np.arange(Y) p0 = [int(X/2), int(Y/2), Lx, Ly, 1, np.pi/2] G = 1-stmpy.tools.gauss2d(x, y, p=p0) else: G = 1 if w is not None: mask2 = np.ones([Y, X]) mask2[Y//2-int(Y*w):Y//2+int(Y*w), :] = 0 mask2[:, X//2-int(X*w):X//2+int(X*w)] = 0 else: mask2 = 1 if mask3 is None: mask3 = 1 else: mask3 = mask_bp(A, p=mask3) F *= G * mask2 * mask3 coords = peak_local_max(F, min_distance=min_dist, threshold_rel=thres) coords = np.fliplr(coords) # This part is to make sure the Bragg peaks are located at even number of pixels if even_out is not False: coords = __even_bp(coords, s=np.shape(A)) if precise is not False: coords = np.asarray(coords, dtype='float32') if p0 is None: p0 = [1, width, width, 1, 1, 0] for i in range(len(coords)): area = stmpy.tools.crop(F/np.sum(F), cen=[int(k) for k in coords[i]], width=width) popt, g = fitGaussian2d(area, p0=p0) coords[i][0] += popt[1] - width coords[i][1] += popt[2] - width # This part shows the Bragg peak positions if show is not False: plt.figure(figsize=[4, 4]) c = np.mean(F) s = np.std(F) plt.imshow(F, cmap=plt.cm.gray_r, interpolation='None', origin='lower', clim=[0, c+5*s], aspect=1) plt.plot(coords[:, 0], coords[:, 1], 'r.') plt.gca().set_aspect(1) plt.axis('tight') center = (np.array(np.shape(A)[::-1])-1) // 2 print('The coordinates of the Bragg peaks are:') pprint(coords) print() print('The coordinates of the Q vectors are:') pprint(coords-center) return coords # help function: fitting 2D gaussian peaks around Bragg peaks def fitGaussian2d(data, p0): ''' Fit a 2D gaussian to the data with initial parameters p0. ''' data = np.array(data) def gauss(xy,amplitude,x0,y0,sigmaX,sigmaY,offset): x,y = xy theta = 90 x0=float(x0);y0=float(y0) a = 0.5*(np.cos(theta)/sigmaX)**2 + 0.5*(np.sin(theta)/sigmaY)**2 b = -np.sin(2*theta)/(2*sigmaX)**2 + np.sin(2*theta)/(2*sigmaY)**2 c = 0.5*(np.sin(theta)/sigmaX)**2 + 0.5*(np.cos(theta)/sigmaY)**2 g = offset+amplitude*np.exp(-( a*(x-x0)**2 -2*b*(x-x0)*(y-y0) + c*(y-y0)**2 )) return g.ravel() x = np.arange(data.shape[0]); y = np.arange(data.shape[1]) X,Y = np.meshgrid(x,y) popt, pcov = opt.curve_fit(gauss, (X,Y), data.ravel(), p0=p0) return popt, gauss((X,Y),*popt).reshape(data.shape) # help function: custom mask to remove unwanted Bragg peaks def mask_bp(A, p): n, offset, thres, *_ = p s = np.shape(A)[-1] t = np.arange(s) x, y = np.meshgrid(t, t) center = (np.array([s, s])-1) // 2 mask = np.ones_like(x) theta = 2 * np.pi / n for i in range(n): angle = theta * i + offset index = np.where(np.absolute(np.cos(angle)*(y-center[1]) - \ np.sin(angle)*(x-center[0])) < thres) mask[index] = 0 return mask # help function: make sure the Bragg peaks are located on even pixels def __even_bp(bp, s): ''' This internal function rounds the Bragg peaks to their nearest even number of Q vectors. ''' *_, s2, s1 = s center = (np.array([s1, s2])-1) // 2 bp_temp = bp - center for i, ix in enumerate(bp_temp): for j, num in enumerate(ix): if (num % 2) != 0: if num > 0: bp_temp[i, j] = num + 1 elif num <0: bp_temp[i, j] = num - 1 else: pass bp_even = bp_temp + center return bp_even #2 - cropedge def cropedge(A, n, bp=None, c1=2, c2=2, a1=None, a2=None, force_commen=False): """ Crop out bad pixels or highly drifted regions from topo/dos map. Inputs: A - Required : 2D or 3D array of image to be cropped. n - Required : List of integers specifying how many bad pixels to crop on each side. Order: [left, right, down, up]. force_commen- Optional : Boolean determining if the atomic lattice is commensurate with the output image. Returns: A_crop - 2D or 3D array of image after cropping. Usage: import stmpy.driftcorr as dfc A_crop = dfc.cropedge(A, n=5) History: 06/04/2019 RL : Initial commit. 11/30/2019 RL : Add support for non-square dataset """ if not isinstance(n, list): n = [n] if force_commen is False: B = _rough_cut(A, n=n) print('Shape before crop:', end=' ') print(A.shape) print('Shape after crop:', end=' ') print(B.shape) return B else: if n != 0: B = _rough_cut(A, n) else: B = np.copy(A) *_, L2, L1 = np.shape(A) if bp is None: bp = findBraggs(A, show=False) bp = sortBraggs(bp, s=np.shape(A)) bp_new = bp - (np.array([L1, L2])-1) // 2 N1 = compute_dist(bp_new[0], bp_new[1]) N2 = compute_dist(bp_new[0], bp_new[-1]) if a1 is None: a1 = c1 * L1 / N1 if a2 is None: a2 = a1 #a2 = c2 * L2 / N2 *_, L2, L1 = np.shape(B) L_new1 = a1 * ((L1)//(a1)) L_new2 = a2 * ((L2)//(a2)) t1 = np.arange(L1) t2 = np.arange(L2) if len(np.shape(A)) == 2: f = interp2d(t1, t2, B, kind='cubic') t_new1 = np.linspace(0, L_new1, num=L1+1) t_new2 = np.linspace(0, L_new2, num=L2+1) z_new = f(t_new1[:-1], t_new2[:-1]) elif len(np.shape(A)) == 3: z_new = np.zeros([np.shape(A)[0], L2, L1]) for i in range(len(A)): f = interp2d(t1, t2, B[i], kind='cubic') t_new1 = np.linspace(0, L_new1, num=L1+1) t_new2 = np.linspace(0, L_new2, num=L2+1) z_new[i] = f(t_new1[:-1], t_new2[:-1]) else: print('ERR: Input must be 2D or 3D numpy array!') return z_new # help function: crop edge without any interpolation def _rough_cut(A, n): B = np.copy(A) if len(n) == 1: n1 = n2 = n3 = n4 = n[0] else: n1, n2, n3, n4, *_ = n if len(B.shape) is 2: if n2 == 0: n2 = -B.shape[1] if n4 == 0: n4 = -B.shape[0] return B[n3:-n4, n1:-n2] elif len(B.shape) is 3: if n2 == 0: n2 = -B.shape[2] if n4 == 0: n4 = -B.shape[1] return B[:, n3:-n4, n1:-n2] # 4. phasemap def phasemap(A, bp, sigma=10, method="lockin"): ''' Calculate local phase and phase shift maps. Two methods are available now: spatial lockin or Gaussian mask convolution Input: A - Required : 2D arrays after global shear correction with bad pixels cropped on the edge bp - Required : Coords of Bragg peaks of FT(A), can be computed by findBraggs(A) sigma - Optional : width of DC filter in lockin method or len(A)/s method - Optional : Specify which method to use to calculate phase map. "lockin": Spatial lock-in method to find phase map "convolution": Gaussian mask convolution method to find phase map Returns: thetax - 2D array, Phase shift map in x direction, relative to perfectly generated cos lattice thetay - 2D array, Phase shift map in y direction, relative to perfectly generated cos lattice Q1 - Coordinates of 1st Bragg peak Q2 - Coordinates of 2nd Bragg peak Usage: import stmpy.driftcorr as dfc thetax, thetay, Q1, Q2 = dfc.phasemap(A, bp, sigma=10, method='lockin') History: 04/28/2017 JG : Initial commit. 04/29/2019 RL : Add "convolution" method, and add documents. 11/30/2019 RL : Add support for non-square dataset ''' *_, s2, s1 = A.shape if not isinstance(sigma, list): sigma = [sigma] if len(sigma) == 1: sigmax = sigmay = sigma[0] else: sigmax, sigmay, *_ = sigma s = np.minimum(s1, s2) bp = sortBraggs(bp, s=np.shape(A)) t1 = np.arange(s1, dtype='float') t2 = np.arange(s2, dtype='float') x, y = np.meshgrid(t1, t2) Q1 = 2*np.pi*np.array([(bp[0][0]-int((s1-1)/2))/s1, (bp[0][1]-int((s2-1)/2))/s2]) Q2 = 2*np.pi*np.array([(bp[1][0]-int((s1-1)/2))/s1, (bp[1][1]-int((s2-1)/2))/s2]) if method is "lockin": Axx = A * np.sin(Q1[0]*x+Q1[1]*y) Axy = A * np.cos(Q1[0]*x+Q1[1]*y) Ayx = A * np.sin(Q2[0]*x+Q2[1]*y) Ayy = A * np.cos(Q2[0]*x+Q2[1]*y) Axxf = FTDCfilter(Axx, sigmax, sigmay) Axyf = FTDCfilter(Axy, sigmax, sigmay) Ayxf = FTDCfilter(Ayx, sigmax, sigmay) Ayyf = FTDCfilter(Ayy, sigmax, sigmay) thetax = np.arctan2(Axxf, Axyf) thetay = np.arctan2(Ayxf, Ayyf) return thetax, thetay, Q1, Q2 elif method is "convolution": t_x = np.arange(s1) t_y = np.arange(s2) xcoords, ycoords = np.meshgrid(t_x, t_y) # (2.* np.pi/s)*(Q1[0] * xcoords + Q1[1] * ycoords) exponent_x = (Q1[0] * xcoords + Q1[1] * ycoords) # (2.* np.pi/s)*(Q2[0] * xcoords + Q2[1] * ycoords) exponent_y = (Q2[0] * xcoords + Q2[1] * ycoords) A_x = A * np.exp(np.complex(0, -1)*exponent_x) A_y = A * np.exp(np.complex(0, -1)*exponent_y) # sx = sigma # sy = sigma * s1 / s2 sx = sigmax sy = sigmay Amp = 1/(4*np.pi*sx*sy) p0 = [int((s-1)/2), int((s-1)/2), sx, sy, Amp, np.pi/2] G = stmpy.tools.gauss2d(t_x, t_y, p=p0, symmetric=True) T_x = sp.signal.fftconvolve(A_x, G, mode='same',) T_y = sp.signal.fftconvolve(A_y, G, mode='same',) R_x = np.abs(T_x) R_y = np.abs(T_y) phi_y = np.angle(T_y) phi_x = np.angle(T_x) return phi_x, phi_y, Q1, Q2 else: print('Only two methods are available now:\n1. lockin\n2. convolution') #5 - fixphaseslip def fixphaseslip(A, thres=None, maxval=None, method='unwrap', orient=0): ''' Fix phase slip by adding 2*pi at phase jump lines. Inputs: A - Required : 2D arrays of phase shift map, potentially containing phase slips thres - Optional : Float number, specifying threshold for finding phase jumps in diff(A). Default: None method - Optional : Specifying which method to fix phase slips. "unwrap": fix phase jumps line by line in x direction and y direction, respectively "spiral": fix phase slip in phase shift maps by flattening A into a 1D array in a spiral way orient - Optional : Used in "spiral" phase fixing method. 0 for clockwise and 1 for counter-clockwise Returns: phase_corr - 2D arrays of phase shift map with phase slips corrected Usage: import stmpy.driftcorr as dfc thetaxf = dfc.fixphaseslip(thetax, method='unwrap') History: 04/28/2017 JG : Initial commit. 04/29/2019 RL : Add "unwrap" method, and add documents. ''' output = np.copy(A[::-1, ::-1]) maxval = 2 * np.pi tol = 0.25 * maxval if len(np.shape(A)) == 2: *_, s2, s1 = np.shape(A) mid2 = s2 // 2 mid1 = s1 // 2 for i in range(s2): output[i, :] = unwrap_phase( output[i, :], tolerance=thres, maxval=maxval) for i in range(s1): output[:, i] = unwrap_phase( output[:, i], tolerance=thres, maxval=maxval) linex = output[:, mid1] liney = output[mid2, :] dphx = np.diff(linex) dphy = np.diff(liney) dphx[np.where(np.abs(dphx) < tol)] = 0 dphx[np.where(dphx < -tol)] = 1 dphx[np.where(dphx > tol)] = -1 dphy[np.where(np.abs(dphy) < tol)] = 0 dphy[np.where(dphy < -tol)] = 1 dphy[np.where(dphy > tol)] = -1 for i in range(s2): output[i, 1:] += 2*np.pi * np.cumsum(dphy) for i in range(s1): output[1:, i] += 2*np.pi * np.cumsum(dphx) return output[::-1, ::-1] #6 - unwrap_phase def unwrap_phase(ph, tolerance=None, maxval=None): maxval = 2 * np.pi if maxval is None else maxval tol = 0.25*maxval if tolerance is None else tolerance*maxval if len(ph) < 2: return ph dph = np.diff(ph) dph[np.where(np.abs(dph) < tol)] = 0 dph[np.where(dph < -tol)] = 1 dph[np.where(dph > tol)] = -1 ph[1:] += maxval * np.cumsum(dph) return ph def unwrap_phase_2d(A, thres=None): output = np.copy(A[::-1, ::-1]) if len(np.shape(A)) == 2: n = np.shape(A)[-1] for i in range(n): output[i, :] = unwrap_phase(output[i, :], tolerance=thres) for i in range(n): output[:, i] = unwrap_phase(output[:, i], tolerance=thres) return output[::-1, ::-1] #7 - driftmap def driftmap(phix=None, phiy=None, Q1=None, Q2=None, method="lockin"): ''' Calculate drift fields based on phase shift maps, with Q1 and Q2 generated by phasemap. Inputs: phix - Optional : 2D arrays of phase shift map in x direction with phase slips corrected phiy - Optional : 2D arrays of phase shift map in y direction with phase slips corrected Q1 - Optional : Coordinates of 1st Bragg peak, generated by phasemap Q2 - Optional : Coordinates of 2nd Bragg peak, generated by phasemap method - Optional : Specifying which method to use. "lockin": Used for phase shift map generated by lockin method "convolution": Used for phase shift map generated by lockin method Returns: ux - 2D array of drift field in x direction uy - 2D array of drift field in y direction Usage: import stmpy.driftcorr as dfc ux, uy = dfc.driftmap(thetaxf, thetayf, Q1, Q2, method='lockin') History: 04/28/2017 JG : Initial commit. 04/29/2019 RL : Add "lockin" method, and add documents. 11/30/2019 RL : Add support for non-square dataset ''' if method is "lockin": tx = np.copy(phix) ty = np.copy(phiy) ux = -(Q2[1]*tx - Q1[1]*ty) / (Q1[0]*Q2[1]-Q1[1]*Q2[0]) uy = -(Q2[0]*tx - Q1[0]*ty) / (Q1[1]*Q2[0]-Q1[0]*Q2[1]) return ux, uy elif method is "convolution": #s = np.shape(thetax)[-1] Qx_mag = np.sqrt((Q1[0])**2 + (Q1[1])**2) Qy_mag = np.sqrt((Q2[0])**2 + (Q2[1])**2) Qx_ang = np.arctan2(Q1[1], Q1[0]) # in radians Qy_ang = np.arctan2(Q2[1], Q2[0]) # in radians Qxdrift = 1/(Qx_mag) * phix # s/(2*np.pi*Qx_mag) * thetax Qydrift = 1/(Qy_mag) * phiy # s/(2*np.pi*Qy_mag) * thetay ux = Qxdrift * np.cos(Qx_ang) - Qydrift * np.sin(Qy_ang-np.pi/2) uy = Qxdrift * np.sin(Qx_ang) + Qydrift * np.cos(Qy_ang-np.pi/2) return -ux, -uy else: print("Only two methods are available now:\n1. lockin\n2. convolution") #8. - driftcorr def driftcorr(A, ux=None, uy=None, method="lockin", interpolation='cubic'): ''' Correct the drift in the topo according to drift fields Inputs: A - Required : 2D or 3D arrays of topo to be drift corrected ux - Optional : 2D arrays of drift field in x direction, generated by driftmap() uy - Optional : 2D arrays of drift field in y direction, generated by driftmap() method - Optional : Specifying which method to use. "lockin": Interpolate A and then apply it to a new set of coordinates, (x-ux, y-uy) "convolution": Used inversion fft to apply the drift fields interpolation - Optional : Specifying which method to use for interpolating Returns: A_corr - 2D or 3D array of topo with drift corrected Usage: import stmpy.driftcorr as dfc A_corr = dfc.driftcorr(ux, uy, method='interpolate', interpolation='cubic') History: 04/28/2017 JG : Initial commit. 04/29/2019 RL : Add "invfft" method, and add documents. 11/30/2019 RL : Add support for non-square dataset ''' if method is "lockin": A_corr = np.zeros_like(A) *_, s2, s1 = np.shape(A) t1 = np.arange(s1, dtype='float') t2 = np.arange(s2, dtype='float') x, y = np.meshgrid(t1, t2) xnew = (x - ux).ravel() ynew = (y - uy).ravel() tmp = np.zeros(s1*s2) if len(A.shape) is 2: tmp_f = interp2d(t1, t2, A, kind=interpolation) for ix in range(tmp.size): tmp[ix] = tmp_f(xnew[ix], ynew[ix]) A_corr = tmp.reshape(s2, s1) return A_corr elif len(A.shape) is 3: for iz, layer in enumerate(A): tmp_f = interp2d(t1, t2, layer, kind=interpolation) for ix in range(tmp.size): tmp[ix] = tmp_f(xnew[ix], ynew[ix]) A_corr[iz] = tmp.reshape(s2, s1) print('Processing slice %d/%d...' % (iz+1, A.shape[0]), end='\r') return A_corr else: print('ERR: Input must be 2D or 3D numpy array!') elif method is "convolution": A_corr = np.zeros_like(A) if len(A.shape) is 2: return _apply_drift_field(A, ux=ux, uy=uy, zeroOut=True) elif len(A.shape) is 3: for iz, layer in enumerate(A): A_corr[iz] = _apply_drift_field( layer, ux=ux, uy=uy, zeroOut=True) print('Processing slice %d/%d...' % (iz+1, A.shape[0]), end='\r') return A_corr else: print('ERR: Input must be 2D or 3D numpy array!') # help function: apply drift field using inverse FT method def _apply_drift_field(A, ux, uy, zeroOut=True): A_corr = np.copy(A) *_, s2, s1 = np.shape(A) t1 = np.arange(s1, dtype='float') t2 = np.arange(s2, dtype='float') x, y = np.meshgrid(t1, t2) xshifted = x - ux yshifted = y - uy if zeroOut is True: A_corr[np.where(xshifted < 0)] = 0 A_corr[np.where(yshifted < 0)] = 0 A_corr[np.where(xshifted > s1)] = 0 A_corr[np.where(yshifted > s2)] = 0 qcoordx = (2*np.pi/s1)*(np.arange(s1)-int(s1/2)) qcoordy = (2*np.pi/s2)*(np.arange(s2)-int(s2/2)) #qcoord = (2*np.pi/s)*(np.arange(s)-(s/2)) xshifted = np.reshape(xshifted, [1, s1*s2]) yshifted = np.reshape(yshifted, [1, s1*s2]) qcoordx = np.reshape(qcoordx, [s1, 1]) qcoordy = np.reshape(qcoordy, [s2, 1]) xphase = np.exp(-1j*(np.matmul(xshifted.T, qcoordx.T).T)) yphase = np.exp(-1j*(np.matmul(yshifted.T, qcoordy.T).T)) avgData = np.mean(A_corr) A_corr -= avgData A_corr = np.reshape(A_corr, s1*s2) data_temp = np.zeros([s2, s1*s2]) for i in range(s2): data_temp[i] = A_corr FT = np.matmul(data_temp * xphase, yphase.T).T invFT = np.fft.ifft2(np.fft.fftshift(FT)) + avgData return np.real(invFT) #9 def generate_bp(A, bp, angle=np.pi/2, orient=np.pi/4, even_out=False, obj=None): ''' Generate Bragg peaks with given q-vectorss Input: A - Required : 2D array of topo in real space, or FFT in q space. bp - Required : Bragg peaks associated with A, to be checked angle - Optional : Angle of the lattice. If the lattice is n-fold symmetry, then angle = 2*pi/n orient - Optional : Initial angle of Bragg peak, or orientation of the scan. Default is np.pi/4 obj - Optional : Data object that has bp_parameters with it, Return: bp_new : new Bragg peak generated from q-vectors Usage: bp_new = dfc.check_bp(A, qx=[qx1,qx2], qy=[qy1,qy2], obj=obj) History: 05-25-2020 RL : Initial commit. 06-08-2020 RL : Add the ability to compute correct Bragg peaks automatically ''' *_, s2, s1 = np.shape(A) bp = sortBraggs(bp, s=np.shape(A)) center = (np.array([s1, s2])-1) // 2 Q1, Q2, Q3, Q4, *_ = bp Qx_mag = compute_dist(Q1, center) Qy_mag = compute_dist(Q2, center) Q_corr = np.mean([Qx_mag, Qy_mag]) Qc1 = np.array([int(k) for k in Q_corr*np.array([np.cos(orient+np.pi), np.sin(orient+np.pi)])]) Qc2 = np.array([int(k) for k in Q_corr*np.array([np.cos(-angle+orient+np.pi), np.sin(-angle+orient+np.pi)])]) bp_out = np.array([Qc1, Qc2, -Qc1, -Qc2]) + center if even_out is not False: bp_out = __even_bp(bp_out, s=np.shape(A)) if obj is not None: pixels = np.shape(A)[::-1] __update_parameters(obj, a0=obj.parameters['a0'], bp=bp_out, pixels=pixels, size=obj.parameters['size'], use_a0=obj.parameters['use_a0']) return sortBraggs(bp_out, s=np.shape(A)) ################################################################################## ####################### Useful functions in the processing ####################### ################################################################################## def sortBraggs(bp, s): ''' Sort the Bragg peaks in the order of "lower left, lower right, upper right, and upper left" ''' *_, s2, s1 = s center = np.array([(s1 - 1) // 2, (s2 - 1) // 2]) out = np.array(sorted(bp-center, key=lambda x: np.arctan2(*x))) + center return out def Gaussian2d(x, y, sigma_x, sigma_y, theta, x0, y0, Amp): ''' x, y: ascending 1D array x0, y0: center ''' a = np.cos(theta)**2/2/sigma_x**2 + np.sin(theta)**2/2/sigma_y**2 b = -np.sin(2*theta)**2/4/sigma_x**2 + np.sin(2*theta)**2/4/sigma_y**2 c = np.sin(theta)**2/2/sigma_x**2 + np.cos(theta)**2/2/sigma_y**2 z = np.zeros((len(x), len(y))) X, Y = np.meshgrid(x, y) z = Amp * np.exp(-(a*(X-x0)**2 + 2*b*(X-x0)*(Y-y0) + c*(Y-y0)**2)) return z def FTDCfilter(A, sigma1, sigma2): ''' Filtering DC component of Fourier transform and inverse FT, using a gaussian with one parameter sigma A is a 2D array, sigma is in unit of px ''' *_, s2, s1 = A.shape m1, m2 = np.arange(s1, dtype='float'), np.arange(s2, dtype='float') c1, c2 = np.float((s1-1)/2), np.float((s2-1)/2) # sigma1 = sigma # sigma2 = sigma * s1 / s2 g = Gaussian2d(m1, m2, sigma1, sigma2, 0, c1, c2, 1) ft_A = np.fft.fftshift(np.fft.fft2(A)) ft_Af = ft_A * g Af = np.fft.ifft2(np.fft.ifftshift(ft_Af)) return np.real(Af) def compute_dist(x1, x2, p=None): ''' Compute the distance between point x1 and x2. ''' if p is None: p1, p2 = 1, 1 else: p1, p2 = p return np.sqrt(((x1[0]-x2[0])*p1)**2+((x1[1]-x2[1])*p2)**2) def bp_to_q(bp, A): ''' Convert the Bragg peaks to Q vectors by subtracting the center of the image. Input: bp - Required : Array of Bragg peaks A - Required : ''' center = (np.array(np.shape(A)[::-1])-1) // 2 return bp - center #15. - display def display(A, B=None, sigma=3, clim_same=True): ''' Display or compare images in both real space and q-space. Inputs: A - Required : Real space image to display. B - Optional : Another real space image to be compared with A. sigma - Optional : sigma for the color limit. clim_same - Optional : If True, then both FT of A and B will be displayed under the same color limit (determined by A). Returns: N/A Usage: import stmpy.driftcorr as dfc dfc.display(topo.z) ''' if B is None: A_fft = stmpy.tools.fft(A, zeroDC=True) c = np.mean(A_fft) s = np.std(A_fft) fig, ax = plt.subplots(1, 2, figsize=[8, 4]) ax[0].imshow(A, cmap=stmpy.cm.blue2, origin='lower') ax[1].imshow(A_fft, cmap=stmpy.cm.gray_r, origin='lower', clim=[0, c+sigma*s]) for ix in ax: ix.set_aspect(1) else: A_fft = stmpy.tools.fft(A, zeroDC=True) B_fft = stmpy.tools.fft(B, zeroDC=True) c1 = np.mean(A_fft) s1 = np.std(A_fft) if clim_same is True: c2 = c1 s2 = s1 else: c2 = np.mean(B_fft) s2 = np.std(B_fft) fig, ax = plt.subplots(2, 2, figsize=[8, 8]) ax[0, 0].imshow(A, cmap=stmpy.cm.blue2, origin='lower') ax[0, 1].imshow(A_fft, cmap=stmpy.cm.gray_r, origin='lower', clim=[0, c1+sigma*s1]) ax[1, 0].imshow(B, cmap=stmpy.cm.blue2, origin='lower') ax[1, 1].imshow(B_fft, cmap=stmpy.cm.gray_r, origin='lower', clim=[0, c2+sigma*s2]) for ix in ax.flatten(): ix.set_aspect(1) def quick_linecut(A, width=2, n=4, bp=None, ax=None, thres=3): """ Take four linecuts automatically, horizontal, vertical, and two diagonal. Inputs: A - Required : FT space image to take linecuts. width - Optional : Number of pixels for averaging. bp - Optional : Bragg peaks thres - Optional : threshold for displaying FT Returns: N/A Usage: import stmpy.driftcorr as dfc r, cut = dfc.quick_linecut(A) """ Y = np.shape(A)[-2] / 2 X = np.shape(A)[-1] / 2 r = [] cut = [] start = [[0, Y], [X, 0], [0, 0], [0, Y*2]] end = [[X*2, Y], [X, Y*2], [X*2, Y*2], [X*2, 0]] color = ['r', 'g', 'b', 'k'] plt.figure(figsize=[4, 4]) if len(np.shape(A)) == 3: if bp is None: bp_x = np.min(findBraggs(np.mean(A, axis=0), rspace=False)) else: bp_x = bp cm = np.mean(np.mean(A, axis=0)) cs = np.std(np.mean(A, axis=0)) plt.imshow(np.mean(A, axis=0), clim=[0, cm+thres*cs]) elif len(np.shape(A)) == 2: if bp is None: bp_x = np.min(findBraggs(A, rspace=False)) else: bp_x = bp cm = np.mean(A) cs = np.std(A) plt.imshow(A, clim=[0, cm+thres*cs]) qscale = X*2 / (X*2 - bp_x * 2) for i in range(n): r1, cut1 = stmpy.tools.linecut(A, start[i], end[i], width=width, show=True, ax=plt.gca(), color=color[i]) r.append(r1) cut.append(cut1) plt.gca().set_xlim(-1, X*2+1) plt.gca().set_ylim(-1, Y*2+1) return qscale, cut def quick_show(A, en, thres=5, rspace=True, saveon=False, qlimit=1.2, imgName='', extension='png'): layers = len(A) if rspace is False: imgsize = np.shape(A)[-1] bp_x = np.min(findBraggs(np.mean(A, axis=0), min_dist=int(imgsize/10), rspace=rspace)) ext = imgsize / (imgsize - 2*bp_x) if layers > 12: skip = layers // 12 else: skip = 1 fig, ax = plt.subplots(3, 4, figsize=[16, 12]) try: for i in range(12): c = np.mean(A[i*skip]) s = np.std(A[i*skip]) if rspace is True: ax[i//4, i % 4].imshow(A[i*skip], clim=[c - thres*s, c+thres*s], cmap=stmpy.cm.jackyPSD) else: ax[i//4, i % 4].imshow(A[i*skip], extent=[-ext, ext, -ext, ext, ], clim=[0, c+thres*s], cmap=stmpy.cm.gray_r) ax[i//4, i % 4].set_xlim(-qlimit, qlimit) ax[i//4, i % 4].set_ylim(-qlimit, qlimit) stmpy.image.add_label("${}$ mV".format( int(en[i*skip])), ax=ax[i//4, i % 4]) except IndexError: pass if saveon is True: plt.savefig("{}.{}".format(imgName, extension), bbox_inches='tight') def quick_show_cut(A, en, qscale, thres=5, thres2=None, saveon=False, qlimit=1.2, imgName='', extension="png"): fname = ["M-0", "M-90", "X-45", "X-135"] X1, Y1 = np.shape(A[0]) X2, Y2 = np.shape(A[-1]) q1 = np.linspace(-qscale, qscale, num=Y1) q2 = np.linspace(-qscale*np.sqrt(2), qscale*np.sqrt(2), num=Y2) if thres2 is None: thres2 = thres for i, ix in enumerate(A): plt.figure(figsize=[6, 3]) c = np.mean(ix) s = np.std(ix) if i in [0, 1]: plt.pcolormesh(q1, en, ix, cmap=stmpy.cm.gray_r, vmin=0, vmax=c+thres*s) else: plt.pcolormesh(q2, en, ix, cmap=stmpy.cm.gray_r, vmin=0, vmax=c+thres2*s) plt.gca().set_xlim(-qlimit, qlimit) plt.axvline(-1, linestyle='--') plt.axvline(1, linestyle='--') if saveon is True: plt.savefig( imgName + " along {}.{}".format(fname[i], extension), facecolor='w') # Quick show single images def quick_show_single(A, en, thres=5, fs=4, qscale=None, rspace=False, saveon=False, qlimit=1.2, imgName='', extension='png', dpi=400): layers = len(A) if rspace is False: if qscale is None: imgsize = np.shape(A)[-1] if len(np.shape(A)) == 3: A_topo = np.mean(A, axis=0) else: A_topo = A bp_x = np.min(findBraggs( A_topo, min_dist=int(imgsize/10), rspace=rspace)) ext = imgsize / (imgsize - 2*bp_x) else: ext = qscale if len(np.shape(A)) == 3: for i in range(layers): plt.figure(figsize=[fs, fs]) c = np.mean(A[i]) s = np.std(A[i]) if rspace is True: plt.imshow(A[i], clim=[c-thres*s, c+thres*s], cmap=stmpy.cm.jackyPSD) else: plt.imshow(A[i], extent=[-ext, ext, -ext, ext, ], clim=[0, c+thres*s], cmap=stmpy.cm.gray_r) plt.xlim(-qlimit, qlimit) plt.ylim(-qlimit, qlimit) #stmpy.image.add_label("${}$ mV".format(int(en[i])), ax=plt.gca()) plt.gca().axes.get_xaxis().set_visible(False) plt.gca().axes.get_yaxis().set_visible(False) plt.gca().set_frame_on(False) plt.gca().set_aspect(1) if saveon is True: if extension == 'png': plt.savefig("{} at {} mV.{}".format(imgName, int( en[i]), extension), dpi=dpi, bbox_inches='tight', pad_inches=0) else: plt.savefig("{} at {} mV.{}".format(imgName, int( en[i]), extension), bbox_inches='tight', pad_inches=0) elif len(np.shape(A)) == 2: plt.figure(figsize=[fs, fs]) c = np.mean(A) s = np.std(A) if rspace is True: plt.imshow(A, clim=[c-thres*s, c+thres*s], cmap=stmpy.cm.jackyPSD) else: plt.imshow(A, extent=[-ext, ext, -ext, ext, ], clim=[0, c+thres*s], cmap=stmpy.cm.gray_r) plt.xlim(-qlimit, qlimit) plt.ylim(-qlimit, qlimit) #stmpy.image.add_label("${}$ mV".format(int(en)), ax=plt.gca()) plt.gca().axes.get_xaxis().set_visible(False) plt.gca().axes.get_yaxis().set_visible(False) plt.gca().set_frame_on(False) plt.gca().set_aspect(1) if saveon is True: if extension == 'png': plt.savefig("{} at {} mV.{}".format(imgName, int( en), extension), dpi=dpi, bbox_inches='tight', pad_inches=0) else: plt.savefig("{} at {} mV.{}".format(imgName, int( en), extension), bbox_inches='tight', pad_inches=0) #11. - global_corr def global_corr(A, bp=None, show=False, angle=np.pi/2, orient=np.pi/4, obj=None, update_obj=False, **kwargs): """ Global shear correct the 2D topo automatically. Inputs: A - Required : 2D array of topo to be shear corrected. bp - Optional : Bragg points. If not offered, it will calculated from findBraggs(A) show - Optional : Boolean specifying if the results are plotted or not angle - Optional : Angle of the lattice. If the lattice is n-fold symmetry, then angle = 2*pi/n orient - Optional : orientation of the Bragg peaks, default as pi/4. Will be passed to gshearcorr **kwargs - Optional : keyword arguments for gshearcorr function obj - Optional : Data object that has bp_parameters with it, update_obj - Optional : Boolean, determines if the bp_parameters attribute will be updated according to current input. Returns: bp_1 - Bragg peaks returned by gshearcorr. To be used in local_corr() data_1 - 2D array of topo after global shear correction Usage: import stmpy.driftcorr as dfc matrix1, data1 = dfc.global_corr(A, show=True) History: 04/29/2019 RL : Initial commit. """ if obj is None: return __global_corr(A, bp=bp, show=show, angle=angle, orient=orient, **kwargs) else: if bp is None: bp = findBraggs(A, obj=obj) matrix, A_gcorr = __global_corr( A, bp=bp, show=show, angle=angle, orient=orient, **kwargs) if update_obj is not False: obj.matrix.append(matrix) bp_new = findBraggs(A_gcorr, obj=obj) pixels = np.shape(A_gcorr)[::-1] __update_parameters(obj, a0=obj.parameters['a0'], bp=bp_new, pixels=pixels, size=obj.parameters['size'], use_a0=obj.parameters['use_a0']) return matrix, A_gcorr def __global_corr(A, bp=None, show=False, angle=np.pi/2, orient=np.pi/4, **kwargs): *_, s2, s1 = np.shape(A) if bp is None: bp_1 = findBraggs(A, thres=0.2, show=show) else: bp_1 = bp m, data_1 = gshearcorr(A, bp_1, rspace=True, angle=angle, orient=orient, **kwargs) if show is True: fig, ax = plt.subplots(1, 2, figsize=[8, 4]) ax[0].imshow(data_1, cmap=stmpy.cm.blue2, origin='lower') ax[0].set_xlim(0, s1) ax[0].set_ylim(0, s2) ax[1].imshow(stmpy.tools.fft(data_1, zeroDC=True), cmap=stmpy.cm.gray_r, origin='lower') fig.suptitle('After global shear correction', fontsize=14) fig, ax = plt.subplots(2, 2, figsize=[8, 8]) ax[0, 0].imshow(data_1, cmap=stmpy.cm.blue2, origin='lower') ax[0, 1].imshow(data_1, cmap=stmpy.cm.blue2, origin='lower') ax[1, 0].imshow(data_1, cmap=stmpy.cm.blue2, origin='lower') ax[1, 1].imshow(data_1, cmap=stmpy.cm.blue2, origin='lower') ax[0, 0].set_xlim(0, s1/10) ax[0, 0].set_ylim(s2-s2/10, s2) ax[0, 1].set_xlim(s1-s1/10, s1) ax[0, 1].set_ylim(s2-s2/10, s2) ax[1, 0].set_xlim(0, s1/10) ax[1, 0].set_ylim(0, s2/10) ax[1, 1].set_xlim(s1-s1/10, s1) ax[1, 1].set_ylim(0, s2/10) fig.suptitle('Bad pixels in 4 corners', fontsize=14) return m, data_1 #12. - local_corr def local_corr(A, bp=None, sigma=10, method="lockin", fixMethod='unwrap', obj=None, update_obj=False, show=False): """ Locally drift correct 2D topo automatically. Inputs: A - Required : 2D array of topo after global shear correction, with bad pixels removed on the edge sigma - Optional : Floating number or list specifying the size of mask to be used in phasemap() bp - Optional : Bragg points. If not offered, it will calculated from findBraggs(A) method - Optional : Specifying which method to in phasemap() "lockin": Spatial lock-in method to find phase map "convolution": Gaussian mask convolution method to find phase map fixMethod - Optional : Specifying which method to use in fixphaseslip() "unwrap": fix phase jumps line by line in x direction and y direction, respectively "spiral": fix phase slip in phase shift maps by flattening A into a 1D array in a spiral way show - Optional : Boolean specifying if the results are plotted or not obj - Optional : Data object that has bp_parameters with it, update_obj - Optional : Boolean, determines if the bp_parameters attribute will be updated according to current input. **kwargs - Optional : key word arguments for findBraggs function Returns: ux - 2D array of drift field in x direction uy - 2D array of drift field in y direction data_corr - 2D array of topo after local drift corrected Usage: import stmpy.driftcorr as dfc ux, uy, data_corr = dfc.local_corr(A, sigma=5, method='lockin', fixMethod='unwrap', show=True) History: 04/29/2019 RL : Initial commit. """ if obj is None: return __local_corr(A, bp=bp, sigma=sigma, method=method, fixMethod=fixMethod, show=show) else: if bp is None: bp = findBraggs(A, obj=obj) ux, uy, A_corr = __local_corr(A, bp=bp, sigma=sigma, method=method, fixMethod=fixMethod, show=show) if update_obj is not False: obj.ux.append(ux) obj.uy.append(uy) return ux, uy, A_corr def __local_corr(A, bp=None, sigma=10, method="lockin", fixMethod='unwrap', show=False): *_, s2, s1 = np.shape(A) if bp is None: bp_2 = findBraggs(A, thres=0.2, show=show) else: bp_2 = bp thetax, thetay, Q1, Q2 = phasemap(A, bp=bp_2, method=method, sigma=sigma) if show is True: fig, ax = plt.subplots(1, 2, figsize=[8, 4]) ax[0].imshow(thetax, origin='lower') ax[1].imshow(thetay, origin='lower') fig.suptitle('Raw phase maps') thetaxf = fixphaseslip(thetax, method=fixMethod) thetayf = fixphaseslip(thetay, method=fixMethod) if show is True: fig, ax = plt.subplots(1, 2, figsize=[8, 4]) ax[0].imshow(thetaxf, origin='lower') ax[1].imshow(thetayf, origin='lower') fig.suptitle('After fixing phase slips') ux, uy = driftmap(thetaxf, thetayf, Q1, Q2, method=method) if method == 'lockin': data_corr = driftcorr(A, ux, uy, method='lockin', interpolation='cubic') elif method == 'convolution': data_corr = driftcorr(A, ux, uy, method='convolution',) else: print("Error: Only two methods are available, lockin or convolution.") if show is True: fig, ax = plt.subplots(2, 2, figsize=[8, 8]) ax[1, 0].imshow(data_corr, cmap=stmpy.cm.blue1, origin='lower') ax[1, 1].imshow(stmpy.tools.fft(data_corr, zeroDC=True), cmap=stmpy.cm.gray_r, origin='lower') ax[0, 0].imshow(A, cmap=stmpy.cm.blue1, origin='lower') ax[0, 1].imshow(stmpy.tools.fft(A, zeroDC=True), cmap=stmpy.cm.gray_r, origin='lower') fig.suptitle('Before and after local drift correction') return ux, uy, data_corr #14. - apply_dfc_3d def apply_dfc_3d(A, ux=None, uy=None, matrix=None, bp=None, n1=None, n2=None, obj=None, update_obj=False, method='lockin'): """ Apply drift field (both global and local) found in 2D to corresponding 3D map. Inputs: A - Required : 3D array of map to be drift corrected bp - Required : Coordinates of Bragg peaks returned by local_corr() ux - Required : 2D array of drift field in x direction. Usually generated by local_corr() uy - Required : 2D array of drift field in y direction. Usually generated by local_corr() crop1 - Optional : List of length 1 or length 4, specifying after global shear correction how much to crop on the edge crop2 - Optional : List of length 1 or length 4, specifying after local drift correction how much to crop on the edge method - Optional : Specifying which method to apply the drift correction "lockin": Interpolate A and then apply it to a new set of coordinates, (x-ux, y-uy) "convolution": Used inversion fft to apply the drift fields obj - Optional : Data object that has bp_parameters with it, update_obj - Optional : Boolean, determines if the bp_parameters attribute will be updated according to current input. Returns: data_corr - 3D array of topo after local drift corrected Usage: import stmpy.driftcorr as dfc data_corr = dfc.apply_dfc_3d(A, bp=bp, ux=ux, uy=uy, n1=n1, n2=n2, bp=bp, method='convolution') History: 04-29-2019 RL : Initial commit. 05-25-2020 RL : Add support for object inputs """ if obj is None: return __apply_dfc_3d(A, ux=ux, uy=uy, matrix=matrix, bp=bp, n1=n1, n2=n2, method=method) else: ux = obj.ux if ux is None else ux uy = obj.uy if uy is None else uy # matrix = obj.matrix if matrix is None else matrix bp = obj.bp if bp is None else bp return __apply_dfc_3d(A, ux=ux, uy=uy, matrix=matrix, bp=bp, n1=n1, n2=n2, method=method) def __apply_dfc_3d(A, ux, uy, matrix, bp=None, n1=None, n2=None, method='lockin'): data_c = np.zeros_like(A) if matrix is None: data_c =
np.copy(A)
numpy.copy
import numpy as np import scipy.io as sio from sklearn.svm import LinearSVC def flatImageByClass(data, tag): X, y = [], [] h, w, n = data.shape for i in range(n): X.append(data[:, :, i].reshape(h * w)) y.append(tag) return X, y data = sio.loadmat("../ExtYaleB10.mat") data_train, data_test = data["train"], data["test"] X_train, y_train = [], [] for tag in range(10): X_add, y_add = flatImageByClass(data_train[0][tag], tag) X_train += X_add y_train += y_add X_train, y_train = np.array(X_train), np.array(y_train) X_test, y_test = [], [] for tag in range(10): X_add, y_add = flatImageByClass(data_test[0][tag], tag) X_test += X_add y_test += y_add X_test, y_test =
np.array(X_test)
numpy.array
import numpy as np import matplotlib.pyplot as plt import tensorflow as tf import scipy.io as sio np.set_printoptions(formatter={'float': '{: .1e}'.format}) """ Clip Gradients Created on Wed Apr 14 21:01:53 2018 @author: <NAME> """ # Import MNIST data from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("./Data/MNIST/", one_hot=True) tf.reset_default_graph() # sess = tf.Session(config=tf.ConfigProto(gpu_options=tf.GPUOptions(allow_growth=True))) # Training Params num_steps = 20000 batch_size = 200 rho_mb = mnist.train.num_examples / batch_size # Network Params MethodName = 'GO' #MethodName = 'GRep' #MethodName = 'RSVI' Layers = 2 K = [784., 128., 64., 32.] h_dim = [0, 1024, 256, 128] alpha_z = 0.1 LR_q_z1 = 5e-5 # 5e-4 LR_q_W1 = 1.5 # 2e-1 LR_q_z2 = 1e-5 # 5e-4 LR_q_W2 = 0.5 # 2e-1 LR_q_W3 = 1.5 # 2e-1 min_z = 1e-5 min_W = 1e-5 min_z_alpha = 1e-3 min_z_beta = 1e-3 min_W_alpha = 1e-3 min_W_beta = 1e-3 # min_mean = 1e-4 min_z_alpha_rate = float(np.log(np.exp(min_z_alpha) - 1.)) min_z_beta_rate = float(np.log(np.exp(min_z_beta) - 1.)) min_W_alpha_rate = float(np.log(np.exp(min_W_alpha) - 1.)) min_W_beta_rate = float(np.log(np.exp(min_W_beta) - 1.)) # Compared method parameters B = 5 Bf = 5. def reject_h_boosted(p, alpha): # compute eps alpha_jian = alpha + B sqrtAlpha = tf.sqrt(9. * alpha_jian - 3.) t = alpha_jian - 1. / 3. powZA = tf.pow((p / t), 1. / 3.) eps = tf.stop_gradient( sqrtAlpha * (powZA - 1.)) b = (alpha_jian) - 1. / 3. c = 1. / tf.sqrt(9. * b) v = 1. + eps * c v = tf.sign(v)*tf.maximum(tf.abs(v),1e-7) z_jian = b * tf.pow(v, 3.) z_jian = tf.maximum(z_jian,1e-7) # compute z_bo ni = alpha.shape[0] ki = alpha.shape[1] alpha = alpha[:, :, tf.newaxis] tmp = tf.range(Bf) tmp = tmp[tf.newaxis, tf.newaxis, :] alpha_vec = tf.tile(alpha, [1, 1, B]) + tf.tile(tmp, [ni, ki, 1]) u = tf.maximum(tf.random_uniform([int(ni), int(ki), B]), 1e-7) u_pow = tf.pow(u, 1. / alpha_vec) z_bo = tf.keras.backend.prod(u_pow, axis=2) * z_jian # g_corr log_q = - tf.lgamma(alpha_jian) + (alpha_jian - 1.) * tf.log(z_jian) - z_jian log_PzPeps = tf.log(3. * b) + 2 * tf.log(v) - 0.5 * tf.log(9. * b) f_corr = tf.reduce_sum(log_q + log_PzPeps) return z_bo, f_corr # Recognition Model - q_z_x def q_z_x(name, x, K, reuse=False): with tf.variable_scope('q_z_x' + name, reuse=reuse): # h1 = tf.nn.relu(tf.layers.dense(x, units=h_dim[1])) h1 = x z_Ralpha1 = tf.layers.dense(h1, units=K, kernel_initializer=tf.random_normal_initializer(0, 0.01)) z_Ralpha1 = max_m_grad(min_z_alpha_rate, z_Ralpha1) # z_Ralpha1 = tf.maximum(min_z_alpha_rate, z_Ralpha1) z_alpha1 = tf.nn.softplus(z_Ralpha1) z_Rbeta1 = tf.layers.dense(h1, units=K, kernel_initializer=tf.random_normal_initializer(0, 0.01)) z_Rbeta1 = max_m_grad(min_z_beta_rate, z_Rbeta1) # z_Rbeta1 = tf.maximum(min_z_beta_rate, z_Rbeta1) z_beta1 = tf.nn.softplus(z_Rbeta1) # z_beta1 = min_m_grad(z_alpha1 / min_mean, z_beta1) if MethodName == 'GO': z_hat1s = tf.random_gamma([1], tf.stop_gradient(z_alpha1), 1.) z_hat1s = tf.maximum(min_z, tf.squeeze(z_hat1s, 0)) Grad_z_alpha1 = GO_Gamma_v2(tf.stop_gradient(z_hat1s), tf.stop_gradient(z_alpha1)) z_hat1 = z_alpha1 * tf.stop_gradient(Grad_z_alpha1) - \ tf.stop_gradient(z_alpha1 * Grad_z_alpha1) + \ tf.stop_gradient(z_hat1s) z1_Fcorr = tf.zeros([1]) if MethodName == 'GRep': posi0 = tf.polygamma(tf.constant(0,dtype=tf.float32),z_alpha1) posi1 = tf.polygamma(tf.constant(1,dtype=tf.float32),z_alpha1) z_hat1s = tf.random_gamma([1], tf.stop_gradient(z_alpha1), 1.) z_hat1s = tf.maximum(min_z, tf.squeeze(z_hat1s, 0)) epsilo = tf.stop_gradient( (tf.log(z_hat1s)-posi0)/tf.maximum((tf.pow(posi1,0.5)),1e-5) ) log_z_hat1 = epsilo*tf.pow(posi1,0.5)+posi0 z_hat1 = tf.exp( log_z_hat1 ) z1_Fcorr = tf.reduce_sum( - tf.lgamma(z_alpha1) + (z_alpha1-1.)*log_z_hat1 - z_hat1 + log_z_hat1 + 0.5 * tf.log( posi1 ) ) if MethodName == 'RSVI': lambda_z1 = tf.squeeze(tf.random_gamma([1], z_alpha1 + Bf, 1.), 0) lambda_z1 = tf.stop_gradient(tf.maximum(min_z, lambda_z1)) z_hat1, z1_Fcorr = reject_h_boosted(lambda_z1, z_alpha1) z1 = z_hat1 / z_beta1 # z1 = tf.maximum(min_z, z1) z1 = max_m_grad(min_z, z1) return z1, z_alpha1, z_beta1, z1_Fcorr def max_m_grad(epsi, x): y = tf.maximum(epsi, x) yout = x - tf.stop_gradient(x) + tf.stop_gradient(y) return yout def min_m_grad(epsi, x): y = tf.minimum(epsi, x) yout = x - tf.stop_gradient(x) + tf.stop_gradient(y) return yout def map_Dir_64(Phi, Eps): # Phi: V * K Eps = tf.cast(Eps, tf.float64) Phi = tf.cast(Phi, tf.float64) PhiT = tf.transpose(Phi) Kphi = PhiT.shape[0] Vphi = PhiT.shape[1] PhiTsort, _ = tf.nn.top_k(PhiT, Vphi) CumPhiT = tf.cumsum(PhiTsort, 1) i_v = tf.range(1, tf.cast(Vphi, tf.float64), dtype=tf.float64) tmp = CumPhiT[:, :Vphi - 1] - tf.expand_dims(i_v, 0) * PhiTsort[:, 1:] tmp1 = tf.to_float(tmp >= (1. - tf.cast(Vphi, tf.float64) * Eps)) B, I = tf.nn.top_k(tmp1) B = tf.cast(B, tf.float64) I = tf.cast(I, tf.float64) I = I + (1. - B) * (tf.cast(Vphi, tf.float64) - 1.) indx0 = tf.range(Kphi, dtype=tf.int64) indx = tf.concat([indx0[:, tf.newaxis], tf.cast(I, tf.int64)], axis=1) delta = (1. - Eps * (tf.cast(Vphi, tf.float64) - I - 1.) - tf.expand_dims(tf.gather_nd(CumPhiT, indx), 1)) / ( I + 1.) Phihat = tf.maximum(Eps, Phi + tf.transpose(delta)) Phiout = Phi - tf.stop_gradient(Phi) + tf.stop_gradient(Phihat) Phiout = tf.cast(Phiout, tf.float32) return Phiout # GO Gamma Gradients def GO_Gamma_v2(x, alpha): # x sim Gamma(alpha, 1) x = tf.cast(x, tf.float64) alpha = tf.cast(alpha, tf.float64) logx = tf.log(x) ex_gamma_xa = tf.exp(x + tf.lgamma(alpha) + (1. - alpha) * logx) psi_m_log = tf.digamma(alpha + 1.) - logx igamma_up_reg = tf.igammac(alpha, x) # Part 1 indx1 = tf.where(x <= 1e-2) x_indx1 = tf.gather_nd(x, indx1) alpha_indx1 = tf.gather_nd(alpha, indx1) GO_Gamma_alpha_value1 = tf.exp(x_indx1) * x_indx1 / alpha_indx1 * ( tf.gather_nd(psi_m_log, indx1) + x_indx1 / tf.pow(alpha_indx1 + 1., 2) - tf.pow(x_indx1 / (alpha_indx1 + 2.), 2) + 0.5 * tf.pow(x_indx1, 3) / tf.pow(alpha_indx1 + 3., 2) ) # Part 2 N_alpha = tf.round(tf.exp( - 0.488484605941243044124888683654717169702053070068359375 * tf.log(alpha) + 1.6948389987594634220613443176262080669403076171875 )) indx2 = tf.where(tf.logical_and( tf.logical_and(x > 1e-2, alpha <= 3.), (x <= (alpha + N_alpha * tf.sqrt(alpha))) )) KK = 15 kk = tf.cast(tf.range(1, KK + 1), tf.float64) x_indx2 = tf.gather_nd(x, indx2) alpha_indx2 = tf.gather_nd(alpha, indx2) GO_Gamma_alpha_value2 = tf.gather_nd(ex_gamma_xa, indx2) * ( -tf.gather_nd(psi_m_log, indx2) * tf.gather_nd(igamma_up_reg, indx2) + ( tf.digamma(alpha_indx2 + KK + 1.) - tf.gather_nd(logx, indx2) - tf.reduce_sum( tf.igammac(tf.expand_dims(alpha_indx2, 1) + tf.expand_dims(kk, 0), tf.expand_dims(x_indx2, 1)) / (tf.expand_dims(alpha_indx2, 1) + tf.expand_dims(kk, 0)) , 1) ) ) # Part 2_1 indx2_1 = tf.where(tf.logical_and( tf.logical_and(x > 1e-2, alpha <= 3.), (x > (alpha + N_alpha * tf.sqrt(alpha))) )) KK = 15 kk = tf.cast(tf.range(1, KK + 1), tf.float64) x_indx2_1 = tf.gather_nd(x, indx2_1) alpha_indx2_1 = tf.gather_nd(alpha, indx2_1) GO_Gamma_alpha_value2_1 = tf.gather_nd(ex_gamma_xa, indx2_1) * ( -tf.gather_nd(psi_m_log, indx2_1) * tf.gather_nd(igamma_up_reg, indx2_1) + ( tf.digamma(alpha_indx2_1 + KK + 1.) - tf.gather_nd(logx, indx2_1) - tf.reduce_sum( tf.igammac(tf.expand_dims(alpha_indx2_1, 1) + tf.expand_dims(kk, 0), tf.expand_dims(x_indx2_1, 1)) / (tf.expand_dims(alpha_indx2_1, 1) + tf.expand_dims(kk, 0)) , 1) ) ) GO_Gamma_alpha_value2_1 = tf.maximum( GO_Gamma_alpha_value2_1, 1. / alpha_indx2_1 - tf.gather_nd(ex_gamma_xa, indx2_1) * tf.gather_nd(psi_m_log, indx2_1) * tf.gather_nd(igamma_up_reg, indx2_1) ) # Part 3 indx3 = tf.where( tf.logical_and( tf.logical_and(x > 1e-2, alpha > 3.), alpha <= 500. ) ) KK = 10 kk = tf.cast(tf.range(1, KK + 1), tf.float64) x_indx3 = tf.gather_nd(x, indx3) alpha_indx3 = tf.gather_nd(alpha, indx3) x_l = alpha_indx3 - tf.log(alpha_indx3) * tf.sqrt(alpha_indx3) logx_l = tf.log(x_l) ex_gamma_xa_l = tf.exp(x_l + tf.lgamma(alpha_indx3) + (1. - alpha_indx3) * logx_l) psi_m_log_l = tf.digamma(alpha_indx3 + 1.) - logx_l igamma_low_reg_l = tf.igamma(alpha_indx3, x_l) # igamma_up_reg_l = tf.igammac(alpha_indx3, x_l) # f_l = ex_gamma_xa_l * ( # -psi_m_log_l * igamma_up_reg_l + # (tf.digamma(alpha_indx3 + KK + 1.) - logx_l - # tf.reduce_sum( # tf.igammac(tf.expand_dims(alpha_indx3, 1) + tf.expand_dims(kk, 0), tf.expand_dims(x_l, 1)) / # (tf.expand_dims(alpha_indx3, 1) + tf.expand_dims(kk, 0)) # , 1)) # ) f_l = ex_gamma_xa_l * ( psi_m_log_l * igamma_low_reg_l + tf.reduce_sum( tf.igamma(tf.expand_dims(alpha_indx3, 1) + tf.expand_dims(kk, 0), tf.expand_dims(x_l, 1)) / (tf.expand_dims(alpha_indx3, 1) + tf.expand_dims(kk, 0)) , 1) ) g_l = (1. + (1. - alpha_indx3) / x_l) * f_l + ( -ex_gamma_xa_l / x_l * igamma_low_reg_l + (psi_m_log_l + tf.reduce_sum( tf.exp( tf.expand_dims(kk, 0) * tf.log(tf.expand_dims(x_l, 1)) + tf.lgamma(tf.expand_dims(alpha_indx3, 1)) - tf.lgamma( tf.expand_dims(alpha_indx3, 1) + tf.expand_dims(kk, 0) + 1.) ) , 1)) ) x_m = alpha_indx3 f_m = 1. + 0.167303227226226980395296095593948848545551300048828125 / \ ( tf.pow(x_m, 1.0008649793164192676186985409003682434558868408203125) - 0.07516433982238841793321881823430885560810565948486328125 ) x_r = 2. * alpha_indx3 - x_l f_r = 1. / alpha_indx3 - tf.exp(x_r + tf.lgamma(alpha_indx3) + (1. - alpha_indx3) * tf.log(x_r)) * ( (tf.digamma(alpha_indx3 + 1.) - tf.log(x_r)) * tf.igammac(alpha_indx3, x_r) ) lambda_r = tf.exp( 959.627335718427275423891842365264892578125 / ( tf.pow(alpha_indx3, 1.324768828487964622553363369661383330821990966796875) + 142.427456986662718918523751199245452880859375 ) - 13.01439996187340142341781756840646266937255859375 ) x_mat_i = tf.concat([tf.expand_dims(x_l, 1), tf.expand_dims(x_m, 1), tf.expand_dims(x_r, 1)], 1) x_mat_bar_i = x_mat_i - tf.expand_dims(alpha_indx3, 1) x_mat_hat_i = tf.sqrt(x_mat_i) - tf.sqrt(tf.expand_dims(alpha_indx3, 1)) f_mat_i = tf.concat([tf.expand_dims(f_l, 1), tf.expand_dims(f_m, 1), tf.expand_dims(f_r, 1)], 1) lambda_mat_i = tf.concat([tf.expand_dims(tf.ones_like(alpha_indx3), 1), tf.expand_dims(tf.ones_like(alpha_indx3), 1), tf.expand_dims(lambda_r, 1) ], 1) x_mat_j = tf.expand_dims(x_l, 1) g_mat_j = tf.expand_dims(g_l, 1) lambda_mat_j = tf.expand_dims(tf.ones_like(alpha_indx3), 1) A = tf.reduce_sum(lambda_mat_i * tf.pow(x_mat_bar_i, 2), 1) + tf.reduce_sum(lambda_mat_j, 1) B = tf.reduce_sum(lambda_mat_i * x_mat_bar_i * x_mat_hat_i, 1) + \ tf.reduce_sum(lambda_mat_j / 2. / tf.sqrt(x_mat_j), 1) C = tf.reduce_sum(lambda_mat_i * x_mat_bar_i, 1) D = tf.reduce_sum(lambda_mat_i * tf.pow(x_mat_hat_i, 2), 1) + tf.reduce_sum(lambda_mat_j / 4. / x_mat_j, 1) E = tf.reduce_sum(lambda_mat_i * x_mat_hat_i, 1) F = tf.reduce_sum(lambda_mat_i, 1) G = tf.reduce_sum(lambda_mat_i * x_mat_bar_i * f_mat_i, 1) + tf.reduce_sum(lambda_mat_j * g_mat_j, 1) H = tf.reduce_sum(lambda_mat_i * x_mat_hat_i * f_mat_i, 1) + \ tf.reduce_sum(lambda_mat_j / 2. / tf.sqrt(x_mat_j) * g_mat_j, 1) I = tf.reduce_sum(lambda_mat_i * f_mat_i, 1) Z = F * tf.pow(B, 2) - 2. * B * C * E + D * tf.pow(C, 2) + A * tf.pow(E, 2) - A * D * F a_cor = 1. / Z * (G * (tf.pow(E, 2) - D * F) + H * (B * F - C * E) - I * (B * E - C * D)) b_cor = 1. / Z * (G * (B * F - C * E) + H * (tf.pow(C, 2) - A * F) - I * (B * C - A * E)) c_cor = 1. / Z * (-G * (B * E - C * D) + I * (tf.pow(B, 2) - A * D) - H * (B * C - A * E)) GO_Gamma_alpha_value3 = a_cor * (x_indx3 - alpha_indx3) + b_cor * (tf.sqrt(x_indx3) - tf.sqrt(alpha_indx3)) + c_cor GO_Gamma_alpha_value3 = tf.maximum( GO_Gamma_alpha_value3, 1. / alpha_indx3 - tf.gather_nd(ex_gamma_xa, indx3) * tf.gather_nd(psi_m_log, indx3) * tf.gather_nd(igamma_up_reg, indx3) ) # Part 4 # indx4 = tf.where( # tf.logical_and( # tf.logical_and(x > 1e-2, alpha > 500.), # (x <= (alpha + 2. * tf.log(alpha) * tf.sqrt(alpha))) # ) # ) indx4 = tf.where( tf.logical_and(x > 1e-2, alpha > 500.) ) x_indx4 = tf.gather_nd(x, indx4) alpha_indx4 = tf.gather_nd(alpha, indx4) f_m_large = 1. + 0.167303227226226980395296095593948848545551300048828125 / \ ( tf.pow(alpha_indx4, 1.0008649793164192676186985409003682434558868408203125) - 0.07516433982238841793321881823430885560810565948486328125 ) g_m_large = 0.54116502161502622048061539317131973803043365478515625 * \ tf.pow(alpha_indx4, -1.010274491769996618728555404231883585453033447265625) GO_Gamma_alpha_value4 = f_m_large + g_m_large * (x_indx4 - alpha_indx4) # Part 4_1 # indx4_1 = tf.where( # tf.logical_and( # tf.logical_and(x > 1e-2, alpha > 500.), # (x > (alpha + 2. * tf.log(alpha) * tf.sqrt(alpha))) # ) # ) # alpha_indx4_1 = tf.gather_nd(alpha, indx4_1) # GO_Gamma_alpha_value4_1 = 1. / alpha_indx4_1 - tf.gather_nd(ex_gamma_xa, indx4_1) * \ # tf.gather_nd(psi_m_log, indx4_1) * tf.gather_nd(igamma_up_reg, indx4_1) # Summerize GO_Gamma_alpha = tf.sparse_to_dense(indx1, x.shape, GO_Gamma_alpha_value1) + \ tf.sparse_to_dense(indx2, x.shape, GO_Gamma_alpha_value2) + \ tf.sparse_to_dense(indx2_1, x.shape, GO_Gamma_alpha_value2_1) + \ tf.sparse_to_dense(indx3, x.shape, GO_Gamma_alpha_value3) + \ tf.sparse_to_dense(indx4, x.shape, GO_Gamma_alpha_value4) # + \ # tf.sparse_to_dense(indx4_1, x.shape, GO_Gamma_alpha_value4_1) GO_Gamma_alpha = tf.cast(GO_Gamma_alpha, tf.float32) return GO_Gamma_alpha # , x_l, x_r, f_l, f_m, f_r, g_l # Recognition Model - q_W def q_W(name, V, K, reuse=False): with tf.variable_scope('q_W' + name, reuse=reuse): W_aW = tf.get_variable("W_aW", [V, K], tf.float32, tf.random_uniform_initializer(0.1, 10)) RW_aW = max_m_grad(min_W_alpha_rate, W_aW) # RW_aW = tf.maximum(min_W_alpha_rate, W_aW) W_alpha = tf.nn.softplus(RW_aW) W_bW = tf.get_variable("W_bW", [V, K], tf.float32, tf.random_uniform_initializer(0.1, 10)) RW_bW = max_m_grad(min_W_beta_rate, W_bW) # RW_bW = tf.maximum(min_W_beta_rate, W_bW) W_beta = tf.nn.softplus(RW_bW) # W_beta = tf.nn.softplus(W_bW) # W_beta = min_m_grad(W_alpha / min_mean, W_beta) if MethodName == 'GO': W_hat1s = tf.random_gamma([1], tf.stop_gradient(W_alpha), 1.) W_hat1s = tf.maximum(min_W, tf.squeeze(W_hat1s, 0)) Grad_W_alpha1 = GO_Gamma_v2(tf.stop_gradient(W_hat1s), tf.stop_gradient(W_alpha)) W_hat1 = W_alpha * tf.stop_gradient(Grad_W_alpha1) - \ tf.stop_gradient(W_alpha * Grad_W_alpha1) + \ tf.stop_gradient(W_hat1s) W1_Fcorr = tf.zeros([1]) if MethodName == 'GRep': posi0 = tf.polygamma(tf.constant(0,dtype=tf.float32),W_alpha) posi1 = tf.polygamma(tf.constant(1,dtype=tf.float32),W_alpha) W_hat1s = tf.random_gamma([1], tf.stop_gradient(W_alpha), 1.) W_hat1s = tf.maximum(min_W, tf.squeeze(W_hat1s, 0)) epsilo = tf.stop_gradient( (tf.log(W_hat1s)-posi0)/tf.maximum((tf.pow(posi1,0.5)),1e-8) ) log_W_hat1 = epsilo*tf.pow(posi1,0.5)+posi0 W_hat1 = tf.exp( log_W_hat1 ) W1_Fcorr = tf.reduce_sum( - tf.lgamma(W_alpha) + (W_alpha-1.)*log_W_hat1 - W_hat1 + log_W_hat1 + 0.5 * tf.log( posi1 ) ) if MethodName == 'RSVI': lambda_W1 = tf.squeeze(tf.random_gamma([1], W_alpha + Bf, 1.), 0) lambda_W1 = tf.stop_gradient(tf.maximum(min_W, lambda_W1)) W_hat1, W1_Fcorr = reject_h_boosted(lambda_W1, W_alpha) W = W_hat1 / W_beta # W = tf.maximum(min_W, W) W = max_m_grad(min_W, W) return W, W_alpha, W_beta, W1_Fcorr def log_gamma_minus(x, a1, b1, a2, b2): yout = tf.reduce_sum( a1 * tf.log(b1) - a2 * tf.log(b2) + tf.lgamma(a2) - tf.lgamma(a1) + (a1 - a2) * tf.log(x) - (b1 - b2) * x ) return yout def log_Gamma(x, a1, b1): yout = tf.reduce_sum( a1 * tf.log(b1) - tf.lgamma(a1) + (a1 - 1.) * tf.log(x) - b1 * x ) return yout def log_Poisson(x, lambda1): yout = tf.reduce_sum( x * tf.log(lambda1) - lambda1 - tf.lgamma(x + 1.) ) return yout # z ~ q(z|x) & W ~ q(W) x = tf.placeholder(tf.float32, shape=[batch_size, K[0]]) z1, z_alpha1, z_beta1, z1_Fcorr = q_z_x('_z_1', x, K[1]) W1, W_alpha1, W_beta1, W1_Fcorr = q_W('_W_1', K[0], K[1]) if Layers >= 2: z2, z_alpha2, z_beta2, z2_Fcorr = q_z_x('_z_2', z1, K[2]) W2, W_alpha2, W_beta2, W2_Fcorr = q_W('_W_2', K[1], K[2]) if Layers >= 3: z3, z_alpha3, z_beta3, z3_Fcorr = q_z_x('_z_3', z2, K[3]) W3, W_alpha3, W_beta3, W3_Fcorr = q_W('_W_3', K[2], K[3]) # Calculate ELBO # truncate Phitheta ELBO_z_trunc = tf.placeholder(tf.float32, [5], name='ELBO_z_trunc') ELBO_W_trunc = tf.placeholder(tf.float32, [5], name='ELBO_W_trunc') ELBO_Wz_trunc = tf.placeholder(tf.float32, [5], name='ELBO_Wz_trunc') # Layer 1 Wz1 = tf.matmul(z1, tf.transpose(W1)) Loglike = log_Poisson(x, Wz1) / (K[0] * batch_size) Loglike_E = log_Poisson(x, Wz1) / (K[0] * batch_size) E_recon1 = tf.reduce_mean(tf.abs(x - Wz1)) z1T = max_m_grad(ELBO_z_trunc[1], z1) W1T = max_m_grad(ELBO_W_trunc[1], W1) # z1T = tf.maximum(ELBO_z_trunc[1], z1) # W1T = tf.maximum(ELBO_W_trunc[1], W1) #z1T = z1 #W1T = W1 if Layers == 1: Log_pmq_z1 = log_gamma_minus(z1T, 0.1, 0.1, tf.stop_gradient(z_alpha1), tf.stop_gradient(z_beta1) ) / (K[0] * batch_size) Log_pmq_z1_E = log_gamma_minus(z1, 0.1, 0.1, z_alpha1, z_beta1) / (K[0] * batch_size) else: Wz2 = tf.matmul(z2, tf.transpose(W2)) # Wz2 = max_m_grad(ELBO_Wz_trunc[2], Wz2) Log_pmq_z1 = log_gamma_minus(z1T, alpha_z, alpha_z / Wz2, tf.stop_gradient(z_alpha1), tf.stop_gradient(z_beta1) ) / (K[0] * batch_size) Log_pmq_z1_E = log_gamma_minus(z1, alpha_z, alpha_z / Wz2, z_alpha1, z_beta1) / (K[0] * batch_size) E_recon2 = tf.reduce_mean(tf.abs(x - tf.matmul(Wz2, tf.transpose(W1)))) Log_pmq_W1 = log_gamma_minus(W1T, 0.1, 0.3, tf.stop_gradient(W_alpha1), tf.stop_gradient(W_beta1) ) / (K[0] * rho_mb * batch_size) Log_pmq_W1_E = log_gamma_minus(W1, 0.1, 0.3, W_alpha1, W_beta1) / (K[0] * rho_mb * batch_size) ELBO = Loglike + Log_pmq_z1 + Log_pmq_W1 ELBO_E = Loglike_E + Log_pmq_z1_E + Log_pmq_W1_E # Layer 2 if Layers >= 2: z2T = max_m_grad(ELBO_z_trunc[2], z2) W2T = max_m_grad(ELBO_W_trunc[2], W2) # z2T = tf.maximum(ELBO_z_trunc[2], z2) # W2T = tf.maximum(ELBO_W_trunc[2], W2) # z2T = z2 # W2T = W2 if Layers == 2: Log_pmq_z2 = log_gamma_minus(z2T, 0.1, 0.1, tf.stop_gradient(z_alpha2), tf.stop_gradient(z_beta2) ) / (K[0] * batch_size) Log_pmq_z2_E = log_gamma_minus(z2, 0.1, 0.1, z_alpha2, z_beta2) / (K[0] * batch_size) else: Wz3 = tf.matmul(z3, tf.transpose(W3)) # Wz3 = max_m_grad(ELBO_Wz_trunc[3], Wz3) Log_pmq_z2 = log_gamma_minus(z2T, alpha_z, alpha_z / Wz3, tf.stop_gradient(z_alpha2), tf.stop_gradient(z_beta2) ) / (K[0] * batch_size) Log_pmq_z2_E = log_gamma_minus(z2, alpha_z, alpha_z / Wz3, z_alpha2, z_beta2) / (K[0] * batch_size) E_recon3 = tf.reduce_mean(tf.abs(x - tf.matmul(tf.matmul(Wz3, tf.transpose(W2)), tf.transpose(W1)))) Log_pmq_W2 = log_gamma_minus(W2T, 0.1, 0.3, tf.stop_gradient(W_alpha2), tf.stop_gradient(W_beta2) ) / (K[0] * rho_mb * batch_size) Log_pmq_W2_E = log_gamma_minus(W2, 0.1, 0.3, W_alpha2, W_beta2) / (K[0] * rho_mb * batch_size) ELBO = ELBO + Log_pmq_z2 + Log_pmq_W2 ELBO_E = ELBO_E + Log_pmq_z2_E + Log_pmq_W2_E # Layer 3 if Layers >= 3: # z3T = max_m_grad(ELBO_z_trunc[3], z3) # W3T = max_m_grad(ELBO_W_trunc[3], W3) # z3T = tf.maximum(ELBO_z_trunc[3], z3) # W3T = tf.maximum(ELBO_W_trunc[3], W3) z3T = z3 W3T = W3 if Layers == 3: Log_pmq_z3 = log_gamma_minus(z3T, 0.1, 0.1, tf.stop_gradient(z_alpha3), tf.stop_gradient(z_beta3) ) / (K[0] * batch_size) Log_pmq_z3_E = log_gamma_minus(z3, 0.1, 0.1, z_alpha3, z_beta3) / (K[0] * batch_size) else: Wz4 = tf.matmul(z4, tf.transpose(W4)) # Wz4 = max_m_grad(ELBO_Wz_trunc[4], Wz4) Log_pmq_z3 = log_gamma_minus(z3T, alpha_z, alpha_z / Wz4, tf.stop_gradient(z_alpha3), tf.stop_gradient(z_beta3) ) / (K[0] * batch_size) Log_pmq_z3_E = log_gamma_minus(z3, alpha_z, alpha_z / Wz4, z_alpha3, z_beta3) / (K[0] * batch_size) Log_pmq_W3 = log_gamma_minus(W3T, 0.1, 0.3, tf.stop_gradient(W_alpha3), tf.stop_gradient(W_beta3) ) / (K[0] * rho_mb * batch_size) Log_pmq_W3_E = log_gamma_minus(W3, 0.1, 0.3, W_alpha3, W_beta3) / (K[0] * rho_mb * batch_size) ELBO = ELBO + Log_pmq_z3 + Log_pmq_W3 ELBO_E = ELBO_E + Log_pmq_z3_E + Log_pmq_W3_E if MethodName != 'GO': # ELBO = tf.stop_gradient(ELBO) * (z1_Fcorr + W1_Fcorr + z2_Fcorr + W2_Fcorr)\ # - tf.stop_gradient(ELBO * (z1_Fcorr + W1_Fcorr + z2_Fcorr + W2_Fcorr)) \ # + ELBO ELBO = tf.stop_gradient(ELBO) * (z1_Fcorr + W1_Fcorr) \ - tf.stop_gradient(ELBO * (z1_Fcorr + W1_Fcorr)) \ + ELBO # Optimizer optimizer_q_z1 = tf.train.AdamOptimizer(learning_rate=LR_q_z1) q_z_vars1 = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='q_z_x_z_1') train_q_z1 = optimizer_q_z1.minimize(-ELBO, var_list=q_z_vars1) optimizer_q_W1 = tf.train.AdamOptimizer(learning_rate=LR_q_W1) q_W_vars1 = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='q_W_W_1') train_q_W1 = optimizer_q_W1.minimize(-ELBO, var_list=q_W_vars1) if Layers >= 2: optimizer_q_z2 = tf.train.AdamOptimizer(learning_rate=LR_q_z2) q_z_vars2 = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='q_z_x_z_2') train_q_z2 = optimizer_q_z2.minimize(-ELBO, var_list=q_z_vars2) optimizer_q_W2 = tf.train.AdamOptimizer(learning_rate=LR_q_W2) q_W_vars2 = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope='q_W_W_2') train_q_W2 = optimizer_q_W2.minimize(-ELBO, var_list=q_W_vars2) init = tf.global_variables_initializer() ELBOTrset = [] ELBOEvalset = [] with tf.Session(config=tf.ConfigProto(gpu_options=tf.GPUOptions(allow_growth=True))) as sess: sess.run(init) for i in range(1, num_steps + 1): batch_x, _ = mnist.train.next_batch(batch_size) batch_x = np.round(batch_x * 10.) ELBO_z_trunc_val = [0.1, 0.1, 0.1, 0.1, 0.1] ELBO_W_trunc_val = [0.01, 0.01, 0.01, 0.01, 0.01] # ELBO_Wz_trunc_val = [0.3, 0.3, 0.3, 0.3, 0.3] # if Layers == 1: _, _, ELBO1, ELBO_Eval1, \ E_recon11, \ z11, z_alpha11, z_beta11, \ W11, W_alpha11, W_beta11, \ = \ sess.run([train_q_z1, train_q_W1, ELBO, ELBO_E, E_recon1, z1, z_alpha1, z_beta1, W1, W_alpha1, W_beta1, ], feed_dict={x: batch_x, ELBO_z_trunc: ELBO_z_trunc_val, ELBO_W_trunc: ELBO_W_trunc_val, ELBO_Wz_trunc: ELBO_Wz_trunc_val, }) if Layers == 2: _, _, _, _, ELBO1, ELBO_Eval1, \ E_recon11, E_recon21, \ Log_pmq_z11, Log_pmq_W11, \ z11, z_alpha11, z_beta11, \ W11, W_alpha11, W_beta11, \ z21, z_alpha21, z_beta21, \ W21, W_alpha21, W_beta21, \ = \ sess.run([train_q_z1, train_q_W1, train_q_z2, train_q_W2, ELBO, ELBO_E, E_recon1, E_recon2, Log_pmq_z1, Log_pmq_W1, z1, z_alpha1, z_beta1, W1, W_alpha1, W_beta1, z2, z_alpha2, z_beta2, W2, W_alpha2, W_beta2, ], feed_dict={x: batch_x, ELBO_z_trunc: ELBO_z_trunc_val, ELBO_W_trunc: ELBO_W_trunc_val, ELBO_Wz_trunc: ELBO_Wz_trunc_val, }) if Layers == 3: _, _, _, _, _, _, ELBO1, ELBO_Eval1, \ E_recon11, E_recon21, E_recon31, \ z11, z_alpha11, z_beta11, \ W11, W_alpha11, W_beta11, \ z21, z_alpha21, z_beta21, \ W21, W_alpha21, W_beta21, \ z31, z_alpha31, z_beta31, \ W31, W_alpha31, W_beta31, \ = \ sess.run([train_q_z1, train_q_W1, train_q_z2, train_q_W2, train_q_z3, train_q_W3, ELBO, ELBO_E, E_recon1, E_recon2, E_recon3, z1, z_alpha1, z_beta1, W1, W_alpha1, W_beta1, z2, z_alpha2, z_beta2, W2, W_alpha2, W_beta2, z3, z_alpha3, z_beta3, W3, W_alpha3, W_beta3, ], feed_dict={x: batch_x, ELBO_z_trunc: ELBO_z_trunc_val, ELBO_W_trunc: ELBO_W_trunc_val, ELBO_Wz_trunc: ELBO_Wz_trunc_val, }) ELBOTrset.append(ELBO1) ELBOEvalset.append(ELBO_Eval1) if i % 10 == 0: if Layers == 1: print('Step %5i: ELBO:[%.2f/%.2f], E_recon:[%.2f], ' 'z1:[%.1e/%.1e/%.1e], W1:[%.1e/%.1e/%.1e], ' % ( i, ELBO_Eval1, ELBO1, E_recon11, np.max(z11), np.max(z_alpha11), np.max(z_beta11), np.max(W11), np.max(W_alpha11), np.max(W_beta11), )) # if i % 200 == 0: # f, a = plt.subplots(5, 6, sharex=True, sharey=True) # for iii in range(5): # for jjj in range(6): # img = np.reshape(W11[:, iii * 6 + jjj], newshape=(28, 28)) # a[iii][jjj].imshow(img) # f.show() if Layers == 2: print('Step %5i: ELBO:[%.2f/%.2f], E_recon:[%.2f/%.2f], ' 'z1:[%.1e/%.1e/%.1e], W1:[%.1e/%.1e/%.1e], ' 'z2:[%.1e/%.1e/%.1e], W2:[%.1e/%.1e/%.1e], ' % ( i, ELBO_Eval1, ELBO1, E_recon11, E_recon21, np.max(z11), np.max(z_alpha11), np.max(z_beta11), np.max(W11), np.max(W_alpha11), np.max(W_beta11), np.max(z21), np.max(z_alpha21), np.max(z_beta21), np.max(W21), np.max(W_alpha21), np.max(W_beta21), )) # if i % 200 == 0: # Dict = np.matmul(W11, W21) # f, a = plt.subplots(5, 6, sharex=True, sharey=True) # for iii in range(5): # for jjj in range(6): # img = np.reshape(Dict[:, iii * 6 + jjj], newshape=(28, 28)) # a[iii][jjj].imshow(img) # f.show() if Layers == 3: print('Step %5i: ELBO:[%.2f/%.2f], E_recon:[%.2f/%.2f/%.2f], ' 'z1:[%.1e/%.1e/%.1e], W1:[%.1e/%.1e/%.1e], ' 'z2:[%.1e/%.1e/%.1e], W2:[%.1e/%.1e/%.1e], ' 'z3:[%.1e/%.1e/%.1e], W3:[%.1e/%.1e/%.1e],' % ( i, ELBO_Eval1, ELBO1, E_recon11, E_recon21, E_recon31, np.max(z11), np.max(z_alpha11), np.max(z_beta11), np.max(W11), np.max(W_alpha11), np.max(W_beta11),
np.max(z21)
numpy.max
#!/usr/bin/env python """ # Author: <NAME> # Created Time : Thu 16 Jul 2020 07:24:49 PM CST # File Name: plot.py # Description: """ import numpy as np import scanpy as sc import matplotlib.pyplot as plt import seaborn as sns def embedding( adata, color='celltype', color_map=None, groupby='batch', groups=None, cond2=None, v2=None, save=None, legend_loc='right margin', legend_fontsize=None, legend_fontweight='bold', na_in_legend=False, sep='_', basis='X_umap', size=10, show=True, ): """ plot separated embeddings with others as background Parameters ---------- adata AnnData color meta information to be shown color_map specific color map groupby condition which is based-on to separate groups specific groups to be shown cond2 another targeted condition v2 another targeted values of another condition basis embeddings used to visualize, default is X_umap for UMAP size dot size on the embedding """ if groups is None: groups = adata.obs[groupby].cat.categories for b in groups: adata.obs['tmp'] = adata.obs[color].astype(str) adata.obs['tmp'][adata.obs[groupby]!=b] = '' if cond2 is not None: adata.obs['tmp'][adata.obs[cond2]!=v2] = '' groups = list(adata[(adata.obs[groupby]==b) & (adata.obs[cond2]==v2)].obs[color].astype('category').cat.categories.values) size = min(size, 120000/len(adata[(adata.obs[groupby]==b) & (adata.obs[cond2]==v2)])) else: groups = list(adata[adata.obs[groupby]==b].obs[color].astype('category').cat.categories.values) size = min(size, 120000/len(adata[adata.obs[groupby]==b])) adata.obs['tmp'] = adata.obs['tmp'].astype('category') if color_map is not None: palette = [color_map[i] if i in color_map else 'gray' for i in adata.obs['tmp'].cat.categories] else: palette = None title = b if cond2 is None else v2+sep+b if save is not None: save_ = '_'+b+save show = False else: save_ = None show = True sc.pl.embedding(adata, color='tmp', basis=basis, groups=groups, title=title, palette=palette, size=size, save=save_, na_in_legend=na_in_legend,legend_loc=legend_loc, legend_fontsize=legend_fontsize, legend_fontweight=legend_fontweight, show=show) del adata.obs['tmp'] del adata.uns['tmp_colors'] def plot_meta( adata, use_rep=None, color='celltype', batch='batch', colors=None, cmap='Blues', vmax=1, vmin=0, mask=True, annot=False, save=None, fontsize=8 ): """ Plot meta correlations among batches Parameters ---------- adata AnnData use_rep the cell representations or embeddings used to calculate the correlations, default is `latent` generated by `SCALE v2` batch the meta information based-on, default is batch colors colors for each batch cmap color map for information to be shown vmax max value vmin min value mask value to be masked annot show specific values save save the figure fontsize font size """ meta = [] name = [] color = [] if colors is None: colors = ['#FFFF00', '#1CE6FF', '#FF34FF', '#FF4A46', '#008941', '#006FA6', '#A30059', '#FFDBE5', '#7A4900', '#0000A6', '#63FFAC', '#B79762', '#004D43', '#8FB0FF', '#997D87', '#5A0007', '#809693', '#6A3A4C', '#1B4400', '#4FC601', '#3B5DFF', '#4A3B53', '#FF2F80', '#61615A', '#BA0900', '#6B7900', '#00C2A0', '#FFAA92', '#FF90C9', '#B903AA', '#D16100', '#DDEFFF', '#000035', '#7B4F4B', '#A1C299', '#300018', '#0AA6D8', '#013349', '#00846F', '#372101', '#FFB500', '#C2FFED', '#A079BF', '#CC0744', '#C0B9B2', '#C2FF99', '#001E09'] adata.obs[color] = adata.obs[color].astype('category') batches = np.unique(adata.obs[batch]) for i,b in enumerate(batches): for cat in adata.obs[color].cat.categories: index = np.where((adata.obs[color]==cat) & (adata.obs[batch]==b))[0] if len(index) > 0: if use_rep and use_rep in adata.obsm: meta.append(adata.obsm[use_rep][index].mean(0)) elif use_rep and use_rep in adata.layers: meta.append(adata.layers[use_rep][index].mean(0)) else: meta.append(adata.X[index].mean(0)) name.append(cat) color.append(colors[i]) meta = np.stack(meta) plt.figure(figsize=(10, 10)) corr = np.corrcoef(meta) if mask: mask = np.zeros_like(corr) mask[np.triu_indices_from(mask, k=1)] = True grid = sns.heatmap(corr, mask=mask, xticklabels=name, yticklabels=name, annot=annot, # name -> [] cmap=cmap, square=True, cbar=True, vmin=vmin, vmax=vmax) [ tick.set_color(c) for tick,c in zip(grid.get_xticklabels(),color) ] [ tick.set_color(c) for tick,c in zip(grid.get_yticklabels(),color) ] plt.xticks(rotation=45, horizontalalignment='right', fontsize=fontsize) plt.yticks(fontsize=fontsize) if save: plt.save(save, bbox_inches='tight') else: plt.show() def plot_meta2( adata, use_rep='latent', color='celltype', batch='batch', color_map=None, figsize=(10, 10), cmap='Blues', batches=None, annot=False, save=None, cbar=True, keep=False, fontsize=8, vmin=0, vmax=1 ): """ Plot meta correlations between two batches Parameters ---------- adata AnnData use_rep the cell representations or embeddings used to calculate the correlations, default is `latent` generated by `SCALE v2` batch the meta information based-on, default is batch colors colors for each batch cmap color map for information to be shown vmax max value vmin min value mask value to be masked annot show specific values save save the figure fontsize font size """ meta = [] name = [] adata.obs[color] = adata.obs[color].astype('category') if batches is None: batches = np.unique(adata.obs[batch]);#print(batches) for i,b in enumerate(batches): for cat in adata.obs[color].cat.categories: index = np.where((adata.obs[color]==cat) & (adata.obs[batch]==b))[0] if len(index) > 0: if use_rep and use_rep in adata.obsm: meta.append(adata.obsm[use_rep][index].mean(0)) elif use_rep and use_rep in adata.layers: meta.append(adata.layers[use_rep][index].mean(0)) else: meta.append(adata.X[index].mean(0)) name.append(cat) meta = np.stack(meta) plt.figure(figsize=figsize) corr = np.corrcoef(meta) xticklabels = adata[adata.obs[batch]==batches[0]].obs[color].cat.categories yticklabels = adata[adata.obs[batch]==batches[1]].obs[color].cat.categories # print(len(xticklabels), len(yticklabels)) corr = corr[len(xticklabels):, :len(xticklabels)] #;print(corr.shape) if keep: categories = adata.obs[color].cat.categories corr_ = np.zeros((len(categories), len(categories))) x_ind = [i for i,k in enumerate(categories) if k in xticklabels] y_ind = [i for i,k in enumerate(categories) if k in yticklabels] corr_[np.ix_(y_ind, x_ind)] = corr corr = corr_ xticklabels, yticklabels = categories, categories # xticklabels, yticklabels = [], [] grid = sns.heatmap(corr, xticklabels=xticklabels, yticklabels=yticklabels, annot=annot, cmap=cmap, square=True, cbar=cbar, vmin=vmin, vmax=vmax) if color_map is not None: [ tick.set_color(color_map[tick.get_text()]) for tick in grid.get_xticklabels() ] [ tick.set_color(color_map[tick.get_text()]) for tick in grid.get_yticklabels() ] plt.xticks(rotation=45, horizontalalignment='right', fontsize=fontsize) plt.yticks(fontsize=fontsize) plt.xlabel(batches[0], fontsize=fontsize) plt.ylabel(batches[1], fontsize=fontsize) if save: plt.save(save, bbox_inches='tight') else: plt.show() from sklearn.metrics import confusion_matrix from sklearn.metrics import adjusted_rand_score, normalized_mutual_info_score, f1_score def reassign_cluster_with_ref(Y_pred, Y): """ Reassign cluster to reference labels Parameters ---------- Y_pred: predict y classes Y: true y classes Returns ------- f1_score: clustering f1 score y_pred: reassignment index predict y classes indices: classes assignment """ def reassign_cluster(y_pred, index): y_ = np.zeros_like(y_pred) for i, j in index: y_[np.where(y_pred==i)] = j return y_ # from sklearn.utils.linear_assignment_ import linear_assignment from scipy.optimize import linear_sum_assignment as linear_assignment # print(Y_pred.size, Y.size) assert Y_pred.size == Y.size D = max(Y_pred.max(), Y.max())+1 w = np.zeros((D,D), dtype=np.int64) for i in range(Y_pred.size): w[Y_pred[i], Y[i]] += 1 ind = linear_assignment(w.max() - w) return reassign_cluster(Y_pred, ind), ind def plot_confusion(y, y_pred, save=None, cmap='Blues'): """ Plot confusion matrix Parameters ---------- y ground truth labels y_pred predicted labels save save the figure cmap color map Return ------ F1 score NMI score ARI score """ y_class, pred_class_ = np.unique(y),
np.unique(y_pred)
numpy.unique
import keras.backend as K import cv2, time, os import numpy as np import model as modellib from skimage import morphology class MAPCallback: def __init__(self, model, val_dataset, class_names, threshold=5, inference_num=50, batch_size=1, old_version=False): super(MAPCallback, self).__init__() self.model = model self.inference_num = inference_num self.class_names = class_names self.num_classes = len(class_names) self.val_dataset = val_dataset self.threshold = threshold self.batch_size = batch_size self.old_version = old_version def _voc_ap(self, rec, prec): # correct AP calculation # first append sentinel values at the end mrec = np.concatenate(([0.], rec, [1.])) mpre = np.concatenate(([0.], prec, [0.])) # compute the precision envelope for i in range(mpre.size - 1, 0, -1): mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i]) # to calculate area under PR curve, look for points # where X axis (recall) changes value i = np.where(mrec[1:] != mrec[:-1])[0] # and sum (\Delta recall) * prec ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) return ap def calculate_result(self): true_res = {} pred_res = [] inference_time = 0 for i in range(self.inference_num): image, class_ids, bbox, point = modellib.load_image_gt_eval(self.val_dataset, i) start = time.time() results = self.model.detect([image])[0] end = time.time() inference_time = inference_time + (end - start) out_boxes = results['rois'] out_scores = results['scores'] out_masks = results['masks'] pred_res_0 = [] pred_res_1 = [] if len(out_boxes) > 0: for out_box, out_score, out_mask in zip( out_boxes, out_scores, out_masks): det_point = np.unravel_index(out_mask[:, :, 0].argmax(), out_mask[:, :, 0].shape) if self.old_version: pred_res_0.append([i, 0, out_score, det_point[1] + 1, det_point[0] + 1]) else: pred_res_0.append([i, 0, out_score * out_mask[:, :, 0].max(), det_point[1] + 1, det_point[0] + 1]) # print([i, 0, out_mask[:, :, 0].max(), det_point[1] + 1, det_point[0] + 1]) det_point = np.unravel_index(out_mask[:, :, 1].argmax(), out_mask[:, :, 1].shape) if self.old_version: pred_res_1.append([i, 1, out_score, det_point[1] + 1, det_point[0] + 1]) else: pred_res_1.append([i, 1, out_score * out_mask[:, :, 1].max(), det_point[1] + 1, det_point[0] + 1]) # print([i, 1, out_score * out_mask[:, :, 1].max(), det_point[1] + 1, det_point[0] + 1]) pred_res_0 = nms_point(pred_res_0, 10) pred_res_1 = nms_point(pred_res_1, 10) pred_res.extend(pred_res_0) pred_res.extend(pred_res_1) true_res[i] = point # [num_guidewire, num_point, 2] # print(point) print('avg_infer_time:' + str(inference_time / self.inference_num)) return true_res, pred_res def compute_aps(self, true_res, pred_res, threshold): APs = {} for cls in range(self.num_classes): pred_res_cls = [x for x in pred_res if x[1] == cls] if len(pred_res_cls) == 0: APs[cls] = 0 continue true_res_cls = {} npos = 0 for index in true_res: # index is the image_id guidewires = true_res[index] # [num_guidewire, num_point, 2] npos += len(guidewires) # compute recall point_pos = np.array([x[cls] for x in guidewires]) # [num_guidewire, 2] true_res_cls[index] = { 'point_pos': point_pos, } ids = [x[0] for x in pred_res_cls] scores = np.array([x[2] for x in pred_res_cls]) points = np.array([x[3:] for x in pred_res_cls]) sorted_ind = np.argsort(-scores) points = points[sorted_ind, :] # sorted ids = [ids[x] for x in sorted_ind] # sorted nd = len(ids) tp = np.zeros(nd) fp = np.zeros(nd) for j in range(nd): ture_point = true_res_cls[ids[j]] point1 = points[j, :] # [2] dis_min = np.inf PGT = ture_point['point_pos'] # [num_guidewire, 2] if len(PGT) > 0: dis_square = np.square(PGT[:, 0] - point1[0]) + np.square(PGT[:, 1] - point1[1]) dis_min = np.min(dis_square) if dis_min < threshold * threshold: tp[j] = 1. else: fp[j] = 1. fp = np.cumsum(fp) tp = np.cumsum(tp) rec = tp / np.maximum(float(npos), np.finfo(np.float64).eps) prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps) ap = self._voc_ap(rec, prec) APs[cls] = ap return APs def on_epoch_end(self, logs=None): logs = logs or {} K.set_learning_phase(0) true_res, pred_res = self.calculate_result() for th in [3, 5, 7, 9]: APs = self.compute_aps(true_res, pred_res, th) for cls in range(self.num_classes): if cls in APs: print(self.class_names[cls] + ' ap: ', APs[cls]) mAP = np.mean([APs[cls] for cls in APs]) print('mAP: ', mAP) logs['mAP'] = mAP def nms_point(point_list, thresh): '''point_list: [i, point_id, score, x, y]''' keep = [] while point_list: keep.append(point_list[0]) now = point_list[0] del point_list[0] del_inds = [] for i in range(len(point_list)): dis_square = np.square(point_list[i][3] - now[3]) + np.square(point_list[i][4] - now[4]) if dis_square < thresh * thresh: del_inds.append(i) if del_inds: del_inds.reverse() for i in del_inds: del point_list[i] return keep class MAPCallbackSame(MAPCallback): def __init__(self, model, val_dataset, class_names, threshold=5, inference_num=50, batch_size=1): super(MAPCallbackSame, self).__init__() self.model = model self.inference_num = inference_num self.class_names = class_names self.num_classes = len(class_names) self.val_dataset = val_dataset self.threshold = threshold self.batch_size = batch_size def compute_point(self, pred, thresh, sigma): point = -1 * np.ones((2, 2), np.int32) idx = np.unravel_index(pred.argmax(), pred.shape) # print(pred.shape) if pred[idx[0], idx[1]] > thresh: point[0] = [idx[0], idx[1]] minus = makeGaussian(pred.shape[0], pred.shape[1], sigma, (idx[1], idx[0])) * pred[idx[0], idx[1]] pred = pred - minus idx_1 = np.unravel_index(pred.argmax(), pred.shape) if pred[idx_1[0], idx_1[1]] > thresh: point[1] = [idx_1[0], idx_1[1]] return point def calculate_result(self): true_res = {} pred_res = [] inference_time = 0 for i in range(self.inference_num): image, class_ids, bbox, point = modellib.load_image_gt_eval(self.val_dataset, i) start = time.time() results = self.model.detect([image])[0] end = time.time() inference_time = inference_time + (end - start) out_boxes = results['rois'] out_scores = results['scores'] out_masks = results['masks'] if len(out_boxes) > 0: for out_box, out_score, out_mask in zip( out_boxes, out_scores, out_masks): det_point = self.compute_point(out_mask[:, :, 0], 0.1, 6) pred_res.append([i, 0, out_score, det_point[0][1] + 1, det_point[0][0] + 1]) pred_res.append([i, 0, out_score, det_point[1][1] + 1, det_point[1][0] + 1]) # print([i, 0, out_score, det_point[0][1], det_point[0][0]]) # print([i, 0, out_score, det_point[1][1], det_point[1][0]]) true_res[i] = point # [num_guidewire, num_point, 2] print('avg_infer_time:' + str(inference_time / self.inference_num)) return true_res, pred_res def compute_aps(self, true_res, pred_res, threshold): APs = {} for cls in range(self.num_classes): pred_res_cls = [x for x in pred_res if x[1] == cls] if len(pred_res_cls) == 0: APs[cls] = 0 continue true_res_cls = {} npos = 0 for index in true_res: # index is the image_id guidewires = true_res[index] # [num_guidewire, num_point, 2] guidewires = np.reshape(guidewires, [guidewires.shape[0] * guidewires.shape[1], 1, 2]) npos += len(guidewires) # compute recall point_pos = np.array([x[cls] for x in guidewires]) # [num_guidewire, 2] true_res_cls[index] = { 'point_pos': point_pos, } ids = [x[0] for x in pred_res_cls] scores = np.array([x[2] for x in pred_res_cls]) points = np.array([x[3:] for x in pred_res_cls]) sorted_ind = np.argsort(-scores) points = points[sorted_ind, :] # sorted ids = [ids[x] for x in sorted_ind] # sorted nd = len(ids) tp = np.zeros(nd) fp = np.zeros(nd) for j in range(nd): ture_point = true_res_cls[ids[j]] point1 = points[j, :] # [2] dis_min = np.inf PGT = ture_point['point_pos'] # [num_guidewire, 2] if len(PGT) > 0: dis_square = np.square(PGT[:, 0] - point1[0]) + np.square(PGT[:, 1] - point1[1]) dis_min = np.min(dis_square) if dis_min < threshold * threshold: tp[j] = 1. else: fp[j] = 1. fp = np.cumsum(fp) tp = np.cumsum(tp) rec = tp / np.maximum(float(npos), np.finfo(np.float64).eps) prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps) ap = self._voc_ap(rec, prec) APs[cls] = ap return APs def makeGaussian(height, width, sigma=3, center=None): """ make一个高斯核,是生成heatmap的一个部分 """ x = np.arange(0, width, 1, float) y = np.arange(0, height, 1, float)[:, np.newaxis] if center is None: x0 = width // 2 y0 = height // 2 else: x0 = center[0] y0 = center[1] return np.exp(-4 * np.log(2) * ((x - x0) ** 2 + (y - y0) ** 2) / (sigma ** 2)) class MAPCallbackMask(MAPCallbackSame): def __init__(self, model, val_dataset, class_names, threshold=0.1, inference_num=50, batch_size=1): # super(MAPCallbackMask, self).__init__() self.model = model self.inference_num = inference_num self.class_names = class_names self.num_classes = len(class_names) self.val_dataset = val_dataset self.threshold = threshold self.batch_size = batch_size def compute_point_from_mask(self, pred, thresh): pred = (pred > thresh).astype('uint8') skeleton = morphology.skeletonize(pred) fil = np.array([[1, 1, 1], [1, 8, 1], [1, 1, 1]]) conv = cv2.filter2D(np.float32(skeleton), -1, fil) result = conv == 9 x, y = np.where(result == True) endpoint = [] num_point = min(len(x), 2) for i in range(num_point): endpoint.append(np.array([x[i], y[i]])) return endpoint def calculate_result(self): true_res = {} pred_res = [] inference_time = 0 for i in range(self.inference_num): image, class_ids, bbox, point = modellib.load_image_gt_eval(self.val_dataset, i) start = time.time() results = self.model.detect([image])[0] end = time.time() inference_time = inference_time + (end - start) out_boxes = results['rois'] out_scores = results['scores'] out_masks = results['masks'] if len(out_boxes) > 0: for out_box, out_score, out_mask in zip( out_boxes, out_scores, out_masks): det_point = self.compute_point_from_mask(out_mask[:, :, 0], self.threshold) for det_point_i in det_point: pred_res.append([i, 0, out_score, det_point_i[1] + 1, det_point_i[0] + 1]) # print([i, 0, out_score, det_point[0][1], det_point[0][0]]) # print([i, 0, out_score, det_point[1][1], det_point[1][0]]) true_res[i] = point # [num_guidewire, num_point, 2] # print(point) print('avg_infer_time:' + str(inference_time / self.inference_num)) return true_res, pred_res def compute_aps(self, true_res, pred_res, threshold): APs = {} for cls in range(self.num_classes): pred_res_cls = [x for x in pred_res if x[1] == cls] if len(pred_res_cls) == 0: APs[cls] = 0 continue true_res_cls = {} npos = 0 for index in true_res: # index is the image_id guidewires = true_res[index] # [num_guidewire, num_point, 2] guidewires = np.reshape(guidewires, [guidewires.shape[0] * guidewires.shape[1], 1, 2]) npos += len(guidewires) # compute recall point_pos = np.array([x[cls] for x in guidewires]) # [num_guidewire, 2] true_res_cls[index] = { 'point_pos': point_pos, } ids = [x[0] for x in pred_res_cls] scores = np.array([x[2] for x in pred_res_cls]) points = np.array([x[3:] for x in pred_res_cls]) sorted_ind = np.argsort(-scores) points = points[sorted_ind, :] # sorted ids = [ids[x] for x in sorted_ind] # sorted nd = len(ids) tp = np.zeros(nd) fp = np.zeros(nd) for j in range(nd): ture_point = true_res_cls[ids[j]] point1 = points[j, :] # [2] dis_min = np.inf PGT = ture_point['point_pos'] # [num_guidewire, 2] if len(PGT) > 0: dis_square = np.square(PGT[:, 0] - point1[0]) + np.square(PGT[:, 1] - point1[1]) dis_min = np.min(dis_square) if dis_min < threshold * threshold: tp[j] = 1. else: fp[j] = 1. fp = np.cumsum(fp) tp = np.cumsum(tp) rec = tp / np.maximum(float(npos), np.finfo(np.float64).eps) prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps) ap = self._voc_ap(rec, prec) APs[cls] = ap return APs def makeGaussian(height, width, sigma=3, center=None): """ make一个高斯核,是生成heatmap的一个部分 """ x = np.arange(0, width, 1, float) y = np.arange(0, height, 1, float)[:, np.newaxis] if center is None: x0 = width // 2 y0 = height // 2 else: x0 = center[0] y0 = center[1] return np.exp(-4 * np.log(2) * ((x - x0) ** 2 + (y - y0) ** 2) / (sigma ** 2)) class MAPCallbackBox: def __init__(self, model, val_dataset, class_names, inference_num=50, batch_size=1): super(MAPCallbackBox, self).__init__() self.model = model self.inference_num = inference_num self.class_names = class_names self.num_classes = len(class_names) self.val_dataset = val_dataset self.batch_size = batch_size def _voc_ap(self, rec, prec): # correct AP calculation # first append sentinel values at the end mrec = np.concatenate(([0.], rec, [1.])) mpre = np.concatenate(([0.], prec, [0.])) # compute the precision envelope for i in range(mpre.size - 1, 0, -1): mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i]) # to calculate area under PR curve, look for points # where X axis (recall) changes value i = np.where(mrec[1:] != mrec[:-1])[0] # and sum (\Delta recall) * prec ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) return ap def calculate_result(self): true_res = {} pred_res = [] inference_time = 0 for i in range(self.inference_num): image, class_ids, bbox, point = modellib.load_image_gt_eval(self.val_dataset, i) start = time.time() results = self.model.detect([image])[0] end = time.time() inference_time = inference_time + (end - start) out_boxes = results['rois'] out_scores = results['scores'] if len(out_boxes) > 0: for out_box, out_score in zip( out_boxes, out_scores): pred_res.append([i, 0, out_score, out_box]) # print([i, 0, out_score, out_box]) true_res[i] = bbox # [num_guidewire, 4] # print(bbox) print('avg_infer_time:' + str(inference_time / self.inference_num)) return true_res, pred_res def compute_iou(self, box, boxes, box_area, boxes_area): # Calculate intersection areas y1 = np.maximum(box[0], boxes[:, 0]) y2 = np.minimum(box[2], boxes[:, 2]) x1 = np.maximum(box[1], boxes[:, 1]) x2 = np.minimum(box[3], boxes[:, 3]) intersection = np.maximum(x2 - x1, 0) * np.maximum(y2 - y1, 0) union = box_area + boxes_area[:] - intersection[:] iou = intersection / union return iou def compute_aps(self, true_res, pred_res): APs = {} for cls in range(self.num_classes): pred_res_cls = [x for x in pred_res if x[1] == cls] if len(pred_res_cls) == 0: APs[cls] = 0 continue true_res_cls = {} npos = 0 for index in true_res: # index is the image_id guidewires = true_res[index] # [num_guidewire, 4] npos += len(guidewires) # compute recall point_pos = np.array([x for x in guidewires]) # [num_guidewire, 4] true_res_cls[index] = { 'point_pos': point_pos, } ids = [x[0] for x in pred_res_cls] scores = np.array([x[2] for x in pred_res_cls]) points = np.array([x[3] for x in pred_res_cls]) sorted_ind = np.argsort(-scores) points = points[sorted_ind, :] # sorted ids = [ids[x] for x in sorted_ind] # sorted nd = len(ids) tp = np.zeros(nd) fp = np.zeros(nd) for j in range(nd): ture_point = true_res_cls[ids[j]] box = points[j, :] # [4] PGT = ture_point['point_pos'] # [num_guidewire, 4] box_area = (box[2] - box[0]) * (box[3] - box[1]) boxes_area = (PGT[:, 2] - PGT[:, 0]) * (PGT[:, 3] - PGT[:, 1]) if len(PGT) > 0: IOU = self.compute_iou(box, PGT, box_area, boxes_area) iou_max = np.max(IOU) if iou_max > 0.5: tp[j] = 1. else: fp[j] = 1. fp = np.cumsum(fp) tp = np.cumsum(tp) rec = tp / np.maximum(float(npos), np.finfo(np.float64).eps) prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps) ap = self._voc_ap(rec, prec) APs[cls] = ap return APs def on_epoch_end(self, logs=None): logs = logs or {} K.set_learning_phase(0) # For BN true_res, pred_res = self.calculate_result() APs = self.compute_aps(true_res, pred_res) for cls in range(self.num_classes): if cls in APs: print(self.class_names[cls] + ' ap: ', APs[cls]) mAP = np.mean([APs[cls] for cls in APs]) print('mAP: ', mAP) logs['mAP'] = mAP class MAPCallbackPCK: def __init__(self, model, val_dataset, class_names, inference_num=50, batch_size=1): super(MAPCallbackPCK, self).__init__() self.model = model self.inference_num = inference_num self.class_names = class_names self.num_classes = len(class_names) self.val_dataset = val_dataset self.batch_size = batch_size def _voc_ap(self, rec, prec): # correct AP calculation # first append sentinel values at the end mrec = np.concatenate(([0.], rec, [1.])) mpre = np.concatenate(([0.], prec, [0.])) # compute the precision envelope for i in range(mpre.size - 1, 0, -1): mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i]) # to calculate area under PR curve, look for points # where X axis (recall) changes value i = np.where(mrec[1:] != mrec[:-1])[0] # and sum (\Delta recall) * prec ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) return ap def check_dt(self, box, gtbox): box_area = (box[2] - box[0]) * (box[3] - box[1]) boxes_area = (gtbox[:, 2] - gtbox[:, 0]) * (gtbox[:, 3] - gtbox[:, 1]) IOU = self.compute_iou(box, gtbox, box_area, boxes_area) iou_max = np.max(IOU) if iou_max > 0.5: return True else: return False def calculate_result(self): true_res = {} pred_res = [] inference_time = 0 for i in range(self.inference_num): image, class_ids, bbox, point = modellib.load_image_gt_eval(self.val_dataset, i) start = time.time() out_masks = self.model.localization([image], [bbox])[0] # print(out_masks.shape) end = time.time() inference_time = inference_time + (end - start) for out_mask in out_masks: det_point = np.unravel_index(out_mask[:, :, 0].argmax(), out_mask[:, :, 0].shape) pred_res.append([i, 0, det_point[1] + 1, det_point[0] + 1]) # print([i, 0, det_point[1] + 1, det_point[0] + 1]) det_point = np.unravel_index(out_mask[:, :, 1].argmax(), out_mask[:, :, 1].shape) pred_res.append([i, 1, det_point[1] + 1, det_point[0] + 1]) # print([i, 1, det_point[1] + 1, det_point[0] + 1]) true_res[i] = point # [num_guidewire, num_point, 2] print('avg_infer_time:' + str(inference_time / self.inference_num)) return true_res, pred_res def compute_iou(self, box, boxes, box_area, boxes_area): # Calculate intersection areas y1 = np.maximum(box[0], boxes[:, 0]) y2 = np.minimum(box[2], boxes[:, 2]) x1 = np.maximum(box[1], boxes[:, 1]) x2 = np.minimum(box[3], boxes[:, 3]) intersection = np.maximum(x2 - x1, 0) * np.maximum(y2 - y1, 0) union = box_area + boxes_area[:] - intersection[:] iou = intersection / union return iou def compute_pck(self, true_res, pred_res, threshold): APs = {} for cls in range(self.num_classes): true_num = 0 pred_res_cls = [x for x in pred_res if x[1] == cls] num_all = len(pred_res_cls) if num_all == 0: APs[cls] = 0 continue true_res_cls = {} for index in true_res: # index is the image_id guidewires = true_res[index] # [num_guidewire, num_point, 2] point_pos = np.array([x[cls] for x in guidewires]) # [num_guidewire, 2] true_res_cls[index] = { 'point_pos': point_pos, } for j in pred_res_cls: ture_point = true_res_cls[j[0]] point1 = j[2:] # [2] PGT = ture_point['point_pos'] # [num_guidewire, 2] if len(PGT) > 0: dis_square = np.square(PGT[:, 0] - point1[0]) + np.square(PGT[:, 1] - point1[1]) dis_min = np.min(dis_square) if dis_min < threshold * threshold: true_num += 1 print(true_num, num_all) APs[cls] = true_num / num_all return APs def on_epoch_end(self, logs=None): logs = logs or {} K.set_learning_phase(0) # For BN true_res, pred_res = self.calculate_result() for th in [3, 5, 7, 9]: APs = self.compute_pck(true_res, pred_res, th) for cls in range(self.num_classes): if cls in APs: print(self.class_names[cls] + ' ap: ', APs[cls]) mAP = np.mean([APs[cls] for cls in APs]) print('mAP: ', mAP) logs['mAP'] = mAP def read_point(txt_path): with open(txt_path, 'r')as f: string = f.readlines() num_guidewire = len(string) point = np.zeros([num_guidewire, 2, 2], dtype=np.int32) bbox = np.zeros([num_guidewire, 4], dtype=np.int32) for index, s in enumerate(string): item = [int(i) for i in s[:-1].split(' ')] bbox[index] =
np.array([item[2], item[0], item[3], item[1]])
numpy.array
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2019/8/8 @Author : AnNing """ import numpy as np from pyproj import Proj, transform # 角度 -> 弧度 DEGREES_TO_RADIANS = np.pi / 180. # 弧度 -> 角度 RADIANS_TO_DEGREES = 180. / np.pi # 地球平均半径 EARTH_MEAN_RADIUS_KM = 6371.009 # 地球极半径 EARTH_POLAR_RADIUS_KM = 6356.752 # 地球赤道半径 EARTH_EQUATOR_RADIUS_KM = 6378.137 WGS84_A = 6378137.0 WGS84_F = 1.0 / 298.257223563 WGS84_B = WGS84_A * (1.0 - WGS84_F) WGS84_E2 = 2 * WGS84_F - WGS84_F ** 2 # Rotational angular velocity of Earth in radians/sec from IERS # Conventions (2003). ANGVEL = 7.2921150e-5 def degree2meter(degree): return degree * np.pi * EARTH_EQUATOR_RADIUS_KM * 1000. / 180. def meter2degree(meter): return (meter * 180) / (np.pi * EARTH_EQUATOR_RADIUS_KM * 1000) class ProjCore: """ 投影公共类 """ def __init__(self, projstr, res, unit, row=None, col=None, pt_tl=None, pt_br=None,): """ [args]: projstr proj4投影参数字符串 res 分辨率 unit 分辨率单位,支持 m km deg, 确保单位与投影方式一致 row 行数 col 列数 pt_tl 左上角经纬度元组, 形式如 (lon, lat) pt_br 右下角经纬度元组, 形式如 (lon, lat) row、 col 和 pt_tl、 pt_br 两对里必须传一对,用以确定网格大小, 不能都是None projstr 样例: 1. 等经纬 "+init=epsg:4326" or "+proj=longlat +datum=WGS84 +no_defs" # "+proj=eqc +lat_ts=0 +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 +datum=WGS84 +x_0=-half_res +y_0=half_res" 2. 极射赤面 "+proj=stere +ellps=clrk66 +lat_0=90 +lat_ts=70 +lon_0=0 +k_0=0.969858730377 +a=6371000 +units=m" 3. 兰勃特等面积 "+proj=laea +lat_0=-74.180000 +lon_0=-146.620000 +x_0=0 +y_0=0 +ellps=WGS84" 4. 阿伯斯 (常用于中国区域) "+proj=aea +lat_0=0 +lon_0=105 +lat_1=25 +lat_2=47 +x_0=0 +y_0=0 +ellps=krass +a=6378245.0 +b=6356863.0" 5. 待补充 """ self.proj4str = projstr self.pfunc = Proj(self.proj4str) # 转换函数 print(self.pfunc) if unit == "km": self.res = res * 1000 self.unit = "m" elif unit == "deg": # self.res = np.deg2rad(res) # pyproj < 2.0使用 self.res = res # pyproj >= 2.0使用 self.unit = unit else: self.unit = unit self.res = res if row is not None and col is not None: self.row = row self.col = col self.x_tl = -(self.col - 1) / 2 * self.res self.y_tl = (self.row - 1) / 2 * self.res elif pt_tl is not None and pt_br is not None: self.x_tl, self.y_tl = self.pfunc(*pt_tl) x_br, y_br = self.pfunc(*pt_br) self.row = int(round((self.y_tl - y_br) / self.res)) + 1 self.col = int(round((x_br - self.x_tl) / self.res)) + 1 else: raise ValueError("row、 col 和 pt_tl、 pt_br 两对里必须传一对,用以确定网格大小, 不能都是None") self.lons = None self.lats = None print("投影后的网络大小: ({},{})".format(self.row, self.col)) def lonslats2ij(self, lons, lats): """ '经纬度转行列号 lons,lats -> i,j '参数是n维数组 经纬度 '返回值是n维数组 行列号 """ if isinstance(lons, (list, tuple)): lons = np.array(lons) if isinstance(lats, (list, tuple)): lats = np.array(lats) if isinstance(lons, np.ndarray): assert lons.shape == lats.shape, \ "lons and lats must have same shape." args_shape = lons.shape # 转成1维,因为proj只接收1维参数 lons = lons.reshape((-1)) lats = lats.reshape((-1)) # 通过平面坐标系计算投影后的行和列 x, y = self.pfunc(lons, lats) i = self.__y2i(y) j = self.__x2j(x) return i.reshape(args_shape), j.reshape(args_shape) else: x, y = self.pfunc(lons, lats) i = self.__y2i(y) j = self.__x2j(x) return i, j def __y2i(self, y): """ y 转 行号 """ if isinstance(y, (list, tuple)): y = np.array(y) return np.rint((self.y_tl - y) / self.res).astype(int) def __x2j(self, x): """ x 转 列号 """ if isinstance(x, (list, tuple)): x = np.array(x) return np.rint((x - self.x_tl) / self.res).astype(int) def grid_lonslats(self): """ '生成投影后网格 各格点的经纬度 """ # 制作一个2维的矩阵 i, j = np.mgrid[0:self.row:1, 0:self.col:1] y = self.__i2y(i) x = self.__j2x(j) # 把二维的x,y 转成1维,因为proj只接收1维参数 x = x.reshape((-1)) y = y.reshape((-1)) lons, lats = self.pfunc(x, y, inverse=True) # 转回2维 self.lons = lons.reshape((self.row, self.col)) self.lats = lats.reshape((self.row, self.col)) return self.lons, self.lats def __i2y(self, i): """ '行号 转 y """ if isinstance(i, (list, tuple)): i = np.array(i) y = self.y_tl - i * self.res return y def __j2x(self, j): """ '列号 转 x """ if isinstance(j, (list, tuple)): j = np.array(j) x = j * self.res + self.x_tl return x def create_lut(self, lons, lats): """ '创建投影查找表, (字典) '即 源数据经纬度位置与投影后位置的对应关系 """ if isinstance(lons, (list, tuple)): lons = np.array(lons) if isinstance(lats, (list, tuple)): lats = np.array(lats) assert lons.shape == lats.shape, "Lons and Lats must have same shape." # 投影后必是2维的,行列 proj1_i,proj1_j prj_i, prj_j = self.lonslats2ij(lons, lats) valid_index = np.logical_and.reduce((prj_i >= 0, prj_i < self.row, prj_j >= 0, prj_j < self.col)) if lons.ndim == 1: pre_n = np.arange(0, lons.size, 1, "i4") # 投影方格以外的数据过滤掉 prj_i = prj_i[valid_index] prj_j = prj_j[valid_index] pre_n = pre_n[valid_index] return {"pre_n": pre_n, "prj_i": prj_i, "prj_j": prj_j} elif lons.ndim == 2: pre_row, pre_col = lons.shape pre_i, pre_j = np.mgrid[0:pre_row:1, 0:pre_col:1] # 投影方格以外的数据过滤掉 prj_i = prj_i[valid_index] prj_j = prj_j[valid_index] pre_i = pre_i[valid_index] pre_j = pre_j[valid_index] return {"pre_i": pre_i, "pre_j": pre_j, "prj_i": prj_i, "prj_j": prj_j} def transform2ij(self, proj_str1, x1, y1): """ '不同投影方式之间转换 '返回值是整数 """ args_shape = x1.shape x1 = np.array(x1).reshape((-1)) # 转成1维 y1 = np.array(y1).reshape((-1)) p1 = Proj(proj_str1) x2, y2 = transform(p1, self.pfunc, x1, y1) i = self.__y2i(y2) j = self.__x2j(x2) return i.reshape(args_shape), j.reshape(args_shape) class ProjGLL: """ 等经纬度区域类 """ def __init__(self, nlat=90., slat=-90., wlon=-180., elon=180., res_lat=None, res_lon=None, row_max=None, col_max=None): """ nlat, slat, wlon, elon: 北纬, 南纬, 西经, 东经 resLat: 纬度分辨率(度) resLon: 经度分辨率(度) """ self.nlat = float(nlat) # 北纬 self.slat = float(slat) # 南纬 self.wlon = float(wlon) # 西经 self.elon = float(elon) # 东经 if res_lat is None and row_max is None: raise ValueError("resLat and rowMax must set one") if res_lon is None and col_max is None: raise ValueError("resLon and colMax must set one") if res_lat is None: self.rowMax = int(row_max) self.resLat = (self.nlat - self.slat) / self.rowMax else: self.resLat = float(res_lat) self.rowMax = int( round((self.nlat - self.slat) / self.resLat)) # 最大行数 if res_lon is None: self.colMax = int(col_max) self.resLon = (self.elon - self.wlon) / self.colMax else: self.resLon = float(res_lon) self.colMax = int( round((self.elon - self.wlon) / self.resLon)) # 最大列数 def generate_lats_lons(self): lats, lons = np.mgrid[ self.nlat - self.resLat / 2.: self.slat + self.resLat * 0.1:-self.resLat, self.wlon + self.resLon / 2.: self.elon - self.resLon * 0.1: self.resLon] return lats, lons def lonslats2ij(self, lons, lats): j = self.lons2j(lons) i = self.lats2i(lats) return i, j def lons2j(self, lons): """ lons: 输入经度 ret: 返回 输入经度在等经纬度网格上的列号,以左上角为起点0,0 """ if isinstance(lons, (list, tuple)): lons = np.array(lons) if isinstance(lons, np.ndarray): idx = np.isclose(lons, 180.) lons[idx] = -180. return np.floor((lons - self.wlon) / self.resLon).astype(int) # 列号 def lats2i(self, lats): """ lats: 输入纬度 ret: 返回 输入纬度在等经纬度网格上的行号,以左上角为起点0,0 """ if isinstance(lats, (list, tuple)): lats = np.array(lats) return np.floor((self.nlat - lats) / self.resLat).astype(int) # 行号 def fill_2d(array2d, mask, use_from): """ 2维矩阵无效值补点 array2d 2维矩阵 mask 无效值掩模矩阵 useFrom u/d/l/r, 用上/下/左/右的点来补点 """ assert len(array2d.shape) == 2, \ "array2d must be 2d array." assert array2d.shape == mask.shape, \ "array2d and musk must have same shape." condition = np.empty_like(mask) # 用上方的有效点补点 if use_from == 'up' or use_from == 'u': condition[1:, :] = mask[1:, :] * (~mask)[:-1, :] condition[0, :] = False index = np.where(condition) array2d[index[0], index[1]] = array2d[index[0] - 1, index[1]] # 用右方的有效点补点 elif use_from == 'right' or use_from == 'r': condition[:, :-1] = mask[:, :-1] * (~mask)[:, 1:] condition[:, -1] = False index = np.where(condition) array2d[index[0], index[1]] = array2d[index[0], index[1] + 1] # 用下方的有效点补点 elif use_from == 'down' or use_from == 'd': condition[:-1, :] = mask[:-1, :] * (~mask)[1:, :] condition[-1, :] = False index = np.where(condition) array2d[index[0], index[1]] = array2d[index[0] + 1, index[1]] # 用左方的有效点补点 elif use_from == 'left' or use_from == 'l': condition[:, 1:] = mask[:, 1:] * (~mask)[:, :-1] condition[:, 0] = False index = np.where(condition) array2d[index[0], index[1]] = array2d[index[0], index[1] - 1] def fill_points_2d(array2d, invalid_value=0): """ 2维矩阵无效值补点 array2d 2维矩阵 invalidValue 无效值 """ # 用右方的有效点补点 mask = np.isclose(array2d, invalid_value) fill_2d(array2d, mask, 'r') # 用左方的有效点补点 mask = np.isclose(array2d, invalid_value) fill_2d(array2d, mask, 'l') # 用上方的有效点补点 mask = np.isclose(array2d, invalid_value) fill_2d(array2d, mask, 'u') # 用下方的有效点补点 mask = np.isclose(array2d, invalid_value) fill_2d(array2d, mask, 'd') def fill_points_2d_nan(array2d): """ 2维矩阵无效值补点 array2d 2维矩阵 invalidValue 无效值 """ # 用右方的有效点补点 mask = np.isnan(array2d) fill_2d(array2d, mask, 'r') # 用左方的有效点补点 mask =
np.isnan(array2d)
numpy.isnan
''' This module includes different trigger policies that are simulated ''' #breakpoint() import json import numpy as np from VaccineAllocation import config from itertools import product, permutations import copy import iteround import datetime as dt CONSTANT_TR = 'constant' STEP_TR = 'step' LINEAR_TR = 'linear' THRESHOLD_TYPES = [CONSTANT_TR, STEP_TR, LINEAR_TR] datetime_formater = '%Y-%m-%d %H:%M:%S' def build_multi_tier_policy_candidates(instance, tiers, threshold_type='constant', lambda_start=None): assert len(tiers) >= 2, 'At least two tiers need to be defined' threshold_candidates = [] if threshold_type == CONSTANT_TR: #breakpoint() gz = config['grid_size'] # lambda_start is given by the field pub; if it is none, then we use the square root staffing rule if lambda_start is None: if np.size(instance.epi.eq_mu) == 1: lambda_start = int(np.floor(instance.epi.eq_mu * instance.lambda_star)) else: lambda_start = int(np.floor(np.max(instance.epi.eq_mu) * instance.lambda_star)) params_trials = [] for tier in tiers: if 'candidate_thresholds' in tier and isinstance(tier['candidate_thresholds'], list): params_trials.append(tier['candidate_thresholds']) else: candidates = [gz * i for i in range(0, int(lambda_start / gz) + 1)] + [lambda_start] params_trials.append(np.unique(candidates)) for policy_params in product(*params_trials): is_valid = True for p_ix in range(len(policy_params) - 1): if policy_params[p_ix] >= policy_params[p_ix + 1]: is_valid = False break if is_valid: T = len(instance.cal) lockdown_thresholds = [[policy_params[i]] * T for i in range(len(policy_params))] threshold_candidates.append(lockdown_thresholds) #breakpoint() return threshold_candidates elif threshold_type == STEP_TR: #breakpoint() # TODO: we need to set a time and two levels gz = config['grid_size'] lambda_start = int(np.floor(instance.epi.eq_mu * instance.lambda_star)) params_trials = [] for tier in tiers: if tier['candidate_thresholds'] is not None: # construct the trial parameters according to the candidate threshold # the candidate threshold should be a list of 2 lists if isinstance(tier['candidate_thresholds'][0], list): candidates1 = tier['candidate_thresholds'][0] else: candidates1 = [gz * i for i in range(0, int(lambda_start / gz) + 1)] + [lambda_start] if isinstance(tier['candidate_thresholds'][1], list): candidates2 = tier['candidate_thresholds'][1] else: candidates2 = [gz * i for i in range(0, int(lambda_start / gz) + 1)] + [lambda_start] else: candidates1 = [gz * i for i in range(0, int(lambda_start / gz) + 1)] + [lambda_start] candidates2 = [gz * i for i in range(0, int(lambda_start / gz) + 1)] + [lambda_start] params_trials.append([(t1, t2) for t1 in candidates1 for t2 in candidates2 if t1 <= t2]) # obtain the possible stepping time points, limited to the start of months T_trials = instance.cal.month_starts for policy_params in product(*params_trials): is_valid = True for p_ix in range(len(policy_params) - 1): if (policy_params[p_ix][0] >= policy_params[p_ix + 1][0]) \ or (policy_params[p_ix][1] >= policy_params[p_ix + 1][1]): is_valid = False break if is_valid: T = len(instance.cal) for tChange in T_trials: lockdown_thresholds = [[policy_params[i][0]] * tChange + [policy_params[i][1]] * (T - tChange) for i in range(len(policy_params))] threshold_candidates.append(lockdown_thresholds) return threshold_candidates elif threshold_type == LINEAR_TR: gz = config['grid_size'] sgz = config['slope_grid_size'] # the grid size for slope search. max_slope = config['max_slope'] # The date the thresholds start to increase (constant threshold up until this point): slope_start = dt.datetime.strptime(config['slope_start_date'], datetime_formater) T_slope_start = np.where(np.array(instance.cal.calendar) == slope_start)[0][0] # lambda_start is given by the field pub; if it is none, then we use the square root staffing rule if lambda_start is None: if np.size(instance.epi.eq_mu) == 1: lambda_start = int(np.floor(instance.epi.eq_mu * instance.lambda_star)) else: lambda_start = int(np.floor(np.max(instance.epi.eq_mu) * instance.lambda_star)) params_trials = [] for tier in tiers: # construct the trial parameters according to the candidate threshold if 'candidate_thresholds' in tier and isinstance(tier['candidate_thresholds'], list): params_trials.append(tier['candidate_thresholds']) else: candidates = [gz * i for i in range(0, int(lambda_start / gz) + 1)] + [lambda_start] params_trials.append(np.unique(candidates)) for policy_params in product(*params_trials): is_valid = True for p_ix in range(len(policy_params) - 1): if policy_params[p_ix] >= policy_params[p_ix + 1]: is_valid = False break if is_valid: T = len(instance.cal) T_slope = T - T_slope_start if config['candidate_slopes'] is not None: slope_candidates = config['candidate_slopes'] else: slope_candidates = [sgz * i for i in range(0, int(max_slope / sgz) + 1)] + [max_slope] # If the intercept is valid, create grids according to slope: for slope in slope_candidates: # The lower bound for green will be constant at -1: lockdown_thresholds = [[policy_params[0]] * T] # The lower bound will be increasing for other stages: lockdown_thresholds += [[policy_params[i]] * T_slope_start + \ [policy_params[i] + (slope) * (t + 1) for t in range(T_slope)] for i in range(1, len(policy_params))] threshold_candidates.append(lockdown_thresholds) #breakpoint() return threshold_candidates else: raise NotImplementedError def build_ACS_policy_candidates(instance, tiers, acs_bounds, acs_time_bounds, threshold_type='constant', lambda_start=None): #breakpoint() assert len(tiers) >= 2, 'At least two tiers need to be defined' threshold_candidates = [] if threshold_type == CONSTANT_TR: gz = config['grid_size'] if lambda_start is None: if np.size(instance.epi.eq_mu) == 1: lambda_start = int(np.floor(instance.epi.eq_mu * instance.lambda_star)) else: lambda_start = int(np.floor(np.max(instance.epi.eq_mu) * instance.lambda_star)) params_trials = [] for tier in tiers: if 'candidate_thresholds' in tier and isinstance(tier['candidate_thresholds'], list): params_trials.append(tier['candidate_thresholds']) else: candidates = [gz * i for i in range(0, int(lambda_start / gz) + 1)] + [lambda_start] params_trials.append(candidates) # append the acs_trigger and acs_length acs_trigger_candidates = np.unique([gz * i for i in range(int(acs_bounds[0] / gz), int(acs_bounds[1] / gz) + 1)] + [acs_bounds[1]]) acs_time_candidates = np.unique([gz * i for i in range(int(acs_time_bounds[0] / gz), int(acs_time_bounds[1] / gz) + 1)] + [acs_time_bounds[1]]) params_trials.append(acs_trigger_candidates) params_trials.append(acs_time_candidates) for policy_params in product(*params_trials): is_valid = True for p_ix in range(len(policy_params) - 3): if policy_params[p_ix] >= policy_params[p_ix + 1]: is_valid = False break if is_valid: T = len(instance.cal) lockdown_thresholds = [[policy_params[i]] * T for i in range(len(policy_params) - 2)] output_trials = [lockdown_thresholds, policy_params[-2], policy_params[-1]] threshold_candidates.append(output_trials) # breakpoint() return threshold_candidates else: raise NotImplementedError def build_CDC_policy_thresholds(instance, tiers): """ Currently there is no optimization on CDC system. Implement the existing system. Assuming only one candidate threshold for each metric. """ nonsurge_staffed_bed, surge_staffed_bed = {}, {} nonsurge_hosp_adm,surge_hosp_adm = {}, {} for id_t, tier in enumerate(tiers): nonsurge_staffed_bed[id_t] = tier["nonsurge_thresholds"]["staffed_bed"][0] nonsurge_hosp_adm[id_t] = tier["nonsurge_thresholds"]["hosp_adm"][0] surge_staffed_bed[id_t] = tier["surge_thresholds"]["staffed_bed"][0] surge_hosp_adm[id_t] = tier["surge_thresholds"]["hosp_adm"][0] nonsurge_thresholds = {"hosp_adm":nonsurge_hosp_adm, "staffed_bed":nonsurge_staffed_bed} surge_thresholds = {"hosp_adm":surge_hosp_adm, "staffed_bed":surge_staffed_bed} nonsurge_hosp_adm_ub = [nonsurge_hosp_adm[i] for i in range(1, len(nonsurge_hosp_adm))] nonsurge_hosp_adm_ub.append(np.inf) nonsurge_staffed_bed_ub = [nonsurge_staffed_bed[i] for i in range(1, len(nonsurge_staffed_bed))] nonsurge_staffed_bed_ub.append(np.inf) surge_hosp_adm_ub =[surge_hosp_adm[i] for i in range(1, len(surge_hosp_adm))] surge_hosp_adm_ub.append(np.inf) surge_staffed_bed_ub = [surge_staffed_bed[i] for i in range(1, len(surge_staffed_bed))] surge_staffed_bed_ub.append(np.inf) nonsurge_thresholds_ub = {"hosp_adm":nonsurge_hosp_adm_ub, "staffed_bed":nonsurge_staffed_bed_ub} surge_thresholds_ub = {"hosp_adm":surge_hosp_adm_ub, "staffed_bed":surge_staffed_bed_ub} return nonsurge_thresholds, surge_thresholds, nonsurge_thresholds_ub, surge_thresholds_ub class CDCTierPolicy(): """ CDC's community levels. CDC system includes three tiers. Green and orange stages are deprecated but maintained for code consitency with our system. """ def __init__(self, instance, tiers, case_threshold, nonsurge_thresholds, surge_thresholds, nonsurge_thresholds_ub, surge_thresholds_ub): """ instance : (Instance) data instance tiers (list of dict): a list of the tiers characterized by a dictionary with the following entries: { "transmission_reduction": float [0,1) "cocooning": float [0,1) "school_closure": int {0,1} } case_thresholds : (Surge threshold. New COVID-19 Cases Per 100,000 people in the past 7 days (non)surge_thresholds : (dict of dict) with entries: { hosp_adm : (list of list) a list with the thresholds for every tier. New COVID-19 admissions per 100,000 population (7-day total) staffed_bed : (list of list) a list with the thresholds for every tier.Percent of staffed inpatient beds occupied by COVID-19 patients (7-day average) } """ self.tiers = tiers self.case_threshold = case_threshold self.nonsurge_thresholds = nonsurge_thresholds self.surge_thresholds = surge_thresholds self.nonsurge_thresholds_ub = nonsurge_thresholds_ub self.surge_thresholds_ub = surge_thresholds_ub self._n = len(self.tiers) self._tier_history = None self._surge_history = None self._intervention_history = None self._instance = instance self.red_counter = 0 @classmethod def policy(cls, instance, tiers): nonsurge_thresholds, surge_thresholds, nonsurge_thresholds_ub, surge_thresholds_ub = build_CDC_policy_thresholds(instance, tiers.tier) case_threshold = tiers.case_threshold return cls(instance, tiers.tier, case_threshold, nonsurge_thresholds, surge_thresholds, nonsurge_thresholds_ub, surge_thresholds_ub) def deep_copy(self): p = CDCTierPolicy(self._instance, self.tiers, self.case_threshold, self.nonsurge_thresholds, self.surge_thresholds, self.nonsurge_thresholds_ub, self.surge_thresholds_ub) p.set_tier_history(self._tier_history_copy) p.set_intervention_history(self._intervention_history_copy) p.set_surge_history(self._surge_history_copy) return p def set_tier_history(self, history): # Set history and saves a copy to reset self._tier_history = history.copy() self._tier_history_copy = history.copy() def set_intervention_history(self, history): # Set history and saves a copy to reset self._intervention_history = history.copy() self._intervention_history_copy = history.copy() def set_surge_history(self, history): ''' Creaate surge history array ''' t = len(history) self._surge_history = np.zeros(t) self._surge_history_copy = np.zeros(t) def reset_history(self): # reset history so that a new simulation can be excecuted self.set_tier_history(self._tier_history_copy) self.set_intervention_history(self._intervention_history_copy) self.set_surge_history(self._surge_history_copy) def compute_cost(self): return sum(self.tiers[i]['daily_cost'] for i in self._tier_history if i is not None and i in range(self._n)) def get_tier_history(self): return self._tier_history def get_interventions_history(self): return self._intervention_history def get_surge_history(self): return self._surge_history def __repr__(self): p_str = "CDC_community_levels" p_str = p_str.replace(' ', '') p_str = p_str.replace(',', '_') p_str = p_str.replace("'", "") p_str = p_str.replace('[', '') p_str = p_str.replace('(', '') p_str = p_str.replace(']', '') p_str = p_str.replace(')', '') return p_str def __call__(self, t, ToIHT, IH, ToIY, ICU, *args, **kwargs): ''' Function that makes an instance of a policy a callable. Args: t (int): time period in the simulation ToIHT (ndarray): daily hospital admission, passed by the simulator IH (ndarray): hospitalizations, passed by the simulator ToIY (ndarray): new symptomatic cases, passed by the simulator ** kwargs: additional parameters that are passed and are used elsewhere ''' if self._tier_history[t] is not None: return self._intervention_history[t],kwargs # Compute 7-day total new cases: N = self._instance.N moving_avg_start = np.maximum(0, t - config['moving_avg_len']) ToIY_total = ToIY.sum((1, 2)) ToIY_total = ToIY_total[moving_avg_start:].sum()* 100000/np.sum(N, axis=(0,1)) # Compute 7-day total daily admission: ToIHT_total = ToIHT.sum((1, 2)) ToIHT_total = ToIHT_total[moving_avg_start:].sum()* 100000/np.sum(N, axis=(0,1)) # Compute 7-day average percent of COVID beds: IHT_total = IH.sum((1, 2)) + ICU.sum((1,2)) IHT_avg = IHT_total[moving_avg_start:].mean()/self._instance.hosp_beds current_tier = self._tier_history[t - 1] valid_interventions_t = kwargs['feasible_interventions'][t] T = self._instance.T effective_tiers = range(len(self.tiers)) if ToIY_total < self.case_threshold: # Nonsurge hosp_adm_thresholds = self.nonsurge_thresholds["hosp_adm"] staffed_bed_thresholds = self.nonsurge_thresholds["staffed_bed"] surge_state = 0 else: hosp_adm_thresholds = self.surge_thresholds["hosp_adm"] staffed_bed_thresholds = self.surge_thresholds["staffed_bed"] surge_state = 1 hosp_adm_thresholds_ub, staffed_bed_thresholds_ub = {}, {} for id_t in effective_tiers: if id_t!= len(effective_tiers) - 1: hosp_adm_thresholds_ub[id_t] = hosp_adm_thresholds[id_t + 1] staffed_bed_thresholds_ub[id_t] = staffed_bed_thresholds[id_t + 1] else: hosp_adm_thresholds_ub[id_t] = np.inf staffed_bed_thresholds_ub[id_t] = np.inf hosp_adm_tier = effective_tiers[[ hosp_adm_thresholds[tier_ix] <= ToIHT_total < hosp_adm_thresholds_ub[tier_ix] for tier_ix in effective_tiers].index(True)] staffed_bed_tier = effective_tiers[[ staffed_bed_thresholds[tier_ix] <= IHT_avg < staffed_bed_thresholds_ub[tier_ix] for tier_ix in effective_tiers].index(True)] new_tier = max(hosp_adm_tier, staffed_bed_tier) if new_tier > current_tier: # bump to the next tier t_end =
np.minimum(t + self.tiers[new_tier]['min_enforcing_time'], T)
numpy.minimum
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/03_hamiltonian.ipynb (unless otherwise specified). __all__ = ['Hamiltonian1D', 'XYHamiltonian', 'XXHamiltonian', 'XYZHamiltonian'] # Cell import numpy as np import picos import networkx as nx import matplotlib.pyplot as plt # Cell class Hamiltonian1D: x = picos.Constant('x', [[0, 1], [1, 0]]) y = picos.Constant('y', [[0, -1j], [1j, 0]]) z = picos.Constant('z', [[1, 0], [0, -1]]) Id = picos.Constant('Id', [[1, 0], [0, 1]]) def __init__(self, N, linear, quadratic): self.N = N self.linear = linear self.quadratic = quadratic def draw_system(self, figsize=(8,6), cmap=plt.cm.plasma): "Conceptual drawing of the system showing interaction strength and on-site field." G = nx.Graph() G.add_nodes_from([(node,{'w': w}) for node,w in zip(np.arange(self.N),self.linear)]) G.add_edges_from([(n,n+1,{'w': w}) if n<self.N-1 else (n,0,{'w': w}) for n,w in zip(np.arange(self.N), self.quadratic)]) plt.figure(figsize=figsize) pos = nx.circular_layout(G) for (n, d) in G.nodes(data=True): nx.draw_networkx_nodes(G, pos=pos, nodelist=[n], node_size=400, node_color=[d['w']/np.max(self.linear)], cmap=cmap, vmin=0, vmax=1) for (u,v,d) in G.edges(data=True): nx.draw_networkx_edges(G, pos=pos, edgelist=[(u,v)], width=5, alpha=d['w']/np.max(self.quadratic)) d = np.array([-0.1, 0]) label_pos = {k: v+d if v[0]<0 else v-d for k,v in pos.items()} nx.draw_networkx_labels(G, pos=label_pos, font_size=25); # Cell class XYHamiltonian(Hamiltonian1D): def __init__(self, N, linear, quadratic, g): super().__init__(N, linear, quadratic) self.g = g self.model = 'xy' def to_sdp(self): "Returns hamiltonian in terms of SDP variables." linear = [(
np.array([i])
numpy.array
import numpy as np import random import warnings import cv2 from tensorflow import keras import albumentations as A from utils.anchors import anchors_for_shape, anchor_targets_bbox, AnchorParameters from utils.bbox_transform import forward_convert from utils.bbox_transform import backward_convert from utils.bbox_transform import get_best_begin_point from utils.bbox_transform import change_rbox_definition from utils.bbox_transform import rotate from utils.anchors import Anchor class Generator(keras.utils.Sequence): """ Abstract generator class. """ def __init__( self, phi=0, image_sizes=(512, 640, 768, 896, 768, 1280, 1408), misc_effect=None, visual_effect=None, use_augmentations=None, horizontal_flip = None, vertical_flip = None, RandomBrightnessContrast = None, RandomColorShift = None, RandomRotate90 = None, batch_size=1, group_method='random', # one of 'none', 'random', 'ratio' shuffle_groups=True, detect_text=False, detect_quadrangle=False, ): """ Initialize Generator object. Args: batch_size: The size of the batches to generate. group_method: Determines how images are grouped together (defaults to 'ratio', one of ('none', 'random', 'ratio')). shuffle_groups: If True, shuffles the groups each epoch. image_sizes: """ self.misc_effect = misc_effect self.visual_effect = visual_effect self.use_augmentations = use_augmentations self.horizontal_flip = horizontal_flip self.vertical_flip = vertical_flip self.RandomBrightnessContrast = RandomBrightnessContrast, self.RandomColorShift = RandomColorShift self.RandomRotate90 = RandomRotate90 self.batch_size = int(batch_size) self.group_method = group_method self.shuffle_groups = shuffle_groups self.detect_text = detect_text self.detect_quadrangle = detect_quadrangle self.image_size = image_sizes[phi] self.groups = None # self.anchors = Anchor(image_size =(self.image_size, self.image_size))._boxes self.anchor_parameters = AnchorParameters.default if not self.detect_text else AnchorParameters( ratios=(0.25, 0.5, 1., 2.), sizes=(16, 32, 64, 128, 256)) self.anchors = anchors_for_shape((self.image_size, self.image_size), anchor_params=self.anchor_parameters) self.num_anchors = self.anchor_parameters.num_anchors() # Define groups self.group_images() # Shuffle when initializing if self.shuffle_groups: random.shuffle(self.groups) def on_epoch_end(self): if self.shuffle_groups: random.shuffle(self.groups) def size(self): """ Size of the dataset. """ raise NotImplementedError('size method not implemented') def get_anchors(self): """ loads the anchors from a txt file """ with open(self.anchors_path) as f: anchors = f.readline() anchors = [float(x) for x in anchors.split(',')] # (N, 2), wh return np.array(anchors).reshape(-1, 2) def num_classes(self): """ Number of classes in the dataset. """ raise NotImplementedError('num_classes method not implemented') def has_label(self, label): """ Returns True if label is a known label. """ raise NotImplementedError('has_label method not implemented') def has_name(self, name): """ Returns True if name is a known class. """ raise NotImplementedError('has_name method not implemented') def name_to_label(self, name): """ Map name to label. """ raise NotImplementedError('name_to_label method not implemented') def label_to_name(self, label): """ Map label to name. """ raise NotImplementedError('label_to_name method not implemented') def image_aspect_ratio(self, image_index): """ Compute the aspect ratio for an image with image_index. """ raise NotImplementedError('image_aspect_ratio method not implemented') def load_image(self, image_index): """ Load an image at the image_index. """ raise NotImplementedError('load_image method not implemented') def load_annotations(self, image_index): """ Load annotations for an image_index. """ raise NotImplementedError('load_annotations method not implemented') def load_annotations_group(self, group): """ Load annotations for all images in group. """ annotations_group = [self.load_annotations(image_index) for image_index in group] for annotations in annotations_group: assert (isinstance(annotations, dict)), '\'load_annotations\' should return a list of dictionaries, received: {}'.format( type(annotations)) assert ( 'labels' in annotations), '\'load_annotations\' should return a list of dictionaries that contain \'labels\' and \'bboxes\'.' assert ( 'bboxes' in annotations), '\'load_annotations\' should return a list of dictionaries that contain \'labels\' and \'bboxes\'.' return annotations_group def filter_annotations(self, image_group, annotations_group, group): """ Filter annotations by removing those that are outside of the image bounds or whose width/height < 0. """ # test all annotations for index, (image, annotations) in enumerate(zip(image_group, annotations_group)): # test x2 < x1 | y2 < y1 | x1 < 0 | y1 < 0 | x2 <= 0 | y2 <= 0 | x2 >= image.shape[1] | y2 >= image.shape[0] invalid_indices = np.where( (annotations['bboxes'][:, 2] <= annotations['bboxes'][:, 0]) | (annotations['bboxes'][:, 3] <= annotations['bboxes'][:, 1]) | (annotations['bboxes'][:, 0] < 0) | (annotations['bboxes'][:, 1] < 0) | (annotations['bboxes'][:, 2] <= 0) | (annotations['bboxes'][:, 3] <= 0) | (annotations['bboxes'][:, 2] > image.shape[1]) | (annotations['bboxes'][:, 3] > image.shape[0]) )[0] # delete invalid indices if len(invalid_indices): warnings.warn('Image with id {} (shape {}) contains the following invalid boxes: {}.'.format( group[index], image.shape, annotations['bboxes'][invalid_indices, :] )) for k in annotations_group[index].keys(): annotations_group[index][k] = np.delete(annotations[k], invalid_indices, axis=0) # if annotations['bboxes'].shape[0] == 0: # warnings.warn('Image with id {} (shape {}) contains no valid boxes before transform'.format( # group[index], # image.shape, # )) return image_group, annotations_group def clip_transformed_annotations(self, image_group, annotations_group): """ Filter annotations by removing those that are outside of the image bounds or whose width/height < 0. """ # test all annotations filtered_image_group = [] filtered_annotations_group = [] for index, (image, annotations) in enumerate(zip(image_group, annotations_group)): image_height = image.shape[0] image_width = image.shape[1] # x1 # annotations['bboxes'][:, 0] = np.clip(annotations['bboxes'][:, 0], 0, image_width - 2) # # y1 # annotations['bboxes'][:, 1] = np.clip(annotations['bboxes'][:, 1], 0, image_height - 2) # # x2 # annotations['bboxes'][:, 2] = np.clip(annotations['bboxes'][:, 2], 1, image_width - 1) # # y2 # annotations['bboxes'][:, 3] = np.clip(annotations['bboxes'][:, 3], 1, image_height - 1) # test x2 < x1 | y2 < y1 | x1 < 0 | y1 < 0 | x2 <= 0 | y2 <= 0 | x2 >= image.shape[1] | y2 >= image.shape[0] out_indices = np.where( ((annotations['bboxes'][:, 2] + annotations['bboxes'][:, 0])/2 < 0) | ((annotations['bboxes'][:, 3] + annotations['bboxes'][:, 1])/2 < 0) | ((annotations['bboxes'][:, 2] + annotations['bboxes'][:, 0])/2 > image_width) | ((annotations['bboxes'][:, 3] + annotations['bboxes'][:, 1])/2 > image_height) )[0] small_indices = np.where( (annotations['bboxes'][:, 2] - annotations['bboxes'][:, 0] < 3) | (annotations['bboxes'][:, 3] - annotations['bboxes'][:, 1] < 3) )[0] # delete invalid indices if len(small_indices) or len(out_indices): # print('!!!!!!!!!!') for k in annotations_group[index].keys(): annotations_group[index][k] = np.delete(annotations[k], small_indices, axis=0) annotations_group[index][k] = np.delete(annotations[k], out_indices, axis=0) # print(annotations['bboxes'][out_indices]) # import cv2 # for invalid_index in small_indices: # x1, y1, x2, y2 = annotations['bboxes'][invalid_index] # label = annotations['labels'][invalid_index] # class_name = self.labels[label] # print('width: {}'.format(x2 - x1)) # print('height: {}'.format(y2 - y1)) # cv2.rectangle(image, (int(round(x1)), int(round(y1))), (int(round(x2)), int(round(y2))), (0, 255, 0), 2) # cv2.putText(image, class_name, (int(round(x1)), int(round(y1))), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 255), 1) # cv2.namedWindow('image', cv2.WINDOW_NORMAL) # cv2.imshow('image', image) # cv2.waitKey(0) filtered_image_group.append(image) filtered_annotations_group.append(annotations_group[index]) return filtered_image_group, filtered_annotations_group def load_image_group(self, group): """ Load images for all images in a group. """ return [self.load_image(image_index) for image_index in group] def augmentations_pipeline(self,image_group, annotations_group): # augmentations_list = list() # if self.horizontal_flip: # H = A.HorizontalFlip(p=0.5) # augmentations_list.append(H) # if self.vertical_flip: # V = A.VerticalFlip(p=0.5) # augmentations_list.append(V) # if self.RandomBrightnessContrast: # B = A.OneOf([ # A.RandomBrightnessContrast(brightness_limit=0.3, # contrast_limit=0.2, # p=.8), # A.RandomGamma(gamma_limit=(80, 120)) # ],p=.8) # augmentations_list.append(B) # if self.RandomColorShift: # C = A.OneOf([ # A.HueSaturationValue(hue_shift_limit=.2, sat_shift_limit=.2, # val_shift_limit=0.2,p=.8), # A.RGBShift(r_shift_limit=20, b_shift_limit=15, g_shift_limit=15) # ]) # augmentations_list.append(C) # augmentations_list.append(A.CLAHE(p=0.8)) # augmentations_list.append(A.ToGray(p=0.01)) # if self.RandomRotate90: # R = A.RandomRotate90(p=0.5) # augmentations_list.append(R) augmentations_list_1= [ # A.Resize(height=1024, width=1024, p=1), # A.RandomSizedCrop(min_max_height=(824, 824), height=1024, width=1024, p=0.5), A.OneOf([ A.HueSaturationValue(hue_shift_limit=0.2, sat_shift_limit= 0.2, val_shift_limit=0.2, p=0.9), A.RandomBrightnessContrast(brightness_limit=0.2, contrast_limit=0.2, p=0.9), ],p=0.9), # augmentations_list_2 = [ A.Rotate (limit=list(np.arange(-90, 90+16, 15)), interpolation=1, border_mode=0, p=0.8), A.ToGray(p=0.01), A.HorizontalFlip(p=0.5), A.VerticalFlip(p=0.5), A.Resize(height=640, width=640, p=1), ] transform_1 = A.Compose(augmentations_list_1, keypoint_params=A.KeypointParams( format='xy',remove_invisible=False), p=1 ) # transform_2 = A.Compose(augmentations_list_2, # keypoint_params=A.KeypointParams( # format='xy',remove_invisible=False), # p=1 # ) for index, (image, annotations) in enumerate(zip(image_group, annotations_group)): # preprocess a single group entry quadrangles = annotations['quadrangles'].reshape(-1,2) transformed = transform_1(image=image, keypoints=(quadrangles) ) aug_quadrangles = np.array(transformed['keypoints']).reshape(-1,4,2).astype(np.float32) xmin = np.min(aug_quadrangles, axis=1)[:, 0] ymin = np.min(aug_quadrangles, axis=1)[:, 1] xmax = np.max(aug_quadrangles, axis=1)[:, 0] ymax = np.max(aug_quadrangles, axis=1)[:, 1] annotations['bboxes'] = np.stack([xmin,ymin,xmax,ymax],axis=1) annotations['quadrangles'] = aug_quadrangles image_group[index] = transformed['image'] # image_group, annotations_group = self.clip_transformed_annotations(image_group, annotations_group) # for index, (image, annotations) in enumerate(zip(image_group, annotations_group)): # # preprocess a single group entry # quadrangles = annotations['quadrangles'].reshape(-1,2) # transformed = transform_2(image=image, # keypoints=(quadrangles) # ) # aug_quadrangles = np.array(transformed['keypoints']).reshape(-1,4,2).astype(np.float32) # xmin = np.min(aug_quadrangles, axis=1)[:, 0] # ymin = np.min(aug_quadrangles, axis=1)[:, 1] # xmax = np.max(aug_quadrangles, axis=1)[:, 0] # ymax = np.max(aug_quadrangles, axis=1)[:, 1] # annotations['bboxes'] = np.stack([xmin,ymin,xmax,ymax],axis=1) # annotations['quadrangles'] = aug_quadrangles # image_group[index] = transformed['image'] return image_group, annotations_group def random_visual_effect_group_entry(self, image, annotations): """ Randomly transforms image and annotation. """ # apply visual effect image = self.visual_effect(image) return image, annotations def random_visual_effect_group(self, image_group, annotations_group): """ Randomly apply visual effect on each image. """ assert (len(image_group) == len(annotations_group)) if self.visual_effect is None: # do nothing return image_group, annotations_group for index in range(len(image_group)): # apply effect on a single group entry image_group[index], annotations_group[index] = self.random_visual_effect_group_entry( image_group[index], annotations_group[index] ) return image_group, annotations_group def random_misc_group_entry(self, image, annotations): """ Randomly transforms image and annotation. """ # randomly transform both image and annotations image, annotations = self.misc_effect(image, annotations) return image, annotations def random_misc_group(self, image_group, annotations_group): """ Randomly transforms each image and its annotations. """ assert (len(image_group) == len(annotations_group)) if self.misc_effect is None: return image_group, annotations_group for index in range(len(image_group)): # transform a single group entry image_group[index], annotations_group[index] = self.random_misc_group_entry(image_group[index], annotations_group[index]) return image_group, annotations_group def preprocess_group_entry(self, image, annotations): """ Preprocess image and its annotations. """ # preprocess the image image, scale = self.preprocess_image(image) # print(image.shape) # print(scale) annotations['bboxes'] *= scale if self.detect_quadrangle: annotations['quadrangles'] *= scale # quadrangles = np.array([self.xywhtheta_to_coords( # self.coords_to_xywhtheta(q.reshape(1,8))) # for q in annotations['quadrangles'] # ] # ).reshape(-1,4,2) # quadrangles = np.array([self.reorder_vertexes(q) for q in quadrangles]) quadrangles = np.array([get_best_begin_point( forward_convert( backward_convert( q.reshape(-1,8)))) for q in annotations['quadrangles'] ]).reshape(-1,4,2) annotations['quadrangles'] = quadrangles # print(quadrangles.shape) return image,annotations # apply resizing to annotations too def preprocess_group(self, image_group, annotations_group): """ Preprocess each image and its annotations in its group. """ assert (len(image_group) == len(annotations_group)) # print(len(image_group)) # print(len(annotations_group)) for index,(image,annotations) in enumerate( zip(image_group,annotations_group)): # preprocess a single group entry image_group[index], annotations_group[index] = self.preprocess_group_entry(image,annotations) return image_group, annotations_group def group_images(self): """ Order the images according to self.order and makes groups of self.batch_size. """ # determine the order of the images order = list(range(self.size())) if self.group_method == 'random': random.shuffle(order) elif self.group_method == 'ratio': order.sort(key=lambda x: self.image_aspect_ratio(x)) # divide into groups, one group = one batch self.groups = [[order[x % len(order)] for x in range(i, i + self.batch_size)] for i in range(0, len(order), self.batch_size)] def compute_inputs(self, image_group, annotations_group): """ Compute inputs for the network using an image_group. """ batch_images = np.array(image_group).astype(np.float32) return [batch_images] def compute_alphas_and_ratios(self, annotations_group): for i, annotations in enumerate(annotations_group): # print(quadrangles) quadrangles = annotations['quadrangles'] alphas = np.zeros((quadrangles.shape[0], 2), dtype=np.float32) xmin = np.min(quadrangles, axis=1)[:, 0] ymin = np.min(quadrangles, axis=1)[:, 1] xmax = np.max(quadrangles, axis=1)[:, 0] ymax = np.max(quadrangles, axis=1)[:, 1] annotations['bboxes'] = np.vstack([xmin,ymin,xmax,ymax]).T # alpha1, alpha2, alpha3, alpha4 alphas[:, 0] = (quadrangles[:, 0, 0] - xmin) / (xmax - xmin) alphas[:, 1] = (quadrangles[:, 1, 1] - ymin) / (ymax - ymin) # alphas[:, 2] = (xmax - quadrangles[:, 2, 0]) / (xmax - xmin) # alphas[:, 3] = (ymax - quadrangles[:, 3, 1]) / (ymax - ymin) annotations['alphas'] = alphas # ratio area1 = 0.5 * alphas[:, 0] * (1 - alphas[:, 1]) area2 = 0.5 * alphas[:, 1] * (1 - alphas[:, 0]) # area3 = 0.5 * alphas[:, 2] * (1 - alphas[:, 1]) # area4 = 0.5 * alphas[:, 3] * (1 - alphas[:, 2]) annotations['ratios'] = 1 - area1 - area2# - area3 - area4 return annotations_group def compute_angle(self, annotations_group): for i, annotations in enumerate(annotations_group): # print(quadrangles) quadrangles = annotations['quadrangles'] angles = np.zeros((quadrangles.shape[0], 1), dtype=np.float64) bboxes = np.zeros((quadrangles.shape[0], 4), dtype=np.float64) rbboxes = change_rbox_definition(backward_convert(quadrangles.reshape(-1,8))) # print(rbboxes.shape) angles[:,0] = rbboxes[:,4]/45.0 quads_off = np.array([rotate(q ,rbboxes[i,4]) for i,q in enumerate(quadrangles)]) # print(bboxes_q.shape) if quads_off.shape[0]==0: quads_off = np.zeros((quadrangles.shape[0], 4,2), dtype=np.float32) bboxes[:,0] = np.min(quads_off, axis=1)[:, 0] bboxes[:,1] = np.min(quads_off, axis=1)[:, 1] bboxes[:,2] = np.max(quads_off, axis=1)[:, 0] bboxes[:,3] = np.max(quads_off, axis=1)[:, 1] # print(bboxes.shape) annotations['bboxes'] = bboxes annotations['quads_off'] = quads_off annotations['angles'] = angles annotations_group[i]= annotations return annotations_group def compute_targets(self, image_group, annotations_group): """ Compute target outputs for the network using images and their annotations. """ """ Compute target outputs for the network using images and their annotations. """ # print(annotations_group) batches_targets = anchor_targets_bbox( self.anchors, image_group, annotations_group, num_classes=self.num_classes(), detect_quadrangle=self.detect_quadrangle ) return list(batches_targets) def compute_inputs_targets(self, group, debug=False): """ Compute inputs and target outputs for the network. """ # load images and annotations # list image_group = self.load_image_group(group) annotations_group = self.load_annotations_group(group) # check validity of annotations # image_group, annotations_group = self.filter_annotations(image_group, annotations_group, group) # randomly apply visual effect image_group, annotations_group = self.random_visual_effect_group(image_group, annotations_group) # randomly transform data # image_group, annotations_group = self.random_transform_group(image_group, annotations_group) # randomly apply misc effect image_group, annotations_group = self.random_misc_group(image_group, annotations_group) if self.use_augmentations: image_group, annotations_group = self.augmentations_pipeline(image_group, annotations_group) # perform preprocessing steps # print((image_group)[0]) # print((annotations_group)[0]) image_group, annotations_group = self.preprocess_group(image_group, annotations_group) # check validity of annotations image_group, annotations_group = self.clip_transformed_annotations(image_group, annotations_group) assert len(image_group) != 0 assert len(image_group) == len(annotations_group) if self.detect_quadrangle: # compute alphas and ratio for targets annotations_group = self.compute_alphas_and_ratios(annotations_group) annotations_group = self.compute_angle(annotations_group) # print(annotations_group) # compute network inputs inputs = self.compute_inputs(image_group, annotations_group) # compute network targets targets = self.compute_targets(image_group, annotations_group) if debug: return inputs, targets, annotations_group return inputs, targets def __len__(self): """ Number of batches for generator. """ return len(self.groups) def __getitem__(self, index): """ Keras sequence method for generating batches. """ group = self.groups[index] inputs, targets = self.compute_inputs_targets(group) return inputs, targets def preprocess_image(self, image): # image, RGB image_height, image_width = image.shape[:2] if image_height > image_width: scale = self.image_size / image_height resized_height = self.image_size resized_width = int(image_width * scale) else: scale = self.image_size / image_width resized_height = int(image_height * scale) resized_width = self.image_size image = cv2.resize(image, (resized_width, resized_height)) image = image.astype(np.float32) image /= 255. mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] image -= mean image /= std pad_h = self.image_size - resized_height pad_w = self.image_size - resized_width image =
np.pad(image, [(0, pad_h), (0, pad_w), (0, 0)], mode='constant')
numpy.pad
""" Tests for the bootstrap_calcs.py file. """ import unittest import numpy as np import numpy.testing as npt import pandas as pd from scipy.stats import norm, gumbel_r import pylogit.bootstrap_calcs as bc try: # Python 3.x does not natively support xrange from past.builtins import xrange except ImportError: pass class ComputationalTests(unittest.TestCase): def setUp(self): """ Note that the spatial test data used in many of these tests comes from Efron, Bradley, and <NAME>. An Introduction to the Bootstrap. CRC press, 1994. Chapter 14. """ # Determine the number of parameters and number of bootstrap replicates num_replicates = 100 num_params = 5 # Create a set of fake bootstrap replicates self.bootstrap_replicates =\ (np.arange(1, 1 + num_replicates)[:, None] * np.arange(1, 1 + num_params)[None, :]) # Create a fake maximum likelihood parameter estimate self.mle_params = self.bootstrap_replicates[50, :] # Create a set of fake jackknife replicates array_container = [] for est in self.mle_params: array_container.append(gumbel_r.rvs(loc=est, size=10)) self.jackknife_replicates =\ np.concatenate([x[:, None] for x in array_container], axis=1) # Create a fake confidence percentage. self.conf_percentage = 94.88 # Store the spatial test data from Efron and Tibshirani (1994) self.test_data =\ np.array([48, 36, 20, 29, 42, 42, 20, 42, 22, 41, 45, 14, 6, 0, 33, 28, 34, 4, 32, 24, 47, 41, 24, 26, 30, 41]) # Note how many test data observations there are. num_test_obs = self.test_data.size # Create the function to calculate the jackknife replicates. def calc_theta(array): result = ((array - array.mean())**2).sum() / float(array.size) return result self.calc_theta = calc_theta self.test_theta_hat = np.array([calc_theta(self.test_data)]) # Create a pandas series of the data. Allows for easy case deletion. raw_series = pd.Series(self.test_data) # Create the array of jackknife replicates jackknife_replicates = np.empty((num_test_obs, 1), dtype=float) for obs in xrange(num_test_obs): current_data = raw_series[raw_series.index != obs].values jackknife_replicates[obs] = calc_theta(current_data) self.test_jackknife_replicates = jackknife_replicates return None def test_calc_percentile_interval(self): # Get the alpha percentage. Should be 5.12 so alpha / 2 should be 2.56 alpha = bc.get_alpha_from_conf_percentage(self.conf_percentage) # These next 2 statements work because there are exactly 100 replicates # We should have the value in BR[lower_row, 0] = 3 so that there are 2 # elements in bootstrap_replicates (BR) that are less than this. I.e. # we want lower_row = 2. Note 2.56 rounded down is 2. lower_row = int(np.floor(alpha / 2.0)) # 100 - 2.56 is 97.44. Rounded up, this is 98. # We want the row such that the value in the first column of that row # is 98, i.e. we want the row at index 97. upper_row = int(np.floor(100 - (alpha / 2.0))) # Create the expected results expected_results =\ bc.combine_conf_endpoints(self.bootstrap_replicates[lower_row], self.bootstrap_replicates[upper_row]) # Alias the function being tested func = bc.calc_percentile_interval # Get the function results func_results = func(self.bootstrap_replicates, self.conf_percentage) # Perform the desired tests self.assertIsInstance(func_results, np.ndarray) self.assertEqual(func_results.shape, expected_results.shape) npt.assert_allclose(func_results, expected_results) return None def test_calc_bias_correction_bca(self): # There are 100 bootstrap replicates, already in ascending order for # each column. If we take row 51 to be the mle, then 50% of the # replicates are less than the mle, and we should have bias = 0. expected_result = np.zeros(self.mle_params.size) # Alias the function to be tested. func = bc.calc_bias_correction_bca # Perform the desired test func_result = func(self.bootstrap_replicates, self.mle_params) self.assertIsInstance(func_result, np.ndarray) self.assertEqual(func_result.shape, expected_result.shape) npt.assert_allclose(func_result, expected_result) # Create a fake mle that should be higher than 95% of the results fake_mle = self.bootstrap_replicates[95] expected_result_2 = norm.ppf(0.95) * np.ones(self.mle_params.size) func_result_2 = func(self.bootstrap_replicates, fake_mle) self.assertIsInstance(func_result_2, np.ndarray) self.assertEqual(func_result_2.shape, expected_result_2.shape) npt.assert_allclose(func_result_2, expected_result_2) return None def test_calc_acceleration_bca(self): # Get the expected result. See page 186 of Efron and Tibshirani (1994) expected_result = np.array([0.061]) # Alias the function being tested func = bc.calc_acceleration_bca # Perform the desired test func_result = func(self.test_jackknife_replicates) self.assertIsInstance(func_result, np.ndarray) self.assertEqual(func_result.shape, expected_result.shape) # Note the absolute tolerance of 5e-4 is used because the results # should agree when rounded to 3 decimal places. This will be the case # if the two sets of results agree to within 5e-4 of each other. npt.assert_allclose(func_result, expected_result, atol=5e-4) return None def test_calc_lower_bca_percentile(self): # Use the parameter values from # Efron, Bradley, and <NAME>. An Introduction to the # Bootstrap. CRC press, 1994. Pages 185-186 # Note that my alpha is Efron's alpha / 2, in percents not decimals alpha_percent = 10 bias_correction = np.array([0.146]) acceleration = np.array([0.061]) # Note the expected results expected_result = np.array([0.110]) # Alias the function being tested func = bc.calc_lower_bca_percentile # Perform the desired tests # Note we divide the function results by 100 since our results are in # terms of percents and Efron's results are in decimals. func_result = func(alpha_percent, bias_correction, acceleration) / 100 self.assertIsInstance(func_result, np.ndarray) self.assertEqual(func_result.shape, expected_result.shape) # Note the absolute tolerance of 5e-4 is used because the results # should agree when rounded to 3 decimal places. This will be the case # if the two sets of results agree to within 5e-4 of each other. npt.assert_allclose(func_result, expected_result, atol=5e-4) return None def test_calc_upper_bca_percentile(self): # Use the parameter values from # Efron, Bradley, and <NAME>. An Introduction to the # Bootstrap. CRC press, 1994. Pages 185-186 # Note that my alpha is Efron's alpha / 2, in percents not decimals alpha_percent = 10 bias_correction = np.array([0.146]) acceleration = np.array([0.061]) # Note the expected results expected_result = np.array([0.985]) # Alias the function being tested func = bc.calc_upper_bca_percentile # Perform the desired tests # Note we divide the function results by 100 since our results are in # terms of percents and Efron's results are in decimals. func_result = func(alpha_percent, bias_correction, acceleration) / 100 self.assertIsInstance(func_result, np.ndarray) self.assertEqual(func_result.shape, expected_result.shape) # Note the absolute tolerance of 1e-3 is used because the results # should be within 0.001 of each other.
npt.assert_allclose(func_result, expected_result, atol=1e-3)
numpy.testing.assert_allclose
""" Derived module from dmdbase.py for dmd with control. Reference: - <NAME>., <NAME>. and <NAME>., 2016. Dynamic mode decomposition with control. SIAM Journal on Applied Dynamical Systems, 15(1), pp.142-161. """ from .dmdbase import DMDBase from past.utils import old_div import numpy as np class DMDc(DMDBase): """ Dynamic Mode Decomposition with control. This version does not allow to manipulate the temporal window within the system is reconstructed. :param svd_rank: the rank for the truncation; If 0, the method computes the optimal rank and uses it for truncation; if positive interger, the method uses the argument for the truncation; if float between 0 and 1, the rank is the number of the biggest singular values that are needed to reach the 'energy' specified by `svd_rank`; if -1, the method does not compute truncation. :type svd_rank: int or float :param int tlsq_rank: rank truncation computing Total Least Square. Default is 0, that means no truncation. :param bool opt: flag to compute optimal amplitudes. See :class:`DMDBase`. Default is False. """ def __init__(self, svd_rank=0, tlsq_rank=0, opt=False): self.svd_rank = svd_rank self.tlsq_rank = tlsq_rank self.opt = opt self.original_time = None self._eigs = None self._Atilde = None self._B = None self._modes = None # Phi self._b = None # amplitudes self._snapshots = None self._snapshots_shape = None self._controlin = None self._controlin_shape = None self._basis = None @property def B(self): """ Get the operator B. :return: the operator B. :rtype: numpy.ndarray """ return self._B @property def basis(self): """ Get the basis used to reduce the linear operator to the low dimensional space. :return: the matrix which columns are the basis vectors. :rtype: numpy.ndarray """ return self._basis def reconstructed_data(self, control_input=None): """ Return the reconstructed data, computed using the `control_input` argument. If the `control_input` is not passed, the original input (in the `fit` method) is used. The input dimension has to be consistent with the dynamics. :param numpy.ndarray control_input: the input control matrix. :return: the matrix that contains the reconstructed snapshots. :rtype: numpy.ndarray """ if control_input is None: controlin, controlin_shape = self._controlin, self._controlin_shape else: controlin, controlin_shape = self._col_major_2darray(control_input) if controlin.shape[1] != self.dynamics.shape[1]-1: raise RuntimeError( 'The number of control inputs and the number of snapshots to reconstruct has to be the same') if np.isnan(self.modes).any(): print('Modes contain nans; aborting without error') return np.nan * np.zeros_like(self._snapshots) omega = old_div(np.log(self.eigs), self.original_time['dt']) eigs = np.exp(omega * self.dmd_time['dt']) A = self.modes.dot(np.diag(eigs)).dot(np.linalg.pinv(self.modes)) data = [self._snapshots[:, 0]] for i, u in enumerate(controlin.T): data.append(A.dot(data[i]) + self._B.dot(u)) data = np.array(data).T return data def _fit_B_known(self, X, Y, B): """ Private method that performs the dynamic mode decomposition algorithm with control when the matrix `B` is provided. :param numpy.ndarray X: the first matrix of original snapshots. :param numpy.ndarray Y: the second matrix of original snapshots. :param numpy.ndarray I: the input control matrix. :param numpy.ndarray B: the matrib B. """ X, Y = self._compute_tlsq(X, Y, self.tlsq_rank) U, s, V = self._compute_svd(X, self.svd_rank) self._Atilde = U.T.conj().dot(Y - B.dot(self._controlin)).dot(V).dot( np.diag(np.reciprocal(s))) self._eigs, self._modes = self._eig_from_lowrank_op( self._Atilde, (Y - B.dot(self._controlin)), U, s, V, True) self._b = self._compute_amplitudes(self._modes, self._snapshots, self._eigs, self.opt) self._B = B self._basis = U return self def _fit_B_unknown(self, X, Y): """ Private method that performs the dynamic mode decomposition algorithm with control when the matrix `B` is not provided. :param numpy.ndarray X: the first matrix of original snapshots. :param numpy.ndarray Y: the second matrix of original snapshots. :param numpy.ndarray I: the input control matrix. """ omega = np.vstack([X, self._controlin]) Up, sp, Vp = self._compute_svd(omega, self.svd_rank) Up1 = Up[:self._snapshots.shape[0], :] Up2 = Up[self._snapshots.shape[0]:, :] # TODO: a second svd_rank? Ur, sr, Vr = self._compute_svd(Y, -1) self._basis = Ur reg = 1e-10 # Prevents nan in the reciprocal self._Atilde = Ur.T.conj().dot(Y).dot(Vp).dot( np.diag(np.reciprocal(sp+reg))).dot(Up1.T.conj()).dot(Ur) self._Btilde = Ur.T.conj().dot(Y).dot(Vp).dot( np.diag(np.reciprocal(sp+reg))).dot(Up2.T.conj()) self._B = Ur.dot(self._Btilde) self._eigs, modes =
np.linalg.eig(self._Atilde)
numpy.linalg.eig
import os import sys import subprocess import argparse import time import math import numpy as np import mrcfile import matplotlib.pyplot as plt from cv2 import * from scipy import ndimage import scipy.signal from scipy.spatial.distance import directed_hausdorff from skimage import feature from skimage.feature import match_template from skimage.filters import threshold_otsu from skimage.transform import rescale import imutils from joblib import Parallel, effective_n_jobs, delayed from sklearn.utils import gen_even_slices from sklearn.metrics.pairwise import euclidean_distances from pathlib import Path from shutil import copyfile from helper_functions import load_obj, save_obj, sort_dict from extract_relion_particle_counts import gen_particle_counts cs2star_path = '/home_local/landeradmin/pyem' #UPDATE THIS depending on where pyem is located in your machine def crop_image(img): """ Crop image based on first nonzero elements Parameters ------------ img: 2d np.ndarray A single class average Returns ----------- 2d np.ndarray Cropped image """ row_idx, col_idx = np.nonzero(img) return(img[np.min(row_idx):np.max(row_idx)+1,np.min(col_idx):np.max(col_idx)+1]) def norm_cross_correlation_cv(img1, img2): """ Calculate the normalized cross-correlation between two images Parameters ------------ img1: 2d np.ndarray A single class average img2: 2d np.ndarray A single class average Returns ----------- 2d np.ndarray Cross-correlation matrix tuple 2D Index corresponding to maximum cross-correlation int Relative delta x to shift img2 to maximize cross-correlation with img1 int Relative delta y to shift img2 to maximize cross-correlation with img1 """ cross_image = cv2.filter2D(img1, -1, img2, borderType=cv2.BORDER_CONSTANT) max_idx = np.unravel_index(np.argmax(cross_image), cross_image.shape) relative_diff_y = max_idx[0] - img1.shape[0]//2 relative_diff_x = max_idx[1] - img1.shape[1]//2 return(cross_image, max_idx, relative_diff_x, relative_diff_y) def get_image_rotation_matrix_map(image_2d_matrix, scale_factor, mirror): """ Wrapper to calclate and store rotated images for each of the class averages Parameters ------------ image_2d_matrix: 3d np.ndarray Axis 0 corresponds to class average number, axis 1 corresponds to class average width, and axis 2 corresponds to class average height scale_factor: float Factor by which to downsample image mirror: int Whether or not to calculate rotations for mirror image Returns ----------- dict Dictionary of dictionaries storing each rotation for each image in image_2d_matrix dict Dictionary of dictionaries storing the maximum shape among all rotations for each image in image_2d_matrix """ #each image has a unique maximum shape image_2d_rotation_matrix_map = {} image_2d_rotation_matrix_max_shape_map = {} image_2d_rotation_mirror_matrix_map = {} image_2d_rotation_mirror_matrix_max_shape_map = {} for i in range(0,image_2d_matrix.shape[0]): curr_img = np.copy(image_2d_matrix[i,:,:]) if scale_factor is not None: curr_img = rescale(curr_img, scale_factor, anti_aliasing=True) max_height, max_width, rotation_matrix_map = get_rotated_image_max_shape(curr_img) image_2d_rotation_matrix_map[i] = rotation_matrix_map image_2d_rotation_matrix_max_shape_map[i] = [max_height, max_width] if mirror: curr_img = np.flip(curr_img, axis=0) max_height, max_width, rotation_matrix_map = get_rotated_image_max_shape(curr_img) image_2d_rotation_mirror_matrix_map[i] = rotation_matrix_map image_2d_rotation_mirror_matrix_max_shape_map[i] = [max_height, max_width] rotation_matrix_map = {} max_shape_map = {} rotation_matrix_map['original'] = image_2d_rotation_matrix_map max_shape_map['original'] = image_2d_rotation_matrix_max_shape_map if mirror: rotation_matrix_map['mirror'] = image_2d_rotation_mirror_matrix_map max_shape_map['mirror'] = image_2d_rotation_mirror_matrix_max_shape_map return(rotation_matrix_map, max_shape_map) def get_rotated_image_max_shape(img): """ Calculates and stores rotated images for a class average Parameters ------------ img: 2d np.ndarray A single class average Returns ----------- int Maximium height among all rotated images int Maximum width among all rotated images dict Dictionary storing each rotation for an image """ rotation_angles = range(0,360,6) max_shape = np.array([0,0]) max_idx_row = -1 max_idx_col = -1 curr_img = np.copy(img) rotation_matrix_map = {} for j in rotation_angles: rotated_img = imutils.rotate_bound(curr_img, j) rotated_img_cropped = crop_image(rotated_img) rotated_img_cropped_shape = rotated_img_cropped.shape if rotated_img_cropped_shape[0] > max_shape[0]: max_shape[0] = rotated_img_cropped_shape[0] max_idx_row = j if rotated_img_cropped_shape[1] > max_shape[1]: max_shape[1] = rotated_img_cropped_shape[1] max_idx_col = j rotation_matrix_map[j] = rotated_img_cropped return((max_shape[0], max_shape[1], rotation_matrix_map)) def rot_trans_invariant_dist_optimized(image_2d_rotation_matrix_map, image_2d_rotation_matrix_max_shape_map, img1_idx, img2_idx, mirror_bool, mrc_height, mrc_width, corr_only=False): """ Calculates rotational and reflectional invariant normalized cross-correlation and shape based distance using the 95th-percentile hausdorff distance between edges. Note that rotation and reflection operations are applied to img2. Parameters ------------ image_2d_rotation_matrix_map: dict Dictionary of dictionaries storing each rotation for each image in image_2d_matrix image_2d_rotation_matrix_max_shape_map: dict Dictionary of dictionaries storing the maximum shape among all rotations for each image in image_2d_matrix img1_idx: int Index of first class average img2_idx: int Index of second class average mirror_bool: Whether or not to calculate distance between mirror image of img2_idx class average mrc_height: Height of input class average mrc_width: Width of input class average Returns ----------- float: Maximum normalized-cross correlation between img2 and img1 float: Minimum 95th percentile hausdorff distance between img2 and img1 int Angle to rotate img2 to maximize cross-correlation with img1 int Relative delta y to shift img2 to maximize cross-correlation with img1 int Relative delta x to shift img2 to maximize cross-correlation with img1 """ rotation_angles = range(0,360,6) img1_cropped = image_2d_rotation_matrix_map['original'][img1_idx][0] max_height = img1_cropped.shape[0] max_width = img1_cropped.shape[1] if mirror_bool: img2_max_height = image_2d_rotation_matrix_max_shape_map['mirror'][img2_idx][0] img2_max_width = image_2d_rotation_matrix_max_shape_map['mirror'][img2_idx][1] else: img2_max_height = image_2d_rotation_matrix_max_shape_map['original'][img2_idx][0] img2_max_width = image_2d_rotation_matrix_max_shape_map['original'][img2_idx][1] if img2_max_height > max_height: max_height = img2_max_height if img2_max_width > max_width: max_width = img2_max_width ###img1 and img2 are mapped to the same dimensions -- note that comparisons between different sets of images are not of the same size### ###normalized cross correlation is independent of size (in the zero-padded sense) but hausdroff distance is not### img1_cropped_padded = np.zeros((max_height,max_width)) # compute offset x_start_new = (max_width - img1_cropped.shape[1]) // 2 y_start_new = (max_height - img1_cropped.shape[0]) // 2 # copy image into center of result image img1_cropped_padded[y_start_new:y_start_new+img1_cropped.shape[0], x_start_new:x_start_new+img1_cropped.shape[1]] = img1_cropped img2_rotation_2d_matrix = np.zeros((len(rotation_angles), max_height, max_width)) for i,angle in enumerate(rotation_angles): if mirror_bool: rotated_img2_cropped = image_2d_rotation_matrix_map['mirror'][img2_idx][angle] else: rotated_img2_cropped = image_2d_rotation_matrix_map['original'][img2_idx][angle] padded_output = np.zeros((max_height,max_width)) # compute offset x_start_new = (max_width - rotated_img2_cropped.shape[1]) // 2 y_start_new = (max_height - rotated_img2_cropped.shape[0]) // 2 # copy image into center of result image padded_output[y_start_new:y_start_new+rotated_img2_cropped.shape[0], x_start_new:x_start_new+rotated_img2_cropped.shape[1]] = rotated_img2_cropped img2_rotation_2d_matrix[i,:,:] = padded_output correlation_dist_matrix = np.zeros(len(rotation_angles)) correlation_params = np.zeros((len(rotation_angles), 3)) #rotation angle, relative_diff_y, relative_diff_x #normalize each image img1_cropped_padded -= np.mean(img1_cropped_padded) img2_rotation_2d_matrix_mean = np.mean(img2_rotation_2d_matrix, axis=(1,2)) img2_rotation_2d_matrix = img2_rotation_2d_matrix - img2_rotation_2d_matrix_mean.reshape(img2_rotation_2d_matrix_mean.shape[0],1,1) img1_cropped_padded /= np.std(img1_cropped_padded) img2_rotation_2d_matrix_std = np.std(img2_rotation_2d_matrix, axis=(1,2)) img2_rotation_2d_matrix = img2_rotation_2d_matrix/img2_rotation_2d_matrix_std.reshape(img2_rotation_2d_matrix_std.shape[0],1,1) img1_cropped_padded_length_norm = img1_cropped_padded/(img1_cropped_padded.shape[0]*img1_cropped_padded.shape[1]) for i in range(0,len(rotation_angles)): cross_image_mat, max_idx, relative_diff_x, relative_diff_y = norm_cross_correlation_cv(img1_cropped_padded_length_norm, img2_rotation_2d_matrix[i,:,:]) #shift of img2 wrt img1 max_cross_cor = cross_image_mat[max_idx] correlation_dist_matrix[i] = max_cross_cor '''img2_shifted = ndimage.shift(np.copy(img2_rotation_2d_matrix[i,:,:]), (relative_diff_y, relative_diff_x)) if blur: cross_corr_match_template = match_template(cv2.GaussianBlur(img2_shifted,(51,51),0), cv2.GaussianBlur(np.copy(img1_cropped_padded),(51,51),0)) else: cross_corr_match_template = match_template(img2_shifted, img1_cropped_padded) print("This %f and this %f should roughly match" % (max_cross_cor, cross_corr_match_template[0][0])) print("relative y %d, relative x %d" % (relative_diff_y, relative_diff_x))''' correlation_params[i,0] = rotation_angles[i] correlation_params[i,1] = relative_diff_y correlation_params[i,2] = relative_diff_x max_corr_idx = np.argmax(correlation_dist_matrix) angle_optimal = correlation_params[max_corr_idx,0] relative_diff_y_optimal = correlation_params[max_corr_idx,1] relative_diff_x_optimal = correlation_params[max_corr_idx,2] if corr_only: return(np.max(correlation_dist_matrix), angle_optimal, relative_diff_y_optimal, relative_diff_x_optimal) zero_val_mapping = img2_rotation_2d_matrix_mean[max_corr_idx]/img2_rotation_2d_matrix_std[max_corr_idx] img2_shifted = ndimage.shift(np.copy(img2_rotation_2d_matrix[max_corr_idx,:,:]), (relative_diff_y_optimal, relative_diff_x_optimal), cval = 0-zero_val_mapping) #to ignore background noise when calculating edges -- 2 rounds of otsu thresholding img1_th = (float(threshold_otsu(cv2.GaussianBlur(img1_cropped_padded,(21,21),0)))) img2_th = (float(threshold_otsu(cv2.GaussianBlur(img2_shifted,(21,21),0)))) img2_shifted[img2_shifted < img2_th] = 0 img1_cropped_padded[img1_cropped_padded < img1_th] = 0 img1_th = (float(threshold_otsu(img1_cropped_padded))) img2_th = (float(threshold_otsu(img2_shifted))) img2_shifted[img2_shifted < img2_th] = 0 img1_cropped_padded[img1_cropped_padded < img1_th] = 0 ##calculate distance between edges using hausdroff metric looping thorugh different values of sigma sigma_vals = [1,2] hausdorff_norm = math.sqrt(math.pow(mrc_height,2) + math.pow(mrc_width,2)) hausdroff_dist_matrix = np.zeros((len(sigma_vals), len(sigma_vals))) img2_edge_matrix = np.zeros((len(sigma_vals), img2_shifted.shape[0], img2_shifted.shape[1])) for i,s1 in enumerate(sigma_vals): img2_edge = feature.canny(img2_shifted, sigma=s1).astype(float) img2_edge_matrix[i,:,:] = img2_edge for i,s1 in enumerate(sigma_vals): img1_edge = feature.canny(img1_cropped_padded, sigma=s1).astype(float) for j,s2 in enumerate(sigma_vals): img2_edge = img2_edge_matrix[j,:,:] img1_edge_idx = np.argwhere(img1_edge == 1) img2_edge_idx = np.argwhere(img2_edge == 1) #hausdroff_21 = directed_hausdorff(img2_edge_idx, img1_edge_idx)[0] #hausdroff_12 = directed_hausdorff(img1_edge_idx, img2_edge_idx)[0] hausdroff_21 = (np.quantile(euclidean_distances(img2_edge_idx, img1_edge_idx).min(axis = 0), .95, axis=0)) hausdroff_12 = (np.quantile(euclidean_distances(img2_edge_idx, img1_edge_idx).min(axis = 1), .95, axis=0)) max_hausdroff_dist = np.max([hausdroff_21, hausdroff_12]) #at certain values of sigma, no edges may be detected leading to a 0 hausdroff distance; we should ignore these #if two images are identical, hausdorff matrix will be all np.inf which is equivalent to all zeros if max_hausdroff_dist == 0: if len(img1_edge_idx) == 0 and len(img2_edge_idx) == 0: max_hausdroff_dist = np.inf hausdroff_dist_matrix[i,j] = max_hausdroff_dist else: hausdroff_dist_matrix[i,j] = max_hausdroff_dist/hausdorff_norm return(np.max(correlation_dist_matrix),
np.min(hausdroff_dist_matrix)
numpy.min
"""Functions to help generate Barrier Certificates (Extra). Written by: The Robotarium Team Modified by: <NAME> (zmk5) """ import time from typing import Union from typing import Callable from cvxopt import matrix from cvxopt import solvers import numpy as np import quadprog as solver2 solvers.options['show_progress'] = False solvers.options['reltol'] = 1e-2 # was e-2 solvers.options['feastol'] = 1e-2 # was e-4 solvers.options['maxiters'] = 50 # default is 100 def create_robust_barriers( max_num_obstacles: int = 100, max_num_robots: int = 30, d: int = 5, wheel_vel_limit: float = 12.5, base_length: float = 0.105, wheel_radius: float = 0.016, projection_distance: float = 0.05, gamma: Union[int, float] = 150, safety_radius: float = 0.12) -> Callable: """Create a robust barrier certificate function.""" D = np.matrix([ [wheel_radius/2, wheel_radius/2], [-wheel_radius/base_length, wheel_radius/base_length]]) L = np.matrix([[1, 0], [0, projection_distance]]) * D disturb = np.matrix([ [-d, -d, d, d], [-d, d, d, -d]]) num_disturbs = np.size(disturb[1, :]) # TODO: Take out 4*max_num_robots? max_num_constraints = (max_num_robots**2-max_num_robots)//2 + max_num_robots*max_num_obstacles + 4*max_num_robots A = np.matrix(np.zeros([max_num_constraints, 2*max_num_robots])) b = np.matrix(np.zeros([max_num_constraints, 1])) Os = np.matrix(np.zeros([2, max_num_robots])) ps = np.matrix(np.zeros([2, max_num_robots])) Ms = np.matrix(np.zeros([2, 2*max_num_robots])) def robust_barriers(dxu, x, obstacles): """Output robust barrier certificate array.""" num_robots = np.size(dxu[0,:]) if obstacles.size != 0: num_obstacles = np.size(obstacles[0,:]) else: num_obstacles = 0 if num_robots < 2: temp = 0 else: temp = (num_robots**2-num_robots)//2 if num_robots == 0: return [] # Generate constraints for barrier certificates based on the size of the safety radius num_constraints = temp + num_robots*num_obstacles A[0:num_constraints, 0:2*num_robots] = 0 Os[0, 0:num_robots] = np.cos(x[2, :]) Os[1, 0:num_robots] =
np.sin(x[2, :])
numpy.sin
from ...util import set_units from ...config import default_units, observing_bands from ...field import Grid, SeparatedCoords, CartesianGrid, Field, UnstructuredCoords import numpy as np import astropy.constants as const import warnings import astropy.units as u __all__ = ['make_spectrum_unit_field', 'make_wavelengths', 'convolve_to_resolution', 'doppler_shift_wavelengths'] @set_units(wavelengths=default_units.length) def make_spectrum_unit_field(wavelengths, spectrum, convert_units_to_default=True): if convert_units_to_default: spectrum = spectrum.to(default_units.flux_wavelength_density, equivalencies = u.spectral_density(wavelengths)) # check if wavelength grid is regular if np.any(np.diff(wavelengths) !=
np.diff(wavelengths)
numpy.diff
import os import numpy as np from pymoo.model.problem import Problem from pymoo.problems.util import load_pareto_front_from_file class MODAct(Problem): """Multi-Objective Design of Actuators MODAct is a framework for real-world constrained multi-objective optimization. Refer to the python package https://github.com/epfl-lamd/modact from requirements. Best-known Pareto fronts must be downloaded from here: https://doi.org/10.5281/zenodo.3824302 Parameters ---------- function: str or modact.problems The name of the benchmark problem to use either as a string or the problem object instance. Example values: cs1, cs3, ct2, ct4, cts3 References: ---------- <NAME> and <NAME>, “Realistic Constrained Multi-Objective Optimization Benchmark Problems from Design,” IEEE Transactions on Evolutionary Computation, pp. 1–1, 2020. """ def __init__(self, function, **kwargs): try: import modact.problems as pb except: raise Exception("Please install the modact library: https://github.com/epfl-lamd/modact") if isinstance(function, pb.Problem): self.fct = function else: self.fct = pb.get_problem(function) lb, ub = self.fct.bounds() n_var = len(lb) n_obj = len(self.fct.weights) n_constr = len(self.fct.c_weights) xl = lb xu = ub self.weights = np.array(self.fct.weights) self.c_weights =
np.array(self.fct.c_weights)
numpy.array
import matplotlib.pyplot as plt import numpy as np def get_measurements(filename: str): time_list = [] with open(filename, 'r') as file: line = file.readline() while line: time_list.append(float(line[:-1])) line = file.readline() file.close() return time_list three_time_list_stream = get_measurements('threelayerstreamingscenario_map_stream.txt') amount_of_runs = len(three_time_list_stream) three_time_list_classic = get_measurements('threelayerstreamingscenario_map_classic.txt') plt.figure(0) plt.plot(list(range(1, amount_of_runs+1)), three_time_list_stream, 'ro', label="stream") plt.plot(list(range(1, amount_of_runs+1)), three_time_list_classic, 'bo', label="classic") plt.legend(loc="upper left") plt.axis([0, amount_of_runs+1, 20, 21]) plt.xticks(np.arange(0, amount_of_runs+1, 1)) plt.xlabel("run number") plt.ylabel("time in s") plt.title("Three hop scenario map combined") plt.savefig('three_hop_scenario_map_combined.png') plt.show() six_time_list_stream = get_measurements('sixlayerstreamingscenario_map_stream.txt') amount_of_runs = len(six_time_list_stream) six_time_list_classic = get_measurements('sixlayerstreamingscenario_map_classic.txt') plt.figure(1) plt.plot(list(range(1, amount_of_runs+1)), six_time_list_stream, 'ro', label="stream") plt.plot(list(range(1, amount_of_runs+1)), six_time_list_classic, 'bo', label="classic") plt.legend(loc="upper left") plt.axis([0, amount_of_runs+1, 20.5, 21.5]) plt.xticks(np.arange(0, amount_of_runs+1, 1)) plt.xlabel("run number") plt.ylabel("time in s") plt.title("Six hop scenario map combined") plt.savefig('six_hop_scenario_map_combined.png') plt.show() # Error bars three_time_list_stream = np.array(three_time_list_stream) three_time_list_classic = np.array(three_time_list_classic) six_time_list_stream = np.array(six_time_list_stream) six_time_list_classic = np.array(six_time_list_classic) three_stream_mean = np.mean(three_time_list_stream) three_classic_mean = np.mean(three_time_list_classic) six_stream_mean = np.mean(six_time_list_stream) six_classic_mean = np.mean(six_time_list_classic) three_stream_median = np.median(three_time_list_stream) three_classic_median = np.median(three_time_list_classic) six_stream_median =
np.mean(six_time_list_stream)
numpy.mean
import abc import math import six import numpy as np from neupy.core.docs import SharedDocsABCMeta __all__ = ('Initializer', 'Constant', 'Normal', 'Uniform', 'Orthogonal', 'HeNormal', 'HeUniform', 'XavierNormal', 'XavierUniform') class UninitializedException(Exception): """ Exception for uninitialized parameters. """ def identify_fans(shape): """ Identify fans from shape. Parameters ---------- shape : tuple or list Matrix shape. Returns ------- tuple Tuple that contains :math:`fan_{in}` and :math:`fan_{out}`. """ fan_in = shape[0] output_feature_shape = shape[1:] if output_feature_shape: fan_out = np.prod(output_feature_shape).item(0) else: fan_out = 1 return fan_in, fan_out def classname(instance): """ Returns instance class name. Parameters ---------- instance : object Returns ------- str """ return instance.__class__.__name__ class Initializer(six.with_metaclass(SharedDocsABCMeta)): """ Base class for parameter initialization. Methods ------- sample(shape) Returns tensor with specified shape. """ inherit_method_docs = True @abc.abstractmethod def sample(self, shape): """ Returns tensor with specified shape. Parameters ---------- shape : tuple Parameter shape. Returns ------- array-like """ raise NotImplementedError def get_value(self): """ This method is the same as ``get_value`` for the Theano shared variables. The main point is to be able to generate understandable message when user try to get value from the uninitialized parameter. """ raise UninitializedException("Cannot get parameter value. " "Parameter hasn't been initialized yet.") def __repr__(self): return '{}()'.format(classname(self)) class Constant(Initializer): """ Initialize parameter that has constant values. Parameters ---------- value : float, int All parameters in the tensor will be equal to this value. Defaults to ``0``. Methods ------- {Initializer.Methods} """ def __init__(self, value=0): self.value = value def sample(self, shape): return
np.ones(shape)
numpy.ones
''' Unit-tests for SuffStatBag ''' from bnpy.suffstats.SuffStatBag import SuffStatBag import numpy as np import unittest class TestSuffStatBag(unittest.TestCase): def shortDescription(self): return None def test_copy(self, K=2, D=2): SS = self.makeSuffStatBagAndFillWithOnes(K, D) self.addELBOtoSuffStatBag(SS, K) SS2 = SS.copy() assert SS2.s == SS.s assert np.all(SS2.N == SS.N) assert np.all(SS2.getELBOTerm('Elogz') == SS.getELBOTerm('Elogz')) assert id(SS2.s) != id(SS.s) assert id(SS2.N) != id(SS.N) def test_removeELBO_and_restoreELBO(self, K=2, D=2): SS = self.makeSuffStatBagAndFillWithOnes(K, D) self.addELBOtoSuffStatBag(SS, K) tmpSS = SS.copy() E = tmpSS.removeELBOTerms() assert SS.hasELBOTerms() assert not tmpSS.hasELBOTerms() with self.assertRaises(AttributeError): tmpSS.getELBOTerm('Elogz') assert hasattr(E, 'Elogz') tmpSS.restoreELBOTerms(E) for key in E._FieldDims: assert np.allclose(SS.getELBOTerm(key), tmpSS.getELBOTerm(key)) def test_ampFactor(self, K=2, D=2): SS = self.makeSuffStatBagAndFillWithOnes(K, D) SS.applyAmpFactor(3.0) assert np.allclose(SS.s, 3.0) assert np.allclose(SS.N, 3.0 * np.ones(K)) assert np.allclose(SS.x, 3.0 * np.ones((K, D))) assert np.allclose(SS.xxT, 3.0 * np.ones((K, D, D))) assert SS.hasAmpFactor() assert SS.ampF == 3.0 def makeSuffStatBagAndFillWithOnes(self, K, D): SS = SuffStatBag(K=K, D=D) s = 1.0 N = np.ones(K) x = np.ones((K, D)) xxT = np.ones((K, D, D)) SS.setField('s', s) SS.setField('N', N, dims='K') SS.setField('x', x, dims=('K', 'D')) SS.setField('xxT', xxT, dims=('K', 'D', 'D')) return SS def addELBOtoSuffStatBag(self, SS, K): SS.setELBOTerm('Elogz', np.ones(K), dims='K') SS.setELBOTerm('Econst', 1.0, dims=None) SS.setMergeTerm('Elogz', 2 * np.ones((K, K)), dims=('K', 'K')) return SS def getExpectedMergedFields(self, K, D, kA=0): s = 1.0 N =
np.ones(K - 1)
numpy.ones
import matplotlib.pyplot as plt import matplotlib.patches as mpatches import numpy as np from math import * import random # -------------CORE DEFINITIONS----------- # class Error(Exception): """Base class for exceptions in this module.""" pass class InputError(Error): """Exception raised for errors in the input. Attributes: expression -- input expression in which the error occurred message -- explanation of the error """ def __init__(self, message): self.message = message #-------------DEFINE SOME UNIVERSAL FUNCTIONS------------# def get_curve_color(buffer): """ Return prefered color for plots for any buffer Parameters ---------- buffer: str Name of buffer Returns ------- str color name """ color = {'NNO': 'green', 'QFM': 'darkorange', 'IW': 'black', 'HM': 'red', 'CoCoO': 'blue', 'ReReO': 'magenta', 'Graphite': 'gray', 'QIF': 'mediumaquamarine', 'SiSiO2': 'purple', 'CrCr2O3': 'teal', 'MoMoO2': 'olive', 'CaCaO': 'peru', 'AlAl2O3': 'chartreuse', 'KK2O': 'deeppink', 'MgMgO': 'maroon', 'MnMnO': 'midnightblue', 'NaNa2O': 'dodgerblue', 'TiTiO2': 'orangered'} return color[buffer] def get_calibration_temp_range(buffer, units='C'): """ Get upper and lower T bounds for which a buffer is calibrated ============================================================= Parameters ---------- buffer: str Name of buffer units: str Can be 'K' or 'C'. Specifies which units to return. Returns ------- tuple (lower_bound, upper_bound) """ if units == 'K' or units == 'C': pass else: raise InputError('Units must be one of "K" or "C".') temp_ranges_C = {'NNO': (600, 1200), 'QFM': (400, 1200), 'IW': (565, 1200), 'HM': (300, 1100), 'CoCoO': (600, 1200), 'ReReO': (565, 1200), 'Graphite': (565, 1200), 'QIF': (150, 1200), 'SiSiO2': (565, 1200), 'CrCr2O3': (327, 1527), 'MoMoO2': (951, 1311), 'CaCaO': (25, 1527), 'AlAl2O3': (25, 1527), 'KK2O': (25, 1527), 'MgMgO': (25, 1527), 'MnMnO': (25, 1527), 'NaNa2O': (25, 1527), 'TiTiO2': (25, 1527)} temp_ranges_K = {k: (v[0]+273, v[1]+273) for k, v in temp_ranges_C.items()} if units == 'C': return temp_ranges_C[buffer] elif units == 'K': return temp_ranges_K[buffer] def set_calibration_temp_range(temperature_min, temperature_max, buffer_min_T, buffer_max_T): """ Set calibrated temperature range for plotting ============================================= Returns variables representing the temperature range over which a particular buffer is calibrated and the user-defined temperatures that fall outside of this range. Outside of the calibrated temperature range, buffer curves are plotted as dashed lines (inside, as solid lines). Parameters ---------- buffer_min_T: float Minimum calibrated temperature of the buffer in degrees C. buffer_max_T: float Maximum calibrated temperature of the buffer in degrees C. Returns ------- Four numpy arrays 1. Usable temperature range in degrees C, with steps of 1 degree 2. Usable temperature range in degrees K, with steps of 1 degree 3. Any user input temperature values that fall below the calibrated temperature range for this buffer, in K 4. Any user input temperature values that fall above the calibrated temperature range for this buffer, in K """ temp_range = np.arange(temperature_min, temperature_max, 1) extrap_lower_min = None extrap_upper_min = None if temp_range[0] >= buffer_min_T: min_range = temp_range[0] else: min_range = buffer_min_T extrap_lower_min = temp_range[0] extrap_lower_max = buffer_min_T if temp_range[-1]+1 <= buffer_max_T: max_range = temp_range[-1]+1 else: max_range = buffer_max_T extrap_upper_min = buffer_max_T extrap_upper_max = temp_range[-1] + 1 usable_temp_range_C = np.arange(min_range, max_range, 1) usable_temp_range_K = usable_temp_range_C + 273.15 if extrap_lower_min is not None: extrap_lower_range = np.arange(extrap_lower_min, extrap_lower_max, 1) + 273.15 else: extrap_lower_range = None if extrap_upper_min is not None: extrap_upper_range = np.arange(extrap_upper_min, extrap_upper_max, 1) + 273.15 else: extrap_upper_range = None return usable_temp_range_C, usable_temp_range_K, extrap_lower_range, extrap_upper_range #-----------------DEFINE BUFFER EQUATIONS-------------# def calc_buffer(P, T, buffer): """ Master function to calc any buffer given a name. Parameters ---------- P: float Pressure in GPa T: float or numpy array Temperature in degrees K buffer: str Name of buffer Returns ------- float or numpy array logfO2 """ if buffer == 'NNO': return calc_NNO(P, T) elif buffer == 'QFM': return calc_QFM(P, T) elif buffer == 'IW': return calc_IW(P, T) elif buffer == 'CrCr2O3': return calc_CrCr2O3(P, T) elif buffer == 'SiSiO2': return calc_SiSiO2(P, T) elif buffer == 'HM': return calc_HM(P, T) elif buffer == 'CoCoO': return calc_CoCoO(P, T) elif buffer == 'ReReO': return calc_ReReO(P, T) elif buffer == 'Graphite': return calc_Graphite(P, T) elif buffer == 'QIF': return calc_QIF(P, T) elif buffer == 'MoMoO2': return calc_MoMoO2(P,T) elif buffer == 'CaCaO': return calc_CaCaO(P,T) elif buffer == 'AlAl2O3': return calc_AlAl2O3(P,T) elif buffer == 'KK2O': return calc_KK2O(P,T) elif buffer == 'MgMgO': return calc_MgMgO(P,T) elif buffer == 'MnMnO': return calc_MnMnO(P,T) elif buffer == 'NaNa2O': return calc_NaNa2O(P,T) elif buffer == 'TiTiO2': return calc_TiTiO2(P,T) else: raise InputError('Buffer name not recognized') def calc_NNO(P, T): """ Ni-NiO (NNO) ============ Define NNO buffer value at P References ---------- Campbell et al. (2009) High-pressure effects on the iron-iron oxide and nickel-nickel oxide oxygen fugacity buffers Parameters ---------- P: float Pressure in GPa T: float or numpy array Temperature in degrees K Returns ------- float or numpy array logfO2 Polynomial coefficients ----------------------- log fO2 = (a0+a1*P+a2*P^2+a3*P^3+a4*P^4) + (b0+b1*P+b2*P^2+b3*P^3)/T a0: 8.699 a1: 0.01642 a2: -0.0002755 a3: 0.000002683 a4: -1.015E-08 b0: -24205 b1: 444.73 b2: -0.59288 b3:0.0015292 """ if isinstance(T, float) or isinstance(T, int): log_fO2 = (8.699 + 0.01642*P -0.0003*P**2 + (2.7*10**(-6))*P**3 - (10**(-8))*P**4) + (-24205 + 444.73*P - 0.5929*P**2 + 0.00153*P**3)/T if isinstance(T, np.ndarray): log_fO2_list = [] for temp in T: log_fO2_list.append((8.699 + 0.01642*P -0.0003*P**2 + (2.7*10**(-6))*P**3 - (10**(-8))*P**4) + (-24205 + 444.73*P - 0.5929*P**2 + 0.00153*P**3)/temp) log_fO2 = np.array(log_fO2_list) return log_fO2 def calc_QFM(P, T): """ Quartz-Fayalite-Magnetite (QFM) =============================== Define QFM buffer value at P Parameters ---------- P: float Pressure in GPa T: float or numpy array Temperature in degrees K Returns ------- float or numpy array logfO2 References ---------- <NAME> in Mineralogical Society of America "Reviews in Mineralogy" Volume 25 """ # translate P to bars P_bars = P*10000 if isinstance(T, float) or isinstance(T, int): if T<573: log_fO2 = (-26445.3/T) + 10.344 + 0.092 * (P_bars-1)/T if T>=573: log_fO2 = (-25096.3/T) + 8.735 + 0.11 * (P_bars-1)/T if isinstance(T, np.ndarray): log_fO2_list = [] for temp in T: if temp<573: log_fO2_list.append((-26445.3/temp) + 10.344 + 0.092 * (P_bars-1)/temp) if temp>=573: log_fO2_list.append((-25096.3/temp) + 8.735 + 0.11 * (P_bars-1)/temp) log_fO2 =
np.array(log_fO2_list)
numpy.array
import numpy as np import tensorflow as tf from scipy import sparse as sp from tensorflow.python.ops import gen_sparse_ops from . import ops def sp_matrix_to_sp_tensor(x): """ Converts a Scipy sparse matrix to a SparseTensor. :param x: a Scipy sparse matrix. :return: a SparseTensor. """ if len(x.shape) != 2: raise ValueError("x must have rank 2") row, col, values = sp.find(x) out = tf.SparseTensor( indices=np.array([row, col]).T, values=values, dense_shape=x.shape ) return tf.sparse.reorder(out) def sp_batch_to_sp_tensor(a_list): """ Converts a list of Scipy sparse matrices to a rank 3 SparseTensor. :param a_list: list of Scipy sparse matrices with the same shape. :return: SparseTensor of rank 3. """ tensor_data = [] for i, a in enumerate(a_list): row, col, values = sp.find(a) batch =
np.ones_like(col)
numpy.ones_like
import pretty_midi as pyd import numpy as np import pandas as pd import time import datetime from util_tools.acc_utils import split_phrases, chord_shift import util_tools.format_converter_update as cvt from util_tools.AccoMontage import find_by_length, dp_search, render_acc, ref_spotlight, get_texture_filter import os os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE" if __name__ == '__main__': """ Inference Script of AccoMontage To run inference with AccoMontage, you should specify the following: Required: SONG_NAME & SONG_ROOT -- directory to a MIDI lead sheet file. This MIDI file should consists of two tracks, each containing melody (monophonic) and chord (polyphonic). Now complex chords (9th, 11th, and more) is supported. SEGMENTATION -- phrase annotation (string) of the MIDI file. For example, for an AABB song with 8 bars for each phrase, the annotation should be in the format 'A8A8B8B8\n'. Note that by default we only support the transition among 4-bar, 6-bar, and 8-bar phrases NOTE_SHIFT -- The number of upbeats in the pickup bar (can be float). If no upbeat, specify 0. Optional: SPOTLIGHT -- a list of names of your prefered reference songs. See all 860 supported reference songs (Chinese POP) at ./data files/POP909 4bin quntization/four_beat_song_index. PREFILTER -- a tuple (a, b) controlling rhythmic patters. a, b can be integers in [0, 4], each controlling horrizontal rhythmic density and vertical voice number. Ther higher number, the denser rhythms. """ """ Configurations upon inference """ #SPOTLIGHT = ['一曲红尘', '向天再借五百年', '夜曲', '我只在乎你', '撕夜', '放生', '明天你是否依然爱我', '映山红', '浪人情歌', '海芋恋', '狂浪生', '用心良苦', '男孩', '祝我生日快乐', '背对背拥抱', '舍得', '葫芦娃', '香水', '小乌龟'] #SPOTLIGHT = ['小龙人'] SPOTLIGHT = [] #PREFILTER = None PREFILTER = (4, 1) #SONG_NAME, SEGMENTATION, NOTE_SHIFT = 'Boggy Brays.mid', 'A8A8B8B8\n', 0 #SONG_NAME, SEGMENTATION, NOTE_SHIFT = 'Cuillin Reel.mid', 'A4A4B8B8\n', 1 #SONG_NAME, SEGMENTATION, NOTE_SHIFT = "<NAME> Champion.mid", 'A4A4B4B4A4A4B4B4\n', 1 SONG_NAME, SEGMENTATION, NOTE_SHIFT = 'Castles in the Air.mid', 'A8A8B8B8\n', 1 #SONG_NAME, SEGMENTATION, NOTE_SHIFT = "Proudlocks's Variation.mid", 'A8A8B8B8\n', 1 #SONG_NAME, SEGMENTATION, NOTE_SHIFT = 'ECNU University Song.mid', 'A8A8B8B8C8D8E4F6A8A8B8B8C8D8E4F6\n', 0 SONG_ROOT='./demo/demo lead sheets' """ Inferencing """ print('Loading Reference Data') data = np.load('./data files/phrase_data0714.npz', allow_pickle=True) melody = data['melody'] acc = data['acc'] chord = data['chord'] #For saving time, we directly load in edge weights instead of actually infering the model. Currently, we only support the transition among 4-bar, 6-bar, and 8-bar phrases edge_weights=np.load('./data files/edge_weights_0714.npz', allow_pickle=True) print('Processing Query Lead Sheet') midi = pyd.PrettyMIDI(os.path.join(SONG_ROOT, SONG_NAME)) melody_track, chord_track = midi.instruments[0], midi.instruments[1] downbeats = midi.get_downbeats() melody_matrix = cvt.melody_data2matrix(melody_track, downbeats)# T*130, quantized at 16th note if not NOTE_SHIFT == 0: melody_matrix = np.concatenate((melody_matrix[int(NOTE_SHIFT*4):, :], melody_matrix[-int(NOTE_SHIFT*4):, :]), axis=0) chroma = cvt.chord_data2matrix(chord_track, downbeats, 'quater') # T*36, quantized at 16th note (quater beat) if not NOTE_SHIFT == 0: chroma = np.concatenate((chroma[int(NOTE_SHIFT*4):, :], chroma[-int(NOTE_SHIFT*4):, :]), axis=0) chord_table = chroma[::4, :] #T'*36, quantized at 4th notes #chord_table[-8:, :] = chord_table[56:64, :] chroma = chroma[:, 12: -12] #T*12, quantized at 16th notes pianoRoll =
np.concatenate((melody_matrix, chroma), axis=-1)
numpy.concatenate
# machine learning module import numpy as np, pandas as pd from sklearn.cluster import KMeans from sklearn.cluster import AgglomerativeClustering import statistics import matplotlib.pyplot as plt import statsmodels.api as sm from sklearn.linear_model import LogisticRegression from sklearn import svm, metrics from sklearn.ensemble import RandomForestRegressor from sklearn.ensemble import RandomForestClassifier # statsquest on youtube is useful def k_means(measures_table, clusters=4, data_only=False, plot=False, loud=False): """ Applies the k-means clustering algorithm to a measures table. The resulting clustering is then reported in terms of its inertia (sum of squared distances of samples to their closest cluster center) and its silhouette score (how distinct clusters are within the sample [see the skikit learn docs for details]). The measures passed as the first parameter can be returned with an added column reporting the cluster each player belongs to using the data_only parameter. Parameters ---------- measures_table : `dataframe <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html>`_ Behavioural measures for a collection of players. clusters : int Number of clusters to compute, default is 4. data_only : bool Whether or not to only return the clustered measures and not the goodness of fit measures, default is False (return only the inertia and silhouette scores). plot : bool Whether or not to plot the distribution of players within the clusters as a bar chart, default is False. loud : bool Whether or not to output status updates as the function progresses, default is False. Returns ---------- item : tuple (Inertia, Silhouette, Clustered measures table) OR just the dataframe. Examples ---------- >>> # this doesn't work yet but put code here """ # get variable names from the behavioural measures variables = list(measures_table.columns)[1:] Kmean = KMeans(n_clusters=clusters) data = np.array(measures_table[variables].values) Kmean.fit(data) silhouette = metrics.silhouette_score(data, Kmean.labels_, metric="euclidean") cluster_centers = Kmean.cluster_centers_ clustered_data = measures_table.copy() clustered_data["cluster"] = Kmean.labels_ if loud: print("variables:", variables) print("centers:", Kmean.cluster_centers_) print("inertia:", Kmean.inertia_) print("silhouette:", silhouette) if plot: bars = [] heights = [] for label in set(sorted(Kmean.labels_)): bars.append(label) heights.append(list(Kmean.labels_).count(label)) colors = ["C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9"] plt.bar(bars, heights, color=colors[: len(bars)]) plt.title( "\nClusters: " + str(len(bars)) + "\nInertia: " + str(round(Kmean.inertia_)) + "\nIterations: " # Kmean.inertia_ is the sum of squared distances of samples to their closest cluster center + str(Kmean.n_iter_), x=1.01, y=0.5, ha="left", ) plt.xlabel("Cluster ID") plt.ylabel("Number of Members") plt.show() if data_only: return clustered_data return clustered_data, Kmean.inertia_, silhouette def k_means_range(measures_table, min_clusters=2, max_clusters=13): """ Computes the k_means calculation above across a range of cluster counts, returning their goodness of fit measures (inertia and silhouette). Parameters ---------- measures_table : `dataframe <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html>`_ Behavioural measures for a collection of players. min_clusters : int The minimum number of clusters to compute, default is 2. max_clusters : int The maximum (inclusive) number of clusters to compute, default is 13. Returns ---------- Two arrays, the inertias for each of the cluster counts, and the silhouette scores for each of the cluster counts. """ # print('calculating k means in range', min_clusters, max_clusters) inertias = [] silhouettes = [] for x in range(min_clusters, max_clusters + 1): k_means_result = k_means(measures_table, clusters=x) inertias.append(k_means_result[1]) silhouettes.append(k_means_result[2]) return inertias, silhouettes def k_means_ensemble(measures_table, ensemble_size=100, min_clusters=2, max_clusters=13): """ Computes the k_means clustering algorithm across a range of cluster counts, a number of times. This is useful for determining clusters in a more robust way but can be slow on large data sets. Parameters ---------- measures_table : `dataframe <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html>`_ Behavioural measures for a collection of players. ensemble_size : int The number of times to repeat the clustering computations, default is 100. min_clusters : int The minimum number of clusters to compute, default is 2. max_clusters : int The maximum (inclusive) number of clusters to compute, default is 13. Returns ---------- Two arrays, the mean inertias for each of the cluster counts, and the mean silhouette scores for each of the cluster counts. """ all_inertias = [] all_silhouettes = [] # call the k_means_range function n times, storing scores in the above arrays for x in range(ensemble_size): k_means_range_result = k_means_range( measures_table, min_clusters=min_clusters, max_clusters=max_clusters ) all_inertias.append(k_means_range_result[0]) all_silhouettes.append(k_means_range_result[1]) # now average each of the elements in the score lists ensemble_inertias = [] ensemble_silhouettes = [] for cluster_num in range(len(all_inertias[0])): inertia_scores = [all_inertias[x][cluster_num] for x in range(ensemble_size)] ensemble_inertias.append(statistics.mean(inertia_scores)) silhouette_scores = [ all_silhouettes[x][cluster_num] for x in range(ensemble_size) ] ensemble_silhouettes.append(statistics.mean(silhouette_scores)) return ensemble_inertias, ensemble_silhouettes def agglomerative_cluster(measures_table, distance_threshold=0, n_clusters=None): """ Performs sklearn's agglomerative clustering algorithm on a dataframe of behavioural measures. See their documentation for details. Note: Either the distance threshold or the n_cluster parameter must be None. Parameters ---------- measures_table : `dataframe <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html>`_ Behavioural measures for a collection of players. distance_threshold : int The maximum distance threshold to perform the clustering to. n_clusters : int The number of clusters to perform the clustering to. Returns ---------- model : sklearn.AgglomerativClustering A fit agglomerative clustering model. """ variables = list(measures_table.columns)[1:] X = measures_table[variables].values model = AgglomerativeClustering( distance_threshold=distance_threshold, n_clusters=n_clusters ) model = model.fit(X) return model def describe_clusters(clustered_measures_table, cluster_col="cluster"): """ Describes cluster centroids (mean values of each measure) for each cluster in a clustered measures table. Parameters ---------- clustered_measures_table : `dataframe <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html>`_ A measures table with a cluster column (e.g. output of k_means() function). Returns -------- dataframe A table describing each cluster as a pandas dataframe. """ unique_clusters = list(set(clustered_measures_table["cluster"].values)) descriptive_table = pd.DataFrame() descriptive_table["cluster_centroid"] = clustered_measures_table.columns[1:] for value in unique_clusters: members = clustered_measures_table[ clustered_measures_table[cluster_col] == value ] centroid = [members[col].mean() for col in members.columns[1:]] descriptive_table["n=" + str(len(members))] = centroid descriptive_table.set_index("cluster_centroid", inplace=True) return descriptive_table def logistic_regression(train_measures, test_measures, label): """ Performs a logistic regression using the `statsmodels library <https://www.statsmodels.org/stable/index.html>`_, returning the predicted labels rounded to the nearest integer. Note: this method is currently hard-coded to only function on Philander 2014's data set. Abstracted logistic regression function coming soon tm. Parameters ------------ train_measures : `dataframe <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html>`_ The training portion of a measures table returned by the `split_measures_table` function in the measures module. test_measures : `dataframe <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html>`_ The (smaller) test portion of a measures table returned by the `split_measures_table` function in the measures module. label : string The column name of the dependent variable in the train and test measures tables, e.g. 'self_exclude'. Returns -------- list A list corresponding to the predicted values for the label column in the test measures table. These can be used with the actual values to compute performance metrics. """ # defines the R style formula to fit formula = str(label) + " ~ gender+age+total_wagered+num_bets+frequency+duration+bets_per_day+net_loss+intensity+variability+frequency_1m+trajectory+z_intensity+z_variability+z_frequency+z_trajectory" model = sm.formula.glm(formula=formula, family=sm.families.Binomial(), data=train_measures) # this is where the stepwise bit could happen - see original code fit_model = model.fit() raw_prediction = fit_model.predict(test_measures) predicted_labels = [value for value in np.where(raw_prediction >= 0.5, 1, 0)] #print(fit_model.summary()) return predicted_labels def lasso_logistic_regression(train_measures, test_measures, label): """ Performs a 'lasso' (optimizes a least-square problem with L1 penalty) logistic regression using `sklearn's linear_model <https://scikit-learn.org/stable/modules/classes.html#module-sklearn.linear_model>`_. This `stackoverflow post <https://stackoverflow.com/questions/41639557/how-to-perform-logistic-lasso-in-python>`_ contains a useful discussion on this type of function-estimation regression pair. Parameters ------------ train_measures : `dataframe <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html>`_ The training portion of a measures table returned by the `split_measures_table` function in the measures module. test_measures : `dataframe <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html>`_ The (smaller) test portion of a measures table returned by the `split_measures_table` function in the measures module. label : string The column name of the dependent variable in the train and test measures tables, e.g. 'self_exclude'. Returns -------- list A list corresponding to the predicted values for the label column in the test measures table. These can be used with the actual values to compute performance metrics. """ train_data = train_measures.drop(['player_id', label], axis=1) train_labels = train_measures[label] test_data = test_measures.drop(['player_id', label], axis=1) model = LogisticRegression(penalty='l1', solver='liblinear') model.fit(train_data, train_labels) predicted_labels = model.predict(test_data) return predicted_labels def svm_eps_regression(train_measures, test_measures, label): """ Creates and trains a support vector machine for epsilon-support vector regression using the sklearn library's implementation. Parameters ------------ train_measures : `dataframe <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html>`_ The training portion of a measures table returned by the `split_measures_table` function in the measures module. test_measures : `dataframe <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html>`_ The (smaller) test portion of a measures table returned by the `split_measures_table` function in the measures module. label : string The column name of the dependent variable in the train and test measures tables, e.g. 'self_exclude'. Returns -------- list A list corresponding to the predicted values for the label column in the test measures table. These can be used with the actual values to compute performance metrics. """ train_data = train_measures.drop(['player_id', label], axis=1) train_labels = train_measures[label] test_data = test_measures.drop(['player_id', label], axis=1) model = svm.SVR(kernel='rbf') model.fit(train_data, train_labels) predicted_labels = model.predict(test_data) # convert probabilities to binary labels for comparison regression_cutoff = 0.5 predicted_labels = np.where(predicted_labels < regression_cutoff, 0, 1) return predicted_labels def svm_c_classification(train_measures, test_measures, label): """ Parameters ------------ train_measures : `dataframe <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html>`_ The training portion of a measures table returned by the `split_measures_table` function in the measures module. test_measures : `dataframe <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html>`_ The (smaller) test portion of a measures table returned by the `split_measures_table` function in the measures module. label : string The column name of the dependent variable in the train and test measures tables, e.g. 'self_exclude'. Returns -------- list A list corresponding to the predicted values for the label column in the test measures table. These can be used with the actual values to compute performance metrics. """ train_data = train_measures.drop(['player_id', label], axis=1) train_labels = train_measures[label] test_data = test_measures.drop(['player_id', label], axis=1) model = svm.SVC(kernel='rbf') model.fit(train_data, train_labels) predicted_labels = model.predict(test_data) return predicted_labels def svm_one_classification(train_measures, test_measures, label): """ Parameters ------------ train_measures : `dataframe <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html>`_ The training portion of a measures table returned by the `split_measures_table` function in the measures module. test_measures : `dataframe <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html>`_ The (smaller) test portion of a measures table returned by the `split_measures_table` function in the measures module. label : string The column name of the dependent variable in the train and test measures tables, e.g. 'self_exclude'. Returns -------- list A list corresponding to the predicted values for the label column in the test measures table. These can be used with the actual values to compute performance metrics. """ train_data = train_measures.drop(['player_id', label], axis=1) train_labels = train_measures[label] test_data = test_measures.drop(['player_id', label], axis=1) model = svm.OneClassSVM(kernel='rbf') model.fit(train_data, train_labels) predicted_labels = model.predict(test_data) # need to add a correction step for the labels here as OneClassSVM returns -1 for outliers and 1 for inliers predicted_labels = np.where(predicted_labels < 0, 1, 0) return predicted_labels def rf_regression(train_measures, test_measures, label): """ Creates and fits a random forest regressor using `sklearn's ensemble module <https://scikit-learn.org/stable/modules/ensemble.html#forest>`_, returning the predicted labels rounded to the nearest integer. Parameters ------------ train_measures : `dataframe <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html>`_ The training portion of a measures table returned by the `split_measures_table` function in the measures module. test_measures : `dataframe <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html>`_ The (smaller) test portion of a measures table returned by the `split_measures_table` function in the measures module. label : string The column name of the dependent variable in the train and test measures tables, e.g. 'self_exclude'. Returns -------- list A list corresponding to the predicted values for the label column in the test measures table. These can be used with the actual values to compute performance metrics. """ train_data = train_measures.drop(['player_id', label], axis=1) train_labels = train_measures[label] test_data = test_measures.drop(['player_id', label], axis=1) model = RandomForestRegressor() model.fit(train_data, train_labels) predicted_labels = model.predict(test_data) # convert probabilities to binary labels for comparison regression_cutoff = 0.5 predicted_labels = np.where(predicted_labels < regression_cutoff, 0, 1) return predicted_labels def rf_classification(train_measures, test_measures, label): """ Parameters ------------ train_measures : `dataframe <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html>`_ The training portion of a measures table returned by the `split_measures_table` function in the measures module. test_measures : `dataframe <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html>`_ The (smaller) test portion of a measures table returned by the `split_measures_table` function in the measures module. label : string The column name of the dependent variable in the train and test measures tables, e.g. 'self_exclude'. Returns -------- list A list corresponding to the predicted values for the label column in the test measures table. These can be used with the actual values to compute performance metrics. """ train_data = train_measures.drop(['player_id', label], axis=1) train_labels = train_measures[label] test_data = test_measures.drop(['player_id', label], axis=1) model = RandomForestClassifier(n_estimators=100) model.fit(train_data, train_labels) predicted_labels = model.predict(test_data) return predicted_labels def compute_performance(method_name, actual, predicted): """ Computes performance metrics including sensitivity, specificity, accuracy, confusion matrix values, odds ratio, and area under curve, for a given classification/regression using its actual and predicted values. Parameters ----------- method_name : string The name of the method which has been applied (for labelling the final performance table), e.g. 'random forest classification'. actual : list The actual values of the test measures table. predicted : list The values predicted by the method for the test measures table. """ # resources: # describes odds ratio and precision equations # https://cran.r-project.org/web/packages/ROCR/ROCR.pdf # describes sklearn's confusion matrix # https://scikit-learn.org/stable/modules/generated/sklearn.metrics.confusion_matrix.html#sklearn-metrics-confusion-matrix result = metrics.classification_report(actual, y_pred=predicted, output_dict=True) sensitivity = result['1']['recall'] specificity = result['0']['recall'] accuracy = result['accuracy'] fpr, tpr, thresholds = metrics.roc_curve(actual, predicted) auc = metrics.auc(fpr, tpr) confusion_matrix = metrics.confusion_matrix(actual, predicted) tn, fp, fn, tp = confusion_matrix.ravel() # odds ratio is (tp x tn)/(fp x fn) odds_ratio = 0 if fp != 0 and fn != 0: odds_ratio = (tp * tn)/(fp * fn) # precision is tp / (tp + fp) precision = tp / (tp + fp) metrics_df = pd.DataFrame() metrics_df['sensitivity'] = [round(sensitivity, 3)] metrics_df['specificity'] = [round(specificity, 3)] metrics_df['accuracy'] = [round(accuracy, 3)] metrics_df['precision'] = [round(precision, 3)] metrics_df['auc'] = [round(auc, 3)] metrics_df['odds_ratio'] = [round(odds_ratio, 3)] metrics_df.index = [method_name] return metrics_df # ========================================================= # Plotting Functions for the Machine Learning Module # ========================================================= import scipy.cluster.hierarchy as sch import scipy.ndimage.filters as snf def plot_cluster_sizes(model): """ Create a bar chart using a previously computed clustering model. Each bar represents a single cluster, with the height of the bars representing the number of members (players) in each cluster. Args: model (sklearn.cluster model): A trained sklearn clustering model, e.g. sklearn.cluster.AgglomerativeClustering. Returns: Matplotlib.pyplot plot object. """ plt.figure() cluster_ids = list(set(list(model.labels_))) cluster_sizes = [list(model.labels_).count(x) for x in cluster_ids] plt.bar( cluster_ids, cluster_sizes, color=plt.rcParams["axes.prop_cycle"].by_key()["color"], ) locs, labels = plt.xticks() plt.xticks(range(len(cluster_ids)), cluster_ids) plt.xlabel("Cluster ID") plt.ylabel("Number of Players per Cluster") plt.grid(axis="x") return plt def plot_agglomeration_dendrogram(model, dt_cutoff=None, **kwargs): """ Create a dendrogram visualising a heirarchical clustering method (agglomerative clustering). A horisontal line can be added using the dt_cutoff parameter to visualise the number of clusters at a given distance threshold. Args: model (sklearn.cluster model): A trained sklearn clustering model, e.g. sklearn.cluster.AgglomerativeClustering. dt_cutoff (Integer): The distance threshold value at which to mark a grey dashed horisontal line. Returns: Matplotlib.pyplot plot object. """ # Create linkage matrix and then plot the sch.dendrogram # create the counts of samples under each node counts =
np.zeros(model.children_.shape[0])
numpy.zeros
import argparse import torch import logging import json import numpy as np import cv2 from tqdm import tqdm import matplotlib.pyplot as plt import seaborn as sns import pandas as pd sns.set(style="darkgrid") parser = argparse.ArgumentParser(prog='calc_mAP.py') parser.add_argument('--net-type', default="RFB", type=str, help='The network architecture ,optional: RFB (higher precision) or slim (faster)') parser.add_argument('--batch-size', type=int, default=16, help='size of each image batch') parser.add_argument('--iou-thres', type=float, default=0.5, help='iou threshold required to qualify as detected') parser.add_argument('--conf-thres', type=float, default=0.001, help='object confidence threshold') parser.add_argument('--nms-thres', type=float, default=0.5, help='iou threshold for non-maximum suppression') parser.add_argument('--save-json', action='store_true', help='save a cocoapi-compatible JSON results file') parser.add_argument('--img-size', type=int, default=160, help='inference size (pixels)') parser.add_argument('--weights', type=str, default='models/train-coco_person_face-0.0.3-RFB-160/RFB-Epoch-199-Loss-4.073122353780837.pth', help='weight path') opt = parser.parse_args() print(opt) from vision.ssd.config.fd_config import define_img_size from vision.datasets.coco_dataset import COCODataset from torch.utils.data import DataLoader define_img_size(opt.img_size, "coco_person_face") from vision.ssd.config import fd_config from vision.ssd.data_preprocessing import TestTransform from vision.ssd.mb_tiny_RFB_fd import create_Mb_Tiny_RFB_fd, create_Mb_Tiny_RFB_fd_predictor from vision.ssd.mb_tiny_fd import create_mb_tiny_fd, create_mb_tiny_fd_predictor from vision.ssd.ssd import MatchPrior from vision.utils.box_utils import iou_of config = fd_config def calc_mAP(weights, batch_size=16, img_size=640, iou_thres=0.5, conf_thres=0.001, nms_thres=0.5, save_json=False, model=None): label_path = "models/train-coco_person_face-0.0.3-RFB-160/coco-person-face-labels.txt" class_names = [name.strip() for name in open(label_path).readlines()] num_classes = len(class_names) if opt.net_type == 'RFB': net = create_Mb_Tiny_RFB_fd(len(class_names), is_test=True, device="cuda:0") predictor = create_Mb_Tiny_RFB_fd_predictor(net, candidate_size=100, device="cuda:0") elif opt.net_type == 'slim': net = create_mb_tiny_fd(len(class_names), is_test=True, device="cuda:0") predictor = create_mb_tiny_fd_predictor(net, candidate_size=100, device="cuda:0") net.load(weights) net.eval() device = "cuda:0" # target_transform = MatchPrior(config.priors, config.center_variance, # config.size_variance, 0.34999999404) # # test_transform = TestTransform(config.image_size, config.image_mean_test, config.image_std) # val_dataset = COCODataset("/media/test/data/coco", transform=test_transform, # target_transform=target_transform, is_test=True) # logging.info("validation dataset size: {}".format(len(val_dataset))) # # val_loader = DataLoader(val_dataset, batch_size, # num_workers=4, # shuffle=False) data_list = json.load(open("/media/test/data/coco/test_datalist.json")) all_correct = None all_p_prob = None all_p_label = None all_g_label = None seen = 0 for data in tqdm(data_list): image_id = data['image_file'] gt_boxes = np.array(data['boxes'], dtype=np.float32) gt_labels = np.array(data['labels'], dtype=np.int64) image = cv2.imread(image_id) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) p_boxes, p_labels, p_probs = predictor.predict(image) nl = gt_labels.shape[0] correct = np.array([0] * p_boxes.shape[0]) for i, gt_box in enumerate(gt_boxes): seen += 1 p_index = np.array(range(p_boxes.shape[0])) gt_label = gt_labels[i] valid_p_boxes = p_boxes[correct == 0] # remove matched predic box valid_p_index = p_index[correct == 0] valid_p_probs = p_probs[correct == 0] valid_p_labels = p_labels[correct == 0] valid_p_boxes = valid_p_boxes[valid_p_labels == gt_label] # select predict label == gt label valid_p_index = valid_p_index[valid_p_labels == gt_label] valid_p_probs = valid_p_probs[valid_p_labels == gt_label] if valid_p_boxes.shape[0] == 0: continue iou = iou_of(torch.tensor(valid_p_boxes), torch.tensor(np.expand_dims(gt_box, axis=0))) max_val = torch.max(iou) if max_val.item() > iou_thres: correct[valid_p_index[torch.argmax(iou).item()]] = 1 all_correct = np.concatenate([all_correct, correct], axis=0) if all_correct is not None else correct all_p_prob =
np.concatenate([all_p_prob, p_probs], axis=0)
numpy.concatenate
"""SGTR algorithm for iteratively solving Ax=b over multiple A's and b's.""" import numpy as np from numpy.linalg import norm as Norm import pandas as pd from .optimizer import Optimizer from .ridge import Ridge from .group_loss_function import GroupLossFunction from .pde_loss_function import PDELossFunction class SGTR: """Class containing logic for the SGTR algorithm.""" def __init__(self, point_optimizer: Optimizer = Ridge(lambda_ = 1e-5), loss_func: GroupLossFunction = PDELossFunction(), threshold_func: callable = Norm, num_tols: int = 50, normalize_by: int = 2): """Initialize components of the SGTR algorithm. Keyword arguments: point_optimizer -- the solver for a single Ax=b problem (Ridge in SGTR) loss_func -- The loss function used for grading prospective solutions. threshold_func -- the function used for thresholding num_tols -- number of threshold tolerances to try for iterative thresh. normalize_by -- the norm by which to normalize the cols in As and bs """ self.point_optimizer = point_optimizer.optimize self.loss_func = loss_func.score self.threshold_func = threshold_func self.num_tols = num_tols self.normalize = normalize_by def format_inputs(self, As, bs): """Format As and bs to list of ndarrays. Keyword arguments: As -- list of As bs -- list of bs Returns: As -- list of As as a list of ndarrays bs -- list of bs as a list of ndarrays """ As = [self.convert_to_ndarray(A.copy()) for A in As] bs = [self.convert_to_ndarray(b.copy()) for b in bs] return As, bs def convert_to_ndarray(self, array_like): """Convert an ndarray-like object to an ndarray. Keyword arguments: array_like -- an ndarray-like object Returns: ndarray -- object converted to ndarray """ if type(array_like) == pd.DataFrame: return array_like.values else: try: return np.asarray(array_like) except Exception as err: print("Exception on convering data:") print(err) raise(Exception("can't convert data to numpy array!")) def compute_norms(self, As, bs): """Compute the norms of As and bs. As list is computed column-wise. Keyword argument: As -- list of As bs -- list of bs Returns: As_norms -- list of As norms bs_norms -- list of bs norms The norm computed is based on the attribute self.normalize. Note that As_norms is computed by taking all As, stacking them, and then computing the norm of each column. """ m = len(As) # m is the number of individual optimizations to run # in SINDy-BVP, m is the number of spatial positions n, d = As[0].shape # d is the number of candidate functions # and n is the number of trials # Initialize an empty vector to hold the norm of each candidate # function. the norm is evaluated over ALL spatial positions for # each candidate function. As_norms = np.zeros(d) for i in range(d): data = np.hstack([A[:, i] for A in As]) As_norms[i] = Norm(data, self.normalize) # Now normalize the bs bs_norms = [m*Norm(b, self.normalize) for b in bs] return As_norms, bs_norms def normalize_data(self, As, bs, As_norms, bs_norms): """Normalize the data in As and bs by norms As_norms, bs_norms. Keyword arguments: As -- list of As bs -- list of bs As_norms -- list of As norms bs_norms -- list of bs norms Returns: normalized_As -- As normalized by the As_norms normalized_bs -- bs normalized by the bs_norms """ normalized_As = [A.copy() for A in As] normalized_bs = [b.copy() for b in bs] for i in range(len(As)): normalized_As[i] = As[i].dot(np.diag(As_norms**-1)) normalized_bs[i] = bs[i]/bs_norms[i] return normalized_As, normalized_bs def compute_tolerances(self, As, bs): """Compute the range of tolerances to use for iterative thresholding. Keyword arguments: As -- list of As bs -- list of bs Returns: tols -- range of tolerances to use for iterative thresholding. """ # Compute the range of tolerances to use for thresholding opt = self.point_optimizer # Use shortcut for optimizer # Compute the solution x for each group using ridge regression x_ridges = [opt(A, b) for (A, b) in zip(As, bs)] # Stack the solutions into matrix, so that each column contains # the coefficient vector for a single candidate function, where # each row is a single spatial point. x_ridge = np.hstack(x_ridges) # Get the norm for each of the candidate function coefficient vectors xr_norms = [Norm(x_ridge[j, :]) for j in range(x_ridge.shape[0])] # Determine the maximum of these norms max_tol = np.max(xr_norms) # And the minimum min_tol =
np.min([x for x in xr_norms if x != 0])
numpy.min
from scirpy._util import ( _is_na, _is_false, _is_true, _normalize_counts, _is_symmetric, _reduce_nonzero, ) from scirpy._util._graph import layout_components from itertools import combinations import igraph as ig import numpy as np import pandas as pd import numpy.testing as npt import pytest import scipy.sparse import warnings def test_reduce_nonzero(): A = np.array([[0, 0, 3], [1, 2, 5], [7, 0, 0]]) B = np.array([[1, 0, 3], [2, 1, 0], [6, 0, 5]]) A_csr = scipy.sparse.csr_matrix(A) B_csr = scipy.sparse.csr_matrix(B) A_csc = scipy.sparse.csc_matrix(A) B_csc = scipy.sparse.csc_matrix(B) expected = np.array([[1, 0, 3], [1, 1, 5], [6, 0, 5]]) with pytest.raises(ValueError): _reduce_nonzero(A, B) npt.assert_equal(_reduce_nonzero(A_csr, B_csr).toarray(), expected) npt.assert_equal(_reduce_nonzero(A_csc, B_csc).toarray(), expected) npt.assert_equal(_reduce_nonzero(A_csr, A_csr.copy()).toarray(), A_csr.toarray()) def test_is_symmatric(): M = np.array([[1, 2, 2], [2, 1, 3], [2, 3, 1]]) S_csr = scipy.sparse.csr_matrix(M) S_csc = scipy.sparse.csc_matrix(M) S_lil = scipy.sparse.lil_matrix(M) assert _is_symmetric(M) assert _is_symmetric(S_csr) assert _is_symmetric(S_csc) assert _is_symmetric(S_lil) M = np.array([[1, 2, 2], [2, 1, np.nan], [2, np.nan, np.nan]]) S_csr = scipy.sparse.csr_matrix(M) S_csc = scipy.sparse.csc_matrix(M) S_lil = scipy.sparse.lil_matrix(M) assert _is_symmetric(M) assert _is_symmetric(S_csr) assert _is_symmetric(S_csc) assert _is_symmetric(S_lil) M = np.array([[1, 2, 2], [2, 1, 3], [3, 2, 1]]) S_csr = scipy.sparse.csr_matrix(M) S_csc = scipy.sparse.csc_matrix(M) S_lil = scipy.sparse.lil_matrix(M) assert not _is_symmetric(M) assert not _is_symmetric(S_csr) assert not _is_symmetric(S_csc) assert not _is_symmetric(S_lil) def test_is_na(): warnings.filterwarnings("error") assert _is_na(None) assert _is_na(np.nan) assert _is_na("nan") assert not _is_na(42) assert not _is_na("Foobar") assert not _is_na(dict()) array_test = np.array(["None", "nan", None, np.nan, "foobar"]) array_expect = np.array([True, True, True, True, False]) array_test_bool =
np.array([True, False, True])
numpy.array
# -*- coding: utf-8 -*- """ @author: <NAME> """ import matplotlib.figure as figure import matplotlib.pyplot as plt import numpy as np import optuna from sklearn import datasets, model_selection, metrics from sklearn.model_selection import train_test_split method_flag = 0 # 0: LightGBM, 1: XGBoost, 2: scikit-learn number_of_test_samples = 150 # the number of test samples fold_number = 2 # "fold_number"-fold cross-validation fraction_of_validation_samples = 0.2 # fraction of validation samples for early stopping. If early stopping is not required and the number of sub-models is set, please set this to 0 number_of_sub_models = 500 # (This is active only when fraction_of_validation_samples = 0) The number of sub-models # load boston dataset boston = datasets.load_boston() x = boston.data y = boston.target # divide samples into training samples and test samples x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=number_of_test_samples, random_state=0) autoscaled_y_train = (y_train - y_train.mean()) / y_train.std() # autoscaling x_train_tmp, x_validation, autoscaled_y_train_tmp, autoscaled_y_validation = train_test_split(x_train, autoscaled_y_train, test_size=fraction_of_validation_samples, random_state=0) # hyperparameter optimization with optuna and modeling6 if method_flag == 0: # LightGBM import lightgbm as lgb if fraction_of_validation_samples == 0: best_n_estimators_in_cv = number_of_sub_models else: model = lgb.LGBMRegressor(n_estimators=1000) model.fit(x_train_tmp, autoscaled_y_train_tmp, eval_set=(x_validation, autoscaled_y_validation), eval_metric='l2', early_stopping_rounds=100) best_n_estimators_in_cv = model.best_iteration_ def objective(trial): param = { 'verbosity': -1, 'boosting_type': trial.suggest_categorical('boosting', ['gbdt', 'dart', 'goss']), 'num_leaves': trial.suggest_int('num_leaves', 10, 1000), 'learning_rate': trial.suggest_loguniform('learning_rate', 1e-8, 1.0) } if param['boosting_type'] == 'dart': param['drop_rate'] = trial.suggest_loguniform('drop_rate', 1e-8, 1.0) param['skip_drop'] = trial.suggest_loguniform('skip_drop', 1e-8, 1.0) if param['boosting_type'] == 'goss': param['top_rate'] = trial.suggest_uniform('top_rate', 0.0, 1.0) param['other_rate'] = trial.suggest_uniform('other_rate', 0.0, 1.0 - param['top_rate']) model = lgb.LGBMRegressor(**param, n_estimators=best_n_estimators_in_cv) estimated_y_in_cv = model_selection.cross_val_predict(model, x_train, autoscaled_y_train, cv=fold_number) estimated_y_in_cv = estimated_y_in_cv * y_train.std() + y_train.mean() r2 = metrics.r2_score(y_train, estimated_y_in_cv) return 1.0 - r2 study = optuna.create_study() study.optimize(objective, n_trials=100) if fraction_of_validation_samples == 0: best_n_estimators = number_of_sub_models else: model = lgb.LGBMRegressor(**study.best_params, n_estimators=1000) model.fit(x_train_tmp, autoscaled_y_train_tmp, eval_set=(x_validation, autoscaled_y_validation), eval_metric='l2', early_stopping_rounds=100) best_n_estimators = model.best_iteration_ model = lgb.LGBMRegressor(**study.best_params, n_estimators=best_n_estimators) elif method_flag == 1: # XGBoost import xgboost as xgb if fraction_of_validation_samples == 0: best_n_estimators_in_cv = number_of_sub_models else: model = xgb.XGBRegressor(n_estimators=1000) model.fit(x_train_tmp, autoscaled_y_train_tmp, eval_set=[(x_validation, autoscaled_y_validation.reshape([len(autoscaled_y_validation), 1]))], eval_metric='rmse', early_stopping_rounds=100) best_n_estimators_in_cv = model.best_iteration def objective(trial): param = { 'silent': 1, 'objective': 'reg:linear', 'booster': trial.suggest_categorical('booster', ['gbtree', 'gblinear', 'dart']), 'lambda': trial.suggest_loguniform('lambda', 1e-8, 1.0), 'alpha': trial.suggest_loguniform('alpha', 1e-8, 1.0) } if param['booster'] == 'gbtree' or param['booster'] == 'dart': param['max_depth'] = trial.suggest_int('max_depth', 1, 9) param['eta'] = trial.suggest_loguniform('eta', 1e-8, 1.0) param['gamma'] = trial.suggest_loguniform('gamma', 1e-8, 1.0) param['grow_policy'] = trial.suggest_categorical('grow_policy', ['depthwise', 'lossguide']) if param['booster'] == 'dart': param['sample_type'] = trial.suggest_categorical('sample_type', ['uniform', 'weighted']) param['normalize_type'] = trial.suggest_categorical('normalize_type', ['tree', 'forest']) param['rate_drop'] = trial.suggest_loguniform('rate_drop', 1e-8, 1.0) param['skip_drop'] = trial.suggest_loguniform('skip_drop', 1e-8, 1.0) model = xgb.XGBRegressor(**param, n_estimators=best_n_estimators_in_cv) estimated_y_in_cv = model_selection.cross_val_predict(model, x_train, autoscaled_y_train, cv=fold_number) estimated_y_in_cv = estimated_y_in_cv * y_train.std() + y_train.mean() r2 = metrics.r2_score(y_train, estimated_y_in_cv) return 1.0 - r2 study = optuna.create_study() study.optimize(objective, n_trials=100) if fraction_of_validation_samples == 0: best_n_estimators = number_of_sub_models else: model = xgb.XGBRegressor(**study.best_params, n_estimators=1000) model.fit(x_train_tmp, autoscaled_y_train_tmp, eval_set=[(x_validation, autoscaled_y_validation.reshape([len(autoscaled_y_validation), 1]))], eval_metric='rmse', early_stopping_rounds=100) best_n_estimators = model.best_iteration model = xgb.XGBRegressor(**study.best_params, n_estimators=best_n_estimators) elif method_flag == 2: # scikit-learn from sklearn.ensemble import GradientBoostingRegressor if fraction_of_validation_samples == 0: best_n_estimators_in_cv = number_of_sub_models else: model = GradientBoostingRegressor(n_estimators=1000, validation_fraction=fraction_of_validation_samples, n_iter_no_change=100) model.fit(x_train, autoscaled_y_train) best_n_estimators_in_cv = len(model.estimators_) def objective(trial): param = { 'learning_rate': trial.suggest_loguniform('learning_rate', 0.01, 1), 'max_depth': trial.suggest_int('max_depth', 1, 9), 'min_samples_leaf': trial.suggest_int('min_samples_leaf', 3, 20), 'max_features': trial.suggest_loguniform('max_features', 0.1, 1.0) } model = GradientBoostingRegressor(**param, n_estimators=best_n_estimators_in_cv) estimated_y_in_cv = model_selection.cross_val_predict(model, x_train, autoscaled_y_train, cv=fold_number) estimated_y_in_cv = estimated_y_in_cv * y_train.std() + y_train.mean() r2 = metrics.r2_score(y_train, estimated_y_in_cv) return 1.0 - r2 study = optuna.create_study() study.optimize(objective, n_trials=100) if fraction_of_validation_samples == 0: best_n_estimators = number_of_sub_models else: model = GradientBoostingRegressor(**study.best_params, n_estimators=1000, validation_fraction=fraction_of_validation_samples, n_iter_no_change=100) model.fit(x_train, autoscaled_y_train) best_n_estimators = len(model.estimators_) model = GradientBoostingRegressor(**study.best_params, n_estimators=best_n_estimators) model.fit(x_train, autoscaled_y_train) calculated_y_train = model.predict(x_train) * y_train.std() + y_train.mean() predicted_y_test = model.predict(x_test) * y_train.std() + y_train.mean() # yy-plot for training data plt.figure(figsize=figure.figaspect(1)) plt.scatter(y_train, calculated_y_train) y_max = np.max(np.array([np.array(y_train), calculated_y_train])) y_min = np.min(np.array([np.array(y_train), calculated_y_train])) plt.plot([y_min - 0.05 * (y_max - y_min), y_max + 0.05 * (y_max - y_min)], [y_min - 0.05 * (y_max - y_min), y_max + 0.05 * (y_max - y_min)], 'k-') plt.ylim(y_min - 0.05 * (y_max - y_min), y_max + 0.05 * (y_max - y_min)) plt.xlim(y_min - 0.05 * (y_max - y_min), y_max + 0.05 * (y_max - y_min)) plt.xlabel('Actual Y') plt.ylabel('Calculated Y') plt.show() # r2, RMSE, MAE print('r2: {0}'.format(float(1 - sum((y_train - calculated_y_train) ** 2) / sum((y_train - y_train.mean()) ** 2)))) print('RMSE: {0}'.format(float((sum((y_train - calculated_y_train) ** 2) / len(y_train)) ** 0.5))) print('MAE: {0}'.format(float(sum(abs(y_train - calculated_y_train)) / len(y_train)))) # estimated_y in cross-validation estimated_y_in_cv = model_selection.cross_val_predict(model, x_train, autoscaled_y_train, cv=fold_number) estimated_y_in_cv = estimated_y_in_cv * y_train.std() + y_train.mean() # yy-plot in cross-validation plt.figure(figsize=figure.figaspect(1)) plt.scatter(y_train, estimated_y_in_cv) y_max = np.max(np.array([
np.array(y_train)
numpy.array
"""Utilities for level object transforms.""" import numpy as np, quaternion from distance.classes import DefaultClasses quaternion # suppress warning SIMPLE_SIZE = 64 WEDGE_DEF_ROT = np.quaternion(np.cos(np.pi/4), 0, np.sin(np.pi/4), 0) _mkwedge = DefaultClasses.level_objects.factory('WedgeGS') def convquat(quat): return np.array([quat.x, quat.y, quat.z, quat.w]) def length(vec): return np.linalg.norm(vec) def normalized(vec): return vec / np.linalg.norm(vec) def rotpoint(rot, point): res = rot * np.quaternion(0, *point) res /= rot return res.imag def rotpointrev(rot, point): res = rot.conj() res *= np.quaternion(0, *point) res *= rot return res.imag def vec_angle(va, vb): ua = normalized(va) ub = normalized(vb) return np.arccos(np.clip(
np.dot(ua, ub)
numpy.dot
""" # ============================================================================= # Simulating the double pendulum using Runge–Kutta method (RK4) # ============================================================================= Created on Tue Jul 21 2020 @author: <NAME> """ import numpy as np import matplotlib.pyplot as plt #initial conditions mercury_arr_x = np.array([ 0.384,0]) mercury_arr_y = np.array([0,10.090399]) venus_arr_x = np.array([ 0.72,0]) venus_arr_y = np.array([0,7.4203409]) earth_arr_x = np.array([ 0.996,0]) earth_arr_y = np.array([0,2*np.pi]) mars_arr_x = np.array([ 1.57,0]) mars_arr_y = np.array([0,4.9117598]) jupiter_arr_x = np.array([ 5.13,0]) jupiter_arr_y = np.array([0,2.80370840]) saturn_arr_x = np.array([ 8.99,0]) saturn_arr_y = np.array([0,2.1502124]) uranus_arr_x = np.array([ 19.1,0]) uranus_arr_y = np.array([0,1.441907]) neptune_arr_x = np.array([ 30,0]) neptune_arr_y = np.array([0,1.150996]) def deriv(planet_arr1,planet_arr2,t): return np.array([planet_arr1[1],-4*pow(np.pi,2)*planet_arr1[0]/(pow(pow(planet_arr1[0],2)+pow(planet_arr2[0],2),1.5))])#pow((pow(planet_arr1[0],2)+pow(planet_arr2[0],2)),1.5) def rk4(deriv,func_i,func_i2, x_i,h): """ Implements the RK4 method Inputs-> deriv: a function that takes two arguments; func_i: the function to be calculated; func_i2: this is just passed as an argument for func_i (see above deriv_a1 and deriv_a2); x_i: the dependent variable of func_i; h: the step size; """ k1 = deriv(func_i,func_i2,x_i) k2 = deriv(func_i+h/2,func_i2,h*k1/2) k3 = deriv(func_i+h/2,func_i2,h*k2/2) k4 = deriv(func_i+h,func_i2,h*k3) func = func_i + (1/6) * h * (k1 +2*k2+2*k3+k4) x = x_i + h return (x,func) def implement_rk4(earth_arr_x,earth_arr_y,t,h,steps_no): time_arr = np.array([t]) func_array1 = np.array([earth_arr_x]) func_array2 = np.array([earth_arr_y]) for i in range(steps_no): temp =earth_arr_x (t,earth_arr_x) = rk4(deriv,earth_arr_x,earth_arr_y,t,h) t -=h (t,earth_arr_y) = rk4(deriv,earth_arr_y,temp,t,h) time_arr =
np.append(time_arr, t)
numpy.append
from __future__ import division import glob import numpy as NP from functools import reduce import numpy.ma as MA import progressbar as PGB import h5py import healpy as HP import warnings import copy import astropy.cosmology as CP from astropy.time import Time, TimeDelta from astropy.io import fits from astropy import units as U from astropy import constants as FCNST from scipy import interpolate from astroutils import DSP_modules as DSP from astroutils import constants as CNST from astroutils import nonmathops as NMO from astroutils import mathops as OPS from astroutils import lookup_operations as LKP import prisim from prisim import interferometry as RI from prisim import primary_beams as PB from prisim import delay_spectrum as DS try: from pyuvdata import UVBeam except ImportError: uvbeam_module_found = False else: uvbeam_module_found = True prisim_path = prisim.__path__[0]+'/' 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 write_PRISim_bispectrum_phase_to_npz(infile_prefix, outfile_prefix, triads=None, bltriplet=None, hdf5file_prefix=None, infmt='npz', datakey='noisy', blltol=0.1): """ ---------------------------------------------------------------------------- Write closure phases computed in a PRISim simulation to a NPZ file with appropriate format for further analysis. Inputs: infile_prefix [string] HDF5 file or NPZ file created by a PRISim simulation or its replication respectively. If infmt is specified as 'hdf5', then hdf5file_prefix will be ignored and all the observing info will be read from here. If infmt is specified as 'npz', then hdf5file_prefix needs to be specified in order to read the observing parameters. triads [list or numpy array or None] Antenna triads given as a list of 3-element lists or a ntriads x 3 array. Each element in the inner list is an antenna label. They will be converted to strings internally. If set to None, then all triads determined by bltriplet will be used. If specified, then inputs in blltol and bltriplet will be ignored. bltriplet [numpy array or None] 3x3 numpy array containing the 3 baseline vectors. The first axis denotes the three baselines, the second axis denotes the East, North, Up coordinates of the baseline vector. Units are in m. Will be used only if triads is set to None. outfile_prefix [string] Prefix of the NPZ file. It will be appended by '_noiseless', '_noisy', and '_noise' and further by extension '.npz' infmt [string] Format of the input file containing visibilities. Accepted values are 'npz' (default), and 'hdf5'. If infmt is specified as 'npz', then hdf5file_prefix also needs to be specified for reading the observing parameters datakey [string] Specifies which -- 'noiseless', 'noisy' (default), or 'noise' -- visibilities are to be written to the output. If set to None, and infmt is 'hdf5', then all three sets of visibilities are written. The datakey string will also be added as a suffix in the output file. blltol [scalar] Baseline length tolerance (in m) for matching baseline vectors in triads. It must be a scalar. Default = 0.1 m. Will be used only if triads is set to None and bltriplet is to be used. ---------------------------------------------------------------------------- """ if not isinstance(infile_prefix, str): raise TypeError('Input infile_prefix must be a string') if not isinstance(outfile_prefix, str): raise TypeError('Input outfile_prefix must be a string') if (triads is None) and (bltriplet is None): raise ValueError('One of triads or bltriplet must be set') if triads is None: if not isinstance(bltriplet, NP.ndarray): raise TypeError('Input bltriplet must be a numpy array') if not isinstance(blltol, (int,float)): raise TypeError('Input blltol must be a scalar') if bltriplet.ndim != 2: raise ValueError('Input bltriplet must be a 2D numpy array') if bltriplet.shape[0] != 3: raise ValueError('Input bltriplet must contain three baseline vectors') if bltriplet.shape[1] != 3: raise ValueError('Input bltriplet must contain baseline vectors along three corrdinates in the ENU frame') else: if not isinstance(triads, (list, NP.ndarray)): raise TypeError('Input triads must be a list or numpy array') triads = NP.asarray(triads).astype(str) if not isinstance(infmt, str): raise TypeError('Input infmt must be a string') if infmt.lower() not in ['npz', 'hdf5']: raise ValueError('Input file format must be npz or hdf5') if infmt.lower() == 'npz': if not isinstance(hdf5file_prefix, str): raise TypeError('If infmt is npz, then hdf5file_prefix needs to be specified for observing parameters information') if datakey is None: datakey = ['noisy'] if isinstance(datakey, str): datakey = [datakey] elif not isinstance(datakey, list): raise TypeError('Input datakey must be a list') for dkey in datakey: if dkey.lower() not in ['noiseless', 'noisy', 'noise']: raise ValueError('Invalid input found in datakey') if infmt.lower() == 'hdf5': fullfnames_with_extension = glob.glob(infile_prefix + '*' + infmt.lower()) fullfnames_without_extension = [fname.split('.hdf5')[0] for fname in fullfnames_with_extension] else: fullfnames_without_extension = [infile_prefix] if len(fullfnames_without_extension) == 0: raise IOError('No input files found with pattern {0}'.format(infile_prefix)) try: if infmt.lower() == 'hdf5': simvis = RI.InterferometerArray(None, None, None, init_file=fullfnames_without_extension[0]) else: simvis = RI.InterferometerArray(None, None, None, init_file=hdf5file_prefix) except: raise IOError('Input PRISim file does not contain a valid PRISim output') latitude = simvis.latitude longitude = simvis.longitude location = ('{0:.5f}d'.format(longitude), '{0:.5f}d'.format(latitude)) last = simvis.lst / 15.0 / 24.0 # from degrees to fraction of day last = last.reshape(-1,1) daydata = NP.asarray(simvis.timestamp[0]).ravel() if infmt.lower() == 'npz': simvisinfo = NP.load(fullfnames_without_extension[0]+'.'+infmt.lower()) skyvis = simvisinfo['noiseless'][0,...] vis = simvisinfo['noisy'] noise = simvisinfo['noise'] n_realize = vis.shape[0] else: n_realize = len(fullfnames_without_extension) cpdata = {} outfile = {} for fileind in range(n_realize): if infmt.lower() == 'npz': simvis.vis_freq = vis[fileind,...] simvis.vis_noise_freq = noise[fileind,...] else: simvis = RI.InterferometerArray(None, None, None, init_file=fullfnames_without_extension[fileind]) if fileind == 0: if triads is None: triads, bltriplets = simvis.getThreePointCombinations(unique=False) # triads = NP.asarray(prisim_BSP_info['antenna_triplets']).reshape(-1,3) # bltriplets = NP.asarray(prisim_BSP_info['baseline_triplets']) triads = NP.asarray(triads).reshape(-1,3) bltriplets = NP.asarray(bltriplets) blinds = [] matchinfo = LKP.find_NN(bltriplet, bltriplets.reshape(-1,3), distance_ULIM=blltol) revind = [] for blnum in NP.arange(bltriplet.shape[0]): if len(matchinfo[0][blnum]) == 0: revind += [blnum] if len(revind) > 0: flip_factor = NP.ones(3, dtype=NP.float) flip_factor[NP.array(revind)] = -1 rev_bltriplet = bltriplet * flip_factor.reshape(-1,1) matchinfo = LKP.find_NN(rev_bltriplet, bltriplets.reshape(-1,3), distance_ULIM=blltol) for blnum in NP.arange(bltriplet.shape[0]): if len(matchinfo[0][blnum]) == 0: raise ValueError('Some baselines in the triplet are not found in the model triads') triadinds = [] for blnum in NP.arange(bltriplet.shape[0]): triadind, blind = NP.unravel_index(NP.asarray(matchinfo[0][blnum]), (bltriplets.shape[0], bltriplets.shape[1])) triadinds += [triadind] triadind_intersection = NP.intersect1d(triadinds[0], NP.intersect1d(triadinds[1], triadinds[2])) if triadind_intersection.size == 0: raise ValueError('Specified triad not found in the PRISim model. Try other permutations of the baseline vectors and/or reverse individual baseline vectors in the triad before giving up.') triads = triads[triadind_intersection,:] selected_bltriplets = bltriplets[triadind_intersection,:,:].reshape(-1,3,3) prisim_BSP_info = simvis.getClosurePhase(antenna_triplets=triads.tolist(), delay_filter_info=None, specsmooth_info=None, spectral_window_info=None, unique=False) if fileind == 0: triads = NP.asarray(prisim_BSP_info['antenna_triplets']).reshape(-1,3) # Re-establish the triads returned after the first iteration (to accunt for any order flips) for outkey in datakey: if fileind == 0: outfile[outkey] = outfile_prefix + '_{0}.npz'.format(outkey) if outkey == 'noiseless': if fileind == 0: # cpdata = prisim_BSP_info['closure_phase_skyvis'][triadind_intersection,:,:][NP.newaxis,...] cpdata[outkey] = prisim_BSP_info['closure_phase_skyvis'][NP.newaxis,...] else: # cpdata = NP.concatenate((cpdata, prisim_BSP_info['closure_phase_skyvis'][triadind_intersection,:,:][NP.newaxis,...]), axis=0) cpdata[outkey] = NP.concatenate((cpdata[outkey], prisim_BSP_info['closure_phase_skyvis'][NP.newaxis,...]), axis=0) if outkey == 'noisy': if fileind == 0: # cpdata = prisim_BSP_info['closure_phase_vis'][triadind_intersection,:,:][NP.newaxis,...] cpdata[outkey] = prisim_BSP_info['closure_phase_vis'][NP.newaxis,...] else: # cpdata = NP.concatenate((cpdata, prisim_BSP_info['closure_phase_vis'][triadind_intersection,:,:][NP.newaxis,...]), axis=0) cpdata[outkey] = NP.concatenate((cpdata[outkey], prisim_BSP_info['closure_phase_vis'][NP.newaxis,...]), axis=0) if outkey == 'noise': if fileind == 0: # cpdata = prisim_BSP_info['closure_phase_noise'][triadind_intersection,:,:] cpdata[outkey] = prisim_BSP_info['closure_phase_noise'][NP.newaxis,:,:] else: # cpdata = NP.concatenate((cpdata, prisim_BSP_info['closure_phase_noise'][triadind_intersection,:,:][NP.newaxis,...]), axis=0) cpdata[outkey] = NP.concatenate((cpdata[outkey], prisim_BSP_info['closure_phase_noise'][NP.newaxis,...]), axis=0) for outkey in datakey: cpdata[outkey] = NP.rollaxis(cpdata[outkey], 3, start=0) flagsdata = NP.zeros(cpdata[outkey].shape, dtype=NP.bool) NP.savez_compressed(outfile[outkey], closures=cpdata[outkey], flags=flagsdata, triads=triads, last=last+NP.zeros((1,n_realize)), days=daydata+NP.arange(n_realize)) ################################################################################ def loadnpz(npzfile, longitude=0.0, latitude=0.0, lst_format='fracday'): """ ---------------------------------------------------------------------------- Read an input NPZ file containing closure phase data output from CASA and return a dictionary Inputs: npzfile [string] Input NPZ file including full path containing closure phase data. It must have the following files/keys inside: 'closures' [numpy array] Closure phase (radians). It is of shape (nlst,ndays,ntriads,nchan) 'triads' [numpy array] Array of triad tuples, of shape (ntriads,3) 'flags' [numpy array] Array of flags (boolean), of shape (nlst,ndays,ntriads,nchan) 'last' [numpy array] Array of LST for each day (CASA units which is MJD+6713). Shape is (nlst,ndays) 'days' [numpy array] Array of days, shape is (ndays,) 'averaged_closures' [numpy array] optional array of closure phases averaged across days. Shape is (nlst,ntriads,nchan) 'std_dev_lst' [numpy array] optional array of standard deviation of closure phases across days. Shape is (nlst,ntriads,nchan) 'std_dev_triads' [numpy array] optional array of standard deviation of closure phases across triads. Shape is (nlst,ndays,nchan) latitude [scalar int or float] Latitude of site (in degrees). Default=0.0 deg. longitude [scalar int or float] Longitude of site (in degrees). Default=0.0 deg. lst_format [string] Specifies the format/units in which the 'last' key is to be interpreted. If set to 'hourangle', the LST is in units of hour angle. If set to 'fracday', the fractional portion of the 'last' value is the LST in units of days. Output: cpinfo [dictionary] Contains one top level keys, namely, 'raw' Under key 'raw' which holds a dictionary, the subkeys include 'cphase' (nlst,ndays,ntriads,nchan), 'triads' (ntriads,3), 'lst' (nlst,ndays), and 'flags' (nlst,ndays,ntriads,nchan), and some other optional keys ---------------------------------------------------------------------------- """ npzdata = NP.load(npzfile) cpdata = npzdata['closures'] triadsdata = npzdata['triads'] flagsdata = npzdata['flags'] location = ('{0:.5f}d'.format(longitude), '{0:.5f}d'.format(latitude)) daydata = Time(npzdata['days'].astype(NP.float64), scale='utc', format='jd', location=location) # lstdata = Time(npzdata['last'].astype(NP.float64) - 6713.0, scale='utc', format='mjd', location=('+21.4278d', '-30.7224d')).sidereal_time('apparent') # Subtract 6713 based on CASA convention to obtain MJD if lst_format.lower() == 'hourangle': lstHA = npzdata['last'] lstday = daydata.reshape(1,-1) + TimeDelta(NP.zeros(lstHA.shape[0]).reshape(-1,1)*U.s) elif lst_format.lower() == 'fracday': lstfrac, lstint = NP.modf(npzdata['last']) lstday = Time(lstint.astype(NP.float64) - 6713.0, scale='utc', format='mjd', location=location) # Subtract 6713 based on CASA convention to obtain MJD lstHA = lstfrac * 24.0 # in hours else: raise ValueError('Input lst_format invalid') cp = cpdata.astype(NP.float64) flags = flagsdata.astype(NP.bool) cpinfo = {} datapool = ['raw'] for dpool in datapool: cpinfo[dpool] = {} if dpool == 'raw': qtys = ['cphase', 'triads', 'flags', 'lst', 'lst-day', 'days', 'dayavg', 'std_triads', 'std_lst'] for qty in qtys: if qty == 'cphase': cpinfo[dpool][qty] = NP.copy(cp) elif qty == 'triads': cpinfo[dpool][qty] = NP.copy(triadsdata) elif qty == 'flags': cpinfo[dpool][qty] = NP.copy(flags) elif qty == 'lst': cpinfo[dpool][qty] = NP.copy(lstHA) elif qty == 'lst-day': cpinfo[dpool][qty] = NP.copy(lstday.jd) elif qty == 'days': cpinfo[dpool][qty] = NP.copy(daydata.jd) elif qty == 'dayavg': if 'averaged_closures' in npzdata: cpinfo[dpool][qty] = NP.copy(cp_dayavg) elif qty == 'std_triads': if 'std_dev_triad' in npzdata: cpinfo[dpool][qty] = NP.copy(cp_std_triads) elif qty == 'std_lst': if 'std_dev_lst' in npzdata: cpinfo[dpool][qty] = NP.copy(cp_std_lst) return cpinfo ################################################################################ def npz2hdf5(npzfile, hdf5file, longitude=0.0, latitude=0.0, lst_format='fracday'): """ ---------------------------------------------------------------------------- Read an input NPZ file containing closure phase data output from CASA and save it to HDF5 format Inputs: npzfile [string] Input NPZ file including full path containing closure phase data. It must have the following files/keys inside: 'closures' [numpy array] Closure phase (radians). It is of shape (nlst,ndays,ntriads,nchan) 'triads' [numpy array] Array of triad tuples, of shape (ntriads,3) 'flags' [numpy array] Array of flags (boolean), of shape (nlst,ndays,ntriads,nchan) 'last' [numpy array] Array of LST for each day (CASA units ehich is MJD+6713). Shape is (nlst,ndays) 'days' [numpy array] Array of days, shape is (ndays,) 'averaged_closures' [numpy array] optional array of closure phases averaged across days. Shape is (nlst,ntriads,nchan) 'std_dev_lst' [numpy array] optional array of standard deviation of closure phases across days. Shape is (nlst,ntriads,nchan) 'std_dev_triads' [numpy array] optional array of standard deviation of closure phases across triads. Shape is (nlst,ndays,nchan) hdf5file [string] Output HDF5 file including full path. latitude [scalar int or float] Latitude of site (in degrees). Default=0.0 deg. longitude [scalar int or float] Longitude of site (in degrees). Default=0.0 deg. lst_format [string] Specifies the format/units in which the 'last' key is to be interpreted. If set to 'hourangle', the LST is in units of hour angle. If set to 'fracday', the fractional portion of the 'last' value is the LST in units of days. ---------------------------------------------------------------------------- """ npzdata = NP.load(npzfile) cpdata = npzdata['closures'] triadsdata = npzdata['triads'] flagsdata = npzdata['flags'] location = ('{0:.5f}d'.format(longitude), '{0:.5f}d'.format(latitude)) daydata = Time(npzdata['days'].astype(NP.float64), scale='utc', format='jd', location=location) # lstdata = Time(npzdata['last'].astype(NP.float64) - 6713.0, scale='utc', format='mjd', location=('+21.4278d', '-30.7224d')).sidereal_time('apparent') # Subtract 6713 based on CASA convention to obtain MJD if lst_format.lower() == 'hourangle': lstHA = npzdata['last'] lstday = daydata.reshape(1,-1) + TimeDelta(NP.zeros(lstHA.shape[0]).reshape(-1,1)*U.s) elif lst_format.lower() == 'fracday': lstfrac, lstint = NP.modf(npzdata['last']) lstday = Time(lstint.astype(NP.float64) - 6713.0, scale='utc', format='mjd', location=location) # Subtract 6713 based on CASA convention to obtain MJD lstHA = lstfrac * 24.0 # in hours else: raise ValueError('Input lst_format invalid') cp = cpdata.astype(NP.float64) flags = flagsdata.astype(NP.bool) if 'averaged_closures' in npzdata: day_avg_cpdata = npzdata['averaged_closures'] cp_dayavg = day_avg_cpdata.astype(NP.float64) if 'std_dev_triad' in npzdata: std_triads_cpdata = npzdata['std_dev_triad'] cp_std_triads = std_triads_cpdata.astype(NP.float64) if 'std_dev_lst' in npzdata: std_lst_cpdata = npzdata['std_dev_lst'] cp_std_lst = std_lst_cpdata.astype(NP.float64) with h5py.File(hdf5file, 'w') as fobj: datapool = ['raw'] for dpool in datapool: if dpool == 'raw': qtys = ['cphase', 'triads', 'flags', 'lst', 'lst-day', 'days', 'dayavg', 'std_triads', 'std_lst'] for qty in qtys: data = None if qty == 'cphase': data = NP.copy(cp) elif qty == 'triads': data = NP.copy(triadsdata) elif qty == 'flags': data = NP.copy(flags) elif qty == 'lst': data = NP.copy(lstHA) elif qty == 'lst-day': data = NP.copy(lstday.jd) elif qty == 'days': data = NP.copy(daydata.jd) elif qty == 'dayavg': if 'averaged_closures' in npzdata: data = NP.copy(cp_dayavg) elif qty == 'std_triads': if 'std_dev_triad' in npzdata: data = NP.copy(cp_std_triads) elif qty == 'std_lst': if 'std_dev_lst' in npzdata: data = NP.copy(cp_std_lst) if data is not None: dset = fobj.create_dataset('{0}/{1}'.format(dpool, qty), data=data, compression='gzip', compression_opts=9) ################################################################################ def save_CPhase_cross_power_spectrum(xcpdps, outfile): """ ---------------------------------------------------------------------------- Save cross-power spectrum information in a dictionary to a HDF5 file Inputs: xcpdps [dictionary] This dictionary is essentially an output of the member function compute_power_spectrum() of class ClosurePhaseDelaySpectrum. It has the following key-value structure: 'triads' ((ntriads,3) array), 'triads_ind', ((ntriads,) array), 'lstXoffsets' ((ndlst_range,) array), 'lst' ((nlst,) array), 'dlst' ((nlst,) array), 'lst_ind' ((nlst,) array), 'days' ((ndays,) array), 'day_ind' ((ndays,) array), 'dday' ((ndays,) array), 'oversampled' and 'resampled' corresponding to whether resample was set to False or True in call to member function FT(). Values under keys 'triads_ind' and 'lst_ind' are numpy array corresponding to triad and time indices used in selecting the data. Values under keys 'oversampled' and 'resampled' each contain a dictionary with the following keys and values: 'z' [numpy array] Redshifts corresponding to the band centers in 'freq_center'. It has shape=(nspw,) 'lags' [numpy array] Delays (in seconds). It has shape=(nlags,) 'kprll' [numpy array] k_parallel modes (in h/Mpc) corresponding to 'lags'. It has shape=(nspw,nlags) 'freq_center' [numpy array] contains the center frequencies (in Hz) of the frequency subbands of the subband delay spectra. It is of size n_win. It is roughly equivalent to redshift(s) 'freq_wts' [numpy array] Contains frequency weights applied on each frequency sub-band during the subband delay transform. It is of size n_win x nchan. 'bw_eff' [numpy array] contains the effective bandwidths (in Hz) of the subbands being delay transformed. It is of size n_win. It is roughly equivalent to width in redshift or along line-of-sight 'shape' [string] shape of the frequency window function applied. Usual values are 'rect' (rectangular), 'bhw' (Blackman-Harris), 'bnw' (Blackman-Nuttall). 'fftpow' [scalar] the power to which the FFT of the window was raised. The value is be a positive scalar with default = 1.0 'lag_corr_length' [numpy array] It is the correlation timescale (in pixels) of the subband delay spectra. It is proportional to inverse of effective bandwidth. It is of size n_win. The unit size of a pixel is determined by the difference between adjacent pixels in lags under key 'lags' which in turn is effectively inverse of the effective bandwidth of the subband specified in bw_eff It further contains one or more of the following keys named 'whole', 'submodel', 'residual', and 'errinfo' each of which is a dictionary. 'whole' contains power spectrum info about the input closure phases. 'submodel' contains power spectrum info about the model that will have been subtracted (as closure phase) from the 'whole' model. 'residual' contains power spectrum info about the closure phases obtained as a difference between 'whole' and 'submodel'. It contains the following keys and values: 'mean' [numpy array] Delay power spectrum incoherently estimated over the axes specified in xinfo['axes'] using the 'mean' key in input cpds or attribute cPhaseDS['processed']['dspec']. It has shape that depends on the combination of input parameters. See examples below. If both collapse_axes and avgcov are not set, those axes will be replaced with square covariance matrices. If collapse_axes is provided but avgcov is False, those axes will be of shape 2*Naxis-1. 'median' [numpy array] Delay power spectrum incoherently averaged over the axes specified in incohax using the 'median' key in input cpds or attribute cPhaseDS['processed']['dspec']. It has shape that depends on the combination of input parameters. See examples below. If both collapse_axes and avgcov are not set, those axes will be replaced with square covariance matrices. If collapse_axes is provided bu avgcov is False, those axes will be of shape 2*Naxis-1. 'diagoffsets' [dictionary] Same keys corresponding to keys under 'collapse_axes' in input containing the diagonal offsets for those axes. If 'avgcov' was set, those entries will be removed from 'diagoffsets' since all the leading diagonal elements have been collapsed (averaged) further. Value under each key is a numpy array where each element in the array corresponds to the index of that leading diagonal. This should match the size of the output along that axis in 'mean' or 'median' above. 'diagweights' [dictionary] Each key is an axis specified in collapse_axes and the value is a numpy array of weights corresponding to the diagonal offsets in that axis. 'axesmap' [dictionary] If covariance in cross-power is calculated but is not collapsed, the number of dimensions in the output will have changed. This parameter tracks where the original axis is now placed. The keys are the original axes that are involved in incoherent cross-power, and the values are the new locations of those original axes in the output. 'nsamples_incoh' [integer] Number of incoherent samples in producing the power spectrum 'nsamples_coh' [integer] Number of coherent samples in producing the power spectrum outfile [string] Full path to the external HDF5 file where the cross- power spectrum information provided in xcpdps will be saved ---------------------------------------------------------------------------- """ if not isinstance(xcpdps, dict): raise TypeError('Input xcpdps must be a dictionary') with h5py.File(outfile, 'w') as fileobj: hdrgrp = fileobj.create_group('header') hdrkeys = ['triads', 'triads_ind', 'lst', 'lst_ind', 'dlst', 'days', 'day_ind', 'dday'] for key in hdrkeys: dset = hdrgrp.create_dataset(key, data=xcpdps[key]) sampling = ['oversampled', 'resampled'] sampling_keys = ['z', 'kprll', 'lags', 'freq_center', 'bw_eff', 'shape', 'freq_wts', 'lag_corr_length'] dpool_keys = ['whole', 'submodel', 'residual', 'errinfo'] for smplng in sampling: if smplng in xcpdps: smplgrp = fileobj.create_group(smplng) for key in sampling_keys: dset = smplgrp.create_dataset(key, data=xcpdps[smplng][key]) for dpool in dpool_keys: if dpool in xcpdps[smplng]: dpoolgrp = smplgrp.create_group(dpool) keys = ['diagoffsets', 'diagweights', 'axesmap', 'nsamples_incoh', 'nsamples_coh'] for key in keys: if key in xcpdps[smplng][dpool]: if isinstance(xcpdps[smplng][dpool][key], dict): subgrp = dpoolgrp.create_group(key) for subkey in xcpdps[smplng][dpool][key]: dset = subgrp.create_dataset(str(subkey), data=xcpdps[smplng][dpool][key][subkey]) else: dset = dpoolgrp.create_dataset(key, data=xcpdps[smplng][dpool][key]) for stat in ['mean', 'median']: if stat in xcpdps[smplng][dpool]: if isinstance(xcpdps[smplng][dpool][stat], list): for ii in range(len(xcpdps[smplng][dpool][stat])): dset = dpoolgrp.create_dataset(stat+'/diagcomb_{0}'.format(ii), data=xcpdps[smplng][dpool][stat][ii].si.value) dset.attrs['units'] = str(xcpdps[smplng][dpool][stat][ii].si.unit) else: dset = dpoolgrp.create_dataset(stat, data=xcpdps[smplng][dpool][stat].si.value) dset.attrs['units'] = str(xcpdps[smplng][dpool][stat].si.unit) ################################################################################ def read_CPhase_cross_power_spectrum(infile): """ ---------------------------------------------------------------------------- Read information about cross power spectrum from an external HDF5 file into a dictionary. This is the counterpart to save_CPhase_corss_power_spectrum() Input: infile [string] Full path to the external HDF5 file that contains info about cross-power spectrum. Output: xcpdps [dictionary] This dictionary has structure the same as output of the member function compute_power_spectrum() of class ClosurePhaseDelaySpectrum. It has the following key-value structure: 'triads' ((ntriads,3) array), 'triads_ind', ((ntriads,) array), 'lstXoffsets' ((ndlst_range,) array), 'lst' ((nlst,) array), 'dlst' ((nlst,) array), 'lst_ind' ((nlst,) array), 'days' ((ndays,) array), 'day_ind' ((ndays,) array), 'dday' ((ndays,) array), 'oversampled' and 'resampled' corresponding to whether resample was set to False or True in call to member function FT(). Values under keys 'triads_ind' and 'lst_ind' are numpy array corresponding to triad and time indices used in selecting the data. Values under keys 'oversampled' and 'resampled' each contain a dictionary with the following keys and values: 'z' [numpy array] Redshifts corresponding to the band centers in 'freq_center'. It has shape=(nspw,) 'lags' [numpy array] Delays (in seconds). It has shape=(nlags,) 'kprll' [numpy array] k_parallel modes (in h/Mpc) corresponding to 'lags'. It has shape=(nspw,nlags) 'freq_center' [numpy array] contains the center frequencies (in Hz) of the frequency subbands of the subband delay spectra. It is of size n_win. It is roughly equivalent to redshift(s) 'freq_wts' [numpy array] Contains frequency weights applied on each frequency sub-band during the subband delay transform. It is of size n_win x nchan. 'bw_eff' [numpy array] contains the effective bandwidths (in Hz) of the subbands being delay transformed. It is of size n_win. It is roughly equivalent to width in redshift or along line-of-sight 'shape' [string] shape of the frequency window function applied. Usual values are 'rect' (rectangular), 'bhw' (Blackman-Harris), 'bnw' (Blackman-Nuttall). 'fftpow' [scalar] the power to which the FFT of the window was raised. The value is be a positive scalar with default = 1.0 'lag_corr_length' [numpy array] It is the correlation timescale (in pixels) of the subband delay spectra. It is proportional to inverse of effective bandwidth. It is of size n_win. The unit size of a pixel is determined by the difference between adjacent pixels in lags under key 'lags' which in turn is effectively inverse of the effective bandwidth of the subband specified in bw_eff It further contains one or more of the following keys named 'whole', 'submodel', 'residual', and 'errinfo' each of which is a dictionary. 'whole' contains power spectrum info about the input closure phases. 'submodel' contains power spectrum info about the model that will have been subtracted (as closure phase) from the 'whole' model. 'residual' contains power spectrum info about the closure phases obtained as a difference between 'whole' and 'submodel'. It contains the following keys and values: 'mean' [numpy array] Delay power spectrum incoherently estimated over the axes specified in xinfo['axes'] using the 'mean' key in input cpds or attribute cPhaseDS['processed']['dspec']. It has shape that depends on the combination of input parameters. See examples below. If both collapse_axes and avgcov are not set, those axes will be replaced with square covariance matrices. If collapse_axes is provided but avgcov is False, those axes will be of shape 2*Naxis-1. 'median' [numpy array] Delay power spectrum incoherently averaged over the axes specified in incohax using the 'median' key in input cpds or attribute cPhaseDS['processed']['dspec']. It has shape that depends on the combination of input parameters. See examples below. If both collapse_axes and avgcov are not set, those axes will be replaced with square covariance matrices. If collapse_axes is provided bu avgcov is False, those axes will be of shape 2*Naxis-1. 'diagoffsets' [dictionary] Same keys corresponding to keys under 'collapse_axes' in input containing the diagonal offsets for those axes. If 'avgcov' was set, those entries will be removed from 'diagoffsets' since all the leading diagonal elements have been collapsed (averaged) further. Value under each key is a numpy array where each element in the array corresponds to the index of that leading diagonal. This should match the size of the output along that axis in 'mean' or 'median' above. 'diagweights' [dictionary] Each key is an axis specified in collapse_axes and the value is a numpy array of weights corresponding to the diagonal offsets in that axis. 'axesmap' [dictionary] If covariance in cross-power is calculated but is not collapsed, the number of dimensions in the output will have changed. This parameter tracks where the original axis is now placed. The keys are the original axes that are involved in incoherent cross-power, and the values are the new locations of those original axes in the output. 'nsamples_incoh' [integer] Number of incoherent samples in producing the power spectrum 'nsamples_coh' [integer] Number of coherent samples in producing the power spectrum outfile [string] Full path to the external HDF5 file where the cross- power spectrum information provided in xcpdps will be saved ---------------------------------------------------------------------------- """ if not isinstance(infile, str): raise TypeError('Input infile must be a string') xcpdps = {} with h5py.File(infile, 'r') as fileobj: hdrgrp = fileobj['header'] hdrkeys = ['triads', 'triads_ind', 'lst', 'lst_ind', 'dlst', 'days', 'day_ind', 'dday'] for key in hdrkeys: xcpdps[key] = hdrgrp[key].value sampling = ['oversampled', 'resampled'] sampling_keys = ['z', 'kprll', 'lags', 'freq_center', 'bw_eff', 'shape', 'freq_wts', 'lag_corr_length'] dpool_keys = ['whole', 'submodel', 'residual', 'errinfo'] for smplng in sampling: if smplng in fileobj: smplgrp = fileobj[smplng] xcpdps[smplng] = {} for key in sampling_keys: xcpdps[smplng][key] = smplgrp[key].value for dpool in dpool_keys: if dpool in smplgrp: xcpdps[smplng][dpool] = {} dpoolgrp = smplgrp[dpool] keys = ['diagoffsets', 'diagweights', 'axesmap', 'nsamples_incoh', 'nsamples_coh'] for key in keys: if key in dpoolgrp: if isinstance(dpoolgrp[key], h5py.Group): xcpdps[smplng][dpool][key] = {} for subkey in dpoolgrp[key]: xcpdps[smplng][dpool][key][int(subkey)] = dpoolgrp[key][subkey].value elif isinstance(dpoolgrp[key], h5py.Dataset): xcpdps[smplng][dpool][key] = dpoolgrp[key].value else: raise TypeError('Invalid h5py data type encountered') for stat in ['mean', 'median']: if stat in dpoolgrp: if isinstance(dpoolgrp[stat], h5py.Dataset): valunits = dpoolgrp[stat].attrs['units'] xcpdps[smplng][dpool][stat] = dpoolgrp[stat].value * U.Unit(valunits) elif isinstance(dpoolgrp[stat], h5py.Group): xcpdps[smplng][dpool][stat] = [] for diagcomb_ind in range(len(dpoolgrp[stat].keys())): if 'diagcomb_{0}'.format(diagcomb_ind) in dpoolgrp[stat]: valunits = dpoolgrp[stat]['diagcomb_{0}'.format(diagcomb_ind)].attrs['units'] xcpdps[smplng][dpool][stat] += [dpoolgrp[stat]['diagcomb_{0}'.format(diagcomb_ind)].value * U.Unit(valunits)] return xcpdps ################################################################################ def incoherent_cross_power_spectrum_average(xcpdps, excpdps=None, diagoffsets=None): """ ---------------------------------------------------------------------------- Perform incoherent averaging of cross power spectrum along specified axes Inputs: xcpdps [dictionary or list of dictionaries] If provided as a list of dictionaries, each dictionary consists of cross power spectral information coming possible from different sources, and they will be averaged be averaged incoherently. If a single dictionary is provided instead of a list of dictionaries, the said averaging does not take place. Each dictionary is essentially an output of the member function compute_power_spectrum() of class ClosurePhaseDelaySpectrum. It has the following key-value structure: 'triads' ((ntriads,3) array), 'triads_ind', ((ntriads,) array), 'lstXoffsets' ((ndlst_range,) array), 'lst' ((nlst,) array), 'dlst' ((nlst,) array), 'lst_ind' ((nlst,) array), 'days' ((ndays,) array), 'day_ind' ((ndays,) array), 'dday' ((ndays,) array), 'oversampled' and 'resampled' corresponding to whether resample was set to False or True in call to member function FT(). Values under keys 'triads_ind' and 'lst_ind' are numpy array corresponding to triad and time indices used in selecting the data. Values under keys 'oversampled' and 'resampled' each contain a dictionary with the following keys and values: 'z' [numpy array] Redshifts corresponding to the band centers in 'freq_center'. It has shape=(nspw,) 'lags' [numpy array] Delays (in seconds). It has shape=(nlags,) 'kprll' [numpy array] k_parallel modes (in h/Mpc) corresponding to 'lags'. It has shape=(nspw,nlags) 'freq_center' [numpy array] contains the center frequencies (in Hz) of the frequency subbands of the subband delay spectra. It is of size n_win. It is roughly equivalent to redshift(s) 'freq_wts' [numpy array] Contains frequency weights applied on each frequency sub-band during the subband delay transform. It is of size n_win x nchan. 'bw_eff' [numpy array] contains the effective bandwidths (in Hz) of the subbands being delay transformed. It is of size n_win. It is roughly equivalent to width in redshift or along line-of-sight 'shape' [string] shape of the frequency window function applied. Usual values are 'rect' (rectangular), 'bhw' (Blackman-Harris), 'bnw' (Blackman-Nuttall). 'fftpow' [scalar] the power to which the FFT of the window was raised. The value is be a positive scalar with default = 1.0 'lag_corr_length' [numpy array] It is the correlation timescale (in pixels) of the subband delay spectra. It is proportional to inverse of effective bandwidth. It is of size n_win. The unit size of a pixel is determined by the difference between adjacent pixels in lags under key 'lags' which in turn is effectively inverse of the effective bandwidth of the subband specified in bw_eff It further contains 3 keys named 'whole', 'submodel', and 'residual' each of which is a dictionary. 'whole' contains power spectrum info about the input closure phases. 'submodel' contains power spectrum info about the model that will have been subtracted (as closure phase) from the 'whole' model. 'residual' contains power spectrum info about the closure phases obtained as a difference between 'whole' and 'submodel'. It contains the following keys and values: 'mean' [numpy array] Delay power spectrum incoherently estimated over the axes specified in xinfo['axes'] using the 'mean' key in input cpds or attribute cPhaseDS['processed']['dspec']. It has shape that depends on the combination of input parameters. See examples below. If both collapse_axes and avgcov are not set, those axes will be replaced with square covariance matrices. If collapse_axes is provided but avgcov is False, those axes will be of shape 2*Naxis-1. 'median' [numpy array] Delay power spectrum incoherently averaged over the axes specified in incohax using the 'median' key in input cpds or attribute cPhaseDS['processed']['dspec']. It has shape that depends on the combination of input parameters. See examples below. If both collapse_axes and avgcov are not set, those axes will be replaced with square covariance matrices. If collapse_axes is provided bu avgcov is False, those axes will be of shape 2*Naxis-1. 'diagoffsets' [dictionary] Same keys corresponding to keys under 'collapse_axes' in input containing the diagonal offsets for those axes. If 'avgcov' was set, those entries will be removed from 'diagoffsets' since all the leading diagonal elements have been collapsed (averaged) further. Value under each key is a numpy array where each element in the array corresponds to the index of that leading diagonal. This should match the size of the output along that axis in 'mean' or 'median' above. 'diagweights' [dictionary] Each key is an axis specified in collapse_axes and the value is a numpy array of weights corresponding to the diagonal offsets in that axis. 'axesmap' [dictionary] If covariance in cross-power is calculated but is not collapsed, the number of dimensions in the output will have changed. This parameter tracks where the original axis is now placed. The keys are the original axes that are involved in incoherent cross-power, and the values are the new locations of those original axes in the output. 'nsamples_incoh' [integer] Number of incoherent samples in producing the power spectrum 'nsamples_coh' [integer] Number of coherent samples in producing the power spectrum excpdps [dictionary or list of dictionaries] If provided as a list of dictionaries, each dictionary consists of cross power spectral information of subsample differences coming possible from different sources, and they will be averaged be averaged incoherently. This is optional. If not set (default=None), no incoherent averaging happens. If a single dictionary is provided instead of a list of dictionaries, the said averaging does not take place. Each dictionary is essentially an output of the member function compute_power_spectrum_uncertainty() of class ClosurePhaseDelaySpectrum. It has the following key-value structure: 'triads' ((ntriads,3) array), 'triads_ind', ((ntriads,) array), 'lstXoffsets' ((ndlst_range,) array), 'lst' ((nlst,) array), 'dlst' ((nlst,) array), 'lst_ind' ((nlst,) array), 'days' ((ndaycomb,) array), 'day_ind' ((ndaycomb,) array), 'dday' ((ndaycomb,) array), 'oversampled' and 'resampled' corresponding to whether resample was set to False or True in call to member function FT(). Values under keys 'triads_ind' and 'lst_ind' are numpy array corresponding to triad and time indices used in selecting the data. Values under keys 'oversampled' and 'resampled' each contain a dictionary with the following keys and values: 'z' [numpy array] Redshifts corresponding to the band centers in 'freq_center'. It has shape=(nspw,) 'lags' [numpy array] Delays (in seconds). It has shape=(nlags,) 'kprll' [numpy array] k_parallel modes (in h/Mpc) corresponding to 'lags'. It has shape=(nspw,nlags) 'freq_center' [numpy array] contains the center frequencies (in Hz) of the frequency subbands of the subband delay spectra. It is of size n_win. It is roughly equivalent to redshift(s) 'freq_wts' [numpy array] Contains frequency weights applied on each frequency sub-band during the subband delay transform. It is of size n_win x nchan. 'bw_eff' [numpy array] contains the effective bandwidths (in Hz) of the subbands being delay transformed. It is of size n_win. It is roughly equivalent to width in redshift or along line-of-sight 'shape' [string] shape of the frequency window function applied. Usual values are 'rect' (rectangular), 'bhw' (Blackman-Harris), 'bnw' (Blackman-Nuttall). 'fftpow' [scalar] the power to which the FFT of the window was raised. The value is be a positive scalar with default = 1.0 'lag_corr_length' [numpy array] It is the correlation timescale (in pixels) of the subband delay spectra. It is proportional to inverse of effective bandwidth. It is of size n_win. The unit size of a pixel is determined by the difference between adjacent pixels in lags under key 'lags' which in turn is effectively inverse of the effective bandwidth of the subband specified in bw_eff It further contains a key named 'errinfo' which is a dictionary. It contains information about power spectrum uncertainties obtained from subsample differences. It contains the following keys and values: 'mean' [numpy array] Delay power spectrum uncertainties incoherently estimated over the axes specified in xinfo['axes'] using the 'mean' key in input cpds or attribute cPhaseDS['errinfo']['dspec']. It has shape that depends on the combination of input parameters. See examples below. If both collapse_axes and avgcov are not set, those axes will be replaced with square covariance matrices. If collapse_axes is provided but avgcov is False, those axes will be of shape 2*Naxis-1. 'median' [numpy array] Delay power spectrum uncertainties incoherently averaged over the axes specified in incohax using the 'median' key in input cpds or attribute cPhaseDS['errinfo']['dspec']. It has shape that depends on the combination of input parameters. See examples below. If both collapse_axes and avgcov are not set, those axes will be replaced with square covariance matrices. If collapse_axes is provided but avgcov is False, those axes will be of shape 2*Naxis-1. 'diagoffsets' [dictionary] Same keys corresponding to keys under 'collapse_axes' in input containing the diagonal offsets for those axes. If 'avgcov' was set, those entries will be removed from 'diagoffsets' since all the leading diagonal elements have been collapsed (averaged) further. Value under each key is a numpy array where each element in the array corresponds to the index of that leading diagonal. This should match the size of the output along that axis in 'mean' or 'median' above. 'diagweights' [dictionary] Each key is an axis specified in collapse_axes and the value is a numpy array of weights corresponding to the diagonal offsets in that axis. 'axesmap' [dictionary] If covariance in cross-power is calculated but is not collapsed, the number of dimensions in the output will have changed. This parameter tracks where the original axis is now placed. The keys are the original axes that are involved in incoherent cross-power, and the values are the new locations of those original axes in the output. 'nsamples_incoh' [integer] Number of incoherent samples in producing the power spectrum 'nsamples_coh' [integer] Number of coherent samples in producing the power spectrum diagoffsets [NoneType or dictionary or list of dictionaries] This info is used for incoherent averaging along specified diagonals along specified axes. This incoherent averaging is performed after incoherently averaging multiple cross-power spectra (if any). If set to None, this incoherent averaging is not performed. Many combinations of axes and diagonals can be specified as individual dictionaries in a list. If only one dictionary is specified, then it assumed that only one combination of axes and diagonals is requested. If a list of dictionaries is given, each dictionary in the list specifies a different combination for incoherent averaging. Each dictionary should have the following key-value pairs. The key is the axis number (allowed values are 1, 2, 3) that denote the axis type (1=LST, 2=Days, 3=Triads to be averaged), and the value under they keys is a list or numpy array of diagonals to be averaged incoherently. These axes-diagonal combinations apply to both the inputs xcpdps and excpdps, except axis=2 does not apply to excpdps (since it is made of subsample differences already) and will be skipped. Outputs: A tuple consisting of two dictionaries. The first dictionary contains the incoherent averaging of xcpdps as specified by the inputs, while the second consists of incoherent of excpdps as specified by the inputs. The structure of these dictionaries are practically the same as the dictionary inputs xcpdps and excpdps respectively. The only differences in dictionary structure are: * Under key ['oversampled'/'resampled']['whole'/'submodel'/'residual' /'effinfo']['mean'/'median'] is a list of numpy arrays, where each array in the list corresponds to the dictionary in the list in input diagoffsets that defines the axes-diagonal combination. ---------------------------------------------------------------------------- """ if isinstance(xcpdps, dict): xcpdps = [xcpdps] if not isinstance(xcpdps, list): raise TypeError('Invalid data type provided for input xcpdps') if excpdps is not None: if isinstance(excpdps, dict): excpdps = [excpdps] if not isinstance(excpdps, list): raise TypeError('Invalid data type provided for input excpdps') if len(xcpdps) != len(excpdps): raise ValueError('Inputs xcpdps and excpdps found to have unequal number of values') out_xcpdps = {'triads': xcpdps[0]['triads'], 'triads_ind': xcpdps[0]['triads_ind'], 'lst': xcpdps[0]['lst'], 'lst_ind': xcpdps[0]['lst_ind'], 'dlst': xcpdps[0]['dlst'], 'days': xcpdps[0]['days'], 'day_ind': xcpdps[0]['day_ind'], 'dday': xcpdps[0]['dday']} out_excpdps = None if excpdps is not None: out_excpdps = {'triads': excpdps[0]['triads'], 'triads_ind': excpdps[0]['triads_ind'], 'lst': excpdps[0]['lst'], 'lst_ind': excpdps[0]['lst_ind'], 'dlst': excpdps[0]['dlst'], 'days': excpdps[0]['days'], 'day_ind': excpdps[0]['day_ind'], 'dday': excpdps[0]['dday']} for smplng in ['oversampled', 'resampled']: if smplng in xcpdps[0]: out_xcpdps[smplng] = {'z': xcpdps[0][smplng]['z'], 'kprll': xcpdps[0][smplng]['kprll'], 'lags': xcpdps[0][smplng]['lags'], 'freq_center': xcpdps[0][smplng]['freq_center'], 'bw_eff': xcpdps[0][smplng]['bw_eff'], 'shape': xcpdps[0][smplng]['shape'], 'freq_wts': xcpdps[0][smplng]['freq_wts'], 'lag_corr_length': xcpdps[0][smplng]['lag_corr_length']} if excpdps is not None: out_excpdps[smplng] = {'z': excpdps[0][smplng]['z'], 'kprll': excpdps[0][smplng]['kprll'], 'lags': excpdps[0][smplng]['lags'], 'freq_center': excpdps[0][smplng]['freq_center'], 'bw_eff': excpdps[0][smplng]['bw_eff'], 'shape': excpdps[0][smplng]['shape'], 'freq_wts': excpdps[0][smplng]['freq_wts'], 'lag_corr_length': excpdps[0][smplng]['lag_corr_length']} for dpool in ['whole', 'submodel', 'residual']: if dpool in xcpdps[0][smplng]: out_xcpdps[smplng][dpool] = {'diagoffsets': xcpdps[0][smplng][dpool]['diagoffsets'], 'axesmap': xcpdps[0][smplng][dpool]['axesmap']} for stat in ['mean', 'median']: if stat in xcpdps[0][smplng][dpool]: out_xcpdps[smplng][dpool][stat] = {} arr = [] diagweights = [] for i in range(len(xcpdps)): arr += [xcpdps[i][smplng][dpool][stat].si.value] arr_units = xcpdps[i][smplng][dpool][stat].si.unit if isinstance(xcpdps[i][smplng][dpool]['diagweights'], dict): diagwts = 1.0 diagwts_shape = NP.ones(xcpdps[i][smplng][dpool][stat].ndim, dtype=NP.int) for ax in xcpdps[i][smplng][dpool]['diagweights']: tmp_shape = NP.copy(diagwts_shape) tmp_shape[xcpdps[i][smplng][dpool]['axesmap'][ax]] = xcpdps[i][smplng][dpool]['diagweights'][ax].size diagwts = diagwts * xcpdps[i][smplng][dpool]['diagweights'][ax].reshape(tuple(tmp_shape)) elif isinstance(xcpdps[i][smplng][dpool]['diagweights'], NP.ndarray): diagwts = NP.copy(xcpdps[i][smplng][dpool]['diagweights']) else: raise TypeError('Diagonal weights in input must be a dictionary or a numpy array') diagweights += [diagwts] diagweights = NP.asarray(diagweights) arr = NP.asarray(arr) arr = NP.nansum(arr * diagweights, axis=0) / NP.nansum(diagweights, axis=0) * arr_units diagweights = NP.nansum(diagweights, axis=0) out_xcpdps[smplng][dpool][stat] = arr out_xcpdps[smplng][dpool]['diagweights'] = diagweights for dpool in ['errinfo']: if dpool in excpdps[0][smplng]: out_excpdps[smplng][dpool] = {'diagoffsets': excpdps[0][smplng][dpool]['diagoffsets'], 'axesmap': excpdps[0][smplng][dpool]['axesmap']} for stat in ['mean', 'median']: if stat in excpdps[0][smplng][dpool]: out_excpdps[smplng][dpool][stat] = {} arr = [] diagweights = [] for i in range(len(excpdps)): arr += [excpdps[i][smplng][dpool][stat].si.value] arr_units = excpdps[i][smplng][dpool][stat].si.unit if isinstance(excpdps[i][smplng][dpool]['diagweights'], dict): diagwts = 1.0 diagwts_shape = NP.ones(excpdps[i][smplng][dpool][stat].ndim, dtype=NP.int) for ax in excpdps[i][smplng][dpool]['diagweights']: tmp_shape = NP.copy(diagwts_shape) tmp_shape[excpdps[i][smplng][dpool]['axesmap'][ax]] = excpdps[i][smplng][dpool]['diagweights'][ax].size diagwts = diagwts * excpdps[i][smplng][dpool]['diagweights'][ax].reshape(tuple(tmp_shape)) elif isinstance(excpdps[i][smplng][dpool]['diagweights'], NP.ndarray): diagwts = NP.copy(excpdps[i][smplng][dpool]['diagweights']) else: raise TypeError('Diagonal weights in input must be a dictionary or a numpy array') diagweights += [diagwts] diagweights = NP.asarray(diagweights) arr = NP.asarray(arr) arr = NP.nansum(arr * diagweights, axis=0) / NP.nansum(diagweights, axis=0) * arr_units diagweights = NP.nansum(diagweights, axis=0) out_excpdps[smplng][dpool][stat] = arr out_excpdps[smplng][dpool]['diagweights'] = diagweights if diagoffsets is not None: if isinstance(diagoffsets, dict): diagoffsets = [diagoffsets] if not isinstance(diagoffsets, list): raise TypeError('Input diagoffsets must be a list of dictionaries') for ind in range(len(diagoffsets)): for ax in diagoffsets[ind]: if not isinstance(diagoffsets[ind][ax], (list, NP.ndarray)): raise TypeError('Values in input dictionary diagoffsets must be a list or numpy array') diagoffsets[ind][ax] = NP.asarray(diagoffsets[ind][ax]) for smplng in ['oversampled', 'resampled']: if smplng in out_xcpdps: for dpool in ['whole', 'submodel', 'residual']: if dpool in out_xcpdps[smplng]: masks = [] for ind in range(len(diagoffsets)): mask_ones = NP.ones(out_xcpdps[smplng][dpool]['diagweights'].shape, dtype=NP.bool) mask_agg = None for ax in diagoffsets[ind]: mltdim_slice = [slice(None)] * mask_ones.ndim mltdim_slice[out_xcpdps[smplng][dpool]['axesmap'][ax].squeeze()] = NP.where(NP.isin(out_xcpdps[smplng][dpool]['diagoffsets'][ax], diagoffsets[ind][ax]))[0] mask_tmp = NP.copy(mask_ones) mask_tmp[tuple(mltdim_slice)] = False if mask_agg is None: mask_agg = NP.copy(mask_tmp) else: mask_agg = NP.logical_or(mask_agg, mask_tmp) masks += [NP.copy(mask_agg)] diagwts = NP.copy(out_xcpdps[smplng][dpool]['diagweights']) out_xcpdps[smplng][dpool]['diagweights'] = [] for stat in ['mean', 'median']: if stat in out_xcpdps[smplng][dpool]: arr = NP.copy(out_xcpdps[smplng][dpool][stat].si.value) arr_units = out_xcpdps[smplng][dpool][stat].si.unit out_xcpdps[smplng][dpool][stat] = [] for ind in range(len(diagoffsets)): masked_diagwts = MA.array(diagwts, mask=masks[ind]) axes_to_avg = tuple([out_xcpdps[smplng][dpool]['axesmap'][ax][0] for ax in diagoffsets[ind]]) out_xcpdps[smplng][dpool][stat] += [MA.sum(arr * masked_diagwts, axis=axes_to_avg, keepdims=True) / MA.sum(masked_diagwts, axis=axes_to_avg, keepdims=True) * arr_units] if len(out_xcpdps[smplng][dpool]['diagweights']) < len(diagoffsets): out_xcpdps[smplng][dpool]['diagweights'] += [MA.sum(masked_diagwts, axis=axes_to_avg, keepdims=True)] if excpdps is not None: for smplng in ['oversampled', 'resampled']: if smplng in out_excpdps: for dpool in ['errinfo']: if dpool in out_excpdps[smplng]: masks = [] for ind in range(len(diagoffsets)): mask_ones = NP.ones(out_excpdps[smplng][dpool]['diagweights'].shape, dtype=NP.bool) mask_agg = None for ax in diagoffsets[ind]: if ax != 2: mltdim_slice = [slice(None)] * mask_ones.ndim mltdim_slice[out_excpdps[smplng][dpool]['axesmap'][ax].squeeze()] = NP.where(NP.isin(out_excpdps[smplng][dpool]['diagoffsets'][ax], diagoffsets[ind][ax]))[0] mask_tmp = NP.copy(mask_ones) mask_tmp[tuple(mltdim_slice)] = False if mask_agg is None: mask_agg = NP.copy(mask_tmp) else: mask_agg = NP.logical_or(mask_agg, mask_tmp) masks += [NP.copy(mask_agg)] diagwts = NP.copy(out_excpdps[smplng][dpool]['diagweights']) out_excpdps[smplng][dpool]['diagweights'] = [] for stat in ['mean', 'median']: if stat in out_excpdps[smplng][dpool]: arr = NP.copy(out_excpdps[smplng][dpool][stat].si.value) arr_units = out_excpdps[smplng][dpool][stat].si.unit out_excpdps[smplng][dpool][stat] = [] for ind in range(len(diagoffsets)): masked_diagwts = MA.array(diagwts, mask=masks[ind]) axes_to_avg = tuple([out_excpdps[smplng][dpool]['axesmap'][ax][0] for ax in diagoffsets[ind] if ax!=2]) out_excpdps[smplng][dpool][stat] += [MA.sum(arr * masked_diagwts, axis=axes_to_avg, keepdims=True) / MA.sum(masked_diagwts, axis=axes_to_avg, keepdims=True) * arr_units] if len(out_excpdps[smplng][dpool]['diagweights']) < len(diagoffsets): out_excpdps[smplng][dpool]['diagweights'] += [MA.sum(masked_diagwts, axis=axes_to_avg, keepdims=True)] return (out_xcpdps, out_excpdps) ################################################################################ def incoherent_kbin_averaging(xcpdps, kbins=None, num_kbins=None, kbintype='log'): """ ---------------------------------------------------------------------------- Averages the power spectrum incoherently by binning in bins of k. Returns the power spectrum in units of both standard power spectrum and \Delta^2 Inputs: xcpdps [dictionary] A dictionary that contains the incoherent averaged power spectrum along LST and/or triads axes. This dictionary is essentially the one(s) returned as the output of the function incoherent_cross_power_spectrum_average() kbins [NoneType, list or numpy array] Bins in k. If set to None (default), it will be determined automatically based on the inputs in num_kbins, and kbintype. If num_kbins is None and kbintype='linear', the negative and positive values of k are folded into a one-sided power spectrum. In this case, the bins will approximately have the same resolution as the k-values in the input power spectrum for all the spectral windows. num_kbins [NoneType or integer] Number of k-bins. Used only if kbins is set to None. If kbintype is set to 'linear', the negative and positive values of k are folded into a one-sided power spectrum. In this case, the bins will approximately have the same resolution as the k-values in the input power spectrum for all the spectral windows. kbintype [string] Specifies the type of binning, used only if kbins is set to None. Accepted values are 'linear' and 'log' for linear and logarithmic bins respectively. Outputs: Dictionary containing the power spectrum information. At the top level, it contains keys specifying the sampling to be 'oversampled' or 'resampled'. Under each of these keys is another dictionary containing the following keys: 'z' [numpy array] Redshifts corresponding to the band centers in 'freq_center'. It has shape=(nspw,) 'lags' [numpy array] Delays (in seconds). It has shape=(nlags,). 'freq_center' [numpy array] contains the center frequencies (in Hz) of the frequency subbands of the subband delay spectra. It is of size n_win. It is roughly equivalent to redshift(s) 'freq_wts' [numpy array] Contains frequency weights applied on each frequency sub-band during the subband delay transform. It is of size n_win x nchan. 'bw_eff' [numpy array] contains the effective bandwidths (in Hz) of the subbands being delay transformed. It is of size n_win. It is roughly equivalent to width in redshift or along line-of-sight 'shape' [string] shape of the frequency window function applied. Usual values are 'rect' (rectangular), 'bhw' (Blackman-Harris), 'bnw' (Blackman-Nuttall). 'fftpow' [scalar] the power to which the FFT of the window was raised. The value is be a positive scalar with default = 1.0 'lag_corr_length' [numpy array] It is the correlation timescale (in pixels) of the subband delay spectra. It is proportional to inverse of effective bandwidth. It is of size n_win. The unit size of a pixel is determined by the difference between adjacent pixels in lags under key 'lags' which in turn is effectively inverse of the effective bandwidth of the subband specified in bw_eff It further contains 3 keys named 'whole', 'submodel', and 'residual' or one key named 'errinfo' each of which is a dictionary. 'whole' contains power spectrum info about the input closure phases. 'submodel' contains power spectrum info about the model that will have been subtracted (as closure phase) from the 'whole' model. 'residual' contains power spectrum info about the closure phases obtained as a difference between 'whole' and 'submodel'. 'errinfo' contains power spectrum information about the subsample differences. There is also another dictionary under key 'kbininfo' that contains information about k-bins. These dictionaries contain the following keys and values: 'whole'/'submodel'/'residual'/'errinfo' [dictionary] It contains the following keys and values: 'mean' [dictionary] Delay power spectrum information under the 'mean' statistic incoherently obtained by averaging the input power spectrum in bins of k. It contains output power spectrum expressed as two quantities each of which is a dictionary with the following key-value pairs: 'PS' [list of numpy arrays] Standard power spectrum in units of 'K2 Mpc3'. Each numpy array in the list maps to a specific combination of axes and axis diagonals chosen for incoherent averaging in earlier processing such as in the function incoherent_cross_power_spectrum_average(). The numpy array has a shape similar to the input power spectrum, but that last axis (k-axis) will have a different size that depends on the k-bins that were used in the incoherent averaging along that axis. 'Del2' [list of numpy arrays] power spectrum in Delta^2 units of 'K2'. Each numpy array in the list maps to a specific combination of axes and axis diagonals chosen for incoherent averaging in earlier processing such as in the function incoherent_cross_power_spectrum_average(). The numpy array has a shape similar to the input power spectrum, but that last axis (k-axis) will have a different size that depends on the k-bins that were used in the incoherent averaging along that axis. 'median' [dictionary] Delay power spectrum information under the 'median' statistic incoherently obtained by averaging the input power spectrum in bins of k. It contains output power spectrum expressed as two quantities each of which is a dictionary with the following key-value pairs: 'PS' [list of numpy arrays] Standard power spectrum in units of 'K2 Mpc3'. Each numpy array in the list maps to a specific combination of axes and axis diagonals chosen for incoherent averaging in earlier processing such as in the function incoherent_cross_power_spectrum_average(). The numpy array has a shape similar to the input power spectrum, but that last axis (k-axis) will have a different size that depends on the k-bins that were used in the incoherent averaging along that axis. 'Del2' [list of numpy arrays] power spectrum in Delta^2 units of 'K2'. Each numpy array in the list maps to a specific combination of axes and axis diagonals chosen for incoherent averaging in earlier processing such as in the function incoherent_cross_power_spectrum_average(). The numpy array has a shape similar to the input power spectrum, but that last axis (k-axis) will have a different size that depends on the k-bins that were used in the incoherent averaging along that axis. 'kbininfo' [dictionary] Contains the k-bin information. It contains the following key-value pairs: 'counts' [list] List of numpy arrays where each numpy array in the stores the counts in the determined k-bins. Each numpy array in the list corresponds to a spectral window (redshift subband). The shape of each numpy array is (nkbins,) 'kbin_edges' [list] List of numpy arrays where each numpy array contains the k-bin edges. Each array in the list corresponds to a spectral window (redshift subband). The shape of each array is (nkbins+1,). 'kbinnum' [list] List of numpy arrays containing the bin number under which the k value falls. Each array in the list corresponds to a spectral window (redshift subband). The shape of each array is (nlags,). 'ri' [list] List of numpy arrays containing the reverse indices for each k-bin. Each array in the list corresponds to a spectral window (redshift subband). The shape of each array is (nlags+nkbins+1,). 'whole'/'submodel'/'residual' or 'errinfo' [dictionary] k-bin info estimated for the different datapools under different stats and PS definitions. It has the keys 'mean' and 'median' for the mean and median statistic respectively. Each of them contain a dictionary with the following key-value pairs: 'PS' [list] List of numpy arrays where each numpy array contains a standard power spectrum typically in units of 'K2 Mpc3'. Its shape is the same as input power spectrum except the k-axis which now has nkbins number of elements. 'Del2' [list] List of numpy arrays where each numpy array contains a Delta^2 power spectrum typically in units of 'K2'. Its shape is the same as input power spectrum except the k-axis which now has nkbins number of elements. ---------------------------------------------------------------------------- """ if not isinstance(xcpdps, dict): raise TypeError('Input xcpdps must be a dictionary') if kbins is not None: if not isinstance(kbins, (list,NP.ndarray)): raise TypeError('Input kbins must be a list or numpy array') else: if not isinstance(kbintype, str): raise TypeError('Input kbintype must be a string') if kbintype.lower() not in ['linear', 'log']: raise ValueError('Input kbintype must be set to "linear" or "log"') if kbintype.lower() == 'log': if num_kbins is None: num_kbins = 10 psinfo = {} keys = ['triads', 'triads_ind', 'lst', 'lst_ind', 'dlst', 'days', 'day_ind', 'dday'] for key in keys: psinfo[key] = xcpdps[key] sampling = ['oversampled', 'resampled'] sampling_keys = ['z', 'freq_center', 'bw_eff', 'shape', 'freq_wts', 'lag_corr_length'] dpool_keys = ['whole', 'submodel', 'residual', 'errinfo'] for smplng in sampling: if smplng in xcpdps: psinfo[smplng] = {} for key in sampling_keys: psinfo[smplng][key] = xcpdps[smplng][key] kprll = xcpdps[smplng]['kprll'] lags = xcpdps[smplng]['lags'] eps = 1e-10 if kbins is None: dkprll = NP.max(NP.mean(NP.diff(kprll, axis=-1), axis=-1)) if kbintype.lower() == 'linear': bins_kprll = NP.linspace(eps, NP.abs(kprll).max()+eps, num=kprll.shape[1]/2+1, endpoint=True) else: bins_kprll = NP.geomspace(eps, NP.abs(kprll).max()+eps, num=num_kbins+1, endpoint=True) bins_kprll = NP.insert(bins_kprll, 0, -eps) else: bins_kprll = NP.asarray(kbins) num_kbins = bins_kprll.size - 1 psinfo[smplng]['kbininfo'] = {'counts': [], 'kbin_edges': [], 'kbinnum': [], 'ri': []} for spw in range(kprll.shape[0]): counts, kbin_edges, kbinnum, ri = OPS.binned_statistic(NP.abs(kprll[spw,:]), statistic='count', bins=bins_kprll) counts = counts.astype(NP.int) psinfo[smplng]['kbininfo']['counts'] += [
NP.copy(counts)
numpy.copy
# -*- coding: utf-8 -*- """ Created on Mon Mar 23 15:34:55 2020 @author: giova """ import meshio import sys # specify where to look for modules sys.path.append("modules") sys.path.append("PRE") import time start = time.process_time() # import modules and specific functions import numpy as np import motoremesh from boundary_conditions import BoundaryConditions import solver from stress_recovery import * # Read mesh file from gmsh mesh = motoremesh.GMSH('beam') bcs = BoundaryConditions() bcs.dirichlet_elements , bcs.dirichlet_nodes = bcs.find_boundary_obj(mesh,'Dirichlet') bcs.neumann_elements , bcs.neumann_nodes = bcs.find_boundary_obj(mesh,'Neumann') bcs.load =
np.array([0,20])
numpy.array
#!/usr/bin/env python3 ########################################################################### # This file is part of rsp2, and is licensed under EITHER the MIT license # or the Apache 2.0 license, at your option. # # http://www.apache.org/licenses/LICENSE-2.0 # http://opensource.org/licenses/MIT # # Be aware that not all of rsp2 is provided under this permissive license, # and that the project as a whole is licensed under the GPL 3.0. ########################################################################### import numpy as np import json import sys import scipy.sparse import typing as tp from . import eigsh_custom, get_OPinv from rsp2.internals import info from rsp2.io import dynmat, eigensols # The default tolerance for eigsh is machine precision, which I feel is # overkill. Hopefully a lighter tolerance will save some time. # # TODO maybe: experiment with this TOL = 1e-10 # absolute cosines greater than this are deemed non-orthogonal OVERLAP_THRESH = 1e-6 DEFAULT_MAX_SOLUTIONS = 12 DEFAULT_SHIFT_INVERT_ATTEMPTS = 4 DEFAULT_NCV = 0 def main_from_rust(): """ Entry point when called from rsp2's rust code. Communicates through JSON over the standard IO streams. """ info('trace: sending dynmat from rust to python') d = json.load(sys.stdin) m = dynmat.from_dict(d.pop('matrix')) shift_invert_attempts = d.pop('shift-invert-attempts') dense = d.pop('dense') max_solutions = d.pop('max-solutions') assert not d out = run(m, dense=dense, shift_invert_attempts=shift_invert_attempts, plain_ncv=DEFAULT_NCV, # FIXME add to input json from rust shift_invert_ncv=DEFAULT_NCV, # FIXME add to input json from rust use_fallback=True, # FIXME add to input json from rust max_solutions=max_solutions, search_solutions=None, # FIXME add to input json from rust ) info('trace: sending eigensolutions from python to rust') json.dump(eigensols.to_cereal(out), sys.stdout) print(file=sys.stdout) # newline def main_from_cli(): """ Entry point for the standalone CLI wrapper. """ import argparse p = argparse.ArgumentParser() p.add_argument('DYNMAT', help='dynmat file (.npz, .json, .json.gz, ...)') p.add_argument('--output', '-o', type=str, required=True) p.add_argument( '--dense', action='store_true', help="Use a dense eigenvalue solver. Almost all other options will be " "ignored in this case." ) p.add_argument('--shift-invert-attempts', type=int, default=DEFAULT_SHIFT_INVERT_ATTEMPTS) p.add_argument( '--no-fallback', dest='use_fallback', action='store_false', help="Disable non-shift-invert-based fallback method." ) p.add_argument( '--max-solutions', type=int, default=None, help="max number of solutions to seek. Default is 12 unless --dense is given." ) p.add_argument( '--shift-invert-ncv', type=int, default=DEFAULT_NCV, help="suggested number of Lanczos vectors. This will automatically be " "clipped into the range of [min(2*max_solutions + 1, n), n]" ) p.add_argument( '--plain-ncv', type=int, default=DEFAULT_NCV, help="suggested number of Lanczos vectors. This will automatically be " "clipped into the range of [min(2*max_solutions + 1, n), n]" ) p.add_argument( '--search-solutions', type=int, default=None, help="actually ask the sparse solver for this many solutions instead " "of --max-solutions. The sparse solver can converge much, much " "faster when a few hundred solutions are requested rather than " "just 12." ) args = p.parse_args() if (not args.dense and args.search_solutions is not None and args.max_solutions is not None and args.search_solutions < args.max_solutions ): p.error("--max-solutions must not exceed --search-solutions") out = run( m=dynmat.from_path(args.DYNMAT), dense=args.dense, shift_invert_attempts=args.shift_invert_attempts, shift_invert_ncv=args.shift_invert_ncv, plain_ncv=args.plain_ncv, max_solutions=args.max_solutions, use_fallback=args.use_fallback, search_solutions=args.search_solutions, ) eigensols.to_path(args.output, out) def run(m: scipy.sparse.bsr_matrix, dense: bool, shift_invert_attempts: int, shift_invert_ncv: int, plain_ncv: int, max_solutions: tp.Optional[int], use_fallback: bool, search_solutions: tp.Optional[int], ): """ A suitable entry point from pure python code. """ if max_solutions is None: if dense: max_solutions = m.shape[0] else: max_solutions = DEFAULT_MAX_SOLUTIONS if search_solutions is None: search_solutions = max_solutions # Logic for deciding when to use shift invert results def inner(): if dense: return try_dense(m, max_solutions) if shift_invert_attempts: esols = try_shift_invert(m, max_solutions=search_solutions, shift_invert_attempts=shift_invert_attempts, ncv=shift_invert_ncv, ) if not all(acousticness(v) > 1. - 1e-3 for v in esols[1]): return esols if use_fallback: return try_regular(m, max_solutions=search_solutions, ncv=plain_ncv, ) else: raise RuntimeError('Failed to diagonalize matrix!') # Cutting out other solutions evals, evecs = inner() if not len(evals): raise RuntimeError('No solutions found!') return evals[:max_solutions], evecs[:max_solutions] # As an optimization, begin by using shift-invert mode, which can converge # in **significantly** fewer iterations than regular mode. # noinspection PyUnreachableCode def try_shift_invert(m, *, shift_invert_attempts, max_solutions, ncv): info('trace: precomputing OPinv for shift-invert') # From what I have seen, shift_invert mode tends to find most of its # solutions fairly quickly, but some may be incorrect. Furthermore, it does # not always find all valid negative solutions. # # I fear that when incorrect solutions appear, it may compromise those found # afterwards. So we make multiple calls with a small number of iterations. MAX_ITER = max(30, int(10 * m.shape[0] ** (1/3))) # A heavy computational step at the beginning of shift-invert mode is # factorizing the matrix; do that ahead of time. OPinv = get_OPinv(m, sigma=0, tol=TOL) found_evals = [] found_evecs = [] # debug info counts = [] for call_i in range(shift_invert_attempts): info('trace: shift-invert call', call_i + 1) (evals, evecs) = eigsh_custom( m, k=max_solutions, maxiter=MAX_ITER, sigma=0, which='SA', tol=TOL, OPinv=OPinv, ncv=ncv, allow_fewer_solutions=True, auto_adjust_k=True, auto_adjust_ncv=True, ) evecs = np.array(list(map(normalize, evecs))) # a tree of counts based on direct field assignment so that static # linters can catch typos. (CLion handles it very impressively!) class Count: def total(self): return int(self) def __int__(self): return sum(map(int, self.__dict__.values())) count = Count() # total solutions found count.good = 0 # total solutions kept count.bad = Count() # total solutions rejected count.bad.repeat = 0 # linearly dependent with prior solutions count.bad.wrong = 0 # non-eigenvector solutions count.bad.ortho_bad = 0 # tried to orthogonalize, got a non-eigenvector count.bad.ortho_fail = 0 # tried to orthogonalize, and failed for (eval, ev) in zip(evals, evecs): # Is it ACTUALLY an eigenvector? if not is_good_esol(m, eval, ev): count.bad.wrong += 1 continue # Linearly dependent with existing solutions? if sum(np.abs(np.vdot(ev, other))**2 for other in found_evecs) > 0.95: count.bad.repeat += 1 continue # Prepare it for possible insertion. ortho_ev = mgs_step(ev, found_evecs) # We didn't ruin it, did we? if not is_good_esol(m, eval, ortho_ev): count.bad.ortho_bad += 1 continue if sum(np.abs(np.vdot(ortho_ev, other))**2 for other in found_evecs) > 1e-6: count.bad.ortho_fail += 1 continue # ship it count.good += 1 found_evecs.append(ortho_ev) found_evals.append(eval) counts.append(count) info(" Good -- Bad (Old Wrong OrthoFail OrthoBad)") for count in counts: info( " {:^4} -- {:^3} ({:^3} {:^5} {:^9} {:^8})".format( count.good, count.bad.total(), count.bad.repeat, count.bad.wrong, count.bad.ortho_fail, count.bad.ortho_bad, ) ) perm = np.argsort(found_evals) evals =
np.array(found_evals)
numpy.array
import os import sys import time import numpy import math import random import copy import json import tarfile import xml.etree.ElementTree as xml import denet.common as common import denet.common.logging as logging from denet.dataset import DatasetAbstract from denet.dataset.image_loader import ImageLoader class DatasetImagenet(DatasetAbstract): def copy(self, copy_data=True): r = super().copy(copy_data) r.images = self.images r.image_loader = self.image_loader return r def shuffle(self, mode="random"): random.shuffle(self.images) def load_from_subset(self, subset): if self.subset_index == subset: return logging.info("Loading from subset %i / %i (%i threads)"%(subset, self.subset_num, self.thread_num)) index_start = subset*self.subset_size index_end = min((subset+1)*self.subset_size, self.subset_total_size) self.data = self.image_loader.load(self.images[index_start:index_end]) self.subset_index = subset def load(self, input_dir, data_format, is_training, thread_num, class_labels=None): from .basic import DatasetFromDir self.input_dir = input_dir if self.input_dir[-1] == '/': self.input_dir = self.input_dir[:-1] self.data_format = data_format self.thread_num = thread_num #generate class labels self.class_labels = class_labels fname = os.path.join(os.path.dirname(self.input_dir), "class_labels.txt") if os.path.isfile(fname) and self.class_labels is None: logging.info("Loading class labels from:", fname) self.class_labels = {} with open(fname, "r") as f: for line in f.readlines(): tokens = line.rstrip('\n').split(" ") self.class_labels[tokens[1]] = int(tokens[0]) elif self.class_labels is None: self.class_labels = DatasetFromDir.find_class_labels(input_dir) #check to see if buffered file list is present list_fname = os.path.join(input_dir, "image_list.json") if os.path.isfile(list_fname): logging.info("Loading dataset metadata:", list_fname) json_data = common.json_from_file(list_fname) if json_data.get("version", 0) < 1: logging.warning("Warning: image_list.json is old version, missing bounding boxs!") self.images= [{"fname":fname, "bboxs":[]} for fname in json_data["images"]] else: self.images = json_data["images"] else: bbox_dir = os.path.join(os.path.dirname(input_dir), "bbox") if not os.path.isdir(bbox_dir): raise Exception("ERROR: cannot find bbox dir:" + bbox_dir) fnames=[] for i,c in enumerate(os.listdir(input_dir).sort()): images_cls = DatasetFromDir.find_paths(os.path.join(input_dir, c), "*.JPEG") logging.info("Found %i images for class"%len(images_cls), c) fnames += images_cls logging.info("Finding bboxs in:", bbox_dir) self.images=[] for i,fname in enumerate(fnames): logging.verbose("%i/%i"%(i, len(fnames))) cls_name = os.path.basename(os.path.dirname(fname)) obj_fname = os.path.join(bbox_dir, cls_name, os.path.splitext(os.path.basename(fname))[0] + ".xml") bboxs=[] if os.path.isfile(obj_fname): obj_tree = xml.parse(obj_fname).getroot() size = obj_tree.find("size") width = int(size.find("width").text) height = int(size.find("height").text) for obj in obj_tree.iter("object"): bndbox = obj.find("bndbox") min_x = int(bndbox.find("xmin").text) min_y = int(bndbox.find("ymin").text) max_x = int(bndbox.find("xmax").text) max_y = int(bndbox.find("ymax").text) bboxs.append({"x0":min_x, "x1":max_x, "y0":min_y, "y1":max_y}) self.images.append({"fname":fname, "bboxs":bboxs}) try: logging.info("Saving dataset metadata:", list_fname) common.json_to_file(list_fname, {"images":self.images, "version":1}) except Exception as e: logging.warning("Warning: failed to write buffered image list - ", e) #add/fix fields to fit new image_loader interface for image in self.images: fname = image["fname"] cls = self.class_labels[os.path.basename(os.path.dirname(fname))] image["class"] = cls image["bboxs"] = [(cls, (bb["x0"], bb["y0"], bb["x1"], bb["y1"])) for bb in image["bboxs"]] param_str = ",".join(data_format.split(",")[1:]) format_params = common.get_params_dict(param_str) self.image_loader = ImageLoader(thread_num, is_training, format_params) #from facebook resnet implementation self.image_loader.rgb_mean = numpy.array([0.485, 0.456, 0.406], dtype=numpy.float32) self.image_loader.rgb_std =
numpy.array([0.229, 0.224, 0.225], dtype=numpy.float32)
numpy.array
""" This module contains all the functions needed for extracting satellite-derived shorelines (SDS) Author: <NAME>, Water Research Laboratory, University of New South Wales """ # load modules import os import numpy as np import matplotlib.pyplot as plt import pdb # image processing modules import skimage.filters as filters import skimage.measure as measure import skimage.morphology as morphology # machine learning modules import sklearn if sklearn.__version__[:4] == '0.20': from sklearn.externals import joblib else: import joblib from shapely.geometry import LineString # other modules import matplotlib.patches as mpatches import matplotlib.lines as mlines import matplotlib.cm as cm from matplotlib import gridspec import pickle from datetime import datetime from pylab import ginput # CoastSat modules from coastsat import SDS_tools, SDS_preprocess np.seterr(all='ignore') # raise/ignore divisions by 0 and nans # Main function for batch shoreline detection def extract_shorelines(metadata, settings): """ Main function to extract shorelines from satellite images KV WRL 2018 Arguments: ----------- metadata: dict contains all the information about the satellite images that were downloaded settings: dict with the following keys 'inputs': dict input parameters (sitename, filepath, polygon, dates, sat_list) 'cloud_thresh': float value between 0 and 1 indicating the maximum cloud fraction in the cropped image that is accepted 'cloud_mask_issue': boolean True if there is an issue with the cloud mask and sand pixels are erroneously being masked on the images 'buffer_size': int size of the buffer (m) around the sandy pixels over which the pixels are considered in the thresholding algorithm 'min_beach_area': int minimum allowable object area (in metres^2) for the class 'sand', the area is converted to number of connected pixels 'min_length_sl': int minimum length (in metres) of shoreline contour to be valid 'sand_color': str default', 'dark' (for grey/black sand beaches) or 'bright' (for white sand beaches) 'output_epsg': int output spatial reference system as EPSG code 'check_detection': bool if True, lets user manually accept/reject the mapped shorelines 'save_figure': bool if True, saves a -jpg file for each mapped shoreline 'adjust_detection': bool if True, allows user to manually adjust the detected shoreline Returns: ----------- output: dict contains the extracted shorelines and corresponding dates + metadata """ sitename = settings['inputs']['sitename'] filepath_data = settings['inputs']['filepath'] filepath_models = os.path.join(os.getcwd(), 'classification', 'models') # initialise output structure output = dict([]) # create a subfolder to store the .jpg images showing the detection filepath_jpg = os.path.join(filepath_data, sitename, 'jpg_files', 'detection') if not os.path.exists(filepath_jpg): os.makedirs(filepath_jpg) # close all open figures plt.close('all') print('Mapping shorelines:') # loop through satellite list for satname in metadata.keys(): # get images filepath = SDS_tools.get_filepath(settings['inputs'],satname) filenames = metadata[satname]['filenames'] # initialise the output variables output_timestamp = [] # datetime at which the image was acquired (UTC time) output_shoreline = [] # vector of shoreline points output_filename = [] # filename of the images from which the shorelines where derived output_cloudcover = [] # cloud cover of the images output_geoaccuracy = []# georeferencing accuracy of the images output_idxkeep = [] # index that were kept during the analysis (cloudy images are skipped) output_t_mndwi = [] # MNDWI threshold used to map the shoreline # load classifiers (if sklearn version above 0.20, learn the new files) str_new = '' if not sklearn.__version__[:4] == '0.20': str_new = '_new' if satname in ['L5','L7','L8']: pixel_size = 15 if settings['sand_color'] == 'dark': clf = joblib.load(os.path.join(filepath_models, 'NN_4classes_Landsat_dark%s.pkl'%str_new)) elif settings['sand_color'] == 'bright': clf = joblib.load(os.path.join(filepath_models, 'NN_4classes_Landsat_bright%s.pkl'%str_new)) else: clf = joblib.load(os.path.join(filepath_models, 'NN_4classes_Landsat%s.pkl'%str_new)) elif satname == 'S2': pixel_size = 10 clf = joblib.load(os.path.join(filepath_models, 'NN_4classes_S2%s.pkl'%str_new)) # convert settings['min_beach_area'] and settings['buffer_size'] from metres to pixels buffer_size_pixels = np.ceil(settings['buffer_size']/pixel_size) min_beach_area_pixels = np.ceil(settings['min_beach_area']/pixel_size**2) # loop through the images for i in range(len(filenames)): print('\r%s: %d%%' % (satname,int(((i+1)/len(filenames))*100)), end='') # get image filename fn = SDS_tools.get_filenames(filenames[i],filepath, satname) # preprocess image (cloud mask + pansharpening/downsampling) im_ms, georef, cloud_mask, im_extra, im_QA, im_nodata = SDS_preprocess.preprocess_single(fn, satname, settings['cloud_mask_issue']) # get image spatial reference system (epsg code) from metadata dict image_epsg = metadata[satname]['epsg'][i] # compute cloud_cover percentage (with no data pixels) cloud_cover_combined = np.divide(sum(sum(cloud_mask.astype(int))), (cloud_mask.shape[0]*cloud_mask.shape[1])) if cloud_cover_combined > 0.99: # if 99% of cloudy pixels in image skip continue # remove no data pixels from the cloud mask # (for example L7 bands of no data should not be accounted for) cloud_mask_adv = np.logical_xor(cloud_mask, im_nodata) # compute updated cloud cover percentage (without no data pixels) cloud_cover = np.divide(sum(sum(cloud_mask_adv.astype(int))), (sum(sum((~im_nodata).astype(int))))) # skip image if cloud cover is above user-defined threshold if cloud_cover > settings['cloud_thresh']: continue # calculate a buffer around the reference shoreline (if any has been digitised) im_ref_buffer = create_shoreline_buffer(cloud_mask.shape, georef, image_epsg, pixel_size, settings) # classify image in 4 classes (sand, whitewater, water, other) with NN classifier im_classif, im_labels = classify_image_NN(im_ms, im_extra, cloud_mask, min_beach_area_pixels, clf) # if adjust_detection is True, let the user adjust the detected shoreline if settings['adjust_detection']: date = filenames[i][:19] skip_image, shoreline, t_mndwi = adjust_detection(im_ms, cloud_mask, im_labels, im_ref_buffer, image_epsg, georef, settings, date, satname, buffer_size_pixels) # if the user decides to skip the image, continue and do not save the mapped shoreline if skip_image: continue # otherwise map the contours automatically with one of the two following functions: # if there are pixels in the 'sand' class --> use find_wl_contours2 (enhanced) # otherwise use find_wl_contours2 (traditional) else: try: # use try/except structure for long runs if sum(sum(im_labels[:,:,0])) < 10 : # minimum number of sand pixels # compute MNDWI image (SWIR-G) im_mndwi = SDS_tools.nd_index(im_ms[:,:,4], im_ms[:,:,1], cloud_mask) # find water contours on MNDWI grayscale image contours_mwi, t_mndwi = find_wl_contours1(im_mndwi, cloud_mask, im_ref_buffer) else: # use classification to refine threshold and extract the sand/water interface contours_mwi, t_mndwi = find_wl_contours2(im_ms, im_labels, cloud_mask, buffer_size_pixels, im_ref_buffer) except: print('Could not map shoreline for this image: ' + filenames[i]) continue # process the water contours into a shoreline shoreline = process_shoreline(contours_mwi, cloud_mask, georef, image_epsg, settings) # visualise the mapped shorelines, there are two options: # if settings['check_detection'] = True, shows the detection to the user for accept/reject # if settings['save_figure'] = True, saves a figure for each mapped shoreline if settings['check_detection'] or settings['save_figure']: date = filenames[i][:19] if not settings['check_detection']: plt.ioff() # turning interactive plotting off skip_image = show_detection(im_ms, cloud_mask, im_labels, shoreline, image_epsg, georef, settings, date, satname) # if the user decides to skip the image, continue and do not save the mapped shoreline if skip_image: continue # append to output variables output_timestamp.append(metadata[satname]['dates'][i]) output_shoreline.append(shoreline) output_filename.append(filenames[i]) output_cloudcover.append(cloud_cover) output_geoaccuracy.append(metadata[satname]['acc_georef'][i]) output_idxkeep.append(i) output_t_mndwi.append(t_mndwi) # create dictionnary of output output[satname] = { 'dates': output_timestamp, 'shorelines': output_shoreline, 'filename': output_filename, 'cloud_cover': output_cloudcover, 'geoaccuracy': output_geoaccuracy, 'idx': output_idxkeep, 'MNDWI_threshold': output_t_mndwi, } print('') # close figure window if still open if plt.get_fignums(): plt.close() # change the format to have one list sorted by date with all the shorelines (easier to use) output = SDS_tools.merge_output(output) # save outputput structure as output.pkl filepath = os.path.join(filepath_data, sitename) with open(os.path.join(filepath, sitename + '_output.pkl'), 'wb') as f: pickle.dump(output, f) return output ################################################################################################### # IMAGE CLASSIFICATION FUNCTIONS ################################################################################################### def calculate_features(im_ms, cloud_mask, im_bool): """ Calculates features on the image that are used for the supervised classification. The features include spectral normalized-difference indices and standard deviation of the image for all the bands and indices. KV WRL 2018 Arguments: ----------- im_ms: np.array RGB + downsampled NIR and SWIR cloud_mask: np.array 2D cloud mask with True where cloud pixels are im_bool: np.array 2D array of boolean indicating where on the image to calculate the features Returns: ----------- features: np.array matrix containing each feature (columns) calculated for all the pixels (rows) indicated in im_bool """ # add all the multispectral bands features = np.expand_dims(im_ms[im_bool,0],axis=1) for k in range(1,im_ms.shape[2]): feature = np.expand_dims(im_ms[im_bool,k],axis=1) features = np.append(features, feature, axis=-1) # NIR-G im_NIRG = SDS_tools.nd_index(im_ms[:,:,3], im_ms[:,:,1], cloud_mask) features = np.append(features, np.expand_dims(im_NIRG[im_bool],axis=1), axis=-1) # SWIR-G im_SWIRG = SDS_tools.nd_index(im_ms[:,:,4], im_ms[:,:,1], cloud_mask) features = np.append(features, np.expand_dims(im_SWIRG[im_bool],axis=1), axis=-1) # NIR-R im_NIRR = SDS_tools.nd_index(im_ms[:,:,3], im_ms[:,:,2], cloud_mask) features = np.append(features, np.expand_dims(im_NIRR[im_bool],axis=1), axis=-1) # SWIR-NIR im_SWIRNIR = SDS_tools.nd_index(im_ms[:,:,4], im_ms[:,:,3], cloud_mask) features = np.append(features, np.expand_dims(im_SWIRNIR[im_bool],axis=1), axis=-1) # B-R im_BR = SDS_tools.nd_index(im_ms[:,:,0], im_ms[:,:,2], cloud_mask) features = np.append(features, np.expand_dims(im_BR[im_bool],axis=1), axis=-1) # calculate standard deviation of individual bands for k in range(im_ms.shape[2]): im_std = SDS_tools.image_std(im_ms[:,:,k], 1) features = np.append(features, np.expand_dims(im_std[im_bool],axis=1), axis=-1) # calculate standard deviation of the spectral indices im_std = SDS_tools.image_std(im_NIRG, 1) features = np.append(features, np.expand_dims(im_std[im_bool],axis=1), axis=-1) im_std = SDS_tools.image_std(im_SWIRG, 1) features = np.append(features, np.expand_dims(im_std[im_bool],axis=1), axis=-1) im_std = SDS_tools.image_std(im_NIRR, 1) features = np.append(features, np.expand_dims(im_std[im_bool],axis=1), axis=-1) im_std = SDS_tools.image_std(im_SWIRNIR, 1) features = np.append(features, np.expand_dims(im_std[im_bool],axis=1), axis=-1) im_std = SDS_tools.image_std(im_BR, 1) features = np.append(features, np.expand_dims(im_std[im_bool],axis=1), axis=-1) return features def classify_image_NN(im_ms, im_extra, cloud_mask, min_beach_area, clf): """ Classifies every pixel in the image in one of 4 classes: - sand --> label = 1 - whitewater (breaking waves and swash) --> label = 2 - water --> label = 3 - other (vegetation, buildings, rocks...) --> label = 0 The classifier is a Neural Network that is already trained. KV WRL 2018 Arguments: ----------- im_ms: np.array Pansharpened RGB + downsampled NIR and SWIR im_extra: only used for Landsat 7 and 8 where im_extra is the panchromatic band cloud_mask: np.array 2D cloud mask with True where cloud pixels are min_beach_area: int minimum number of pixels that have to be connected to belong to the SAND class clf: joblib object pre-trained classifier Returns: ----------- im_classif: np.array 2D image containing labels im_labels: np.array of booleans 3D image containing a boolean image for each class (im_classif == label) """ # calculate features vec_features = calculate_features(im_ms, cloud_mask, np.ones(cloud_mask.shape).astype(bool)) vec_features[np.isnan(vec_features)] = 1e-9 # NaN values are create when std is too close to 0 # remove NaNs and cloudy pixels vec_cloud = cloud_mask.reshape(cloud_mask.shape[0]*cloud_mask.shape[1]) vec_nan = np.any(np.isnan(vec_features), axis=1) vec_inf = np.any(np.isinf(vec_features), axis=1) vec_mask = np.logical_or(vec_cloud,np.logical_or(vec_nan,vec_inf)) vec_features = vec_features[~vec_mask, :] # classify pixels labels = clf.predict(vec_features) # recompose image vec_classif = np.nan*np.ones((cloud_mask.shape[0]*cloud_mask.shape[1])) vec_classif[~vec_mask] = labels im_classif = vec_classif.reshape((cloud_mask.shape[0], cloud_mask.shape[1])) # create a stack of boolean images for each label im_sand = im_classif == 1 im_swash = im_classif == 2 im_water = im_classif == 3 # remove small patches of sand or water that could be around the image (usually noise) im_sand = morphology.remove_small_objects(im_sand, min_size=min_beach_area, connectivity=2) im_water = morphology.remove_small_objects(im_water, min_size=min_beach_area, connectivity=2) im_labels = np.stack((im_sand,im_swash,im_water), axis=-1) return im_classif, im_labels ################################################################################################### # CONTOUR MAPPING FUNCTIONS ################################################################################################### def find_wl_contours1(im_ndwi, cloud_mask, im_ref_buffer): """ Traditional method for shoreline detection using a global threshold. Finds the water line by thresholding the Normalized Difference Water Index and applying the Marching Squares Algorithm to contour the iso-value corresponding to the threshold. KV WRL 2018 Arguments: ----------- im_ndwi: np.ndarray Image (2D) with the NDWI (water index) cloud_mask: np.ndarray 2D cloud mask with True where cloud pixels are im_ref_buffer: np.array Binary image containing a buffer around the reference shoreline Returns: ----------- contours: list of np.arrays contains the coordinates of the contour lines t_mwi: float Otsu threshold used to map the contours """ # reshape image to vector vec_ndwi = im_ndwi.reshape(im_ndwi.shape[0] * im_ndwi.shape[1]) vec_mask = cloud_mask.reshape(cloud_mask.shape[0] * cloud_mask.shape[1]) vec = vec_ndwi[~vec_mask] # apply otsu's threshold vec = vec[~np.isnan(vec)] t_otsu = filters.threshold_otsu(vec) # use Marching Squares algorithm to detect contours on ndwi image im_ndwi_buffer = np.copy(im_ndwi) im_ndwi_buffer[~im_ref_buffer] = np.nan contours = measure.find_contours(im_ndwi_buffer, t_otsu) # remove contours that contain NaNs (due to cloud pixels in the contour) contours = process_contours(contours) return contours, t_otsu def find_wl_contours2(im_ms, im_labels, cloud_mask, buffer_size, im_ref_buffer): """ New robust method for extracting shorelines. Incorporates the classification component to refine the treshold and make it specific to the sand/water interface. KV WRL 2018 Arguments: ----------- im_ms: np.array RGB + downsampled NIR and SWIR im_labels: np.array 3D image containing a boolean image for each class in the order (sand, swash, water) cloud_mask: np.array 2D cloud mask with True where cloud pixels are buffer_size: int size of the buffer around the sandy beach over which the pixels are considered in the thresholding algorithm. im_ref_buffer: np.array binary image containing a buffer around the reference shoreline Returns: ----------- contours_mwi: list of np.arrays contains the coordinates of the contour lines extracted from the MNDWI (Modified Normalized Difference Water Index) image t_mwi: float Otsu sand/water threshold used to map the contours """ nrows = cloud_mask.shape[0] ncols = cloud_mask.shape[1] # calculate Normalized Difference Modified Water Index (SWIR - G) im_mwi = SDS_tools.nd_index(im_ms[:,:,4], im_ms[:,:,1], cloud_mask) # calculate Normalized Difference Modified Water Index (NIR - G) im_wi = SDS_tools.nd_index(im_ms[:,:,3], im_ms[:,:,1], cloud_mask) # stack indices together im_ind = np.stack((im_wi, im_mwi), axis=-1) vec_ind = im_ind.reshape(nrows*ncols,2) # reshape labels into vectors vec_sand = im_labels[:,:,0].reshape(ncols*nrows) vec_water = im_labels[:,:,2].reshape(ncols*nrows) # create a buffer around the sandy beach se = morphology.disk(buffer_size) im_buffer = morphology.binary_dilation(im_labels[:,:,0], se) vec_buffer = im_buffer.reshape(nrows*ncols) # select water/sand/swash pixels that are within the buffer int_water = vec_ind[np.logical_and(vec_buffer,vec_water),:] int_sand = vec_ind[np.logical_and(vec_buffer,vec_sand),:] # make sure both classes have the same number of pixels before thresholding if len(int_water) > 0 and len(int_sand) > 0: if np.argmin([int_sand.shape[0],int_water.shape[0]]) == 1: int_sand = int_sand[np.random.choice(int_sand.shape[0],int_water.shape[0], replace=False),:] else: int_water = int_water[np.random.choice(int_water.shape[0],int_sand.shape[0], replace=False),:] # threshold the sand/water intensities int_all = np.append(int_water,int_sand, axis=0) t_mwi = filters.threshold_otsu(int_all[:,0]) t_wi = filters.threshold_otsu(int_all[:,1]) # find contour with MS algorithm im_wi_buffer = np.copy(im_wi) im_wi_buffer[~im_ref_buffer] = np.nan im_mwi_buffer = np.copy(im_mwi) im_mwi_buffer[~im_ref_buffer] = np.nan contours_wi = measure.find_contours(im_wi_buffer, t_wi) contours_mwi = measure.find_contours(im_mwi_buffer, t_mwi) # remove contour points that are NaNs (around clouds) contours_wi = process_contours(contours_wi) contours_mwi = process_contours(contours_mwi) # only return MNDWI contours and threshold return contours_mwi, t_mwi ################################################################################################### # SHORELINE PROCESSING FUNCTIONS ################################################################################################### def create_shoreline_buffer(im_shape, georef, image_epsg, pixel_size, settings): """ Creates a buffer around the reference shoreline. The size of the buffer is given by settings['max_dist_ref']. KV WRL 2018 Arguments: ----------- im_shape: np.array size of the image (rows,columns) georef: np.array vector of 6 elements [Xtr, Xscale, Xshear, Ytr, Yshear, Yscale] image_epsg: int spatial reference system of the image from which the contours were extracted pixel_size: int size of the pixel in metres (15 for Landsat, 10 for Sentinel-2) settings: dict with the following keys 'output_epsg': int output spatial reference system 'reference_shoreline': np.array coordinates of the reference shoreline 'max_dist_ref': int maximum distance from the reference shoreline in metres Returns: ----------- im_buffer: np.array binary image, True where the buffer is, False otherwise """ # initialise the image buffer im_buffer = np.ones(im_shape).astype(bool) if 'reference_shoreline' in settings.keys(): # convert reference shoreline to pixel coordinates ref_sl = settings['reference_shoreline'] ref_sl_conv = SDS_tools.convert_epsg(ref_sl, settings['output_epsg'],image_epsg)[:,:-1] ref_sl_pix = SDS_tools.convert_world2pix(ref_sl_conv, georef) ref_sl_pix_rounded = np.round(ref_sl_pix).astype(int) # make sure that the pixel coordinates of the reference shoreline are inside the image idx_row = np.logical_and(ref_sl_pix_rounded[:,0] > 0, ref_sl_pix_rounded[:,0] < im_shape[1]) idx_col = np.logical_and(ref_sl_pix_rounded[:,1] > 0, ref_sl_pix_rounded[:,1] < im_shape[0]) idx_inside = np.logical_and(idx_row, idx_col) ref_sl_pix_rounded = ref_sl_pix_rounded[idx_inside,:] # create binary image of the reference shoreline (1 where the shoreline is 0 otherwise) im_binary = np.zeros(im_shape) for j in range(len(ref_sl_pix_rounded)): im_binary[ref_sl_pix_rounded[j,1], ref_sl_pix_rounded[j,0]] = 1 im_binary = im_binary.astype(bool) # dilate the binary image to create a buffer around the reference shoreline max_dist_ref_pixels = np.ceil(settings['max_dist_ref']/pixel_size) se = morphology.disk(max_dist_ref_pixels) im_buffer = morphology.binary_dilation(im_binary, se) return im_buffer def process_contours(contours): """ Remove contours that contain NaNs, usually these are contours that are in contact with clouds. KV WRL 2020 Arguments: ----------- contours: list of np.array image contours as detected by the function skimage.measure.find_contours Returns: ----------- contours: list of np.array processed image contours (only the ones that do not contains NaNs) """ # initialise variable contours_nonans = [] # loop through contours and only keep the ones without NaNs for k in range(len(contours)): if np.any(np.isnan(contours[k])): index_nan = np.where(np.isnan(contours[k]))[0] contours_temp = np.delete(contours[k], index_nan, axis=0) if len(contours_temp) > 1: contours_nonans.append(contours_temp) else: contours_nonans.append(contours[k]) return contours_nonans def process_shoreline(contours, cloud_mask, georef, image_epsg, settings): """ Converts the contours from image coordinates to world coordinates. This function also removes the contours that are too small to be a shoreline (based on the parameter settings['min_length_sl']) KV WRL 2018 Arguments: ----------- contours: np.array or list of np.array image contours as detected by the function find_contours cloud_mask: np.array 2D cloud mask with True where cloud pixels are georef: np.array vector of 6 elements [Xtr, Xscale, Xshear, Ytr, Yshear, Yscale] image_epsg: int spatial reference system of the image from which the contours were extracted settings: dict with the following keys 'output_epsg': int output spatial reference system 'min_length_sl': float minimum length of shoreline contour to be kept (in meters) Returns: ----------- shoreline: np.array array of points with the X and Y coordinates of the shoreline """ # convert pixel coordinates to world coordinates contours_world = SDS_tools.convert_pix2world(contours, georef) # convert world coordinates to desired spatial reference system contours_epsg = SDS_tools.convert_epsg(contours_world, image_epsg, settings['output_epsg']) # remove contours that have a perimeter < min_length_sl (provided in settings dict) # this enables to remove the very small contours that do not correspond to the shoreline contours_long = [] for l, wl in enumerate(contours_epsg): coords = [(wl[k,0], wl[k,1]) for k in range(len(wl))] a = LineString(coords) # shapely LineString structure if a.length >= settings['min_length_sl']: contours_long.append(wl) # format points into np.array x_points = np.array([]) y_points = np.array([]) for k in range(len(contours_long)): x_points = np.append(x_points,contours_long[k][:,0]) y_points = np.append(y_points,contours_long[k][:,1]) contours_array = np.transpose(np.array([x_points,y_points])) shoreline = contours_array # now remove any shoreline points that are attached to cloud pixels if sum(sum(cloud_mask)) > 0: # get the coordinates of the cloud pixels idx_cloud = np.where(cloud_mask) idx_cloud = np.array([(idx_cloud[0][k], idx_cloud[1][k]) for k in range(len(idx_cloud[0]))]) # convert to world coordinates and same epsg as the shoreline points coords_cloud = SDS_tools.convert_epsg(SDS_tools.convert_pix2world(idx_cloud, georef), image_epsg, settings['output_epsg'])[:,:-1] # only keep the shoreline points that are at least 30m from any cloud pixel idx_keep = np.ones(len(shoreline)).astype(bool) for k in range(len(shoreline)): if np.any(np.linalg.norm(shoreline[k,:] - coords_cloud, axis=1) < 30): idx_keep[k] = False shoreline = shoreline[idx_keep] return shoreline ################################################################################################### # PLOTTING FUNCTIONS ################################################################################################### def show_detection(im_ms, cloud_mask, im_labels, shoreline,image_epsg, georef, settings, date, satname): """ Shows the detected shoreline to the user for visual quality control. The user can accept/reject the detected shorelines by using keep/skip buttons. KV WRL 2018 Arguments: ----------- im_ms: np.array RGB + downsampled NIR and SWIR cloud_mask: np.array 2D cloud mask with True where cloud pixels are im_labels: np.array 3D image containing a boolean image for each class in the order (sand, swash, water) shoreline: np.array array of points with the X and Y coordinates of the shoreline image_epsg: int spatial reference system of the image from which the contours were extracted georef: np.array vector of 6 elements [Xtr, Xscale, Xshear, Ytr, Yshear, Yscale] date: string date at which the image was taken satname: string indicates the satname (L5,L7,L8 or S2) settings: dict with the following keys 'inputs': dict input parameters (sitename, filepath, polygon, dates, sat_list) 'output_epsg': int output spatial reference system as EPSG code 'check_detection': bool if True, lets user manually accept/reject the mapped shorelines 'save_figure': bool if True, saves a -jpg file for each mapped shoreline Returns: ----------- skip_image: boolean True if the user wants to skip the image, False otherwise """ sitename = settings['inputs']['sitename'] filepath_data = settings['inputs']['filepath'] # subfolder where the .jpg file is stored if the user accepts the shoreline detection filepath = os.path.join(filepath_data, sitename, 'jpg_files', 'detection') im_RGB = SDS_preprocess.rescale_image_intensity(im_ms[:,:,[2,1,0]], cloud_mask, 99.9) # compute classified image im_class = np.copy(im_RGB) cmap = cm.get_cmap('tab20c') colorpalette = cmap(np.arange(0,13,1)) colours = np.zeros((3,4)) colours[0,:] = colorpalette[5] colours[1,:] = np.array([204/255,1,1,1]) colours[2,:] = np.array([0,91/255,1,1]) for k in range(0,im_labels.shape[2]): im_class[im_labels[:,:,k],0] = colours[k,0] im_class[im_labels[:,:,k],1] = colours[k,1] im_class[im_labels[:,:,k],2] = colours[k,2] # compute MNDWI grayscale image im_mwi = SDS_tools.nd_index(im_ms[:,:,4], im_ms[:,:,1], cloud_mask) # transform world coordinates of shoreline into pixel coordinates # use try/except in case there are no coordinates to be transformed (shoreline = []) try: sl_pix = SDS_tools.convert_world2pix(SDS_tools.convert_epsg(shoreline, settings['output_epsg'], image_epsg)[:,[0,1]], georef) except: # if try fails, just add nan into the shoreline vector so the next parts can still run sl_pix = np.array([[np.nan, np.nan],[np.nan, np.nan]]) if plt.get_fignums(): # get open figure if it exists fig = plt.gcf() ax1 = fig.axes[0] ax2 = fig.axes[1] ax3 = fig.axes[2] else: # else create a new figure fig = plt.figure() fig.set_size_inches([18, 9]) mng = plt.get_current_fig_manager() mng.window.showMaximized() # according to the image shape, decide whether it is better to have the images # in vertical subplots or horizontal subplots if im_RGB.shape[1] > 2.5*im_RGB.shape[0]: # vertical subplots gs = gridspec.GridSpec(3, 1) gs.update(bottom=0.03, top=0.97, left=0.03, right=0.97) ax1 = fig.add_subplot(gs[0,0]) ax2 = fig.add_subplot(gs[1,0], sharex=ax1, sharey=ax1) ax3 = fig.add_subplot(gs[2,0], sharex=ax1, sharey=ax1) else: # horizontal subplots gs = gridspec.GridSpec(1, 3) gs.update(bottom=0.05, top=0.95, left=0.05, right=0.95) ax1 = fig.add_subplot(gs[0,0]) ax2 = fig.add_subplot(gs[0,1], sharex=ax1, sharey=ax1) ax3 = fig.add_subplot(gs[0,2], sharex=ax1, sharey=ax1) # change the color of nans to either black (0.0) or white (1.0) or somewhere in between nan_color = 1.0 im_RGB = np.where(np.isnan(im_RGB), nan_color, im_RGB) im_class = np.where(np.isnan(im_class), 1.0, im_class) # create image 1 (RGB) ax1.imshow(im_RGB) ax1.plot(sl_pix[:,0], sl_pix[:,1], 'k.', markersize=3) ax1.axis('off') ax1.set_title(sitename, fontweight='bold', fontsize=16) # create image 2 (classification) ax2.imshow(im_class) ax2.plot(sl_pix[:,0], sl_pix[:,1], 'k.', markersize=3) ax2.axis('off') orange_patch = mpatches.Patch(color=colours[0,:], label='sand') white_patch = mpatches.Patch(color=colours[1,:], label='whitewater') blue_patch = mpatches.Patch(color=colours[2,:], label='water') black_line = mlines.Line2D([],[],color='k',linestyle='-', label='shoreline') ax2.legend(handles=[orange_patch,white_patch,blue_patch, black_line], bbox_to_anchor=(1, 0.5), fontsize=10) ax2.set_title(date, fontweight='bold', fontsize=16) # create image 3 (MNDWI) ax3.imshow(im_mwi, cmap='bwr') ax3.plot(sl_pix[:,0], sl_pix[:,1], 'k.', markersize=3) ax3.axis('off') ax3.set_title(satname, fontweight='bold', fontsize=16) # additional options # ax1.set_anchor('W') # ax2.set_anchor('W') # cb = plt.colorbar() # cb.ax.tick_params(labelsize=10) # cb.set_label('MNDWI values') # ax3.set_anchor('W') # if check_detection is True, let user manually accept/reject the images skip_image = False if settings['check_detection']: # set a key event to accept/reject the detections (see https://stackoverflow.com/a/15033071) # this variable needs to be immuatable so we can access it after the keypress event key_event = {} def press(event): # store what key was pressed in the dictionary key_event['pressed'] = event.key # let the user press a key, right arrow to keep the image, left arrow to skip it # to break the loop the user can press 'escape' while True: btn_keep = plt.text(1.1, 0.9, 'keep ⇨', size=12, ha="right", va="top", transform=ax1.transAxes, bbox=dict(boxstyle="square", ec='k',fc='w')) btn_skip = plt.text(-0.1, 0.9, '⇦ skip', size=12, ha="left", va="top", transform=ax1.transAxes, bbox=dict(boxstyle="square", ec='k',fc='w')) btn_esc = plt.text(0.5, 0, '<esc> to quit', size=12, ha="center", va="top", transform=ax1.transAxes, bbox=dict(boxstyle="square", ec='k',fc='w')) plt.draw() fig.canvas.mpl_connect('key_press_event', press) plt.waitforbuttonpress() # after button is pressed, remove the buttons btn_skip.remove() btn_keep.remove() btn_esc.remove() # keep/skip image according to the pressed key, 'escape' to break the loop if key_event.get('pressed') == 'right': skip_image = False break elif key_event.get('pressed') == 'left': skip_image = True break elif key_event.get('pressed') == 'escape': plt.close() raise StopIteration('User cancelled checking shoreline detection') else: plt.waitforbuttonpress() # if save_figure is True, save a .jpg under /jpg_files/detection if settings['save_figure'] and not skip_image: fig.savefig(os.path.join(filepath, date + '_' + satname + '.jpg'), dpi=150) # don't close the figure window, but remove all axes and settings, ready for next plot for ax in fig.axes: ax.clear() return skip_image def adjust_detection(im_ms, cloud_mask, im_labels, im_ref_buffer, image_epsg, georef, settings, date, satname, buffer_size_pixels): """ Advanced version of show detection where the user can adjust the detected shorelines with a slide bar. KV WRL 2020 Arguments: ----------- im_ms: np.array RGB + downsampled NIR and SWIR cloud_mask: np.array 2D cloud mask with True where cloud pixels are im_labels: np.array 3D image containing a boolean image for each class in the order (sand, swash, water) im_ref_buffer: np.array Binary image containing a buffer around the reference shoreline image_epsg: int spatial reference system of the image from which the contours were extracted georef: np.array vector of 6 elements [Xtr, Xscale, Xshear, Ytr, Yshear, Yscale] date: string date at which the image was taken satname: string indicates the satname (L5,L7,L8 or S2) buffer_size_pixels: int buffer_size converted to number of pixels settings: dict with the following keys 'inputs': dict input parameters (sitename, filepath, polygon, dates, sat_list) 'output_epsg': int output spatial reference system as EPSG code 'save_figure': bool if True, saves a -jpg file for each mapped shoreline Returns: ----------- skip_image: boolean True if the user wants to skip the image, False otherwise shoreline: np.array array of points with the X and Y coordinates of the shoreline t_mndwi: float value of the MNDWI threshold used to map the shoreline """ sitename = settings['inputs']['sitename'] filepath_data = settings['inputs']['filepath'] # subfolder where the .jpg file is stored if the user accepts the shoreline detection filepath = os.path.join(filepath_data, sitename, 'jpg_files', 'detection') # format date date_str = datetime.strptime(date,'%Y-%m-%d-%H-%M-%S').strftime('%Y-%m-%d %H:%M:%S') im_RGB = SDS_preprocess.rescale_image_intensity(im_ms[:,:,[2,1,0]], cloud_mask, 99.9) # compute classified image im_class = np.copy(im_RGB) cmap = cm.get_cmap('tab20c') colorpalette = cmap(np.arange(0,13,1)) colours = np.zeros((3,4)) colours[0,:] = colorpalette[5] colours[1,:] =
np.array([204/255,1,1,1])
numpy.array
__doc__ = """Snake friction case from <NAME> et. al. Nat. Comm. 2021""" """ This environment is constructed based on the PyElastica:ContinuumSnakeCase """ from typing import Optional from collections import defaultdict from functools import partial from tqdm import tqdm import gym from gym import error, spaces, utils from gym.utils import seeding from elastica import * from elastica.utils import _bspline import numpy as np from gym_softrobot.utils.render.continuum_snake_postprocessing import ( plot_snake_velocity, plot_video, plot_curvature, ) from gym_softrobot.utils.render.post_processing import plot_video def compute_projected_velocity(plot_params: dict, period): time_per_period = np.array(plot_params["time"]) / period avg_velocity = np.array(plot_params["avg_velocity"]) center_of_mass = np.array(plot_params["center_of_mass"]) # Compute rod velocity in rod direction. We need to compute that because, # after snake starts to move it chooses an arbitrary direction, which does not # have to be initial tangent direction of the rod. Thus we need to project the # snake velocity with respect to its new tangent and roll direction, after that # we will get the correct forward and lateral speed. After this projection # lateral velocity of the snake has to be oscillating between + and - values with # zero mean. # Number of steps in one period. period_step = int(1.0 / (time_per_period[-1] - time_per_period[-2])) number_of_period = int(time_per_period[-1]) if number_of_period-2 <= 0: return (0,0,0,0) # Center of mass position averaged in one period center_of_mass_averaged_over_one_period = np.zeros((number_of_period - 2, 3)) for i in range(1, number_of_period - 1): # position of center of mass averaged over one period center_of_mass_averaged_over_one_period[i - 1] = np.mean( center_of_mass[(i + 1) * period_step : (i + 2) * period_step] - center_of_mass[(i + 0) * period_step : (i + 1) * period_step], axis=0, ) # Average the rod directions over multiple periods and get the direction of the rod. direction_of_rod = np.mean(center_of_mass_averaged_over_one_period, axis=0) direction_of_rod /= np.linalg.norm(direction_of_rod, ord=2) # Compute the projected rod velocity in the direction of the rod velocity_mag_in_direction_of_rod = np.einsum( "ji,i->j", avg_velocity, direction_of_rod ) velocity_in_direction_of_rod = np.einsum( "j,i->ji", velocity_mag_in_direction_of_rod, direction_of_rod ) # Get the lateral or roll velocity of the rod after subtracting its projected # velocity in the direction of rod velocity_in_rod_roll_dir = avg_velocity - velocity_in_direction_of_rod # Compute the average velocity over the simulation, this can be used for optimizing snake # for fastest forward velocity. We start after first period, because of the ramping up happens # in first period. average_velocity_over_simulation = np.mean( velocity_in_direction_of_rod[period_step * 2 :], axis=0 ) return ( velocity_in_direction_of_rod, velocity_in_rod_roll_dir, average_velocity_over_simulation[2], average_velocity_over_simulation[0], ) class SnakeSimulator(BaseSystemCollection, Constraints, Forcing, CallBacks): pass class ContinuumSnakeCallBack(CallBackBaseClass): """ Call back function for continuum snake """ def __init__(self, step_skip: int, callback_params: dict): CallBackBaseClass.__init__(self) self.every = step_skip self.callback_params = callback_params def make_callback(self, system, time, current_step: int): if current_step % self.every == 0: self.callback_params["time"].append(time) self.callback_params["step"].append(current_step) self.callback_params["position"].append( system.position_collection.copy() ) self.callback_params["velocity"].append( system.velocity_collection.copy() ) self.callback_params["avg_velocity"].append( system.compute_velocity_center_of_mass() ) self.callback_params["center_of_mass"].append( system.compute_position_center_of_mass() ) self.callback_params["curvature"].append(system.kappa.copy()) return class ContinuumSnakeEnv(gym.Env): metadata = {'render.modes': ['rgb_array', 'human']} def __init__(self): # Action space action_space_low = -np.ones(7) * 1e-2; action_space_low[-1] = 0.5 action_space_high = np.ones(7) * 1e-2; action_space_high[-1] = 3.0 self.action_space = spaces.Box(action_space_low, action_space_high, dtype=np.float32) # State space self._n_elem = 50 observation_space = (((self._n_elem+1) * 3 * 2) + ((self._n_elem) * 9),) self.observation_space = spaces.Box(-np.inf, np.inf, shape=observation_space, dtype=np.float32) self.metadata = {} # Determinism self.seed() self.viewer = None self.rendere = None def seed(self, seed=None): # Deprecated in new gym self.np_random, seed = seeding.np_random(seed) return [seed] def reset( self, *, seed: Optional[int] = None, return_info: bool = False, options: Optional[dict] = None, ): super().reset(seed=seed) self.snake_sim, self.stepper, self.muscle_torque, self.data = self._build() self.time= np.float64(0.0) if return_info: return self.get_state(), {} else: return self.get_state() def get_state(self): # Build state rod = self.shearable_rod pos_state = rod.position_collection.ravel() vel_state = rod.velocity_collection.ravel() dir_state = rod.director_collection.ravel() return np.concatenate([pos_state, vel_state, dir_state], dtype=np.float32) def set_action(self, action): wave_length = action[-1] b_coeff = action[:-1] self.muscle_torque().__init__( base_length=self.base_length, b_coeff=b_coeff, period=self.period, wave_number=2.0 * np.pi / (wave_length), phase_shift=0.0, rest_lengths=self.shearable_rod.rest_lengths, ramp_up_time=self.period, direction=np.array([0.0, 1.0, 0.0]), with_spline=True, ) def step(self, action): err_msg = f"{action!r} ({type(action)}) invalid: expected {self.action_space}" assert self.action_space.contains(action), err_msg """ Set action """ self.set_action(action) """ Run simulation """ for _ in range(self.step_skip): self.time = self.stepper(time=self.time) # Compute the average forward velocity. These will be used for optimization. [_, _, avg_forward, avg_lateral] = compute_projected_velocity(self.data, self.period) done = False if self.time >= self.final_time: done = True info = {} return self.get_state(), avg_forward, done, info def render(self, mode='human', close=False): ''' filename_plot = "continuum_snake_velocity.png" plot_snake_velocity(self.data, self.period, filename_plot, 1) plot_curvature(self.data, self.shearable_rod.rest_lengths, self.period, 1) if SAVE_VIDEO: filename_video = "continuum_snake.mp4" plot_video( self.data, video_name=filename_video, fps=60, xlim=(0, 4), ylim=(-1, 1), ) ''' maxwidth = 800 aspect_ratio = (3/4) if self.viewer is None: from gym_softrobot.utils.render import pyglet_rendering from gym_softrobot.utils.render.povray_renderer import Session self.viewer = pyglet_rendering.SimpleImageViewer(maxwidth=maxwidth) self.renderer = Session(width=maxwidth, height=int(maxwidth*aspect_ratio)) self.renderer.add_rod(self.shearable_rod) # Temporary rendering to add side-view state_image = self.renderer.render(maxwidth, int(maxwidth*aspect_ratio*0.7)) state_image_side = self.renderer.render( maxwidth//2, int(maxwidth*aspect_ratio*0.3), camera_param=('location',[0.0, 0.0, -0.5],'look_at',[0.0,0,0]) ) state_image_top = self.renderer.render( maxwidth//2, int(maxwidth*aspect_ratio*0.3), camera_param=('location',[0.0, 0.3, 0.0],'look_at',[0.0,0,0]) ) state_image = np.vstack([ state_image, np.hstack([state_image_side, state_image_top]) ]) self.viewer.imshow(state_image) return state_image def close(self): pass def _build(self, include_callback:bool=False): # Initialize the simulation class snake_sim = SnakeSimulator() # Simulation parameters period = 2 self.period = period final_time = (11.0 + 0.01) * period self.final_time = final_time time_step = 8e-6 total_steps = int(final_time / time_step) rendering_fps = 5 step_skip = int(1.0 / (rendering_fps * time_step)) self.step_skip = step_skip callback_step_skip = int(1.0 / (60 * time_step)) # setting up test params n_elem = self._n_elem start = np.zeros((3,)) direction = np.array([0.0, 0.0, 1.0]) normal = np.array([0.0, 1.0, 0.0]) base_length = 0.35 self.base_length = base_length base_radius = base_length * 0.011 density = 1000 nu = 1e-4 E = 1e6 poisson_ratio = 0.5 shear_modulus = E / (poisson_ratio + 1.0) # Add rod self.shearable_rod = CosseratRod.straight_rod( n_elem, start, direction, normal, base_length, base_radius, density, nu, E, shear_modulus=shear_modulus, ) snake_sim.append(self.shearable_rod) # Add gravitational forces gravitational_acc = -9.80665 snake_sim.add_forcing_to(self.shearable_rod).using( GravityForces, acc_gravity=np.array([0.0, gravitational_acc, 0.0]) ) # Add muscle torques wave_length = 1 muscle_torque = snake_sim.add_forcing_to(self.shearable_rod).using( MuscleTorques, base_length=base_length, b_coeff=np.zeros(4), period=period, wave_number=2.0 * np.pi / (wave_length), phase_shift=0.0, rest_lengths=self.shearable_rod.rest_lengths, ramp_up_time=period, direction=normal, with_spline=True, ) # Add friction forces origin_plane =
np.array([0.0, -base_radius, 0.0])
numpy.array
#!/usr/bin/python # -*- coding: utf-8 -*- # # This file is part of pyunicorn. # Copyright (C) 2008--2019 <NAME> and pyunicorn authors # URL: <http://www.pik-potsdam.de/members/donges/software> # License: BSD (3-clause) # # Please acknowledge and cite the use of this software and its authors # when results are used in publications or published elsewhere. # # You can use the following reference: # <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, # <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, # and <NAME>, "Unified functional network and nonlinear time series analysis # for complex systems science: The pyunicorn package" """ Provides classes for analyzing spatially embedded complex networks, handling multivariate data and generating time series surrogates. Written by <NAME>. CMSI Method Reference: [Pompe2011]_ """ # array object and fast numerics import numpy # # Define class CouplingAnalysisPurePython # class CouplingAnalysisPurePython: """ Contains methods to calculate coupling matrices from large arrays of scalar time series. Comprises linear and information theoretic measures, lagged and directed (causal) couplings. """ # # Definitions of internal methods # def __init__(self, dataarray, only_tri=False, silence_level=0): """ Initialize an instance of CouplingAnalysisPurePython. Possible choices for only_tri: - "True" will calculate only the upper triangle of the coupling matrix, excluding the diagonal, assuming symmetry (not for directed measures) - "False" will calculate the whole matrix (asymmetry somes from different integration ranges) :type dataarray: 4D, 3D or 2D Numpy array [time, index, index] or [time, index] :arg dataarray: The time series array with time in first dimension :arg bool only_tri: Symmetric/asymmetric assumption on coupling matrix. :arg int silence_level: The inverse level of verbosity of the object. """ # only_tri will calculate the upper triangle excluding the diagonal # only. This assumes stationarity on the time series self.only_tri = only_tri # Set silence level self.silence_level = silence_level # Flatten observable anomaly array along lon/lat dimension to allow # for more convinient indexing and transpose the whole array as this # is faster in loops if numpy.ndim(dataarray) == 4: (self.total_time, n_lev, n_lat, n_lon) = dataarray.shape self.N = n_lev * n_lat * n_lon self.dataarray = numpy.\ fastCopyAndTranspose(dataarray.reshape(-1, self.N)) if numpy.ndim(dataarray) == 3: (self.total_time, n_lat, n_lon) = dataarray.shape self.N = n_lat * n_lon self.dataarray = numpy.\ fastCopyAndTranspose(dataarray.reshape(-1, self.N)) elif numpy.ndim(dataarray) == 2: (self.total_time, self.N) = dataarray.shape self.dataarray = numpy.fastCopyAndTranspose(dataarray) else: print("irregular array shape...") self.dataarray = numpy.fastCopyAndTranspose(dataarray) # factorials below 10 in a list for permutation patterns self.factorial = \ numpy.array([1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]) self.patternized = False self.has_fft = False self.originalFFT = None # lag_mode dict self.lag_modi = {"all": 0, "sum": 1, "max": 2} def __str__(self): """ Return a string representation of the CouplingAnalysisPurePython object. """ shape = self.dataarray.shape return 'CouplingAnalysisPurePython: %i variables, %i timesteps.' % ( shape[0], shape[1]) # # Define methods to calculate correlation strength and lags # # # Routines for calculating Cross Correlation # def cross_correlation(self, tau_max=0, lag_mode='all'): """ Returns the normalized cross correlation from all pairs of nodes from a range of time lags. The calculation ranges are shown below:: (-------------------------total_time--------------------------) (---tau_max---)(---------corr_range------------)(---tau_max---) CC is calculated about corr_range and with the other time series shifted by tau Possible choices for lag_mode: - "all" will return the full function for all lags, possible large memory need if only_tri is True, only the upper triangle contains the values, the lower one is zeros - "sum" will return the sum over positive and negative lags seperatly, each inclunding tau=0 corrmat[0] is the positive sum, corrmat[1] the negative sum - "max" will return only the maximum coupling (in corrmat[0]) and its lag (in corrmat[1]) :arg int tau_max: maximum lag in both directions, including last lag :arg str lag_mode: the output mode :rtype: 3D numpy array (float) [index, index, index] :return: correlation matrix with different lag_mode choices """ # Normalize anomaly time series to zero mean and unit variance for all # lags, array contains normalizations for all lags corr_range = self.total_time - 2*tau_max normalized_array = numpy.empty((2*tau_max + 1, self.N, corr_range), dtype="float32") for t in range(2*tau_max + 1): # Remove mean value from time series at each vertex (grid point) normalized_array[t] = self.dataarray[:, t:t+corr_range] - \ self.dataarray[:, t:t+corr_range].\ mean(axis=1).reshape(self.N, 1) # Normalize the variance of anomalies to one normalized_array[t] /= normalized_array[t].\ std(axis=1).reshape(self.N, 1) # Correct for grid points with zero variance in their time series normalized_array[t][numpy.isnan(normalized_array[t])] = 0 return self._calculate_cc(normalized_array, corr_range=corr_range, tau_max=tau_max, lag_mode=lag_mode) def shuffled_surrogate_for_cc(self, fourier=False, tau_max=1, lag_mode='all'): """ Returns a correlation matrix calculated with an independently shuffled surrogate of the dataarray of length corr_range for all taus. :arg int corr_range: length of sample :arg int tau_max: maximum lag in both directions, including last lag :arg str lag_mode: output mode :rtype: 3D numpy array (float) [index, index, index] :return: correlation matrix with different lag_mode choices """ corr_range = self.total_time - 2*tau_max # Shuffle a copy of dataarray separatly for each node array = numpy.copy(self.dataarray) if fourier: array = self.correlatedNoiseSurrogates(array) else: for i in range(self.N): numpy.random.shuffle(array[i]) sample_array = numpy.zeros((1, self.N, corr_range), dtype="float32") sample_array[0] = array[:, :corr_range] sample_array[0] -= sample_array[0].mean(axis=1).reshape(self.N, 1) sample_array[0] /= sample_array[0].std(axis=1).reshape(self.N, 1) sample_array[0, numpy.isnan(sample_array[0])] = 0 res = self._calculate_cc(sample_array, corr_range=corr_range, tau_max=0, lag_mode='all') if lag_mode == 'all': corrmat = numpy.repeat(res, 2*tau_max + 1, axis=0) elif lag_mode == 'sum': corrmat = numpy.array([abs(res[0]), abs(res[0])]) * (tau_max+1.) elif lag_mode == 'max': corrmat = numpy.array([abs(res[0]), numpy.random.randint(-tau_max, tau_max+1, (self.N, self.N))]) return corrmat def time_surrogate_for_cc(self, sample_range=100, tau_max=1, lag_mode='all'): """ Returns a joint shuffled surrogate of the full dataarray of length sample_range for all taus. Used for time evolution analysis. First one initializes the CouplingAnalysis class with the full dataarray and then this function is called for every single surrogate. :arg int sample_range: length of sample :arg int tau_max: maximum lag in both directions, including last lag :arg str lag_mode: output mode :rtype: 3D numpy array (float) [index, index, index] :return: correlation matrix with different lag_mode choices """ perm = numpy.random.permutation( range(tau_max, self.total_time - tau_max))[:sample_range] sample_array = numpy.empty((2*tau_max + 1, self.N, sample_range), dtype="float32") for t in range(2 * tau_max + 1): tau = t - tau_max sample_array[t] = self.dataarray[:, perm + tau] sample_array[t] -= sample_array[t].mean(axis=1).reshape(self.N, 1) sample_array[t] /= sample_array[t].std(axis=1).reshape(self.N, 1) sample_array[t][numpy.isnan(sample_array[t])] = 0 return self._calculate_cc(sample_array, corr_range=sample_range, tau_max=tau_max, lag_mode=lag_mode) def _calculate_cc(self, array, corr_range, tau_max, lag_mode): """ Returns the CC matrix. :arg int tau_max: maximum lag in both directions, including last lag :arg str lag_mode: output mode :rtype: 3D numpy array (float) [index, index, index] :return: correlation matrix with different lag_mode choices ## lag_mode dict mode = self.lag_modi[lag_mode] """ # lag_mode dict mode = self.lag_modi[lag_mode] only_tri = int(self.only_tri) if lag_mode == 'all': corrmat = numpy.zeros((2*tau_max + 1, self.N, self.N), dtype='float32') elif lag_mode == 'sum': corrmat = numpy.zeros((2, self.N, self.N), dtype='float32') elif lag_mode == 'max': corrmat = numpy.zeros((2, self.N, self.N), dtype='float32') # loop over all node pairs, NOT symmetric due to time shifts! for i in range(self.N-only_tri): for j in range((i+1)*only_tri, self.N): if mode == 2: maxcross = 0.0 argmax = 0 # loop over taus INCLUDING the last tau value for t in range(2*tau_max+1): # here the actual cross correlation is calculated crossij = (array[tau_max, i, :] * array[t, j, :]).mean() # fill in values in matrix depending on lag_mode if mode == 0: corrmat[t, i, j] = crossij elif mode == 1: if t <= tau_max: corrmat[1, i, j] += numpy.abs(crossij) if t >= tau_max: corrmat[0, i, j] += numpy.abs(crossij) elif mode == 2: # calculate max and argmax by comparing to previous # value and storing max if
numpy.abs(crossij)
numpy.abs
import numpy as np def VGGPreprocessing(originImgMatrix): "The only preprocessing we do is subtracting the mean RGB value, \ computed on the training set, from each pixel.\ 原论文中对输入的RGB矩阵做了一个减去均值的预处理,该函数实现这个预处理" if type(originImgMatrix) is not np.ndarray: originImgMatrix =
np.ndarray(originImgMatrix)
numpy.ndarray
# -*- coding: utf-8 -*- import sys sys.path.append('..') import numpy as np import vectorflow as vf male_heights = np.random.normal(171, 6, 500) female_heights = np.random.normal(158, 5, 500) male_weights = np.random.normal(70, 10, 500) female_weights = np.random.normal(57, 8, 500) male_bfrs = np.random.normal(16, 2, 500) female_bfrs = np.random.normal(22, 2, 500) male_labels = [1] * 500 female_labels = [-1] * 500 train_set = np.array([np.concatenate((male_heights, female_heights)), np.concatenate((male_weights, female_weights)), np.concatenate((male_bfrs, female_bfrs)), np.concatenate((male_labels, female_labels))]).T # 随机打乱样本顺序 np.random.shuffle(train_set) # 构造计算图:输入向量,是一个3x1矩阵,不需要初始化,不参与训练 x = vf.core.Variable(dim=(3, 1), init=False, trainable=False) # 类别标签,1男,-1女 label = vf.core.Variable(dim=(1, 1), init=False, trainable=False) # 权值向量,是一个1x3矩阵,需要初始化,参与训练 w = vf.core.Variable(dim=(1, 3), init=True, trainable=True) # 偏置,是一个1x1矩阵,需要初始化,参与训练 b = vf.core.Variable(dim=(1, 1), init=True, trainable=True) # 预测输出 output = vf.operator.Add(vf.operator.MatMul(w, x), b) predict = vf.operator.Logistic(output) # 对数损失 loss = vf.loss.LogLoss(vf.operator.Multiply(label, output)) # 学习率 learning_rate = 0.0001 # 构造Adam优化器 optimizer = vf.optimizer.Adam(vf.default_graph, loss, learning_rate) # 批大小为16 batch_size = 16 # 训练执行50个epoch for epoch in range(50): # 批计数器清零 batch_count = 0 # 遍历训练集中的样本 for i in range(len(train_set)): # 取第i个样本的前3列,构造3x1矩阵对象 features = np.mat(train_set[i,:-1]).T # 取第i个样本的最后一列,是该样本的性别标签(1男,-1女),构造1x1矩阵对象 l =
np.mat(train_set[i,-1])
numpy.mat
# This module has been generated automatically from space group information # obtained from the Computational Crystallography Toolbox # """ Space groups This module contains a list of all the 230 space groups that can occur in a crystal. The variable space_groups contains a dictionary that maps space group numbers and space group names to the corresponding space group objects. .. moduleauthor:: <NAME> <<EMAIL>> """ #----------------------------------------------------------------------------- # Copyright (C) 2013 The Mosaic Development Team # # Distributed under the terms of the BSD License. The full license is in # the file LICENSE.txt, distributed as part of this software. #----------------------------------------------------------------------------- import numpy as N class SpaceGroup(object): """ Space group All possible space group objects are created in this module. Other modules should access these objects through the dictionary space_groups rather than create their own space group objects. """ def __init__(self, number, symbol, transformations): """ :param number: the number assigned to the space group by international convention :type number: int :param symbol: the Hermann-Mauguin space-group symbol as used in PDB and mmCIF files :type symbol: str :param transformations: a list of space group transformations, each consisting of a tuple of three integer arrays (rot, tn, td), where rot is the rotation matrix and tn/td are the numerator and denominator of the translation vector. The transformations are defined in fractional coordinates. :type transformations: list """ self.number = number self.symbol = symbol self.transformations = transformations self.transposed_rotations = N.array([N.transpose(t[0]) for t in transformations]) self.phase_factors = N.exp(N.array([(-2j*N.pi*t[1])/t[2] for t in transformations])) def __repr__(self): return "SpaceGroup(%d, %s)" % (self.number, repr(self.symbol)) def __len__(self): """ :return: the number of space group transformations :rtype: int """ return len(self.transformations) def symmetryEquivalentMillerIndices(self, hkl): """ :param hkl: a set of Miller indices :type hkl: Scientific.N.array_type :return: a tuple (miller_indices, phase_factor) of two arrays of length equal to the number of space group transformations. miller_indices contains the Miller indices of each reflection equivalent by symmetry to the reflection hkl (including hkl itself as the first element). phase_factor contains the phase factors that must be applied to the structure factor of reflection hkl to obtain the structure factor of the symmetry equivalent reflection. :rtype: tuple """ hkls = N.dot(self.transposed_rotations, hkl) p = N.multiply.reduce(self.phase_factors**hkl, -1) return hkls, p space_groups = {} transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(1, 'P 1', transformations) space_groups[1] = sg space_groups['P 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(2, 'P -1', transformations) space_groups[2] = sg space_groups['P -1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(3, 'P 1 2 1', transformations) space_groups[3] = sg space_groups['P 1 2 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(4, 'P 1 21 1', transformations) space_groups[4] = sg space_groups['P 1 21 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(5, 'C 1 2 1', transformations) space_groups[5] = sg space_groups['C 1 2 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(6, 'P 1 m 1', transformations) space_groups[6] = sg space_groups['P 1 m 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(7, 'P 1 c 1', transformations) space_groups[7] = sg space_groups['P 1 c 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(8, 'C 1 m 1', transformations) space_groups[8] = sg space_groups['C 1 m 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(9, 'C 1 c 1', transformations) space_groups[9] = sg space_groups['C 1 c 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(10, 'P 1 2/m 1', transformations) space_groups[10] = sg space_groups['P 1 2/m 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(11, 'P 1 21/m 1', transformations) space_groups[11] = sg space_groups['P 1 21/m 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(12, 'C 1 2/m 1', transformations) space_groups[12] = sg space_groups['C 1 2/m 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(13, 'P 1 2/c 1', transformations) space_groups[13] = sg space_groups['P 1 2/c 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(14, 'P 1 21/c 1', transformations) space_groups[14] = sg space_groups['P 1 21/c 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(15, 'C 1 2/c 1', transformations) space_groups[15] = sg space_groups['C 1 2/c 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(16, 'P 2 2 2', transformations) space_groups[16] = sg space_groups['P 2 2 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(17, 'P 2 2 21', transformations) space_groups[17] = sg space_groups['P 2 2 21'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(18, 'P 21 21 2', transformations) space_groups[18] = sg space_groups['P 21 21 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(19, 'P 21 21 21', transformations) space_groups[19] = sg space_groups['P 21 21 21'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(20, 'C 2 2 21', transformations) space_groups[20] = sg space_groups['C 2 2 21'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(21, 'C 2 2 2', transformations) space_groups[21] = sg space_groups['C 2 2 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(22, 'F 2 2 2', transformations) space_groups[22] = sg space_groups['F 2 2 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(23, 'I 2 2 2', transformations) space_groups[23] = sg space_groups['I 2 2 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(24, 'I 21 21 21', transformations) space_groups[24] = sg space_groups['I 21 21 21'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(25, 'P m m 2', transformations) space_groups[25] = sg space_groups['P m m 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(26, 'P m c 21', transformations) space_groups[26] = sg space_groups['P m c 21'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(27, 'P c c 2', transformations) space_groups[27] = sg space_groups['P c c 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(28, 'P m a 2', transformations) space_groups[28] = sg space_groups['P m a 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(29, 'P c a 21', transformations) space_groups[29] = sg space_groups['P c a 21'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(30, 'P n c 2', transformations) space_groups[30] = sg space_groups['P n c 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(31, 'P m n 21', transformations) space_groups[31] = sg space_groups['P m n 21'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(32, 'P b a 2', transformations) space_groups[32] = sg space_groups['P b a 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(33, 'P n a 21', transformations) space_groups[33] = sg space_groups['P n a 21'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(34, 'P n n 2', transformations) space_groups[34] = sg space_groups['P n n 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(35, 'C m m 2', transformations) space_groups[35] = sg space_groups['C m m 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(36, 'C m c 21', transformations) space_groups[36] = sg space_groups['C m c 21'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(37, 'C c c 2', transformations) space_groups[37] = sg space_groups['C c c 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(38, 'A m m 2', transformations) space_groups[38] = sg space_groups['A m m 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(39, 'A b m 2', transformations) space_groups[39] = sg space_groups['A b m 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(40, 'A m a 2', transformations) space_groups[40] = sg space_groups['A m a 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(41, 'A b a 2', transformations) space_groups[41] = sg space_groups['A b a 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(42, 'F m m 2', transformations) space_groups[42] = sg space_groups['F m m 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,3,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,3,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([3,1,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([3,1,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([3,3,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([3,3,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(43, 'F d d 2', transformations) space_groups[43] = sg space_groups['F d d 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(44, 'I m m 2', transformations) space_groups[44] = sg space_groups['I m m 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(45, 'I b a 2', transformations) space_groups[45] = sg space_groups['I b a 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(46, 'I m a 2', transformations) space_groups[46] = sg space_groups['I m a 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(47, 'P m m m', transformations) space_groups[47] = sg space_groups['P m m m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(48, 'P n n n :2', transformations) space_groups[48] = sg space_groups['P n n n :2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(49, 'P c c m', transformations) space_groups[49] = sg space_groups['P c c m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(50, 'P b a n :2', transformations) space_groups[50] = sg space_groups['P b a n :2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(51, 'P m m a', transformations) space_groups[51] = sg space_groups['P m m a'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(52, 'P n n a', transformations) space_groups[52] = sg space_groups['P n n a'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(53, 'P m n a', transformations) space_groups[53] = sg space_groups['P m n a'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(54, 'P c c a', transformations) space_groups[54] = sg space_groups['P c c a'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(55, 'P b a m', transformations) space_groups[55] = sg space_groups['P b a m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(56, 'P c c n', transformations) space_groups[56] = sg space_groups['P c c n'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(57, 'P b c m', transformations) space_groups[57] = sg space_groups['P b c m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(58, 'P n n m', transformations) space_groups[58] = sg space_groups['P n n m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(59, 'P m m n :2', transformations) space_groups[59] = sg space_groups['P m m n :2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(60, 'P b c n', transformations) space_groups[60] = sg space_groups['P b c n'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(61, 'P b c a', transformations) space_groups[61] = sg space_groups['P b c a'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(62, 'P n m a', transformations) space_groups[62] = sg space_groups['P n m a'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(63, 'C m c m', transformations) space_groups[63] = sg space_groups['C m c m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(64, 'C m c a', transformations) space_groups[64] = sg space_groups['C m c a'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(65, 'C m m m', transformations) space_groups[65] = sg space_groups['C m m m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(66, 'C c c m', transformations) space_groups[66] = sg space_groups['C c c m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(67, 'C m m a', transformations) space_groups[67] = sg space_groups['C m m a'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(68, 'C c c a :2', transformations) space_groups[68] = sg space_groups['C c c a :2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(69, 'F m m m', transformations) space_groups[69] = sg space_groups['F m m m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([4,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([4,4,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([4,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([4,4,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,3,3]) trans_den = N.array([1,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,3]) trans_den = N.array([4,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,3,1]) trans_den = N.array([4,4,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,1,1]) trans_den = N.array([4,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,1,1]) trans_den = N.array([4,4,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,3]) trans_den = N.array([2,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([3,0,3]) trans_den = N.array([4,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([3,1,1]) trans_den = N.array([4,4,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,-1,1]) trans_den = N.array([2,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([4,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,-1,1]) trans_den = N.array([4,4,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,3,1]) trans_den = N.array([2,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([3,1,1]) trans_den = N.array([4,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([3,3,0]) trans_den = N.array([4,4,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,-1]) trans_den = N.array([2,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,-1]) trans_den = N.array([4,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([4,4,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(70, 'F d d d :2', transformations) space_groups[70] = sg space_groups['F d d d :2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(71, 'I m m m', transformations) space_groups[71] = sg space_groups['I m m m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(72, 'I b a m', transformations) space_groups[72] = sg space_groups['I b a m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(73, 'I b c a', transformations) space_groups[73] = sg space_groups['I b c a'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(74, 'I m m a', transformations) space_groups[74] = sg space_groups['I m m a'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(75, 'P 4', transformations) space_groups[75] = sg space_groups['P 4'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,3]) trans_den = N.array([1,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(76, 'P 41', transformations) space_groups[76] = sg space_groups['P 41'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(77, 'P 42', transformations) space_groups[77] = sg space_groups['P 42'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,3]) trans_den = N.array([1,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(78, 'P 43', transformations) space_groups[78] = sg space_groups['P 43'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(79, 'I 4', transformations) space_groups[79] = sg space_groups['I 4'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,3]) trans_den = N.array([2,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,3]) trans_den = N.array([2,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,5]) trans_den = N.array([1,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,5]) trans_den = N.array([1,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(80, 'I 41', transformations) space_groups[80] = sg space_groups['I 41'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(81, 'P -4', transformations) space_groups[81] = sg space_groups['P -4'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(82, 'I -4', transformations) space_groups[82] = sg space_groups['I -4'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(83, 'P 4/m', transformations) space_groups[83] = sg space_groups['P 4/m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(84, 'P 42/m', transformations) space_groups[84] = sg space_groups['P 42/m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(85, 'P 4/n :2', transformations) space_groups[85] = sg space_groups['P 4/n :2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(86, 'P 42/n :2', transformations) space_groups[86] = sg space_groups['P 42/n :2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(87, 'I 4/m', transformations) space_groups[87] = sg space_groups['I 4/m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,3,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-3,-3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([3,5,5]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([3,3,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,-1,-1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(88, 'I 41/a :2', transformations) space_groups[88] = sg space_groups['I 41/a :2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(89, 'P 4 2 2', transformations) space_groups[89] = sg space_groups['P 4 2 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(90, 'P 4 21 2', transformations) space_groups[90] = sg space_groups['P 4 21 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,3]) trans_den = N.array([1,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,3]) trans_den = N.array([1,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,4]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(91, 'P 41 2 2', transformations) space_groups[91] = sg space_groups['P 41 2 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,3]) trans_den = N.array([2,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,3]) trans_den = N.array([2,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(92, 'P 41 21 2', transformations) space_groups[92] = sg space_groups['P 41 21 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(93, 'P 42 2 2', transformations) space_groups[93] = sg space_groups['P 42 2 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(94, 'P 42 21 2', transformations) space_groups[94] = sg space_groups['P 42 21 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,3]) trans_den = N.array([1,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,3]) trans_den = N.array([1,1,4]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(95, 'P 43 2 2', transformations) space_groups[95] = sg space_groups['P 43 2 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,3]) trans_den = N.array([2,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,3]) trans_den = N.array([2,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(96, 'P 43 21 2', transformations) space_groups[96] = sg space_groups['P 43 21 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(97, 'I 4 2 2', transformations) space_groups[97] = sg space_groups['I 4 2 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,3]) trans_den = N.array([2,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,3]) trans_den = N.array([2,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,3]) trans_den = N.array([2,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,3]) trans_den = N.array([2,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,5]) trans_den = N.array([1,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,5]) trans_den = N.array([1,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,5]) trans_den = N.array([1,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,5]) trans_den = N.array([1,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(98, 'I 41 2 2', transformations) space_groups[98] = sg space_groups['I 41 2 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(99, 'P 4 m m', transformations) space_groups[99] = sg space_groups['P 4 m m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(100, 'P 4 b m', transformations) space_groups[100] = sg space_groups['P 4 b m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(101, 'P 42 c m', transformations) space_groups[101] = sg space_groups['P 42 c m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(102, 'P 42 n m', transformations) space_groups[102] = sg space_groups['P 42 n m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(103, 'P 4 c c', transformations) space_groups[103] = sg space_groups['P 4 c c'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(104, 'P 4 n c', transformations) space_groups[104] = sg space_groups['P 4 n c'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(105, 'P 42 m c', transformations) space_groups[105] = sg space_groups['P 42 m c'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(106, 'P 42 b c', transformations) space_groups[106] = sg space_groups['P 42 b c'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(107, 'I 4 m m', transformations) space_groups[107] = sg space_groups['I 4 m m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(108, 'I 4 c m', transformations) space_groups[108] = sg space_groups['I 4 c m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,3]) trans_den = N.array([2,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,3]) trans_den = N.array([2,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,3]) trans_den = N.array([2,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,3]) trans_den = N.array([2,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,5]) trans_den = N.array([1,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,5]) trans_den = N.array([1,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,5]) trans_den = N.array([1,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,5]) trans_den = N.array([1,2,4]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(109, 'I 41 m d', transformations) space_groups[109] = sg space_groups['I 41 m d'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,3]) trans_den = N.array([2,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,3]) trans_den = N.array([2,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,5]) trans_den = N.array([1,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,5]) trans_den = N.array([1,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,3]) trans_den = N.array([1,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,3]) trans_den = N.array([1,2,4]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(110, 'I 41 c d', transformations) space_groups[110] = sg space_groups['I 41 c d'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(111, 'P -4 2 m', transformations) space_groups[111] = sg space_groups['P -4 2 m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(112, 'P -4 2 c', transformations) space_groups[112] = sg space_groups['P -4 2 c'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(113, 'P -4 21 m', transformations) space_groups[113] = sg space_groups['P -4 21 m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(114, 'P -4 21 c', transformations) space_groups[114] = sg space_groups['P -4 21 c'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(115, 'P -4 m 2', transformations) space_groups[115] = sg space_groups['P -4 m 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(116, 'P -4 c 2', transformations) space_groups[116] = sg space_groups['P -4 c 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(117, 'P -4 b 2', transformations) space_groups[117] = sg space_groups['P -4 b 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(118, 'P -4 n 2', transformations) space_groups[118] = sg space_groups['P -4 n 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(119, 'I -4 m 2', transformations) space_groups[119] = sg space_groups['I -4 m 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(120, 'I -4 c 2', transformations) space_groups[120] = sg space_groups['I -4 c 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(121, 'I -4 2 m', transformations) space_groups[121] = sg space_groups['I -4 2 m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,3]) trans_den = N.array([2,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,3]) trans_den = N.array([2,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,3]) trans_den = N.array([2,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,3]) trans_den = N.array([2,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,5]) trans_den = N.array([1,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,5]) trans_den = N.array([1,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,5]) trans_den = N.array([1,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,5]) trans_den = N.array([1,2,4]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(122, 'I -4 2 d', transformations) space_groups[122] = sg space_groups['I -4 2 d'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(123, 'P 4/m m m', transformations) space_groups[123] = sg space_groups['P 4/m m m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(124, 'P 4/m c c', transformations) space_groups[124] = sg space_groups['P 4/m c c'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(125, 'P 4/n b m :2', transformations) space_groups[125] = sg space_groups['P 4/n b m :2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(126, 'P 4/n n c :2', transformations) space_groups[126] = sg space_groups['P 4/n n c :2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(127, 'P 4/m b m', transformations) space_groups[127] = sg space_groups['P 4/m b m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(128, 'P 4/m n c', transformations) space_groups[128] = sg space_groups['P 4/m n c'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(129, 'P 4/n m m :2', transformations) space_groups[129] = sg space_groups['P 4/n m m :2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(130, 'P 4/n c c :2', transformations) space_groups[130] = sg space_groups['P 4/n c c :2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(131, 'P 42/m m c', transformations) space_groups[131] = sg space_groups['P 42/m m c'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(132, 'P 42/m c m', transformations) space_groups[132] = sg space_groups['P 42/m c m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(133, 'P 42/n b c :2', transformations) space_groups[133] = sg space_groups['P 42/n b c :2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(134, 'P 42/n n m :2', transformations) space_groups[134] = sg space_groups['P 42/n n m :2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(135, 'P 42/m b c', transformations) space_groups[135] = sg space_groups['P 42/m b c'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(136, 'P 42/m n m', transformations) space_groups[136] = sg space_groups['P 42/m n m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(137, 'P 42/n m c :2', transformations) space_groups[137] = sg space_groups['P 42/n m c :2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(138, 'P 42/n c m :2', transformations) space_groups[138] = sg space_groups['P 42/n c m :2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(139, 'I 4/m m m', transformations) space_groups[139] = sg space_groups['I 4/m m m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(140, 'I 4/m c m', transformations) space_groups[140] = sg space_groups['I 4/m c m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,3,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,3,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-3,-1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-3,-1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([3,5,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([3,3,5]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([3,5,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([3,3,5]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,-1,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,-1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,-1,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,-1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(141, 'I 41/a m d :2', transformations) space_groups[141] = sg space_groups['I 41/a m d :2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,3,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,3,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-3,-1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-3,-3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([3,5,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([3,3,5]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([3,5,5]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([3,3,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,-1,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,-1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,-1,-1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(142, 'I 41/a c d :2', transformations) space_groups[142] = sg space_groups['I 41/a c d :2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(143, 'P 3', transformations) space_groups[143] = sg space_groups['P 3'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,2]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(144, 'P 31', transformations) space_groups[144] = sg space_groups['P 31'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,2]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(145, 'P 32', transformations) space_groups[145] = sg space_groups['P 32'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(146, 'R 3 :H', transformations) space_groups[146] = sg space_groups['R 3 :H'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(147, 'P -3', transformations) space_groups[147] = sg space_groups['P -3'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(148, 'R -3 :H', transformations) space_groups[148] = sg space_groups['R -3 :H'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(149, 'P 3 1 2', transformations) space_groups[149] = sg space_groups['P 3 1 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(150, 'P 3 2 1', transformations) space_groups[150] = sg space_groups['P 3 2 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,2]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,2]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(151, 'P 31 1 2', transformations) space_groups[151] = sg space_groups['P 31 1 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,2]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,2]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(152, 'P 31 2 1', transformations) space_groups[152] = sg space_groups['P 31 2 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,2]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,2]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(153, 'P 32 1 2', transformations) space_groups[153] = sg space_groups['P 32 1 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,2]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,2]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(154, 'P 32 2 1', transformations) space_groups[154] = sg space_groups['P 32 2 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(155, 'R 3 2 :H', transformations) space_groups[155] = sg space_groups['R 3 2 :H'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(156, 'P 3 m 1', transformations) space_groups[156] = sg space_groups['P 3 m 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(157, 'P 3 1 m', transformations) space_groups[157] = sg space_groups['P 3 1 m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(158, 'P 3 c 1', transformations) space_groups[158] = sg space_groups['P 3 c 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(159, 'P 3 1 c', transformations) space_groups[159] = sg space_groups['P 3 1 c'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(160, 'R 3 m :H', transformations) space_groups[160] = sg space_groups['R 3 m :H'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,7]) trans_den = N.array([3,3,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,7]) trans_den = N.array([3,3,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,7]) trans_den = N.array([3,3,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,5]) trans_den = N.array([3,3,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,5]) trans_den = N.array([3,3,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,5]) trans_den = N.array([3,3,6]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(161, 'R 3 c :H', transformations) space_groups[161] = sg space_groups['R 3 c :H'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(162, 'P -3 1 m', transformations) space_groups[162] = sg space_groups['P -3 1 m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(163, 'P -3 1 c', transformations) space_groups[163] = sg space_groups['P -3 1 c'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(164, 'P -3 m 1', transformations) space_groups[164] = sg space_groups['P -3 m 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(165, 'P -3 c 1', transformations) space_groups[165] = sg space_groups['P -3 c 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(166, 'R -3 m :H', transformations) space_groups[166] = sg space_groups['R -3 m :H'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,2,7]) trans_den = N.array([3,3,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,2,7]) trans_den = N.array([3,3,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,2,7]) trans_den = N.array([3,3,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,2,2]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,1]) trans_den = N.array([3,3,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,1]) trans_den = N.array([3,3,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,2,1]) trans_den = N.array([3,3,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([2,1,5]) trans_den = N.array([3,3,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([2,1,5]) trans_den = N.array([3,3,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([2,1,5]) trans_den = N.array([3,3,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([2,1,1]) trans_den = N.array([3,3,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,-1]) trans_den = N.array([3,3,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,-1]) trans_den = N.array([3,3,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([2,1,-1]) trans_den = N.array([3,3,6]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(167, 'R -3 c :H', transformations) space_groups[167] = sg space_groups['R -3 c :H'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(168, 'P 6', transformations) space_groups[168] = sg space_groups['P 6'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,5]) trans_den = N.array([1,1,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,2]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(169, 'P 61', transformations) space_groups[169] = sg space_groups['P 61'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,5]) trans_den = N.array([1,1,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,2]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(170, 'P 65', transformations) space_groups[170] = sg space_groups['P 65'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,2]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,2]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(171, 'P 62', transformations) space_groups[171] = sg space_groups['P 62'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,2]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,2]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(172, 'P 64', transformations) space_groups[172] = sg space_groups['P 64'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(173, 'P 63', transformations) space_groups[173] = sg space_groups['P 63'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(174, 'P -6', transformations) space_groups[174] = sg space_groups['P -6'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(175, 'P 6/m', transformations) space_groups[175] = sg space_groups['P 6/m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(176, 'P 63/m', transformations) space_groups[176] = sg space_groups['P 63/m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(177, 'P 6 2 2', transformations) space_groups[177] = sg space_groups['P 6 2 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,5]) trans_den = N.array([1,1,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,2]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,2]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,5]) trans_den = N.array([1,1,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,6]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(178, 'P 61 2 2', transformations) space_groups[178] = sg space_groups['P 61 2 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,5]) trans_den = N.array([1,1,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,2]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,2]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,6]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,5]) trans_den = N.array([1,1,6]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(179, 'P 65 2 2', transformations) space_groups[179] = sg space_groups['P 65 2 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,2]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,2]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,2]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,2]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(180, 'P 62 2 2', transformations) space_groups[180] = sg space_groups['P 62 2 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,2]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,2]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,2]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,2]) trans_den = N.array([1,1,3]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(181, 'P 64 2 2', transformations) space_groups[181] = sg space_groups['P 64 2 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(182, 'P 63 2 2', transformations) space_groups[182] = sg space_groups['P 63 2 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(183, 'P 6 m m', transformations) space_groups[183] = sg space_groups['P 6 m m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(184, 'P 6 c c', transformations) space_groups[184] = sg space_groups['P 6 c c'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(185, 'P 63 c m', transformations) space_groups[185] = sg space_groups['P 63 c m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(186, 'P 63 m c', transformations) space_groups[186] = sg space_groups['P 63 m c'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(187, 'P -6 m 2', transformations) space_groups[187] = sg space_groups['P -6 m 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(188, 'P -6 c 2', transformations) space_groups[188] = sg space_groups['P -6 c 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(189, 'P -6 2 m', transformations) space_groups[189] = sg space_groups['P -6 2 m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(190, 'P -6 2 c', transformations) space_groups[190] = sg space_groups['P -6 2 c'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(191, 'P 6/m m m', transformations) space_groups[191] = sg space_groups['P 6/m m m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(192, 'P 6/m c c', transformations) space_groups[192] = sg space_groups['P 6/m c c'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(193, 'P 63/m c m', transformations) space_groups[193] = sg space_groups['P 63/m c m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,1,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,1,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,-1,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,-1,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(194, 'P 63/m m c', transformations) space_groups[194] = sg space_groups['P 63/m m c'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(195, 'P 2 3', transformations) space_groups[195] = sg space_groups['P 2 3'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(196, 'F 2 3', transformations) space_groups[196] = sg space_groups['F 2 3'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(197, 'I 2 3', transformations) space_groups[197] = sg space_groups['I 2 3'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(198, 'P 21 3', transformations) space_groups[198] = sg space_groups['P 21 3'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(199, 'I 21 3', transformations) space_groups[199] = sg space_groups['I 21 3'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(200, 'P m -3', transformations) space_groups[200] = sg space_groups['P m -3'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(201, 'P n -3 :2', transformations) space_groups[201] = sg space_groups['P n -3 :2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(202, 'F m -3', transformations) space_groups[202] = sg space_groups['F m -3'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([4,4,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([4,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([4,4,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([4,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([4,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([4,4,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([4,4,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([4,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([4,4,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([4,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([4,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([4,4,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,3,1]) trans_den = N.array([4,4,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,3,3]) trans_den = N.array([1,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,3]) trans_den = N.array([4,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,3,1]) trans_den = N.array([4,4,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,3]) trans_den = N.array([4,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,3,3]) trans_den = N.array([1,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,3,3]) trans_den = N.array([1,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,3]) trans_den = N.array([4,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,3,1]) trans_den = N.array([4,4,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([-1,1,1]) trans_den = N.array([4,4,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([-1,1,1]) trans_den = N.array([4,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([-1,1,1]) trans_den = N.array([4,4,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([-1,1,1]) trans_den = N.array([4,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,1,1]) trans_den = N.array([4,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,1,1]) trans_den = N.array([4,4,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([3,1,1]) trans_den = N.array([4,4,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,3]) trans_den = N.array([2,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([3,0,3]) trans_den = N.array([4,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([3,1,1]) trans_den = N.array([4,4,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([3,0,3]) trans_den = N.array([4,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,3]) trans_den = N.array([2,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,3]) trans_den = N.array([2,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([3,0,3]) trans_den = N.array([4,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([3,1,1]) trans_den = N.array([4,4,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,-1,1]) trans_den = N.array([4,4,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,-1,1]) trans_den = N.array([2,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([4,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,-1,1]) trans_den = N.array([4,4,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([4,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,-1,1]) trans_den = N.array([2,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,-1,1]) trans_den = N.array([2,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([4,1,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,-1,1]) trans_den = N.array([4,4,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([3,3,0]) trans_den = N.array([4,4,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,3,1]) trans_den = N.array([2,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([3,1,1]) trans_den = N.array([4,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([3,3,0]) trans_den = N.array([4,4,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([3,1,1]) trans_den = N.array([4,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,3,1]) trans_den = N.array([2,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,3,1]) trans_den = N.array([2,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([3,1,1]) trans_den = N.array([4,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([3,3,0]) trans_den = N.array([4,4,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([4,4,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,-1]) trans_den = N.array([2,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,-1]) trans_den = N.array([4,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([4,4,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,-1]) trans_den = N.array([4,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,-1]) trans_den = N.array([2,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,-1]) trans_den = N.array([2,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,-1]) trans_den = N.array([4,2,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([4,4,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(203, 'F d -3 :2', transformations) space_groups[203] = sg space_groups['F d -3 :2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(204, 'I m -3', transformations) space_groups[204] = sg space_groups['I m -3'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(205, 'P a -3', transformations) space_groups[205] = sg space_groups['P a -3'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(206, 'I a -3', transformations) space_groups[206] = sg space_groups['I a -3'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(207, 'P 4 3 2', transformations) space_groups[207] = sg space_groups['P 4 3 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(208, 'P 42 3 2', transformations) space_groups[208] = sg space_groups['P 42 3 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(209, 'F 4 3 2', transformations) space_groups[209] = sg space_groups['F 4 3 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,3,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,3,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,3,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,3,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,3,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,3,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,3,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,3,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,3,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,3,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,3,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,3,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([3,1,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([3,1,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([3,1,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([3,1,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([3,1,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([3,1,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([3,1,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([3,1,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([3,1,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([3,1,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([3,1,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([3,1,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([3,3,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([3,3,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([3,3,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([3,3,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([3,3,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([3,3,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([3,3,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([3,3,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([3,3,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([3,3,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([3,3,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([3,3,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(210, 'F 41 3 2', transformations) space_groups[210] = sg space_groups['F 41 3 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(211, 'I 4 3 2', transformations) space_groups[211] = sg space_groups['I 4 3 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([3,3,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,3,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,3,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([3,1,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([3,1,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([3,3,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,3,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([3,3,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([3,1,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(212, 'P 43 3 2', transformations) space_groups[212] = sg space_groups['P 43 3 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([3,1,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([3,1,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,3,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,3,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([3,1,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([3,3,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([3,3,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,3,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([3,3,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(213, 'P 41 3 2', transformations) space_groups[213] = sg space_groups['P 41 3 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,3,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,3,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,3,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,3,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,3,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,3,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([3,3,5]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([3,5,5]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([3,5,5]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([3,5,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([3,5,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([3,3,5]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([3,5,5]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([3,3,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([3,3,5]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([3,3,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([3,5,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([3,3,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(214, 'I 41 3 2', transformations) space_groups[214] = sg space_groups['I 41 3 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(215, 'P -4 3 m', transformations) space_groups[215] = sg space_groups['P -4 3 m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(216, 'F -4 3 m', transformations) space_groups[216] = sg space_groups['F -4 3 m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(217, 'I -4 3 m', transformations) space_groups[217] = sg space_groups['I -4 3 m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(218, 'P -4 3 n', transformations) space_groups[218] = sg space_groups['P -4 3 n'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(219, 'F -4 3 c', transformations) space_groups[219] = sg space_groups['F -4 3 c'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,3,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,3,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,3,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,3,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,3,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,3,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([3,3,5]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([3,5,5]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([3,5,5]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([3,5,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([3,5,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([3,3,5]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([3,5,5]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([3,3,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([3,3,5]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([3,3,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([3,5,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([3,3,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(220, 'I -4 3 d', transformations) space_groups[220] = sg space_groups['I -4 3 d'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(221, 'P m -3 m', transformations) space_groups[221] = sg space_groups['P m -3 m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(222, 'P n -3 n :2', transformations) space_groups[222] = sg space_groups['P n -3 n :2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(223, 'P m -3 n', transformations) space_groups[223] = sg space_groups['P m -3 n'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(224, 'P n -3 m :2', transformations) space_groups[224] = sg space_groups['P n -3 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,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(225, 'F m -3 m', transformations) space_groups[225] = sg space_groups['F m -3 m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,1,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([-1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,0,-1,0,1,0]) rot.shape = (3, 3) trans_num = N.array([-1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,0,-1,0,1,0,0]) rot.shape = (3, 3) trans_num = N.array([-1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,0,-1,0,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([-1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,-1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,1,0,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,-1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,-1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,1,-1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,-1,1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,1,0,0,0,-1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,1,0,0,0,-1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,0,1,-1,0,0,0,1,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,0,0,1,1,0,0]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([0,-1,0,-1,0,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot =
N.array([0,1,0,1,0,0,0,0,1])
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])
numpy.array
import numpy as np def haldane_honeycomb(kx, ky, m=0.5, phi=np.pi/2): k = np.array([kx / np.sqrt(3.), ky * 2. / 3.]) t1 = t2 = 1. a1 = np.array([np.sqrt(3) * 0.5, 0.5]) a2 = np.array([0, -1]) a3 = np.array([-np.sqrt(3) * 0.5, 0.5]) b1 = a2 - a3 b2 = a3 - a1 b3 = a1 - a2 pauli0 = np.eye(2) pauli1 = np.array([[0, 1], [1, 0]]) pauli2 = np.array([[0, -1j], [1j, 0]]) pauli3 = np.array([[1, 0], [0, -1]]) hk = 2 * t2 * np.cos(phi) * ( np.cos(k @ b1) + np.cos(k @ b2) + np.cos(k @ b3) ) * pauli0 + t1 * ( (np.cos(k @ a1) + np.cos(k @ a2) + np.cos(k @ a3)) * pauli1 + (
np.sin(k @ a1)
numpy.sin
# _*_ coding:utf-8 _*_ ''' @Author: <NAME> @Date: 2018.12.9 @Purpose: 文本情感分析(positive,negative,neutral) @Reference: https://github.com/Edward1Chou/SentimentAnalysis @算法:Bi_LSTM @需要有事先标准好的数据集 @positive: [1,0,0] @neutral: [0,1,0] @negative:[0,0,1] ''' import logging logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) import codecs import jieba datapaths=r"C:\Users\RY\Desktop\情感分析\SentimentAnalysis-master\data\\" positive_data=[] y_positive=[] neutral_data=[] y_neutral=[] negative_data=[] y_negative=[] print("#------------------------------------------------------#") print("加载数据集") with codecs.open(datapaths+"pos.csv","r","utf-8") as f1,\ codecs.open(datapaths+"neutral.csv","r","utf-8") as f2,\ codecs.open(datapaths+"neg.csv","r","utf-8") as f3: for line in f1: positive_data.append(" ".join(i for i in jieba.lcut(line.strip(),cut_all=False))) y_positive.append([1,0,0]) for line in f2: neutral_data.append(" ".join(i for i in jieba.lcut(line.strip(),cut_all=False))) y_neutral.append([0,1,0]) for line in f3: negative_data.append(" ".join(i for i in jieba.lcut(line.strip(),cut_all=False))) y_negative.append([0,0,1]) print("positive data:{}".format(len(positive_data))) print("neutral data:{}".format(len(neutral_data))) print("negative data:{}".format(len(negative_data))) x_text=positive_data+neutral_data+negative_data y_label=y_positive+y_neutral+y_negative print("#------------------------------------------------------#") print("\n") from tensorflow.contrib import learn import tensorflow as tf import numpy as np import collections max_document_length=200 min_frequency=1 vocab = learn.preprocessing.VocabularyProcessor(max_document_length,min_frequency, tokenizer_fn=list) x = np.array(list(vocab.fit_transform(x_text))) vocab_dict = collections.OrderedDict(vocab.vocabulary_._mapping) with codecs.open(r"C:\Users\RY\Desktop\vocabulary.txt","w","utf-8") as f: for key,value in vocab_dict.items(): f.write("{} {}\n".format(key,value)) print("#----------------------------------------------------------#") print("\n") print("#----------------------------------------------------------#") print("数据混洗") np.random.seed(10) y=np.array(y_label) shuffle_indices = np.random.permutation(np.arange(len(y))) x_shuffled = x[shuffle_indices] y_shuffled = y[shuffle_indices] test_sample_percentage=0.2 test_sample_index = -1 * int(test_sample_percentage * float(len(y))) x_train, x_test = x_shuffled[:test_sample_index], x_shuffled[test_sample_index:] y_train, y_test = y_shuffled[:test_sample_index], y_shuffled[test_sample_index:] train_positive_label=0 train_neutral_label=0 train_negative_label=0 test_positive_label=0 test_neutral_label=0 test_negative_label=0 for i in range(len(y_train)): if y_train[i,0] == 1: train_positive_label += 1 elif y_train[i,1] == 1: train_neutral_label += 1 else: train_negative_label += 1 for i in range(len(y_test)): if y_test[i,0] == 1: test_positive_label += 1 elif y_test[i,1] == 1: test_neutral_label += 1 else: test_negative_label += 1 print("训练集中 positive 样本个数:{}".format(train_positive_label)) print("训练集中 neutral 样本个数:{}".format(train_neutral_label)) print("训练集中 negative 样本个数:{}".format(train_negative_label)) print("测试集中 positive 样本个数:{}".format(test_positive_label)) print("测试集中 neutral 样本个数:{}".format(test_neutral_label)) print("测试集中 negative 样本个数:{}".format(test_negative_label)) print("#----------------------------------------------------------#") print("\n") print("#----------------------------------------------------------#") print("读取預训练词向量矩阵") pretrainpath=r"E:\中科大MS\預训练模型\\" embedding_index={} with codecs.open(pretrainpath+"sgns.wiki.bigram","r","utf-8") as f: line=f.readline() nwords=int(line.strip().split(" ")[0]) ndims=int(line.strip().split(" ")[1]) for line in f: values=line.split() words=values[0] coefs=np.asarray(values[1:],dtype="float32") embedding_index[words]=coefs print("預训练模型中Token总数:{} = {}".format(nwords,len(embedding_index))) print("預训练模型的维度:{}".format(ndims)) print("#----------------------------------------------------------#") print("\n") print("#----------------------------------------------------------#") print("将vocabulary中的 index-word 对应关系映射到 index-word vector形式") embedding_matrix=[] notfoundword=0 for word in vocab_dict.keys(): if word in embedding_index.keys(): embedding_matrix.append(embedding_index[word]) else: notfoundword += 1 embedding_matrix.append(np.random.uniform(-1,1,size=ndims)) embedding_matrix=
np.array(embedding_matrix,dtype=np.float32)
numpy.array
"""Primary tests.""" import copy import functools import pickle from typing import Any, Callable, Dict, List, Optional, Tuple import warnings import numpy as np import pytest import scipy.optimize from pyblp import ( Agents, CustomMoment, DemographicCovarianceMoment, Formulation, Integration, Iteration, Optimization, Problem, Products, Simulation, build_ownership, data_to_dict, parallel ) from pyblp.utilities.basics import Array, Options, update_matrices, compute_finite_differences from .conftest import SimulatedProblemFixture @pytest.mark.usefixtures('simulated_problem') @pytest.mark.parametrize('solve_options_update', [ pytest.param({'method': '2s'}, id="two-step"), pytest.param({'scale_objective': True}, id="scaled objective"), pytest.param({'center_moments': False, 'W_type': 'unadjusted', 'se_type': 'clustered'}, id="complex covariances"), pytest.param({'delta_behavior': 'last'}, id="faster starting delta values"), pytest.param({'fp_type': 'linear'}, id="non-safe linear fixed point"), pytest.param({'fp_type': 'safe_nonlinear'}, id="nonlinear fixed point"), pytest.param({'fp_type': 'nonlinear'}, id="non-safe nonlinear fixed point"), pytest.param( {'iteration': Iteration('hybr', {'xtol': 1e-12}, compute_jacobian=True)}, id="linear Newton fixed point" ), pytest.param( {'fp_type': 'safe_nonlinear', 'iteration': Iteration('hybr', {'xtol': 1e-12}, compute_jacobian=True)}, id="nonlinear Newton fixed point" ) ]) def test_accuracy(simulated_problem: SimulatedProblemFixture, solve_options_update: Options) -> None: """Test that starting parameters that are half their true values give rise to errors of less than 10%.""" simulation, _, problem, solve_options, _ = simulated_problem # skip different iteration configurations when they won't matter if simulation.K2 == 0 and {'delta_behavior', 'fp_type', 'iteration'} & set(solve_options_update): return pytest.skip("A different iteration configuration has no impact when there is no heterogeneity.") if simulation.epsilon_scale != 1 and 'nonlinear' in solve_options_update.get('fp_type', 'safe_linear'): return pytest.skip("Nonlinear fixed point configurations are not supported when epsilon is scaled.") # update the default options and solve the problem updated_solve_options = copy.deepcopy(solve_options) updated_solve_options.update(solve_options_update) updated_solve_options.update({k: 0.5 * solve_options[k] for k in ['sigma', 'pi', 'rho', 'beta']}) results = problem.solve(**updated_solve_options) # test the accuracy of the estimated parameters keys = ['sigma', 'pi', 'rho', 'beta'] if problem.K3 > 0: keys.append('gamma') for key in keys: np.testing.assert_allclose(getattr(simulation, key), getattr(results, key), atol=0, rtol=0.1, err_msg=key) @pytest.mark.usefixtures('simulated_problem') @pytest.mark.parametrize('compute_options', [ pytest.param({'method': 'approximate'}, id="approximation"), pytest.param({'method': 'normal'}, id="normal distribution"), pytest.param({'method': 'empirical'}, id="empirical distribution") ]) def test_optimal_instruments(simulated_problem: SimulatedProblemFixture, compute_options: Options) -> None: """Test that starting parameters that are half their true values also give rise to errors of less than 10% under optimal instruments. """ simulation, _, problem, solve_options, problem_results = simulated_problem # compute optimal instruments and update the problem (only use a few draws to speed up the test) compute_options = copy.deepcopy(compute_options) compute_options.update({ 'draws': 5, 'seed': 0 }) new_problem = problem_results.compute_optimal_instruments(**compute_options).to_problem() # update the default options and solve the problem updated_solve_options = copy.deepcopy(solve_options) updated_solve_options.update({k: 0.5 * solve_options[k] for k in ['sigma', 'pi', 'rho', 'beta']}) new_results = new_problem.solve(**updated_solve_options) # test the accuracy of the estimated parameters keys = ['beta', 'sigma', 'pi', 'rho'] if problem.K3 > 0: keys.append('gamma') for key in keys: np.testing.assert_allclose(getattr(simulation, key), getattr(new_results, key), atol=0, rtol=0.1, err_msg=key) @pytest.mark.usefixtures('simulated_problem') def test_importance_sampling(simulated_problem: SimulatedProblemFixture) -> None: """Test that starting parameters that are half their true values also give rise to errors of less than 20% under importance sampling. """ simulation, _, problem, solve_options, problem_results = simulated_problem # importance sampling is only relevant when there are agent data if problem.K2 == 0: return pytest.skip("There are no agent data.") # it suffices to test importance sampling for problems without demographics if problem.D > 0: return pytest.skip("Testing importance sampling is hard with demographics.") # compute a more precise delta delta = problem_results.compute_delta(integration=simulation.integration) # do importance sampling and verify that the mean utility didn't change if precise integration isn't used sampling_results = problem_results.importance_sampling( draws=500, ar_constant=2, seed=0, delta=delta, integration=Integration('mlhs', 50000, {'seed': 0}), ) # solve the new problem new_problem = sampling_results.to_problem() updated_solve_options = copy.deepcopy(solve_options) updated_solve_options.update({k: 0.5 * solve_options[k] for k in ['sigma', 'pi', 'rho', 'beta']}) new_results = new_problem.solve(**updated_solve_options) # test the accuracy of the estimated parameters keys = ['beta', 'sigma', 'pi', 'rho'] if problem.K3 > 0: keys.append('gamma') for key in keys: np.testing.assert_allclose(getattr(simulation, key), getattr(new_results, key), atol=0, rtol=0.2, err_msg=key) @pytest.mark.usefixtures('simulated_problem') def test_bootstrap(simulated_problem: SimulatedProblemFixture) -> None: """Test that post-estimation output medians are within 5% parametric bootstrap confidence intervals.""" _, _, problem, solve_options, problem_results = simulated_problem # create bootstrapped results (use only a few draws and don't iterate for speed) bootstrapped_results = problem_results.bootstrap(draws=100, seed=0, iteration=Iteration('return')) # test that post-estimation outputs are within 95% confidence intervals t = problem.products.market_ids[0] merger_ids = np.where(problem.products.firm_ids == 1, 0, problem.products.firm_ids) merger_ids_t = merger_ids[problem.products.market_ids == t] method_mapping = { "aggregate elasticities": lambda r: r.compute_aggregate_elasticities(), "consumer surpluses": lambda r: r.compute_consumer_surpluses(), "approximate prices": lambda r: r.compute_approximate_prices(merger_ids), "own elasticities": lambda r: r.extract_diagonals(r.compute_elasticities()), "aggregate elasticity in t": lambda r: r.compute_aggregate_elasticities(market_id=t), "consumer surplus in t": lambda r: r.compute_consumer_surpluses(market_id=t), "approximate prices in t": lambda r: r.compute_approximate_prices(merger_ids_t, market_id=t) } for name, method in method_mapping.items(): values = method(problem_results) bootstrapped_values = method(bootstrapped_results) median = np.median(values) bootstrapped_medians = np.nanmedian(bootstrapped_values, axis=range(1, bootstrapped_values.ndim)) lb, ub = np.percentile(bootstrapped_medians, [2.5, 97.5]) np.testing.assert_array_less(np.squeeze(lb), np.squeeze(median) + 1e-14, err_msg=name) np.testing.assert_array_less(np.squeeze(median), np.squeeze(ub) + 1e-14, err_msg=name) @pytest.mark.usefixtures('simulated_problem') def test_bootstrap_se(simulated_problem: SimulatedProblemFixture) -> None: """Test that bootstrapped SEs are close to analytic ones. Or at least the same order of magnitude -- especially for large numbers of RCs they may not necessarily be very close to each other. """ _, _, _, _, problem_results = simulated_problem # compute bootstrapped results (ignore supply side iteration because we will only use the parameter draws) bootstrapped_results = problem_results.bootstrap(draws=1000, seed=0, iteration=Iteration('return')) # compare SEs for key in ['sigma', 'pi', 'rho', 'beta', 'gamma']: analytic_se = np.nan_to_num(getattr(problem_results, f'{key}_se')) bootstrapped_se = getattr(bootstrapped_results, f'bootstrapped_{key}').std(axis=0) np.testing.assert_allclose(analytic_se, bootstrapped_se, atol=0.001, rtol=0.5, err_msg=key) @pytest.mark.usefixtures('simulated_problem') def test_result_serialization(simulated_problem: SimulatedProblemFixture) -> None: """Test that result objects can be serialized and that their string representations are the same when they are unpickled. """ simulation, simulation_results, problem, solve_options, problem_results = simulated_problem originals = [ Formulation('x + y', absorb='C(z)', absorb_method='lsmr', absorb_options={'tol': 1e-10}), Integration('halton', size=10, specification_options={'seed': 0, 'scramble': True}), Iteration('lm', method_options={'max_evaluations': 100}, compute_jacobian=True), Optimization('nelder-mead', method_options={'xatol': 1e-5}, compute_gradient=False, universal_display=False), problem, simulation, simulation_results, problem_results, problem_results.compute_optimal_instruments(), problem_results.bootstrap(draws=1, seed=0), data_to_dict(simulation_results.product_data), solve_options['micro_moments'], ] for original in originals: unpickled = pickle.loads(pickle.dumps(original)) assert str(original) == str(unpickled), str(original) @pytest.mark.usefixtures('simulated_problem') @pytest.mark.parametrize('solve_options_update', [ pytest.param({'costs_bounds': (-1e10, 1e10)}, id="non-binding costs bounds"), pytest.param({'check_optimality': 'both'}, id="Hessian computation") ]) def test_trivial_changes(simulated_problem: SimulatedProblemFixture, solve_options_update: Dict) -> None: """Test that solving a problem with arguments that shouldn't give rise to meaningful differences doesn't give rise to any differences. """ simulation, _, problem, solve_options, results = simulated_problem # solve the problem with the updated options updated_solve_options = copy.deepcopy(solve_options) updated_solve_options.update(solve_options_update) updated_results = problem.solve(**updated_solve_options) # test that all arrays in the results are essentially identical for key, result in results.__dict__.items(): if isinstance(result, np.ndarray) and result.dtype != np.object: if 'hessian' not in key: np.testing.assert_allclose(result, getattr(updated_results, key), atol=1e-14, rtol=0, err_msg=key) @pytest.mark.usefixtures('simulated_problem') def test_parallel(simulated_problem: SimulatedProblemFixture) -> None: """Test that solving problems and computing results in parallel gives rise to the same results as when using serial processing. """ _, _, problem, solve_options, results = simulated_problem # compute marginal costs as a test of results (everything else has already been computed without parallelization) costs = results.compute_costs() # solve the problem and compute costs in parallel with parallel(2): parallel_results = problem.solve(**solve_options) parallel_costs = parallel_results.compute_costs() # test that all arrays in the results are essentially identical for key, result in results.__dict__.items(): if isinstance(result, np.ndarray) and result.dtype != np.object: np.testing.assert_allclose(result, getattr(parallel_results, key), atol=1e-14, rtol=0, err_msg=key) # test that marginal costs are essentially equal np.testing.assert_allclose(costs, parallel_costs, atol=1e-14, rtol=0) @pytest.mark.usefixtures('simulated_problem') @pytest.mark.parametrize(['ED', 'ES', 'absorb_method', 'absorb_options'], [ pytest.param(1, 0, None, None, id="1 demand FE, default method"), pytest.param(0, 1, None, None, id="1 supply FE, default method"), pytest.param(1, 1, None, None, id="1 demand- and 1 supply FE, default method"), pytest.param(2, 0, None, None, id="2 demand FEs, default method"), pytest.param(0, 2, 'sw', None, id="2 supply FEs, SW"), pytest.param(3, 1, 'lsmr', None, id="3 demand- and 1 supply FEs, LSMR"), pytest.param(1, 3, 'map', {'transform': 'cimmino', 'acceleration': 'cg'}, id="1 demand- and 3 supply FEs, MAP-CG"), ]) def test_fixed_effects( simulated_problem: SimulatedProblemFixture, ED: int, ES: int, absorb_method: Optional[str], absorb_options: Optional[dict]) -> None: """Test that absorbing different numbers of demand- and supply-side fixed effects gives rise to essentially identical first-stage results as does including indicator variables. Also test that optimal instruments results, marginal costs, and test statistics remain unchanged. """ simulation, simulation_results, problem, solve_options, problem_results = simulated_problem # there cannot be supply-side fixed effects if there isn't a supply side if problem.K3 == 0: ES = 0 if ED == ES == 0: return pytest.skip("There are no fixed effects to test.") # configure the optimization routine to only do a few iterations to save time and never get to the point where small # numerical differences between methods build up into noticeable differences solve_options = copy.deepcopy(solve_options) solve_options['optimization'] = Optimization('l-bfgs-b', {'maxfun': 3}) # make product data mutable and add instruments product_data = {k: simulation_results.product_data[k] for k in simulation_results.product_data.dtype.names} product_data.update({ 'demand_instruments': problem.products.ZD[:, :-problem.K1], 'supply_instruments': problem.products.ZS[:, :-problem.K3] }) # remove constants and delete associated elements in the initial beta product_formulations = list(problem.product_formulations).copy() if ED > 0: assert product_formulations[0] is not None constant_indices = [i for i, e in enumerate(product_formulations[0]._expressions) if not e.free_symbols] solve_options['beta'] = np.delete(solve_options['beta'], constant_indices, axis=0) product_formulations[0] = Formulation(f'{product_formulations[0]._formula} - 1') if ES > 0: assert product_formulations[2] is not None product_formulations[2] = Formulation(f'{product_formulations[2]._formula} - 1') # add fixed effect IDs to the data demand_id_names: List[str] = [] supply_id_names: List[str] = [] state = np.random.RandomState(seed=0) for side, count, names in [('demand', ED, demand_id_names), ('supply', ES, supply_id_names)]: for index in range(count): name = f'{side}_ids{index}' ids = state.choice(['a', 'b', 'c'], problem.N) product_data[name] = ids names.append(name) # split apart excluded demand-side instruments so they can be included in formulations instrument_names: List[str] = [] for index, instrument in enumerate(product_data['demand_instruments'].T): name = f'demand_instrument{index}' product_data[name] = instrument instrument_names.append(name) # build formulas for the IDs demand_id_formula = ' + '.join(demand_id_names) supply_id_formula = ' + '.join(supply_id_names) # solve the first stage of a problem in which the fixed effects are absorbed solve_options1 = copy.deepcopy(solve_options) product_formulations1 = product_formulations.copy() if ED > 0: assert product_formulations[0] is not None product_formulations1[0] = Formulation( product_formulations[0]._formula, demand_id_formula, absorb_method, absorb_options ) if ES > 0: assert product_formulations[2] is not None product_formulations1[2] = Formulation( product_formulations[2]._formula, supply_id_formula, absorb_method, absorb_options ) problem1 = Problem( product_formulations1, product_data, problem.agent_formulation, simulation.agent_data, distributions=simulation.distributions, epsilon_scale=simulation.epsilon_scale, costs_type=simulation.costs_type ) if solve_options1['micro_moments']: solve_options1['W'] = scipy.linalg.pinv(scipy.linalg.block_diag( problem1.products.ZD.T @ problem1.products.ZD, problem1.products.ZS.T @ problem1.products.ZS, np.eye(len(solve_options1['micro_moments'])), )) problem_results1 = problem1.solve(**solve_options1) # solve the first stage of a problem in which fixed effects are included as indicator variables solve_options2 = copy.deepcopy(solve_options) product_formulations2 = product_formulations.copy() if ED > 0: assert product_formulations[0] is not None product_formulations2[0] = Formulation(f'{product_formulations[0]._formula} + {demand_id_formula}') if ES > 0: assert product_formulations[2] is not None product_formulations2[2] = Formulation(f'{product_formulations[2]._formula} + {supply_id_formula}') problem2 = Problem( product_formulations2, product_data, problem.agent_formulation, simulation.agent_data, distributions=simulation.distributions, epsilon_scale=simulation.epsilon_scale, costs_type=simulation.costs_type ) solve_options2['beta'] = np.r_[ solve_options2['beta'], np.full((problem2.K1 - solve_options2['beta'].size, 1), np.nan) ] if solve_options2['micro_moments']: solve_options2['W'] = scipy.linalg.pinv(scipy.linalg.block_diag( problem2.products.ZD.T @ problem2.products.ZD, problem2.products.ZS.T @ problem2.products.ZS, np.eye(len(solve_options2['micro_moments'])), )) problem_results2 = problem2.solve(**solve_options2) # solve the first stage of a problem in which some fixed effects are absorbed and some are included as indicators if ED == ES == 0: problem_results3 = problem_results2 else: solve_options3 = copy.deepcopy(solve_options) product_formulations3 = product_formulations.copy() if ED > 0: assert product_formulations[0] is not None product_formulations3[0] = Formulation( f'{product_formulations[0]._formula} + {demand_id_names[0]}', ' + '.join(demand_id_names[1:]) or None ) if ES > 0: assert product_formulations[2] is not None product_formulations3[2] = Formulation( f'{product_formulations[2]._formula} + {supply_id_names[0]}', ' + '.join(supply_id_names[1:]) or None ) problem3 = Problem( product_formulations3, product_data, problem.agent_formulation, simulation.agent_data, distributions=simulation.distributions, epsilon_scale=simulation.epsilon_scale, costs_type=simulation.costs_type ) solve_options3['beta'] = np.r_[ solve_options3['beta'], np.full((problem3.K1 - solve_options3['beta'].size, 1), np.nan) ] if solve_options3['micro_moments']: solve_options3['W'] = scipy.linalg.pinv(scipy.linalg.block_diag( problem3.products.ZD.T @ problem3.products.ZD, problem3.products.ZS.T @ problem3.products.ZS, np.eye(len(solve_options3['micro_moments'])), )) problem_results3 = problem3.solve(**solve_options3) # compute optimal instruments (use only two draws for speed; accuracy is not a concern here) Z_results1 = problem_results1.compute_optimal_instruments(draws=2, seed=0) Z_results2 = problem_results2.compute_optimal_instruments(draws=2, seed=0) Z_results3 = problem_results3.compute_optimal_instruments(draws=2, seed=0) # compute marginal costs costs1 = problem_results1.compute_costs() costs2 = problem_results2.compute_costs() costs3 = problem_results3.compute_costs() J1 = problem_results1.run_hansen_test() J2 = problem_results2.run_hansen_test() J3 = problem_results3.run_hansen_test() LR1 = problem_results1.run_distance_test(problem_results) LR2 = problem_results2.run_distance_test(problem_results) LR3 = problem_results3.run_distance_test(problem_results) LM1 = problem_results1.run_lm_test() LM2 = problem_results2.run_lm_test() LM3 = problem_results3.run_lm_test() wald1 = problem_results1.run_wald_test( problem_results1.parameters[:2], np.eye(problem_results1.parameters.size)[:2] ) wald2 = problem_results2.run_wald_test( problem_results2.parameters[:2], np.eye(problem_results2.parameters.size)[:2] ) wald3 = problem_results3.run_wald_test( problem_results3.parameters[:2], np.eye(problem_results3.parameters.size)[:2] ) # choose tolerances atol = 1e-8 rtol = 1e-5 # test that all problem results expected to be identical are essentially identical, except for standard errors under # micro moments, which are expected to be slightly different problem_results_keys = [ 'theta', 'sigma', 'pi', 'rho', 'beta', 'gamma', 'sigma_se', 'pi_se', 'rho_se', 'beta_se', 'gamma_se', 'delta', 'tilde_costs', 'xi', 'omega', 'xi_by_theta_jacobian', 'omega_by_theta_jacobian', 'objective', 'gradient', 'projected_gradient' ] for key in problem_results_keys: if key.endswith('_se') and solve_options['micro_moments']: continue result1 = getattr(problem_results1, key) result2 = getattr(problem_results2, key) result3 = getattr(problem_results3, key) if key in {'beta', 'gamma', 'beta_se', 'gamma_se'}: result2 = result2[:result1.size] result3 = result3[:result1.size] np.testing.assert_allclose(result1, result2, atol=atol, rtol=rtol, err_msg=key, equal_nan=True) np.testing.assert_allclose(result1, result3, atol=atol, rtol=rtol, err_msg=key, equal_nan=True) # test that all optimal instrument results expected to be identical are essentially identical Z_results_keys = [ 'demand_instruments', 'supply_instruments', 'inverse_covariance_matrix', 'expected_xi_by_theta_jacobian', 'expected_omega_by_theta_jacobian' ] for key in Z_results_keys: result1 = getattr(Z_results1, key) result2 = getattr(Z_results2, key) result3 = getattr(Z_results3, key) np.testing.assert_allclose(result1, result2, atol=atol, rtol=rtol, err_msg=key) np.testing.assert_allclose(result1, result3, atol=atol, rtol=rtol, err_msg=key) # test that marginal costs and test statistics are essentially identical np.testing.assert_allclose(costs1, costs2, atol=atol, rtol=rtol) np.testing.assert_allclose(costs1, costs3, atol=atol, rtol=rtol) np.testing.assert_allclose(J1, J2, atol=atol, rtol=rtol) np.testing.assert_allclose(J1, J3, atol=atol, rtol=rtol) np.testing.assert_allclose(LR1, LR2, atol=atol, rtol=rtol) np.testing.assert_allclose(LR1, LR3, atol=atol, rtol=rtol) np.testing.assert_allclose(LM1, LM2, atol=atol, rtol=rtol) np.testing.assert_allclose(LM1, LM3, atol=atol, rtol=rtol) np.testing.assert_allclose(wald1, wald2, atol=atol, rtol=rtol) np.testing.assert_allclose(wald1, wald3, atol=atol, rtol=rtol) @pytest.mark.usefixtures('simulated_problem') def test_special_ownership(simulated_problem: SimulatedProblemFixture) -> None: """Test that ownership matrices constructed according to special cases take on expected forms.""" simulation, simulation_results, _, _, _ = simulated_problem # test monopoly ownership matrices monopoly_ownership1 = build_ownership(simulation_results.product_data, 'monopoly') monopoly_ownership2 = build_ownership(simulation_results.product_data, lambda f, g: 1) np.testing.assert_equal(monopoly_ownership1, monopoly_ownership2) assert (monopoly_ownership1[~np.isnan(monopoly_ownership1)] == 1).all() # test single product ownership matrices single_ownership = build_ownership(simulation_results.product_data, 'single') assert np.nansum(single_ownership) == simulation.N @pytest.mark.usefixtures('simulated_problem') def test_costs(simulated_problem: SimulatedProblemFixture) -> None: """Test that marginal costs computed under specified firm IDs and ownership are the same as costs computed when firm IDs and ownership are left unspecified. """ _, simulation_results, _, _, results = simulated_problem # compute costs in the simplest way possible costs1 = results.compute_costs() # under custom ownership, just test that results are the same under ownership specification if simulation_results.product_data.ownership.size > 0: costs2 = results.compute_costs(ownership=simulation_results.product_data.ownership) np.testing.assert_equal(costs1, costs2) return # otherwise, also test that results are the same under a firm IDs specification costs2 = results.compute_costs(firm_ids=simulation_results.product_data.firm_ids) costs3 = results.compute_costs(ownership=build_ownership(simulation_results.product_data)) np.testing.assert_equal(costs1, costs2) np.testing.assert_equal(costs1, costs3) @pytest.mark.usefixtures('simulated_problem') @pytest.mark.parametrize('ownership', [ pytest.param(False, id="firm IDs change"), pytest.param(True, id="ownership change") ]) @pytest.mark.parametrize('solve_options', [ pytest.param({}, id="defaults"), pytest.param({'iteration': Iteration('simple')}, id="configured iteration") ]) def test_merger(simulated_problem: SimulatedProblemFixture, ownership: bool, solve_options: Options) -> None: """Test that prices and shares simulated under changed firm IDs are reasonably close to prices and shares computed from the results of a solved problem. In particular, test that unchanged prices and shares are farther from their simulated counterparts than those computed by approximating a merger, which in turn are farther from their simulated counterparts than those computed by fully solving a merger. Also test that simple acquisitions increase HHI. These inequalities are only guaranteed because of the way in which the simulations are configured. """ simulation, simulation_results, problem, _, results = simulated_problem # skip simulations that complicate the test if simulation.products.ownership.size > 0: return pytest.skip("Merger testing doesn't work with custom ownership.") if 'shares' in str(simulation.product_formulations[2]): return pytest.skip("Merger testing doesn't work with quantity-dependent costs.") # create changed ownership or firm IDs associated with a merger merger_product_data = copy.deepcopy(simulation_results.product_data) if ownership: merger_ids = None merger_ownership = build_ownership(merger_product_data, lambda f, g: 1 if f == g or (f < 2 and g < 2) else 0) merger_product_data = update_matrices(merger_product_data, { 'ownership': (merger_ownership, merger_ownership.dtype) }) else: merger_ownership = None merger_product_data.firm_ids[merger_product_data.firm_ids < 2] = 0 merger_ids = merger_product_data.firm_ids # get actual prices and shares merger_simulation = Simulation( simulation.product_formulations, merger_product_data, simulation.beta, simulation.sigma, simulation.pi, simulation.gamma, simulation.rho, simulation.agent_formulation, simulation.agent_data, xi=simulation.xi, omega=simulation.omega, distributions=simulation.distributions, epsilon_scale=simulation.epsilon_scale, costs_type=simulation.costs_type ) actual = merger_simulation.replace_endogenous(**solve_options) # compute marginal costs; get estimated prices and shares costs = results.compute_costs() results_simulation = Simulation( simulation.product_formulations[:2], merger_product_data, results.beta, results.sigma, results.pi, rho=results.rho, agent_formulation=simulation.agent_formulation, agent_data=simulation.agent_data, xi=results.xi, distributions=simulation.distributions, epsilon_scale=simulation.epsilon_scale ) estimated = results_simulation.replace_endogenous(costs, problem.products.prices, **solve_options) estimated_prices = results.compute_prices(merger_ids, merger_ownership, costs, **solve_options) approximated_prices = results.compute_approximate_prices(merger_ids, merger_ownership, costs) estimated_shares = results.compute_shares(estimated_prices) approximated_shares = results.compute_shares(approximated_prices) # test that we get the same results from solving the simulation np.testing.assert_allclose(estimated.product_data.prices, estimated_prices, atol=1e-14, rtol=0, verbose=True) np.testing.assert_allclose(estimated.product_data.shares, estimated_shares, atol=1e-14, rtol=0, verbose=True) # test that estimated prices are closer to changed prices than approximate prices approximated_prices_error = np.linalg.norm(actual.product_data.prices - approximated_prices) estimated_prices_error = np.linalg.norm(actual.product_data.prices - estimated_prices) np.testing.assert_array_less(estimated_prices_error, approximated_prices_error, verbose=True) # test that estimated shares are closer to changed shares than approximate shares approximated_shares_error = np.linalg.norm(actual.product_data.shares - approximated_shares) estimated_shares_error = np.linalg.norm(actual.product_data.shares - estimated_shares) np.testing.assert_array_less(estimated_shares_error, approximated_shares_error, verbose=True) # test that median HHI increases if not ownership: hhi = results.compute_hhi() changed_hhi = results.compute_hhi(merger_ids, estimated_shares) np.testing.assert_array_less(np.median(hhi), np.median(changed_hhi), verbose=True) @pytest.mark.usefixtures('simulated_problem') def test_shares(simulated_problem: SimulatedProblemFixture) -> None: """Test that shares computed from estimated parameters are essentially equal to actual shares.""" simulation, simulation_results, _, _, results = simulated_problem shares1 = results.compute_shares() shares2 = results.compute_shares(agent_data=simulation.agent_data, delta=results.delta) np.testing.assert_allclose(simulation_results.product_data.shares, shares1, atol=1e-14, rtol=0, verbose=True) np.testing.assert_allclose(simulation_results.product_data.shares, shares2, atol=1e-14, rtol=0, verbose=True) @pytest.mark.usefixtures('simulated_problem') def test_probabilities(simulated_problem: SimulatedProblemFixture) -> None: """Test that integrating over choice probabilities computed from estimated parameters essentially gives actual shares. """ _, simulation_results, problem, _, results = simulated_problem # only do the test for a single market t = problem.products.market_ids[0] shares = problem.products.shares[problem.products.market_ids.flat == t] weights = problem.agents.weights[problem.agents.market_ids.flat == t] # compute and compare shares estimated_shares = results.compute_probabilities(market_id=t) @ weights np.testing.assert_allclose(shares, estimated_shares, atol=1e-14, rtol=0, verbose=True) @pytest.mark.usefixtures('simulated_problem') def test_surplus(simulated_problem: SimulatedProblemFixture) -> None: """Test that integrating over individual-level surpluses gives market-level surpluses.""" _, _, problem, _, results = simulated_problem # compute surpluses for a single market t = problem.products.market_ids[0] surpluses = results.compute_consumer_surpluses(market_id=t, keep_all=True) surplus = results.compute_consumer_surpluses(market_id=t) # test that we get the same result when manually integrating over surpluses weights = problem.agents.weights[problem.agents.market_ids.flat == t] np.testing.assert_allclose(surpluses @ weights, surplus, atol=1e-14, rtol=0, verbose=True) @pytest.mark.usefixtures('simulated_problem') def test_shares_by_prices_jacobian(simulated_problem: SimulatedProblemFixture) -> None: """Use central finite differences to test that analytic values in the Jacobian of shares with respect to prices are essentially equal. """ simulation, simulation_results, _, _, results = simulated_problem product_data = simulation_results.product_data # only do the test for a single market t = product_data.market_ids[0] shares = product_data.shares[product_data.market_ids.flat == t] prices = product_data.prices[product_data.market_ids.flat == t] # extract the Jacobian from the analytic expression for elasticities and approximate it with finite differences exact = results.compute_elasticities(market_id=t) * shares / prices.T approximate = compute_finite_differences(lambda p: results.compute_shares(p, market_id=t), prices) np.testing.assert_allclose(exact, approximate, atol=1e-8, rtol=0) @pytest.mark.usefixtures('simulated_problem') @pytest.mark.parametrize('factor', [pytest.param(0.01, id="large"), pytest.param(0.0001, id="small")]) def test_elasticity_aggregates_and_means(simulated_problem: SimulatedProblemFixture, factor: float) -> None: """Test that the magnitude of simulated aggregate elasticities is less than the magnitude of mean elasticities, both for prices and for other characteristics. """ simulation, _, _, _, results = simulated_problem # test that demand for an entire product category is less elastic for prices than for individual products np.testing.assert_array_less( np.abs(results.compute_aggregate_elasticities(factor)), np.abs(results.extract_diagonal_means(results.compute_elasticities())), verbose=True ) # test the same inequality but for all non-price variables (including the mean utility) names = {n for f in simulation._X1_formulations + simulation._X2_formulations for n in f.names} for name in names - {'prices'} | {None}: np.testing.assert_array_less( np.abs(results.compute_aggregate_elasticities(factor, name)), np.abs(results.extract_diagonal_means(results.compute_elasticities(name))), err_msg=name, verbose=True ) @pytest.mark.usefixtures('simulated_problem') def test_diversion_ratios(simulated_problem: SimulatedProblemFixture) -> None: """Test that simulated diversion ratio rows sum to one.""" simulation, _, _, _, results = simulated_problem # only do the test for a single market t = simulation.products.market_ids[0] # test price-based ratios ratios = results.compute_diversion_ratios(market_id=t) long_run_ratios = results.compute_long_run_diversion_ratios(market_id=t) np.testing.assert_allclose(ratios.sum(axis=1), 1, atol=1e-14, rtol=0) np.testing.assert_allclose(long_run_ratios.sum(axis=1), 1, atol=1e-14, rtol=0) # test ratios based on other variables (including mean utilities) names = {n for f in simulation._X1_formulations + simulation._X2_formulations for n in f.names} for name in names - {'prices'} | {None}: ratios = results.compute_diversion_ratios(name, market_id=t) np.testing.assert_allclose(ratios.sum(axis=1), 1, atol=1e-14, rtol=0, err_msg=name) @pytest.mark.usefixtures('simulated_problem') def test_result_positivity(simulated_problem: SimulatedProblemFixture) -> None: """Test that simulated markups, profits, consumer surpluses are positive, both before and after a merger.""" simulation, _, _, _, results = simulated_problem # only do the test for a single market t = simulation.products.market_ids[0] # compute post-merger prices and shares changed_prices = results.compute_approximate_prices(market_id=t) changed_shares = results.compute_shares(changed_prices, market_id=t) # compute surpluses and test positivity test_positive = lambda x: np.testing.assert_array_less(-1e-14, x, verbose=True) test_positive(results.compute_markups(market_id=t)) test_positive(results.compute_profits(market_id=t)) test_positive(results.compute_consumer_surpluses(market_id=t)) test_positive(results.compute_markups(changed_prices, market_id=t)) test_positive(results.compute_profits(changed_prices, changed_shares, market_id=t)) test_positive(results.compute_consumer_surpluses(changed_prices, market_id=t)) # compute willingness to pay when the simulation has product IDs and test its positivity if simulation.products.product_ids.size > 0: unique_product_ids = np.unique(simulation.products.product_ids[simulation.products.market_ids == t]) eliminate0 = results.compute_consumer_surpluses(market_id=t) eliminate1 = results.compute_consumer_surpluses(market_id=t, eliminate_product_ids=unique_product_ids[:1]) eliminate2 = results.compute_consumer_surpluses(market_id=t, eliminate_product_ids=unique_product_ids[:2]) test_positive(eliminate0 - eliminate1) test_positive(eliminate1 - eliminate2) @pytest.mark.usefixtures('simulated_problem') def test_second_step(simulated_problem: SimulatedProblemFixture) -> None: """Test that results from two-step GMM on simulated data are identical to results from one-step GMM configured with results from a first step. """ simulation, _, problem, solve_options, _ = simulated_problem # use two steps and remove sigma bounds so that it can't get stuck at zero (use a small number of optimization # iterations to speed up the test) updated_solve_options = copy.deepcopy(solve_options) updated_solve_options.update({ 'method': '2s', 'optimization': Optimization('l-bfgs-b', {'maxfun': 3}), 'sigma_bounds': (np.full_like(simulation.sigma, -np.inf), np.full_like(simulation.sigma, +np.inf)), }) # get two-step GMM results results12 = problem.solve(**updated_solve_options) assert results12.last_results is not None assert results12.last_results.last_results is None or results12.last_results.last_results.step == 0 assert results12.step == 2 and results12.last_results.step == 1 # get results from the first step updated_solve_options1 = copy.deepcopy(updated_solve_options) updated_solve_options1['method'] = '1s' results1 = problem.solve(**updated_solve_options1) # get results from the second step updated_solve_options2 = copy.deepcopy(updated_solve_options1) updated_solve_options2.update({ 'sigma': results1.sigma, 'pi': results1.pi, 'rho': results1.rho, 'beta': np.where(np.isnan(solve_options['beta']), np.nan, results1.beta), 'delta': results1.delta, 'W': results1.updated_W, }) results2 = problem.solve(**updated_solve_options2) assert results1.last_results is None or results1.last_results.step == 0 assert results2.last_results is None or results2.last_results.step == 0 assert results1.step == results2.step == 1 # test that results are essentially identical for key, result12 in results12.__dict__.items(): if 'cumulative' not in key and isinstance(result12, np.ndarray) and result12.dtype != np.object: np.testing.assert_allclose(result12, getattr(results2, key), atol=1e-14, rtol=0, err_msg=key) @pytest.mark.usefixtures('simulated_problem') def test_return(simulated_problem: SimulatedProblemFixture) -> None: """Test that using a trivial optimization and fixed point iteration routines that just return initial values yield results that are the same as the specified initial values. """ simulation, simulation_results, problem, solve_options, _ = simulated_problem # specify initial values and the trivial routines initial_values = { 'sigma': simulation.sigma, 'pi': simulation.pi, 'rho': simulation.rho, 'beta': simulation.beta, 'gamma': simulation.gamma if problem.K3 > 0 else None, 'delta': problem.products.X1 @ simulation.beta + simulation.xi } updated_solve_options = copy.deepcopy(solve_options) updated_solve_options.update({ 'optimization': Optimization('return'), 'iteration': Iteration('return'), **initial_values }) # obtain problem results and test that initial values are the same results = problem.solve(**updated_solve_options) for key, initial in initial_values.items(): if initial is not None: np.testing.assert_allclose(initial, getattr(results, key), atol=1e-14, rtol=1e-14, err_msg=key) @pytest.mark.usefixtures('simulated_problem') @pytest.mark.parametrize('scipy_method', [ pytest.param('l-bfgs-b', id="L-BFGS-B"), pytest.param('trust-constr', id="Trust Region") ]) def test_gradient_optionality(simulated_problem: SimulatedProblemFixture, scipy_method: str) -> None: """Test that the option of not computing the gradient for simulated data does not affect estimates when the gradient isn't used. Allow Jacobian-based results to differ slightly more when finite differences are used to compute them. """ simulation, _, problem, solve_options, results = simulated_problem # this test only requires a few optimization iterations (enough for gradient problems to be clear) method_options = {'maxiter': 3} def custom_method( initial: Array, bounds: List[Tuple[float, float]], objective_function: Callable, _: Any) -> ( Tuple[Array, bool]): """Optimize without gradients.""" optimize_results = scipy.optimize.minimize( lambda x: objective_function(x)[0], initial, method=scipy_method, bounds=bounds, options=method_options ) return optimize_results.x, optimize_results.success # solve the problem when not using gradients and when not computing them (use the identity weighting matrix to make # tiny gradients with some initial weighting matrices less problematic when comparing values) updated_solve_options1 = copy.deepcopy(solve_options) updated_solve_options2 = copy.deepcopy(solve_options) updated_solve_options1.update({ 'optimization': Optimization(custom_method), }) updated_solve_options2.update({ 'optimization': Optimization(scipy_method, method_options, compute_gradient=False), 'finite_differences': True, }) results1 = problem.solve(**updated_solve_options1) results2 = problem.solve(**updated_solve_options2) # test that all arrays close except for those created with finite differences after the fact for key, result1 in results1.__dict__.items(): if isinstance(result1, np.ndarray) and result1.dtype != np.object: if not any(s in key for s in ['gradient', '_jacobian', '_se', '_covariances']): np.testing.assert_allclose(result1, getattr(results2, key), atol=1e-14, rtol=0, err_msg=key) @pytest.mark.usefixtures('simulated_problem') @pytest.mark.parametrize('method', [ pytest.param('l-bfgs-b', id="L-BFGS-B"), pytest.param('trust-constr', id="trust-region"), pytest.param('tnc', id="TNC"), pytest.param('slsqp', id="SLSQP"), pytest.param('knitro', id="Knitro"), pytest.param('cg', id="CG"), pytest.param('bfgs', id="BFGS"), pytest.param('newton-cg', id="Newton-CG"), pytest.param('nelder-mead', id="Nelder-Mead"), pytest.param('powell', id="Powell") ]) def test_bounds(simulated_problem: SimulatedProblemFixture, method: str) -> None: """Test that non-binding bounds on parameters in simulated problems do not affect estimates and that binding bounds are respected. Forcing parameters to be far from their optimal values creates instability problems, so this is also a test of how well estimation handles unstable problems. """ simulation, _, problem, solve_options, _ = simulated_problem # skip optimization methods that haven't been configured properly updated_solve_options = copy.deepcopy(solve_options) try: updated_solve_options['optimization'] = Optimization( method, compute_gradient=method not in {'nelder-mead', 'powell'} ) except OSError as exception: return pytest.skip(f"Failed to use the {method} method in this environment: {exception}.") # solve the problem when unbounded unbounded_solve_options = copy.deepcopy(updated_solve_options) unbounded_solve_options.update({ 'sigma_bounds': (np.full_like(simulation.sigma, -np.inf),
np.full_like(simulation.sigma, +np.inf)
numpy.full_like
# # generate mock data for PyCALI. # import numpy as np from numpy import fft import pycali import matplotlib.pyplot as plt import copy def convolve_fft(con, resp): """ convolution continuum with a response function using FFT """ resp_pad =
np.zeros(con.shape[0])
numpy.zeros
""" Top level process to generate the funscript actions by tracking selected features in the video """ import cv2 import copy import time import math import funscript_editor.utils.logging as logging import threading from dataclasses import dataclass from PyQt5 import QtCore from scipy.interpolate import interp1d from funscript_editor.algorithms.videotracker import StaticVideoTracker from funscript_editor.data.ffmpegstream import FFmpegStream from funscript_editor.data.funscript import Funscript from funscript_editor.utils.config import HYPERPARAMETER, SETTINGS, PROJECTION from funscript_editor.algorithms.scenedetect import SceneDetectFromFile, SceneContentDetector, SceneThresholdDetector from funscript_editor.algorithms.signal import Signal from funscript_editor.ui.opencvui import OpenCV_GUI, OpenCV_GUI_Parameters import multiprocessing as mp import numpy as np @dataclass class FunscriptGeneratorParameter: """ Funscript Generator Parameter Dataclass with default values """ video_path: str track_men: bool supervised_tracking: bool metric: str projection: str invert: bool start_frame: int end_frame: int = -1 # default is video end (-1) number_of_trackers: int = 1 supervised_tracking_is_exit_condition: bool = True # Settings points: str = "local_min_max" additional_points: str = "none" raw_output: bool = SETTINGS["raw_output"] max_playback_fps: int = max((0, int(SETTINGS['max_playback_fps']))) scene_detector: str = SETTINGS['scene_detector'] # General Hyperparameter skip_frames: int = 1 top_points_offset: float = 10.0 bottom_points_offset: float = -10.0 def merge_score(item: list, number_of_trackers: int, return_queue: mp.Queue = None) -> list: """ Merge score for given number of trackers Note: Python multiprocessing methods use a mp.SimpleQueue to pass tasks to the worker processes. Everything that goes through the mp.SimpleQueue must be pickable. In python functions are only picklable if they are defined at the top-level of a module. Args: item (list): score for each tracker number_of_trackers (int): number of used tracker (pairs) return_queue (mp.Queue, optional): return queue to return values via queue Returns: list: merged score """ if number_of_trackers == 1: if return_queue is not None: return_queue.put(item[0] if len(item) > 0 else []) else: return item[0] if len(item) > 0 else [] else: max_frame_number = max([len(item[i]) for i in range(number_of_trackers)]) arr =
np.ma.empty((max_frame_number,number_of_trackers))
numpy.ma.empty
# -*- coding: utf-8 -*- # # This file is part of QuTiP: Quantum Toolbox in Python. # # Copyright (c) 2011 and later, <NAME> and <NAME>. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names # of its contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Significant parts of this code were contributed by <NAME>. # ############################################################################### """ This module contains functions for solving stochastic schrodinger and master equations. The API should not be considered stable, and is subject to change when we work more on optimizing this module for performance and features. """ __all__ = ['ssesolve', 'ssepdpsolve', 'smesolve', 'smepdpsolve'] import numpy as np import scipy.sparse as sp from scipy.linalg.blas import get_blas_funcs try: norm = get_blas_funcs("znrm2", dtype=np.float64) except: from scipy.linalg import norm from numpy.random import RandomState from qutip.qobj import Qobj, isket from qutip.states import ket2dm from qutip.solver import Result from qutip.expect import expect, expect_rho_vec from qutip.superoperator import (spre, spost, mat2vec, vec2mat, liouvillian, lindblad_dissipator) from qutip.cy.spmatfuncs import cy_expect_psi_csr, spmv, cy_expect_rho_vec from qutip.cy.stochastic import (cy_d1_rho_photocurrent, cy_d2_rho_photocurrent) from qutip.parallel import serial_map from qutip.ui.progressbar import TextProgressBar from qutip.solver import Options, _solver_safety_check from qutip.settings import debug if debug: import qutip.logging_utils import inspect logger = qutip.logging_utils.get_logger() class StochasticSolverOptions: """Class of options for stochastic solvers such as :func:`qutip.stochastic.ssesolve`, :func:`qutip.stochastic.smesolve`, etc. Options can be specified either as arguments to the constructor:: sso = StochasticSolverOptions(nsubsteps=100, ...) or by changing the class attributes after creation:: sso = StochasticSolverOptions() sso.nsubsteps = 1000 The stochastic solvers :func:`qutip.stochastic.ssesolve`, :func:`qutip.stochastic.smesolve`, :func:`qutip.stochastic.ssepdpsolve` and :func:`qutip.stochastic.smepdpsolve` all take the same keyword arguments as the constructor of these class, and internally they use these arguments to construct an instance of this class, so it is rarely needed to explicitly create an instance of this class. Attributes ---------- H : :class:`qutip.Qobj` System Hamiltonian. state0 : :class:`qutip.Qobj` Initial state vector (ket) or density matrix. times : *list* / *array* List of times for :math:`t`. Must be uniformly spaced. c_ops : list of :class:`qutip.Qobj` List of deterministic collapse operators. sc_ops : list of :class:`qutip.Qobj` List of stochastic collapse operators. Each stochastic collapse operator will give a deterministic and stochastic contribution to the equation of motion according to how the d1 and d2 functions are defined. e_ops : list of :class:`qutip.Qobj` Single operator or list of operators for which to evaluate expectation values. m_ops : list of :class:`qutip.Qobj` List of operators representing the measurement operators. The expected format is a nested list with one measurement operator for each stochastic increament, for each stochastic collapse operator. args : dict / list List of dictionary of additional problem-specific parameters. Implicit methods can adjust tolerance via args = {'tol':value} ntraj : int Number of trajectors. nsubsteps : int Number of sub steps between each time-spep given in `times`. d1 : function Function for calculating the operator-valued coefficient to the deterministic increment dt. d2 : function Function for calculating the operator-valued coefficient to the stochastic increment(s) dW_n, where n is in [0, d2_len[. d2_len : int (default 1) The number of stochastic increments in the process. dW_factors : array Array of length d2_len, containing scaling factors for each measurement operator in m_ops. rhs : function Function for calculating the deterministic and stochastic contributions to the right-hand side of the stochastic differential equation. This only needs to be specified when implementing a custom SDE solver. generate_A_ops : function Function that generates a list of pre-computed operators or super- operators. These precomputed operators are used in some d1 and d2 functions. generate_noise : function Function for generate an array of pre-computed noise signal. homogeneous : bool (True) Wheter or not the stochastic process is homogenous. Inhomogenous processes are only supported for poisson distributions. solver : string Name of the solver method to use for solving the stochastic equations. Valid values are: 1/2 order algorithms: 'euler-maruyama', 'fast-euler-maruyama', 'pc-euler' is a predictor-corrector method which is more stable than explicit methods, 1 order algorithms: 'milstein', 'fast-milstein', 'platen', 'milstein-imp' is semi-implicit Milstein method, 3/2 order algorithms: 'taylor15', 'taylor15-imp' is semi-implicit Taylor 1.5 method. Implicit methods can adjust tolerance via args = {'tol':value}, default is {'tol':1e-6} method : string ('homodyne', 'heterodyne', 'photocurrent') The name of the type of measurement process that give rise to the stochastic equation to solve. Specifying a method with this keyword argument is a short-hand notation for using pre-defined d1 and d2 functions for the corresponding stochastic processes. distribution : string ('normal', 'poission') The name of the distribution used for the stochastic increments. store_measurements : bool (default False) Whether or not to store the measurement results in the :class:`qutip.solver.SolverResult` instance returned by the solver. noise : array Vector specifying the noise. normalize : bool (default True) Whether or not to normalize the wave function during the evolution. options : :class:`qutip.solver.Options` Generic solver options. map_func: function A map function or managing the calls to single-trajactory solvers. map_kwargs: dictionary Optional keyword arguments to the map_func function function. progress_bar : :class:`qutip.ui.BaseProgressBar` Optional progress bar class instance. """ def __init__(self, H=None, state0=None, times=None, c_ops=[], sc_ops=[], e_ops=[], m_ops=None, args=None, ntraj=1, nsubsteps=1, d1=None, d2=None, d2_len=1, dW_factors=None, rhs=None, generate_A_ops=None, generate_noise=None, homogeneous=True, solver=None, method=None, distribution='normal', store_measurement=False, noise=None, normalize=True, options=None, progress_bar=None, map_func=None, map_kwargs=None): if options is None: options = Options() if progress_bar is None: progress_bar = TextProgressBar() self.H = H self.d1 = d1 self.d2 = d2 self.d2_len = d2_len self.dW_factors = dW_factors if dW_factors else np.ones(d2_len) self.state0 = state0 self.times = times self.c_ops = c_ops self.sc_ops = sc_ops self.e_ops = e_ops if m_ops is None: self.m_ops = [[c for _ in range(d2_len)] for c in sc_ops] else: self.m_ops = m_ops self.ntraj = ntraj self.nsubsteps = nsubsteps self.solver = solver self.method = method self.distribution = distribution self.homogeneous = homogeneous self.rhs = rhs self.options = options self.progress_bar = progress_bar self.store_measurement = store_measurement self.store_states = options.store_states self.noise = noise self.args = args self.normalize = normalize self.generate_noise = generate_noise self.generate_A_ops = generate_A_ops if self.ntraj > 1 and map_func: self.map_func = map_func else: self.map_func = serial_map self.map_kwargs = map_kwargs if map_kwargs is not None else {} def ssesolve(H, psi0, times, sc_ops=[], e_ops=[], _safe_mode=True, **kwargs): """ Solve the stochastic Schrödinger equation. Dispatch to specific solvers depending on the value of the `solver` keyword argument. Parameters ---------- H : :class:`qutip.Qobj` System Hamiltonian. psi0 : :class:`qutip.Qobj` Initial state vector (ket). times : *list* / *array* List of times for :math:`t`. Must be uniformly spaced. sc_ops : list of :class:`qutip.Qobj` List of stochastic collapse operators. Each stochastic collapse operator will give a deterministic and stochastic contribution to the equation of motion according to how the d1 and d2 functions are defined. e_ops : list of :class:`qutip.Qobj` Single operator or list of operators for which to evaluate expectation values. kwargs : *dictionary* Optional keyword arguments. See :class:`qutip.stochastic.StochasticSolverOptions`. Returns ------- output: :class:`qutip.solver.SolverResult` An instance of the class :class:`qutip.solver.SolverResult`. """ if debug: logger.debug(inspect.stack()[0][3]) if isinstance(e_ops, dict): e_ops_dict = e_ops e_ops = [e for e in e_ops.values()] else: e_ops_dict = None if _safe_mode: _solver_safety_check(H, psi0, sc_ops, e_ops) sso = StochasticSolverOptions(H=H, state0=psi0, times=times, sc_ops=sc_ops, e_ops=e_ops, **kwargs) if sso.generate_A_ops is None: sso.generate_A_ops = _generate_psi_A_ops if (sso.d1 is None) or (sso.d2 is None): if sso.method == 'homodyne': sso.d1 = d1_psi_homodyne sso.d2 = d2_psi_homodyne sso.d2_len = 1 sso.homogeneous = True sso.distribution = 'normal' if "dW_factors" not in kwargs: sso.dW_factors = np.array([1]) if "m_ops" not in kwargs: sso.m_ops = [[c + c.dag()] for c in sso.sc_ops] elif sso.method == 'heterodyne': sso.d1 = d1_psi_heterodyne sso.d2 = d2_psi_heterodyne sso.d2_len = 2 sso.homogeneous = True sso.distribution = 'normal' if "dW_factors" not in kwargs: sso.dW_factors = np.array([np.sqrt(2), np.sqrt(2)]) if "m_ops" not in kwargs: sso.m_ops = [[(c + c.dag()), (-1j) * (c - c.dag())] for idx, c in enumerate(sso.sc_ops)] elif sso.method == 'photocurrent': sso.d1 = d1_psi_photocurrent sso.d2 = d2_psi_photocurrent sso.d2_len = 1 sso.homogeneous = False sso.distribution = 'poisson' if "dW_factors" not in kwargs: sso.dW_factors = np.array([1]) if "m_ops" not in kwargs: sso.m_ops = [[None] for c in sso.sc_ops] else: raise Exception("Unrecognized method '%s'." % sso.method) if sso.distribution == 'poisson': sso.homogeneous = False if sso.solver == 'euler-maruyama' or sso.solver is None: sso.rhs = _rhs_psi_euler_maruyama elif sso.solver == 'platen': sso.rhs = _rhs_psi_platen else: raise Exception("Unrecognized solver '%s'." % sso.solver) res = _ssesolve_generic(sso, sso.options, sso.progress_bar) if e_ops_dict: res.expect = {e: res.expect[n] for n, e in enumerate(e_ops_dict.keys())} return res def smesolve(H, rho0, times, c_ops=[], sc_ops=[], e_ops=[], _safe_mode=True ,**kwargs): """ Solve stochastic master equation. Dispatch to specific solvers depending on the value of the `solver` keyword argument. Parameters ---------- H : :class:`qutip.Qobj` System Hamiltonian. rho0 : :class:`qutip.Qobj` Initial density matrix or state vector (ket). times : *list* / *array* List of times for :math:`t`. Must be uniformly spaced. c_ops : list of :class:`qutip.Qobj` Deterministic collapse operator which will contribute with a standard Lindblad type of dissipation. sc_ops : list of :class:`qutip.Qobj` List of stochastic collapse operators. Each stochastic collapse operator will give a deterministic and stochastic contribution to the eqaution of motion according to how the d1 and d2 functions are defined. e_ops : list of :class:`qutip.Qobj` / callback function single single operator or list of operators for which to evaluate expectation values. kwargs : *dictionary* Optional keyword arguments. See :class:`qutip.stochastic.StochasticSolverOptions`. Returns ------- output: :class:`qutip.solver.SolverResult` An instance of the class :class:`qutip.solver.SolverResult`. TODO ---- Add checks for commuting jump operators in Milstein method. """ if debug: logger.debug(inspect.stack()[0][3]) if isket(rho0): rho0 = ket2dm(rho0) if isinstance(e_ops, dict): e_ops_dict = e_ops e_ops = [e for e in e_ops.values()] else: e_ops_dict = None if _safe_mode: _solver_safety_check(H, rho0, c_ops+sc_ops, e_ops) sso = StochasticSolverOptions(H=H, state0=rho0, times=times, c_ops=c_ops, sc_ops=sc_ops, e_ops=e_ops, **kwargs) if (sso.d1 is None) or (sso.d2 is None): if sso.method == 'homodyne' or sso.method is None: sso.d1 = d1_rho_homodyne sso.d2 = d2_rho_homodyne sso.d2_len = 1 sso.homogeneous = True sso.distribution = 'normal' if "dW_factors" not in kwargs: sso.dW_factors = np.array([np.sqrt(1)]) if "m_ops" not in kwargs: sso.m_ops = [[c + c.dag()] for c in sso.sc_ops] elif sso.method == 'heterodyne': sso.d1 = d1_rho_heterodyne sso.d2 = d2_rho_heterodyne sso.d2_len = 2 sso.homogeneous = True sso.distribution = 'normal' if "dW_factors" not in kwargs: sso.dW_factors = np.array([np.sqrt(2), np.sqrt(2)]) if "m_ops" not in kwargs: sso.m_ops = [[(c + c.dag()), -1j * (c - c.dag())] for c in sso.sc_ops] elif sso.method == 'photocurrent': sso.d1 = cy_d1_rho_photocurrent sso.d2 = cy_d2_rho_photocurrent sso.d2_len = 1 sso.homogeneous = False sso.distribution = 'poisson' if "dW_factors" not in kwargs: sso.dW_factors = np.array([1]) if "m_ops" not in kwargs: sso.m_ops = [[None] for c in sso.sc_ops] else: raise Exception("Unrecognized method '%s'." % sso.method) if sso.distribution == 'poisson': sso.homogeneous = False if sso.generate_A_ops is None: sso.generate_A_ops = _generate_rho_A_ops if sso.rhs is None: if sso.solver == 'euler-maruyama' or sso.solver is None: sso.rhs = _rhs_rho_euler_maruyama elif sso.solver == 'milstein': if sso.method == 'homodyne' or sso.method is None: if len(sc_ops) == 1: sso.rhs = _rhs_rho_milstein_homodyne_single else: sso.rhs = _rhs_rho_milstein_homodyne elif sso.method == 'heterodyne': sso.rhs = _rhs_rho_milstein_homodyne sso.d2_len = 1 sso.sc_ops = [] for sc in iter(sc_ops): sso.sc_ops += [sc / np.sqrt(2), -1.0j * sc / np.sqrt(2)] elif sso.solver == 'fast-euler-maruyama' and sso.method == 'homodyne': sso.rhs = _rhs_rho_euler_homodyne_fast sso.generate_A_ops = _generate_A_ops_Euler elif sso.solver == 'fast-milstein': sso.generate_A_ops = _generate_A_ops_Milstein sso.generate_noise = _generate_noise_Milstein if sso.method == 'homodyne' or sso.method is None: if len(sc_ops) == 1: sso.rhs = _rhs_rho_milstein_homodyne_single_fast elif len(sc_ops) == 2: sso.rhs = _rhs_rho_milstein_homodyne_two_fast else: sso.rhs = _rhs_rho_milstein_homodyne_fast elif sso.method == 'heterodyne': sso.d2_len = 1 sso.sc_ops = [] for sc in iter(sc_ops): sso.sc_ops += [sc / np.sqrt(2), -1.0j * sc / np.sqrt(2)] if len(sc_ops) == 1: sso.rhs = _rhs_rho_milstein_homodyne_two_fast else: sso.rhs = _rhs_rho_milstein_homodyne_fast elif sso.solver == 'taylor15': sso.generate_A_ops = _generate_A_ops_simple sso.generate_noise = _generate_noise_Taylor_15 if sso.method == 'homodyne' or sso.method is None: if len(sc_ops) == 1: sso.rhs = _rhs_rho_taylor_15_one #elif len(sc_ops) == 2: # sso.rhs = _rhs_rho_taylor_15_two else: raise Exception("Only one stochastic operator is supported") else: raise Exception("Only homodyne is available") elif sso.solver == 'milstein-imp': sso.generate_A_ops = _generate_A_ops_implicit sso.generate_noise = _generate_noise_Milstein if sso.args == None: sso.args = {'tol':1e-6} if sso.method == 'homodyne' or sso.method is None: if len(sc_ops) == 1: sso.rhs = _rhs_rho_milstein_implicit else: raise Exception("Only one stochastic operator is supported") else: raise Exception("Only homodyne is available") elif sso.solver == 'taylor15-imp': sso.generate_A_ops = _generate_A_ops_implicit sso.generate_noise = _generate_noise_Taylor_15 if sso.args == None: sso.args = {'tol':1e-6} if sso.method == 'homodyne' or sso.method is None: if len(sc_ops) == 1: sso.rhs = _rhs_rho_taylor_15_implicit else: raise Exception("Only one stochastic operator is supported") else: raise Exception("Only homodyne is available") elif sso.solver == 'pc-euler': sso.generate_A_ops = _generate_A_ops_Milstein sso.generate_noise = _generate_noise_Milstein # could also work without this if sso.method == 'homodyne' or sso.method is None: if len(sc_ops) == 1: sso.rhs = _rhs_rho_pred_corr_homodyne_single else: raise Exception("Only one stochastic operator is supported") else: raise Exception("Only homodyne is available") else: raise Exception("Unrecognized solver '%s'." % sso.solver) res = _smesolve_generic(sso, sso.options, sso.progress_bar) if e_ops_dict: res.expect = {e: res.expect[n] for n, e in enumerate(e_ops_dict.keys())} return res def ssepdpsolve(H, psi0, times, c_ops, e_ops, **kwargs): """ A stochastic (piecewse deterministic process) PDP solver for wavefunction evolution. For most purposes, use :func:`qutip.mcsolve` instead for quantum trajectory simulations. Parameters ---------- H : :class:`qutip.Qobj` System Hamiltonian. psi0 : :class:`qutip.Qobj` Initial state vector (ket). times : *list* / *array* List of times for :math:`t`. Must be uniformly spaced. c_ops : list of :class:`qutip.Qobj` Deterministic collapse operator which will contribute with a standard Lindblad type of dissipation. e_ops : list of :class:`qutip.Qobj` / callback function single single operator or list of operators for which to evaluate expectation values. kwargs : *dictionary* Optional keyword arguments. See :class:`qutip.stochastic.StochasticSolverOptions`. Returns ------- output: :class:`qutip.solver.SolverResult` An instance of the class :class:`qutip.solver.SolverResult`. """ if debug: logger.debug(inspect.stack()[0][3]) if isinstance(e_ops, dict): e_ops_dict = e_ops e_ops = [e for e in e_ops.values()] else: e_ops_dict = None sso = StochasticSolverOptions(H=H, state0=psi0, times=times, c_ops=c_ops, e_ops=e_ops, **kwargs) res = _ssepdpsolve_generic(sso, sso.options, sso.progress_bar) if e_ops_dict: res.expect = {e: res.expect[n] for n, e in enumerate(e_ops_dict.keys())} return res def smepdpsolve(H, rho0, times, c_ops, e_ops, **kwargs): """ A stochastic (piecewse deterministic process) PDP solver for density matrix evolution. Parameters ---------- H : :class:`qutip.Qobj` System Hamiltonian. rho0 : :class:`qutip.Qobj` Initial density matrix. times : *list* / *array* List of times for :math:`t`. Must be uniformly spaced. c_ops : list of :class:`qutip.Qobj` Deterministic collapse operator which will contribute with a standard Lindblad type of dissipation. sc_ops : list of :class:`qutip.Qobj` List of stochastic collapse operators. Each stochastic collapse operator will give a deterministic and stochastic contribution to the eqaution of motion according to how the d1 and d2 functions are defined. e_ops : list of :class:`qutip.Qobj` / callback function single single operator or list of operators for which to evaluate expectation values. kwargs : *dictionary* Optional keyword arguments. See :class:`qutip.stochastic.StochasticSolverOptions`. Returns ------- output: :class:`qutip.solver.SolverResult` An instance of the class :class:`qutip.solver.SolverResult`. """ if debug: logger.debug(inspect.stack()[0][3]) if isinstance(e_ops, dict): e_ops_dict = e_ops e_ops = [e for e in e_ops.values()] else: e_ops_dict = None sso = StochasticSolverOptions(H=H, state0=rho0, times=times, c_ops=c_ops, e_ops=e_ops, **kwargs) res = _smepdpsolve_generic(sso, sso.options, sso.progress_bar) if e_ops_dict: res.expect = {e: res.expect[n] for n, e in enumerate(e_ops_dict.keys())} return res # ----------------------------------------------------------------------------- # Generic parameterized stochastic Schrodinger equation solver # def _ssesolve_generic(sso, options, progress_bar): """ Internal function for carrying out a sse integration. Used by ssesolve. """ if debug: logger.debug(inspect.stack()[0][3]) sso.N_store = len(sso.times) sso.N_substeps = sso.nsubsteps sso.dt = (sso.times[1] - sso.times[0]) / sso.N_substeps nt = sso.ntraj data = Result() data.solver = "ssesolve" data.times = sso.times data.expect = np.zeros((len(sso.e_ops), sso.N_store), dtype=complex) data.ss = np.zeros((len(sso.e_ops), sso.N_store), dtype=complex) data.noise = [] data.measurement = [] # pre-compute collapse operator combinations that are commonly needed # when evaluating the RHS of stochastic Schrodinger equations sso.A_ops = sso.generate_A_ops(sso.sc_ops, sso.H) map_kwargs = {'progress_bar': progress_bar} map_kwargs.update(sso.map_kwargs) task = _ssesolve_single_trajectory task_args = (sso,) task_kwargs = {} results = sso.map_func(task, list(range(sso.ntraj)), task_args, task_kwargs, **map_kwargs) for result in results: states_list, dW, m, expect, ss = result data.states.append(states_list) data.noise.append(dW) data.measurement.append(m) data.expect += expect data.ss += ss # average density matrices if options.average_states and np.any(data.states): data.states = [sum([ket2dm(data.states[mm][n]) for mm in range(nt)]).unit() for n in range(len(data.times))] # average data.expect = data.expect / nt # standard error if nt > 1: data.se = (data.ss - nt * (data.expect ** 2)) / (nt * (nt - 1)) else: data.se = None # convert complex data to real if hermitian data.expect = [np.real(data.expect[n, :]) if e.isherm else data.expect[n, :] for n, e in enumerate(sso.e_ops)] return data def _ssesolve_single_trajectory(n, sso): """ Internal function. See ssesolve. """ dt = sso.dt times = sso.times d1, d2 = sso.d1, sso.d2 d2_len = sso.d2_len e_ops = sso.e_ops H_data = sso.H.data A_ops = sso.A_ops expect = np.zeros((len(sso.e_ops), sso.N_store), dtype=complex) ss = np.zeros((len(sso.e_ops), sso.N_store), dtype=complex) psi_t = sso.state0.full().ravel() dims = sso.state0.dims # reseed the random number generator so that forked # processes do not get the same sequence of random numbers np.random.seed((n+1) * np.random.randint(0, 4294967295 // (sso.ntraj+1))) if sso.noise is None: if sso.homogeneous: if sso.distribution == 'normal': dW = np.sqrt(dt) * \ np.random.randn(len(A_ops), sso.N_store, sso.N_substeps, d2_len) else: raise TypeError('Unsupported increment distribution for ' + 'homogeneous process.') else: if sso.distribution != 'poisson': raise TypeError('Unsupported increment distribution for ' + 'inhomogeneous process.') dW = np.zeros((len(A_ops), sso.N_store, sso.N_substeps, d2_len)) else: dW = sso.noise[n] states_list = [] measurements = np.zeros((len(times), len(sso.m_ops), d2_len), dtype=complex) for t_idx, t in enumerate(times): if e_ops: for e_idx, e in enumerate(e_ops): s = cy_expect_psi_csr(e.data.data, e.data.indices, e.data.indptr, psi_t, 0) expect[e_idx, t_idx] += s ss[e_idx, t_idx] += s ** 2 else: states_list.append(Qobj(psi_t, dims=dims)) for j in range(sso.N_substeps): if sso.noise is None and not sso.homogeneous: for a_idx, A in enumerate(A_ops): # dw_expect = norm(spmv(A[0], psi_t)) ** 2 * dt dw_expect = cy_expect_psi_csr(A[3].data, A[3].indices, A[3].indptr, psi_t, 1) * dt dW[a_idx, t_idx, j, :] = np.random.poisson(dw_expect, d2_len) psi_t = sso.rhs(H_data, psi_t, t + dt * j, A_ops, dt, dW[:, t_idx, j, :], d1, d2, sso.args) # optionally renormalize the wave function if sso.normalize: psi_t /= norm(psi_t) if sso.store_measurement: for m_idx, m in enumerate(sso.m_ops): for dW_idx, dW_factor in enumerate(sso.dW_factors): if m[dW_idx]: m_data = m[dW_idx].data m_expt = cy_expect_psi_csr(m_data.data, m_data.indices, m_data.indptr, psi_t, 0) else: m_expt = 0 mm = (m_expt + dW_factor * dW[m_idx, t_idx, :, dW_idx].sum() / (dt * sso.N_substeps)) measurements[t_idx, m_idx, dW_idx] = mm if d2_len == 1: measurements = measurements.squeeze(axis=(2)) return states_list, dW, measurements, expect, ss # ----------------------------------------------------------------------------- # Generic parameterized stochastic master equation solver # def _smesolve_generic(sso, options, progress_bar): """ Internal function. See smesolve. """ if debug: logger.debug(inspect.stack()[0][3]) sso.N_store = len(sso.times) sso.N_substeps = sso.nsubsteps sso.dt = (sso.times[1] - sso.times[0]) / sso.N_substeps nt = sso.ntraj data = Result() data.solver = "smesolve" data.times = sso.times data.expect = np.zeros((len(sso.e_ops), sso.N_store), dtype=complex) data.ss = np.zeros((len(sso.e_ops), sso.N_store), dtype=complex) data.noise = [] data.measurement = [] # Liouvillian for the deterministic part. # needs to be modified for TD systems sso.L = liouvillian(sso.H, sso.c_ops) # pre-compute suporoperator operator combinations that are commonly needed # when evaluating the RHS of stochastic master equations sso.A_ops = sso.generate_A_ops(sso.sc_ops, sso.L.data, sso.dt) # use .data instead of Qobj ? sso.s_e_ops = [spre(e) for e in sso.e_ops] if sso.m_ops: sso.s_m_ops = [[spre(m) if m else None for m in m_op] for m_op in sso.m_ops] else: sso.s_m_ops = [[spre(c) for _ in range(sso.d2_len)] for c in sso.sc_ops] map_kwargs = {'progress_bar': progress_bar} map_kwargs.update(sso.map_kwargs) task = _smesolve_single_trajectory task_args = (sso,) task_kwargs = {} results = sso.map_func(task, list(range(sso.ntraj)), task_args, task_kwargs, **map_kwargs) for result in results: states_list, dW, m, expect, ss = result data.states.append(states_list) data.noise.append(dW) data.measurement.append(m) data.expect += expect data.ss += ss # average density matrices if options.average_states and np.any(data.states): data.states = [sum([data.states[mm][n] for mm in range(nt)]).unit() for n in range(len(data.times))] # average data.expect = data.expect / nt # standard error if nt > 1: data.se = (data.ss - nt * (data.expect ** 2)) / (nt * (nt - 1)) else: data.se = None # convert complex data to real if hermitian data.expect = [np.real(data.expect[n, :]) if e.isherm else data.expect[n, :] for n, e in enumerate(sso.e_ops)] return data def _smesolve_single_trajectory(n, sso): """ Internal function. See smesolve. """ dt = sso.dt times = sso.times d1, d2 = sso.d1, sso.d2 d2_len = sso.d2_len L_data = sso.L.data N_substeps = sso.N_substeps N_store = sso.N_store A_ops = sso.A_ops rho_t = mat2vec(sso.state0.full()).ravel() dims = sso.state0.dims expect = np.zeros((len(sso.e_ops), sso.N_store), dtype=complex) ss = np.zeros((len(sso.e_ops), sso.N_store), dtype=complex) # reseed the random number generator so that forked # processes do not get the same sequence of random numbers np.random.seed((n+1) * np.random.randint(0, 4294967295 // (sso.ntraj+1))) if sso.noise is None: if sso.generate_noise: dW = sso.generate_noise(len(A_ops), N_store, N_substeps, sso.d2_len, dt) elif sso.homogeneous: if sso.distribution == 'normal': dW = np.sqrt(dt) * np.random.randn(len(A_ops), N_store, N_substeps, d2_len) else: raise TypeError('Unsupported increment distribution for ' + 'homogeneous process.') else: if sso.distribution != 'poisson': raise TypeError('Unsupported increment distribution for ' + 'inhomogeneous process.') dW = np.zeros((len(A_ops), N_store, N_substeps, d2_len)) else: dW = sso.noise[n] states_list = [] measurements = np.zeros((len(times), len(sso.s_m_ops), d2_len), dtype=complex) for t_idx, t in enumerate(times): if sso.s_e_ops: for e_idx, e in enumerate(sso.s_e_ops): s = cy_expect_rho_vec(e.data, rho_t, 0) expect[e_idx, t_idx] += s ss[e_idx, t_idx] += s ** 2 if sso.store_states or not sso.s_e_ops: states_list.append(Qobj(vec2mat(rho_t), dims=dims)) rho_prev = np.copy(rho_t) for j in range(N_substeps): if sso.noise is None and not sso.homogeneous: for a_idx, A in enumerate(A_ops): dw_expect = cy_expect_rho_vec(A[4], rho_t, 1) * dt if dw_expect > 0: dW[a_idx, t_idx, j, :] = np.random.poisson(dw_expect, d2_len) else: dW[a_idx, t_idx, j, :] = np.zeros(d2_len) rho_t = sso.rhs(L_data, rho_t, t + dt * j, A_ops, dt, dW[:, t_idx, j, :], d1, d2, sso.args) if sso.store_measurement: for m_idx, m in enumerate(sso.s_m_ops): for dW_idx, dW_factor in enumerate(sso.dW_factors): if m[dW_idx]: m_expt = cy_expect_rho_vec(m[dW_idx].data, rho_prev, 0) else: m_expt = 0 measurements[t_idx, m_idx, dW_idx] = m_expt + dW_factor * \ dW[m_idx, t_idx, :, dW_idx].sum() / (dt * N_substeps) if d2_len == 1: measurements = measurements.squeeze(axis=(2)) return states_list, dW, measurements, expect, ss # ----------------------------------------------------------------------------- # Generic parameterized stochastic SE PDP solver # def _ssepdpsolve_generic(sso, options, progress_bar): """ For internal use. See ssepdpsolve. """ if debug: logger.debug(inspect.stack()[0][3]) N_store = len(sso.times) N_substeps = sso.nsubsteps dt = (sso.times[1] - sso.times[0]) / N_substeps nt = sso.ntraj data = Result() data.solver = "sepdpsolve" data.times = sso.tlist data.expect = np.zeros((len(sso.e_ops), N_store), dtype=complex) data.ss = np.zeros((len(sso.e_ops), N_store), dtype=complex) data.jump_times = [] data.jump_op_idx = [] # effective hamiltonian for deterministic part Heff = sso.H for c in sso.c_ops: Heff += -0.5j * c.dag() * c progress_bar.start(sso.ntraj) for n in range(sso.ntraj): progress_bar.update(n) psi_t = sso.state0.full().ravel() states_list, jump_times, jump_op_idx = \ _ssepdpsolve_single_trajectory(data, Heff, dt, sso.times, N_store, N_substeps, psi_t, sso.state0.dims, sso.c_ops, sso.e_ops) data.states.append(states_list) data.jump_times.append(jump_times) data.jump_op_idx.append(jump_op_idx) progress_bar.finished() # average density matrices if options.average_states and np.any(data.states): data.states = [sum([data.states[m][n] for m in range(nt)]).unit() for n in range(len(data.times))] # average data.expect = data.expect / nt # standard error if nt > 1: data.se = (data.ss - nt * (data.expect ** 2)) / (nt * (nt - 1)) else: data.se = None # convert complex data to real if hermitian data.expect = [np.real(data.expect[n, :]) if e.isherm else data.expect[n, :] for n, e in enumerate(sso.e_ops)] return data def _ssepdpsolve_single_trajectory(data, Heff, dt, times, N_store, N_substeps, psi_t, dims, c_ops, e_ops): """ Internal function. See ssepdpsolve. """ states_list = [] phi_t = np.copy(psi_t) prng = RandomState() # todo: seed it r_jump, r_op = prng.rand(2) jump_times = [] jump_op_idx = [] for t_idx, t in enumerate(times): if e_ops: for e_idx, e in enumerate(e_ops): s = cy_expect_psi_csr( e.data.data, e.data.indices, e.data.indptr, psi_t, 0) data.expect[e_idx, t_idx] += s data.ss[e_idx, t_idx] += s ** 2 else: states_list.append(Qobj(psi_t, dims=dims)) for j in range(N_substeps): if norm(phi_t) ** 2 < r_jump: # jump occurs p = np.array([norm(c.data * psi_t) ** 2 for c in c_ops]) p = np.cumsum(p / np.sum(p)) n = np.where(p >= r_op)[0][0] # apply jump psi_t = c_ops[n].data * psi_t psi_t /= norm(psi_t) phi_t = np.copy(psi_t) # store info about jump jump_times.append(times[t_idx] + dt * j) jump_op_idx.append(n) # get new random numbers for next jump r_jump, r_op = prng.rand(2) # deterministic evolution wihtout correction for norm decay dphi_t = (-1.0j * dt) * (Heff.data * phi_t) # deterministic evolution with correction for norm decay dpsi_t = (-1.0j * dt) * (Heff.data * psi_t) A = 0.5 * np.sum([norm(c.data * psi_t) ** 2 for c in c_ops]) dpsi_t += dt * A * psi_t # increment wavefunctions phi_t += dphi_t psi_t += dpsi_t # ensure that normalized wavefunction remains normalized # this allows larger time step than otherwise would be possible psi_t /= norm(psi_t) return states_list, jump_times, jump_op_idx # ----------------------------------------------------------------------------- # Generic parameterized stochastic ME PDP solver # def _smepdpsolve_generic(sso, options, progress_bar): """ For internal use. See smepdpsolve. """ if debug: logger.debug(inspect.stack()[0][3]) N_store = len(sso.times) N_substeps = sso.nsubsteps dt = (sso.times[1] - sso.times[0]) / N_substeps nt = sso.ntraj data = Result() data.solver = "smepdpsolve" data.times = sso.times data.expect = np.zeros((len(sso.e_ops), N_store), dtype=complex) data.jump_times = [] data.jump_op_idx = [] # Liouvillian for the deterministic part. # needs to be modified for TD systems L = liouvillian(sso.H, sso.c_ops) progress_bar.start(sso.ntraj) for n in range(sso.ntraj): progress_bar.update(n) rho_t = mat2vec(sso.rho0.full()).ravel() states_list, jump_times, jump_op_idx = \ _smepdpsolve_single_trajectory(data, L, dt, sso.times, N_store, N_substeps, rho_t, sso.rho0.dims, sso.c_ops, sso.e_ops) data.states.append(states_list) data.jump_times.append(jump_times) data.jump_op_idx.append(jump_op_idx) progress_bar.finished() # average density matrices if options.average_states and np.any(data.states): data.states = [sum([data.states[m][n] for m in range(nt)]).unit() for n in range(len(data.times))] # average data.expect = data.expect / sso.ntraj # standard error if nt > 1: data.se = (data.ss - nt * (data.expect ** 2)) / (nt * (nt - 1)) else: data.se = None return data def _smepdpsolve_single_trajectory(data, L, dt, times, N_store, N_substeps, rho_t, dims, c_ops, e_ops): """ Internal function. See smepdpsolve. """ states_list = [] rho_t = np.copy(rho_t) sigma_t = np.copy(rho_t) prng = RandomState() # todo: seed it r_jump, r_op = prng.rand(2) jump_times = [] jump_op_idx = [] for t_idx, t in enumerate(times): if e_ops: for e_idx, e in enumerate(e_ops): data.expect[e_idx, t_idx] += expect_rho_vec(e, rho_t) else: states_list.append(Qobj(vec2mat(rho_t), dims=dims)) for j in range(N_substeps): if sigma_t.norm() < r_jump: # jump occurs p = np.array([expect(c.dag() * c, rho_t) for c in c_ops]) p = np.cumsum(p / np.sum(p)) n = np.where(p >= r_op)[0][0] # apply jump rho_t = c_ops[n] * rho_t * c_ops[n].dag() rho_t /= expect(c_ops[n].dag() * c_ops[n], rho_t) sigma_t = np.copy(rho_t) # store info about jump jump_times.append(times[t_idx] + dt * j) jump_op_idx.append(n) # get new random numbers for next jump r_jump, r_op = prng.rand(2) # deterministic evolution wihtout correction for norm decay dsigma_t = spmv(L.data, sigma_t) * dt # deterministic evolution with correction for norm decay drho_t = spmv(L.data, rho_t) * dt rho_t += drho_t # increment density matrices sigma_t += dsigma_t rho_t += drho_t return states_list, jump_times, jump_op_idx # ----------------------------------------------------------------------------- # Helper-functions for stochastic DE # # d1 = deterministic part of the contribution to the DE RHS function, to be # multiplied by the increament dt # # d1 = stochastic part of the contribution to the DE RHS function, to be # multiplied by the increament dW # # # For SSE # # Function sigurature: # # def d(A, psi): # # psi = wave function at the current time step # # A[0] = c # A[1] = c + c.dag() # A[2] = c - c.dag() # A[3] = c.dag() * c # # where c is a collapse operator. The combinations of c's stored in A are # precomputed before the time-evolution is started to avoid repeated # computations. def _generate_psi_A_ops(sc_ops, H): """ pre-compute superoperator operator combinations that are commonly needed when evaluating the RHS of stochastic schrodinger equations """ A_ops = [] for c_idx, c in enumerate(sc_ops): A_ops.append([c.data, (c + c.dag()).data, (c - c.dag()).data, (c.dag() * c).data]) return A_ops def d1_psi_homodyne(t, psi, A, args): """ OK Need to cythonize .. math:: D_1(C, \psi) = \\frac{1}{2}(\\langle C + C^\\dagger\\rangle\\C psi - C^\\dagger C\\psi - \\frac{1}{4}\\langle C + C^\\dagger\\rangle^2\\psi) """ e1 = cy_expect_psi_csr(A[1].data, A[1].indices, A[1].indptr, psi, 0) return 0.5 * (e1 * spmv(A[0], psi) - spmv(A[3], psi) - 0.25 * e1 ** 2 * psi) def d2_psi_homodyne(t, psi, A, args): """ OK Need to cythonize .. math:: D_2(\psi, t) = (C - \\frac{1}{2}\\langle C + C^\\dagger\\rangle)\\psi """ e1 = cy_expect_psi_csr(A[1].data, A[1].indices, A[1].indptr, psi, 0) return [spmv(A[0], psi) - 0.5 * e1 * psi] def d1_psi_heterodyne(t, psi, A, args): """ Need to cythonize .. math:: D_1(\psi, t) = -\\frac{1}{2}(C^\\dagger C - \\langle C^\\dagger \\rangle C + \\frac{1}{2}\\langle C \\rangle\\langle C^\\dagger \\rangle))\psi """ e_C = cy_expect_psi_csr(A[0].data, A[0].indices, A[0].indptr, psi, 0) B = A[0].T.conj() e_Cd = cy_expect_psi_csr(B.data, B.indices, B.indptr, psi, 0) return (-0.5 * spmv(A[3], psi) + 0.5 * e_Cd * spmv(A[0], psi) - 0.25 * e_C * e_Cd * psi) def d2_psi_heterodyne(t, psi, A, args): """ Need to cythonize X = \\frac{1}{2}(C + C^\\dagger) Y = \\frac{1}{2}(C - C^\\dagger) D_{2,1}(\psi, t) = \\sqrt(1/2) (C - \\langle X \\rangle) \\psi D_{2,2}(\psi, t) = -i\\sqrt(1/2) (C - \\langle Y \\rangle) \\psi """ X = 0.5 * cy_expect_psi_csr(A[1].data, A[1].indices, A[1].indptr, psi, 0) Y = 0.5 * cy_expect_psi_csr(A[2].data, A[2].indices, A[2].indptr, psi, 0) d2_1 = np.sqrt(0.5) * (spmv(A[0], psi) - X * psi) d2_2 = -1.0j * np.sqrt(0.5) * (spmv(A[0], psi) - Y * psi) return [d2_1, d2_2] def d1_psi_photocurrent(t, psi, A, args): """ Need to cythonize. Note: requires poisson increments .. math:: D_1(\psi, t) = - \\frac{1}{2}(C^\dagger C \psi - ||C\psi||^2 \psi) """ return (-0.5 * (spmv(A[3], psi) - norm(spmv(A[0], psi)) ** 2 * psi)) def d2_psi_photocurrent(t, psi, A, args): """ Need to cythonize Note: requires poisson increments .. math:: D_2(\psi, t) = C\psi / ||C\psi|| - \psi """ psi_1 = spmv(A[0], psi) n1 = norm(psi_1) if n1 != 0: return [psi_1 / n1 - psi] else: return [- psi] # # For SME # # def d(A, rho_vec): # # rho = density operator in vector form at the current time stemp # # A[_idx_A_L] = spre(a) = A_L # A[_idx_A_R] = spost(a) = A_R # A[_idx_Ad_L] = spre(a.dag()) = Ad_L # A[_idx_Ad_R] = spost(a.dag()) = Ad_R # A[_idx_AdA_L] = spre(a.dag() * a) = (Ad A)_L # A[_idx_AdA_R] = spost(a.dag() * a) = (Ad A)_R # A[_idx_A_LxAd_R] = (spre(a) * spost(a.dag()) = A_L * Ad_R # A[_idx_LD] = lindblad_dissipator(a) _idx_A_L = 0 _idx_A_R = 1 _idx_Ad_L = 2 _idx_Ad_R = 3 _idx_AdA_L = 4 _idx_AdA_R = 5 _idx_A_LxAd_R = 6 _idx_LD = 7 def _generate_rho_A_ops(sc, L, dt): """ pre-compute superoperator operator combinations that are commonly needed when evaluating the RHS of stochastic master equations """ out = [] for c_idx, c in enumerate(sc): n = c.dag() * c out.append([spre(c).data, spost(c).data, spre(c.dag()).data, spost(c.dag()).data, spre(n).data, spost(n).data, (spre(c) * spost(c.dag())).data, lindblad_dissipator(c, data_only=True)]) return out def _generate_A_ops_Euler(sc, L, dt): """ combine precomputed operators in one long operator for the Euler method """ A_len = len(sc) out = [] out += [spre(c).data + spost(c.dag()).data for c in sc] out += [(L + np.sum( [lindblad_dissipator(c, data_only=True) for c in sc], axis=0)) * dt] out1 = [[sp.vstack(out).tocsr(), sc[0].shape[0]]] # the following hack is required for compatibility with old A_ops out1 += [[] for n in range(A_len - 1)] # XXX: fix this! out1[0][0].indices =
np.array(out1[0][0].indices, dtype=np.int32)
numpy.array
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Sep 25 16:10:11 2020 @author: <NAME> This file contains the functions that are needed for the harmonization of the Hitran absorption cross section data and for the calculations of the fit coefficients. """ from glob import glob from os import path import matplotlib.patches as ptch import matplotlib.pyplot as plt import numpy as np import pyarts from matplotlib.font_manager import FontProperties from scipy.interpolate import interp1d from scipy.linalg import lstsq # %% constants # speed of light c0 = 299792458.0 # [m/s] # %% fit related functions def fit_poly22(xdata, ydata, zdata): ''' 2d quadratic fit: z = p00 + p10*x + p01*y + p20*x**2 + p02*y**2 Args: xdata: vector independent data. ydata: vector independent data. zdata: vector data, which depends on xdata and ydata. Returns: poly: vector coefficients of fit, see above for the order. res: float summed residuums. rnk: int Effective rank of design matrix M. s: ndarray or None Singular values of M. ''' M = np.ones((len(xdata), 5)) M[:, 1] = xdata # p01 M[:, 2] = ydata # p01 M[:, 3] = xdata ** 2 # p20 M[:, 4] = ydata ** 2 # p02 poly, res, rnk, s = lstsq(M, zdata) return poly, res, rnk, s def fit_poly21(xdata, ydata, zdata): ''' 2d semi quadratic fit: z = p00 + p10*x + p01*y + p20*x**2 Args: xdata: vector independent data. ydata: vector independent data. zdata: vector data, which depends on xdata and ydata. Returns: poly: vector coefficients of fit, see above for the order. res: float summed residuums. rnk: int Effective rank of design matrix M. s: ndarray or None Singular values of M. ''' M = np.ones((len(xdata), 4)) M[:, 1] = xdata # p01 M[:, 2] = ydata # p10 M[:, 3] = xdata ** 2 # p20 poly, res, rnk, s = lstsq(M, zdata) return poly, res, rnk, s def fit_poly12(xdata, ydata, zdata): ''' 2d semi quadratic fit: z = p00 + p10*x + p01*y + p02*y**2 Args: xdata: vector independent data. ydata: vector independent data. zdata: vector data, which depends on xdata and ydata. Returns: poly: vector coefficients of fit, see above for the order. res: float summed residuums. rnk: int Effective rank of design matrix M. s: ndarray or None Singular values of M. ''' M = np.ones((len(xdata), 4)) M[:, 1] = xdata # p01 M[:, 2] = ydata # p10 M[:, 3] = ydata ** 2 # p02 poly, res, rnk, s = lstsq(M, zdata) return poly, res, rnk, s def fit_poly11(xdata, ydata, zdata): ''' 2d linear fit: z = p00 + p10*x + p01*y Args: xdata: vector independent data. ydata: vector independent data. zdata: vector data, which depends on xdata and ydata. Returns: poly: vector coefficients of fit, see above for the order. res: float summed residuums. rnk: int Effective rank of design matrix M. s: ndarray or None Singular values of M. ''' M = np.ones((len(xdata), 3)) M[:, 1] = xdata # p10 M[:, 2] = ydata # p01 poly, res, rnk, s = lstsq(M, zdata) return poly, res, rnk, s def fit_poly2(xdata, zdata): ''' 1d quadratic fit: z = p0 + p1*x + p2*x**2 Args: xdata: vector independent data. zdata: vector data, which depends on xdata. Returns: poly: vector coefficients of fit, see above for the order. res: float summed residuums. rnk: int Effective rank of design matrix M. s: ndarray or None Singular values of M. ''' # 1d quadratic fit: # z = p0 + p1*x + p2*x**2 M = np.ones((len(xdata), 3)) M[:, 1] = xdata # p1 M[:, 2] = xdata ** 2 # p2 poly, res, rnk, s = lstsq(M, zdata) return poly, res, rnk, s def fit_poly1(xdata, zdata): ''' 1d linear fit: z = p0 + p1*x Args: xdata: vector independent data zdata: vector data, which depends on xdata Returns: poly: vector coefficients of fit, see above for the order res: float summed residuums rnk: int Effective rank of design matrix M s: ndarray or None Singular values of M ''' M = np.ones((len(xdata), 2)) M[:, 1] = xdata # p1 poly, res, rnk, s = lstsq(M, zdata) return poly, res, rnk, s def calc_Rsquare(y, yfit, Ncoeffs): ''' calculates the adjusted R-square statistic Args: y: vector true value. yfit: vector fited value. Ncoeffs: int number of fit coefficients. Returns: rsquare: float adjusted R-square statistic. ''' Delta_y = y - yfit Var_y = y - np.nanmean(y) SSE = np.nansum(Delta_y ** 2) SST = np.nansum(Var_y ** 2) n = len(y) if SST == 0 or (n - Ncoeffs) == 0: SST = np.nan n = np.nan return 1. - SSE * (n - 1.) / (SST * (n - Ncoeffs)) def calculate_xsec(T, P, coeffs): ''' Low level function to calculate the absorption cross section from the fitted coefficients Args: T: float Temperature in K. P: float Pressure in Pa. coeffs: matrix fit coefficients. Returns: Xsec: vector Absorption cross section in m**2. The fit model 2d quadratic fit: z= p00 + p10*x + p01*y + p20*x**2 + p02*y**2 z=Xsec x=T y=P coeffs[0,:] p00 coeffs[1,:] p10 coeffs[2,:] p01 coeffs[3,:] p20 coeffs[4,:] p02 ''' #distinguish if we calculate xsec for a lot of frequencies if len(np.shape(coeffs))>1: poly = np.zeros(5) poly[0] = 1 poly[1] = T poly[2] = P poly[3] = T ** 2 poly[4] = P ** 2 # allocate Xsec = np.zeros(np.shape(coeffs)) for i in range(5): Xsec[i, :] = coeffs[i, :] * poly[i] #or for a lot of states else: poly = np.zeros((5,len(T))) poly[0,:] = 1. poly[1,:] = T poly[2,:] = P poly[3,:] = T ** 2 poly[4,:] = P ** 2 # allocate Xsec = np.zeros( (len(coeffs),len(T)) ) for i in range(5): Xsec[i, :] = coeffs[i] * poly[i,:] Xsec = np.sum(Xsec, axis=0) return Xsec def calculate_xsec_fullmodel(T, P, coeffs, minT=0., maxT=np.inf, minP=0, maxP=np.inf): ''' Function to calculate the absorption cross section from the fitted coefficients including extrapolation Args: T: float Temperature in K. P: float Pressure in Pa. coeffs: matrix fit coefficients. minT: float minimum temperature of the data in K. maxT: float maximum temperature of the data in K. minP: float minimum pressure of the data in Pa. maxP: float maximum pressure of the data in Pa. Returns: Xsec: vector Absorption cross section in m**2. The fit model 2d quadratic fit: z= p00 + p10*x + p01*y + p20*x**2 + p02*y**2 z=Xsec x=T y=P coeffs[0,:] p00 coeffs[1,:] p10 coeffs[2,:] p01 coeffs[3,:] p20 coeffs[4,:] p02 ''' if (P < minP or P > maxP or T < minT or T > maxT): if P < minP: P0 = minP elif P > maxP: P0 = maxP else: P0 = P # P=P0 if T < minT: T0 = minT elif T > maxT: T0 = maxT else: T0 = T xsec_0 = calculate_xsec(T0, P0, coeffs) DxsecDT, DxsecDp = xsec_derivative(T0, P0, coeffs) xsec = xsec_0 + DxsecDT * (T - T0) + DxsecDp * (P - P0) else: # calculate raw xsecs xsec = calculate_xsec(T, P, coeffs) #Check for negative values and remove them without introducing bias, meaning #the integral over the spectrum must not change. logic = xsec < 0 if np.sum(logic) > 0: #original sum over spectrum sumX_org=np.sum(xsec); #remove negative values xsec[logic]=0 if sumX_org>=0: #estimate ratio between altered and original sum of spectrum w=sumX_org/np.sum(xsec) #scale altered spectrum xsec=xsec*w return xsec def xsec_derivative(T, P, coeffs): ''' Fucntion to calculate the derivative of the absorption cross section from the fitted coefficients. Args: T: float Temperature in K. P: float Pressure in Pa. coeffs: matrix fit coefficients. Returns: DxsecDT: vector Temperature derivative. DxsecDp: vector Pressure derivative. The fit model 2d quadratic fit: z= p00 + p10*x + p01*y + p20*x**2 + p02*y**2 z=Xsec x=T y=P coeffs[0,:] p00 coeffs[1,:] p10 coeffs[2,:] p01 coeffs[3,:] p20 coeffs[4,:] p02 ''' # p00 = coeffs[0, :] p10 = coeffs[1, :] p01 = coeffs[2, :] p20 = coeffs[3, :] p02 = coeffs[4, :] # FofP = P DxsecDT = p10 + 2*p20*T DxsecDp = p01 + 2*p02*P return DxsecDT, DxsecDp def fit_xsec_data(T, P, Xsec, min_deltaP=100, min_deltaT=20.,cnt_limit=2, k_outlier=1.5): ''' FUnction to calculate the fit of the xsec at an arbitrary frequency Args: T: vector temperatures. P: vector pressures same lenghth as `T`. Xsec: vector cross section same length as `T`. min_deltaP: float, optional minimum variability of sqrt(`P`) for fit. Defaults to 100 min_deltaT: float, optional minimum variability of `T` for fit. Defaults to 20. cnt_limit: integer, optional maximum number of iteration of the fit due to outlier removal. k_outlier: float, optional scaling factor for outlier detection Returns: fit_result: dictionary results of the fit. The fit model 2d quadratic fit: z= p00 + p10*x + p01*y + p20*x**2 + p02*y**2 z=Xsec x=T y=P coeffs[0,:] p00 coeffs[1,:] p10 coeffs[2,:] p01 coeffs[3,:] p20 coeffs[4,:] p02 ''' FofP = P FofXsec = Xsec # check for bad values logic_inf = np.isinf(T) | np.isinf(FofP) | np.isinf(FofXsec) logic_nan = np.isnan(T) | np.isnan(FofP) | np.isnan(FofXsec) logic_bad = logic_inf | logic_nan if np.sum(logic_bad) < len(T): # remove bad values xData = T[~logic_bad] yData = FofP[~logic_bad] zData =FofXsec[~logic_bad] # get number of unique temperatures and pressures N_Tunique = np.size(
np.unique(xData)
numpy.unique
"""Module containing functions related to the plotting of data and features. It contains the following functions: plot_audio() """ import os import numpy as np import pandas as pd import librosa.display import matplotlib.pyplot as plt from sklearn.metrics import roc_curve, roc_auc_score def plot_audio(audio_filename, sr, waveplot=True): """ thingy. Parameters ---------- audio_filename : TYPE DESCRIPTION. sr : TYPE DESCRIPTION. waveplot : TYPE, optional DESCRIPTION. The default is True. Returns ------- None. """ if audio_filename[-4:] == ".wav": y, _ = librosa.load(audio_filename, sr=sr) else: y = pd.read_csv(audio_filename, header=None).to_numpy().flatten() y = y[~
np.isnan(y)
numpy.isnan
# 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])
numpy.asarray
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.optim.optimizer import Optimizer import math import time numpy_to_torch_dtype_dict = { np.dtype('bool') : torch.bool, np.dtype('uint8') : torch.uint8, np.dtype('int8') : torch.int8, np.dtype('int16') : torch.int16,
np.dtype('int32')
numpy.dtype
#Helper functions import sys import numpy as np from numpy.lib import scimath as scm import scipy.constants as con import scipy.linalg as sli def generate_channel_tap(*arg): #arg={'Rxantennalocations': , 'frequency':, 'K':, 'tau':, 'pdb':, 'AS_Tx':, 'AoD':, 'AS_Rx':, 'AoA': } #Models defined only in the horizontal plane # IEEE 802.11n-03/940r4 TGn Channel Models #d is a Mx1 distance vector between antenna elements #f is the transmission frequency #sigma is the angular spread (standard deviation in radians. #AoA is th angle of arrival in degrees #Add the receiver array at some point K=arg[0]['K'] #Rician factor P=10**(arg[0]['pdb']/10.0) matdict=arg[0] #we can pass the arguments as is X=generate_corr_mat(matdict) L=generate_los_mat(matdict) channel_tap=np.sqrt(P)*(np.sqrt(K/(K+1))*L+np.sqrt(1/(K+1))*X) return channel_tap def generate_corr_mat(*arg): #arg={'Rxantennalocations': , 'frequency':, 'K':, 'tau':, 'pdb':, 'AS_Tx':, 'AoD':, 'AS_Rx':, 'AoA': } #The same dictionary OK as an argument as for generate channel tap #Models defined only in the horizontal plane # IEEE 802.11n-03/940r4 TGn Channel Models #d is a Mx1 distance vector between antenna elements #f is the transmission frequency #sigma is the angular spread (standard deviation in radians. #AoA is th angle of arrival in radians #Add the receiver array at some point Rxantennalocations=arg[0]['Rxantennalocations'] # Distance array for the receiver antenna Txantennalocations=np.array([0]) # Only one TX antenna frequency=arg[0]['frequency'] # Frequency lamda=con.c/frequency sigmarx=arg[0]['AS_Rx']*2*np.pi/360 # Angle spread for the receiver in degrees AoA=arg[0]['AoA'] #Angle of arrival for received in degrees dmatrx=sli.toeplitz(Rxantennalocations,Rxantennalocations) rxantennas=dmatrx.shape[0] # Number of receive antennas txantennas=1 #number of transmit antennas Drx=2*np.pi*dmatrx/lamda if (sigmarx !=float('-inf')): #Combine these to matrix phirangerx=np.linspace(-np.pi,np.pi,2**16)+2*np.pi/360*AoA dphirx=np.diff(phirangerx)[0] #There's an error due to numerical integration. With angle 0 the correlation must be 1 #calculate that. Ff the sigmarx =-inf, the is undefined Kcorrrx=1/(np.sum(laplacian_pdf(sigmarx,phirangerx-2*np.pi/360*AoA))*dphirx) laplacianweightmatrx=np.ones((rxantennas,1))@laplacian_pdf(sigmarx,phirangerx-2*np.pi/360*AoA) Rrx=np.zeros((rxantennas,rxantennas),dtype='complex') for i in range(rxantennas): Rrx[i,:]=Kcorrrx*np.sum(np.exp(1j*Drx[i,:].reshape((-1,1))*np.sin(phirangerx))*laplacianweightmatrx,1)*dphirx else: Rrx=np.zeros((rxantennas,rxantennas),dtype='complex') #Would require similar computations if the TX would be modeled Rtx=np.diagflat(np.ones((txantennas,1))) #Random matrix Hiid=1/np.sqrt(2)*(np.random.randn(rxantennas,txantennas)+1j*np.random.rand(rxantennas,txantennas)) #Correlation matrix X=scm.sqrt(Rrx)@[email protected](Rtx) return X def generate_los_mat(*arg): #Distance array, frequency, AoA #arg={'Rxantennalocations': , 'frequency':, 'K':, 'tau':, 'pdb':, 'AS_Tx':, 'AoD':, 'AS_Rx':, 'AoA': } #The same dictionary OK as an argument as for generate channel tap #Models defined only in the horizontal plane # IEEE 802.11n-03/940r4 TGn Channel Models #Rxantennalocations is a Mx1 distance vector between antenna elements #frequency is the transmission frequency #AS_Rx is the angular spread (standard deviation in degrees. #AoA is th angle of arrival in degrees #Add the receiver array at some point Rxantennalocations=arg[0]['Rxantennalocations'] # Distance array for the receiver antenna Txantennalocations=np.array([0]) # Only one TX antenna frequency=arg[0]['frequency'] # Frequency lamda=con.c/frequency sigmarx=arg[0]['AS_Rx'] # Angle spread for the receiver if (sigmarx !=float('-inf')): AoA=arg[0]['AoA'] #Angle of arrival for received in degrees AoD=np.r_[0] lamda=con.c/frequency Drx=2*np.pi*Rxantennalocations/lamda*np.sin(2*np.pi/360*AoA) #Relative phase shift in receiver array Dtx=2*np.pi*Txantennalocations/lamda*np.sin(2*np.pi/360*AoD) #Relative phase shift in transmitter array LOS_vectorrx=np.exp(-1j*Drx) LOS_vectorrx=LOS_vectorrx.reshape((-1,1)) LOS_vectortx=np.exp(1j*Dtx) LOS_vectortx=LOS_vectortx.reshape((-1,1)) LOS_mat=LOS_vectorrx@LOS_vectortx.transpose() else: Drx=np.zeros_like(Rxantennalocations) Dtx=np.zeros_like(Txantennalocations) LOS_vectorrx=Drx LOS_vectorrx=LOS_vectorrx.reshape((-1,1)) LOS_vectortx=Dtx LOS_vectortx=LOS_vectortx.reshape((-1,1)) LOS_mat=LOS_vectorrx@LOS_vectortx.transpose() return LOS_mat def generate_lossless_channel(*arg): Rxantennalocations=arg[0]['Rxantennalocations'] antennasrx=Rxantennalocations.shape[0] #antennas of the receiver, currently only 1 antenna at the tx antennastx=1 H=np.ones((1,antennasrx,antennastx))/np.sqrt(antennasrx*antennastx) #No power gain H.shape=(1,antennasrx,antennastx) return H def lambda2meter(distlambda,f): d=np.array([distlambda*con.c/f]) return d def channel_propagate(signal,H): #Calculate the convolution of the 3D matrix filter #y(n)=SUM s(n-k)@H(k,:,:).T convlen=signal.shape[0]+H.shape[0]-1 srx=np.zeros((convlen,H.shape[1])) for i in range(H.shape[0]): #0th dim is the "time", k of the filter in zt=np.zeros((i,H.shape[1])) zt.shape=(-1,H.shape[1]) zb=np.zeros((H.shape[0]-1,H.shape[1])) zb.shape=(-1,H.shape[1]) s_shift=np.r_['0',np.zeros((i,H.shape[1]),dtype='complex'),signal@H[i,:,:].T,np.zeros((H.shape[0]-1-i,H.shape[1]))] srx=srx+s_shift return srx def get_802_11n_channel_params(model): # See the channel and loss model in IEEE 802.11n-03/940r4 TGn Channel Models # This function hard-codes the WLAN 802.11n channel model parameters and # returns the ones corresponding to the desired channel model. #param_dict={'K':K, 'tau':tau, 'pdb':pdb, 'AS_Tx':AS_Tx, 'AoD':AoD, 'AS_Rx':AS_Rx, 'AoA':AoA} #The IS a more clever way of doing these but at least they are done now. if model=='A': lossdict={'dbp':5, 's1':2, 's2': 3.5, 'f1':3, 'f2':4} tau = np.array([0]) K=np.zeros(tau.size) #K-factor for Line-of-sight pdb = np.array([0],ndmin=2) AoA = np.array([45],ndmin=2) AS_Rx = np.array([40],ndmin=2) AoD = np.array([45],ndmin=2) AS_Tx = np.array([40],ndmin=2) elif model=='B': lossdict={'dbp':5, 's1':2, 's2': 3.5, 'f1':3, 'f2':4} tau = np.array([0,10,20,30,40,50,60,70,80]) * 1e-9 # Path delays, in seconds K=np.zeros(tau.size) #K-factor for Line-of-sight # Average path gains of cluster, in dB pdb1 = np.array([0,-5.4,-10.8,-16.2,-21.7],ndmin=2) pdb2 = np.array([-3.2,-6.3,-9.4,-12.5,-15.6,-18.7,-21.8],ndmin=2) #these must be reshaped last because others refer their dimensions # Angular spreads AS_Tx_C1 = np.ones(pdb1.shape)*14.4 AS_Tx_C1 = np.r_['1', AS_Tx_C1, -1*np.inf*np.ones((1,4))] AS_Tx_C2 = np.ones(pdb2.shape)*25.4 AS_Tx_C2 = np.r_['1', -1*np.inf*np.ones((1,2)), AS_Tx_C2 ] AS_Tx = np.r_['0', AS_Tx_C1, AS_Tx_C2] # Mean angles of departure AoD_C1 = np.ones(pdb1.shape)*225.1 AoD_C1 = np.r_['1', AoD_C1, -1*np.inf*np.ones((1,4))] AoD_C2 = np.ones(pdb2.shape)*106.5 AoD_C2 = np.r_['1', -1*np.inf*np.ones((1,2)), AoD_C2 ] AoD = np.r_['0',AoD_C1, AoD_C2] # Spatial parameters on receiver side: # Angular spreads AS_Rx_C1 = np.ones(pdb1.shape)*14.4 AS_Rx_C1 = np.r_['1', AS_Rx_C1, -1*np.inf*np.ones((1,4))] AS_Rx_C2 = np.ones(pdb2.shape)*25.4 AS_Rx_C2 = np.r_['1', -1*np.inf*np.ones((1,2)), AS_Rx_C2 ] AS_Rx = np.r_['0', AS_Rx_C1, AS_Rx_C2] # Mean angles of arrival AoA_C1 = np.ones(pdb1.shape)*4.3 AoA_C2 = np.ones(pdb2.shape)*118.4 AoA_C1 = np.r_['1', AoA_C1, -1*np.inf*np.ones((1,4))] AoA_C2 = np.r_['1', -1*np.inf*np.ones((1,2)), AoA_C2 ] AoA = np.r_['0', AoA_C1, AoA_C2] #Reshape pdb's pdb1 = np.r_['1', pdb1, -1*np.inf*np.ones((1,4))] pdb2 = np.r_['1', -1*np.inf*np.ones((1,2)), pdb2 ] pdb = np.r_['0',pdb1,pdb2] elif model=='C': lossdict={'dbp':5, 's1':2, 's2': 3.5, 'f1':3, 'f2':5} tau = np.array([0,10,20,30,40,50,60,70,80,90,110,140,170,200]) * 1e-9 K=np.zeros(tau.size) #K-factor for Line-of-sight pdb1 = np.array([0,-2.1,-4.3,-6.5,-8.6,-10.8,-13.0,-15.2,-17.3,-19.5],ndmin=2) pdb2 = np.array([-5.0,-7.2,-9.3,-11.5,-13.7,-15.8,-18.0,-20.2],ndmin=2) AoA1 = 290.3*np.ones(pdb1.shape) AoA1 = np.r_['1',AoA1,-1*np.inf*np.ones((1,4))] AoA2 = 332.3*np.ones(pdb2.shape) AoA2 = np.r_['1',-1*np.inf*np.ones((1,6)),AoA2] AoA = np.r_['0',AoA1, AoA2] AS_Rx1 = 24.6*np.ones(pdb1.shape) AS_Rx1 = np.r_['1',AS_Rx1,-1*np.inf*np.ones((1,4))] AS_Rx2 = 22.4*np.ones(pdb2.shape) AS_Rx2 = np.r_['1',-1*np.inf*np.ones((1,6)),AS_Rx2] AS_Rx = np.r_['0',AS_Rx1, AS_Rx2] AoD1 = 13.5*np.ones(pdb1.shape) AoD1 = np.r_['1',AoD1,-1*np.inf*np.ones((1,4))] AoD2 = 56.4*np.ones(pdb2.shape) AoD2 = np.r_['1',-1*np.inf*np.ones((1,6)),AoD2] AoD = np.r_['0',AoD1, AoD2] AS_Tx1 = 24.7*np.ones(pdb1.shape) AS_Tx1 = np.r_['1',AS_Tx1,-1*np.inf*np.ones((1,4))] AS_Tx2 = 22.5*np.ones(pdb2.shape) AS_Tx2 = np.r_['1',-1*np.inf*np.ones((1,6)),AS_Tx2] AS_Tx = np.r_['0',AS_Tx1, AS_Tx2] #Reshape pdb's pdb1 = np.r_['1',pdb1,-1*np.inf*np.ones((1,4))] pdb2 = np.r_['1',-1*np.inf*np.ones((1,6)),pdb2] pdb = np.r_['0',pdb1, pdb2] elif model=='D': lossdict={'dbp':10, 's1':2, 's2': 3.5, 'f1':3, 'f2':5} tau = np.array([0,10,20,30,40,50,60,70,80,90,110,140,170,200,240,290,340,390]) * 1e-9 K=np.zeros(tau.size) #K-factor for Line-of-sight K[0]=3 pdb1 = np.array([0,-0.9,-1.7,-2.6,-3.5,-4.3,-5.2,-6.1,-6.9,-7.8,-9.0,-11.1,-13.7,-16.3,-19.3,-23.2],ndmin=2) pdb2 = np.array([-6.6,-9.5,-12.1,-14.7,-17.4,-21.9,-25.5],ndmin=2) pdb3 = np.array([-18.8,-23.2,-25.2,-26.7],ndmin=2) # path losses vector ASt1 = 27.4*np.ones(pdb1.shape) ASt1 = np.r_['1',ASt1,-1*np.inf*np.ones((1,2))] ASt2 = 32.1*np.ones(pdb2.shape) ASt2 = np.r_['1', -1*np.inf*np.ones((1,10)), ASt2, -1*np.inf*np.ones((1,1)) ] ASt3 = 36.8*np.ones(pdb3.shape) ASt3 = np.r_['1',-1*np.inf*np.ones((1,14)),ASt3] AS_Tx = np.r_['0',ASt1, ASt2, ASt3] # Tx angular spread vector ASr1 = 27.7*np.ones(pdb1.shape) ASr1 = np.r_['1',ASr1,-1*np.inf*np.ones((1,2))] ASr2 = 31.4*np.ones(pdb2.shape) ASr2 = np.r_['1',-1*np.inf*np.ones((1,10)),ASr2,-1*np.inf*np.ones((1,1))] ASr3 = 37.4*np.ones(pdb3.shape) ASr3 = np.r_['1',-1*np.inf*np.ones((1,14)),ASr3] AS_Rx = np.r_['0',ASr1, ASr2, ASr3] # Rx angular spread vector AoD1 = 332.1*np.ones(pdb1.shape) AoD1 = np.r_['1',AoD1,-1*np.inf*np.ones((1,2))] AoD2 = 49.3*np.ones(pdb2.shape) AoD2 = np.r_['1',-1*np.inf*np.ones((1,10)),AoD2,-1*np.inf*np.ones((1,1))] AoD3 = 275.9*np.ones(pdb3.shape) AoD3 = np.r_['1',-1*np.inf*np.ones((1,14)),AoD3] AoD = np.r_['0',AoD1, AoD2, AoD3] # Tx angles of departure AoA1 = 158.9*np.ones(pdb1.shape) AoA1 = np.r_['1',AoA1,-1*np.inf*np.ones((1,2))] AoA2 = 320.2*np.ones(pdb2.shape) AoA2 = np.r_['1',-1*np.inf*np.ones((1,10)),AoA2,-1*np.inf*np.ones((1,1))] AoA3 = 276.1*np.ones(pdb3.shape) AoA3 = np.r_['1',-1*np.inf*np.ones((1,14)),AoA3] AoA = np.r_['0',AoA1, AoA2, AoA3] # Rx angles of arrival #Reshape pdb's pdb1 = np.r_['1',pdb1,-1*np.inf*np.ones((1,2))] pdb2 = np.r_['1',-1*np.inf*np.ones((1,10)),pdb2,-1*np.inf*np.ones((1,1))] pdb3 = np.r_['1',-1*np.inf*np.ones((1,14)),pdb3] pdb = np.r_['0',pdb1,pdb2,pdb3] # path loss vector elif model=='E': lossdict={'dbp':20, 's1':2, 's2': 3.5, 'f1':3, 'f2':6} tau = np.array([0,10,20,30,50,80,110,140,180,230,280,330,380,430,490,560,640,730]) * 1e-9 K=np.zeros(tau.size) #K-factor for Line-of-sight K[0]=6 pdb1 = np.array([-2.6,-3.0,-3.5,-3.9,-4.5,-5.6,-6.9,-8.2,-9.8,-11.7,-13.9,-16.1,-18.3,-20.5,-22.9],ndmin=2) pdb2 = np.array([-1.8,-3.2,-4.5,-5.8,-7.1,-9.9,-10.3,-14.3,-14.7,-18.7,-19.9,-22.4],ndmin=2) pdb3 = np.array([-7.9,-9.6,-14.2,-13.8,-18.6,-18.1,-22.8],ndmin=2) pdb4 = np.array([-20.6,-20.5,-20.7,-24.6],ndmin=2) AoA1 = 163.7*np.ones(pdb1.shape) AoA1 = np.r_['1',AoA1,-1*np.inf*np.ones((1,3))] AoA2 = 251.8*np.ones(pdb2.shape) AoA2 = np.r_['1',-1*np.inf*np.ones((1,4)),AoA2,-1*np.inf*np.ones((1,2))] AoA3 = 80.0*np.ones(pdb3.shape) AoA3 = np.r_['1',-1*np.inf*np.ones((1,8)),AoA3,-1*np.inf*np.ones((1,3))] AoA4 = 182.0*np.ones(pdb4.shape) AoA4 = np.r_['1',-1*np.inf*np.ones((1,14)),AoA4] AoA = np.r_['0',AoA1, AoA2, AoA3, AoA4] AS_Rx1 = 35.8*np.ones(pdb1.shape) AS_Rx1 = np.r_['1',AS_Rx1,-1*np.inf*np.ones((1,3))] AS_Rx2 = 41.6*np.ones(pdb2.shape) AS_Rx2 = np.r_['1',-1*np.inf*np.ones((1,4)),AS_Rx2,-1*np.inf*np.ones((1,2))] AS_Rx3 = 37.4*np.ones(pdb3.shape) AS_Rx3 = np.r_['1',-1*np.inf*np.ones((1,8)),AS_Rx3,-1*np.inf*np.ones((1,3))] AS_Rx4 = 40.3*np.ones(pdb4.shape) AS_Rx4 = np.r_['1',-1*np.inf*np.ones((1,14)),AS_Rx4] AS_Rx = np.r_['0',AS_Rx1, AS_Rx2, AS_Rx3, AS_Rx4] AoD1 = 105.6*np.ones(pdb1.shape) AoD1 = np.r_['1',AoD1,-1*np.inf*np.ones((1,3))] AoD2 = 293.1*np.ones(pdb2.shape) AoD2 = np.r_['1',-1*np.inf*np.ones((1,4)),AoD2,-1*np.inf*np.ones((1,2))] AoD3 = 61.9*np.ones(pdb3.shape) AoD3 = np.r_['1',-1*np.inf*np.ones((1,8)),AoD3,-1*np.inf*np.ones((1,3))] AoD4 = 275.7*np.ones(pdb4.shape) AoD4 = np.r_['1',-1*np.inf*np.ones((1,14)),AoD4] AoD = np.r_['0',AoD1, AoD2, AoD3, AoD4] AS_Tx1 = 36.1*np.ones(pdb1.shape) AS_Tx1 = np.r_['1',AS_Tx1,-1*np.inf*np.ones((1,3))] AS_Tx2 = 42.5*np.ones(pdb2.shape) AS_Tx2 = np.r_['1',-1*np.inf*np.ones((1,4)),AS_Tx2,-1*np.inf*np.ones((1,2))] AS_Tx3 = 38.0*np.ones(pdb3.shape) AS_Tx3 = np.r_['1',-1*np.inf*np.ones((1,8)),AS_Tx3,-1*np.inf*np.ones((1,3))] AS_Tx4 = 38.7*np.ones(pdb4.shape) AS_Tx4 = np.r_['1',-1*np.inf*np.ones((1,14)),AS_Tx4] AS_Tx = np.r_['0',AS_Tx1, AS_Tx2, AS_Tx3, AS_Tx4] #Reshape pdb's pdb1 = np.r_['1', pdb1,-1*np.inf*np.ones((1,3))] pdb2 = np.r_['1',-1*np.inf*np.ones((1,4)),pdb2,-1*np.inf*np.ones((1,2))] pdb3 = np.r_['1',-1*np.inf*np.ones((1,8)),pdb3,-1*np.inf*np.ones((1,3))] pdb4 = np.r_['1',-1*np.inf*np.ones((1,14)),pdb4] pdb = np.r_['0',pdb1, pdb2, pdb3, pdb4] elif model=='F': lossdict={'dbp':30, 's1':2, 's2': 3.5, 'f1':3, 'f2':6} tau = np.array([0,10,20,30,50,80,110,140,180,230,280,330,400,490,600,730,880,1050]) * 1e-9 K=np.zeros(tau.size) #K-factor for Line-of-sight K[0]=6 pdb1 = np.array([-3.3,-3.6,-3.9,-4.2,-4.6,-5.3,-6.2,-7.1,-8.2,-9.5,-11.0,-12.5,-14.3,-16.7,-19.9],ndmin=2) pdb2 = np.array([-1.8,-2.8,-3.5,-4.4,-5.3,-7.4,-7.0,-10.3,-10.4,-13.8,-15.7,-19.9],ndmin=2) pdb3 = np.array([-5.7,-6.7,-10.4,-9.6,-14.1,-12.7,-18.5],ndmin=2) pdb4 = np.array([-8.8,-13.3,-18.7],ndmin=2) pdb5 = np.array([-12.9,-14.2],ndmin=2) pdb6 = np.array([-16.3,-21.2],ndmin=2) AoA1 = 315.1*np.ones(pdb1.shape) AoA1 = np.r_['1',AoA1,-1*np.inf*np.ones((1,3))] AoA2 = 180.4*np.ones(pdb2.shape) AoA2 = np.r_['1',-1*np.inf*np.ones((1,4)),AoA2, -1*np.inf*np.ones((1,2))] AoA3 = 74.7*np.ones(pdb3.shape) AoA3 = np.r_['1',-1*np.inf*np.ones((1,8)),AoA3, -1*np.inf*np.ones((1,3))] AoA4 = 251.5*np.ones(pdb4.shape) AoA4 = np.r_['1',-1*np.inf*np.ones((1,12)),AoA4,-1*np.inf*np.ones((1,3)) ] AoA5 = 68.5*np.ones(pdb5.shape) AoA5 = np.r_['1',-1*np.inf*np.ones((1,14)),AoA5,-1*np.inf*np.ones((1,2))] AoA6 = 246.2*np.ones(pdb6.shape) AoA6 = np.r_['1',-1*np.inf*np.ones((1,16)),AoA6] AoA = np.r_['0',AoA1, AoA2, AoA3, AoA4, AoA5, AoA6] AS_Rx1 = 48.0*np.ones(pdb1.shape) AS_Rx1 = np.r_['1',AS_Rx1,-1*np.inf*np.ones((1,3))] AS_Rx2 = 55.0*np.ones(pdb2.shape) AS_Rx2 = np.r_['1',-1*np.inf*np.ones((1,4)),AS_Rx2,-1*np.inf*np.ones((1,2))] AS_Rx3 = 42.0*np.ones(pdb3.shape) AS_Rx3 = np.r_['1',-1*np.inf*np.ones((1,8)),AS_Rx3,-1*np.inf*np.ones((1,3))] AS_Rx4 = 28.6*np.ones(pdb4.shape) AS_Rx4 = np.r_['1',-1*np.inf*np.ones((1,12)),AS_Rx4,-1*np.inf*np.ones((1,3))] AS_Rx5 = 30.7*np.ones(pdb5.shape) AS_Rx5 = np.r_['1',-1*np.inf*np.ones((1,14)),AS_Rx5,-1*np.inf*np.ones((1,2))] AS_Rx6 = 38.2*np.ones(pdb6.shape) AS_Rx6 = np.r_['1',-1*np.inf*np.ones((1,16)),AS_Rx6] AS_Rx = np.r_['0',AS_Rx1, AS_Rx2, AS_Rx3, AS_Rx4, AS_Rx5, AS_Rx6] AoD1 = 56.2*np.ones(pdb1.shape) AoD1 = np.r_['1',AoD1,-1*np.inf*np.ones((1,3))] AoD2 = 183.7*np.ones(pdb2.shape) AoD2 = np.r_['1',-1*np.inf*np.ones((1,4)),AoD2,-1*np.inf*np.ones((1,2))] AoD3 = 153.0*np.ones(pdb3.shape) AoD3 = np.r_['1',-1*np.inf*np.ones((1,8)),AoD3,-1*np.inf*np.ones((1,3))] AoD4 = 112.5*np.ones(pdb4.shape) AoD4 = np.r_['1',-1*np.inf*np.ones((1,12)),AoD4,-1*np.inf*np.ones((1,3))] AoD5 = 291.0*np.ones(pdb5.shape) AoD5 = np.r_['1',-1*np.inf*np.ones((1,14)),AoD5,-1*np.inf*np.ones((1,2))] AoD6 = 62.3*np.ones(pdb6.shape) AoD6 = np.r_['1',-1*np.inf*np.ones((1,16)),AoD6] AoD = np.r_['0',AoD1, AoD2, AoD3, AoD4, AoD5, AoD6] AS_Tx1 = 41.6*np.ones(pdb1.shape) AS_Tx1 = np.r_['1',AS_Tx1,-1*np.inf*np.ones((1,3))] AS_Tx2 = 55.2*np.ones(pdb2.shape) AS_Tx2 = np.r_['1',-1*np.inf*np.ones((1,4)),AS_Tx2,-1*np.inf*np.ones((1,2))] AS_Tx3 = 47.4*np.ones(pdb3.shape) AS_Tx3 = np.r_['1',-1*np.inf*np.ones((1,8)),AS_Tx3,-1*np.inf*np.ones((1,3))] AS_Tx4 = 27.2*np.ones(pdb4.shape) AS_Tx4 = np.r_['1',-1*np.inf*np.ones((1,12)),AS_Tx4,-1*np.inf*np.ones((1,3))] AS_Tx5 = 33.0*np.ones(pdb5.shape) AS_Tx5 = np.r_['1',-1*np.inf*np.ones((1,14)),AS_Tx5,-1*np.inf*np.ones((1,2))] AS_Tx6 = 38.0*np.ones(pdb6.shape) AS_Tx6 = np.r_['1',-1*np.inf*np.ones((1,16)),AS_Tx6] AS_Tx = np.r_['0',AS_Tx1, AS_Tx2, AS_Tx3, AS_Tx4,AS_Tx5,AS_Tx6] #Reshape pdb's pdb1 = np.r_['1', pdb1,-1*np.inf*np.ones((1,3))] pdb2 = np.r_['1',-1*np.inf*
np.ones((1,4))
numpy.ones
# -*- coding: utf-8 -*- """ Created on Tue Mar 3 15:10:24 2020 @author: Nicolai ---------------- """ import numpy as np import time from scipy.stats import cauchy import testFunctions as tf def L_SHADE(population, p, H, function, minError, maxGeneration): ''' implementation of L-SHADE based on: \n Improving the Search Performance of SHADE Using Linear Population Size Reduction\n by Tanabe and Fukunaga\n adaptions: * no constraint handling implemented * population size reduction based on generation insteas of function evaluation Parameters ---------- population: numpy array 2D numpy array where lines are candidates and colums is the dimension p: float ]0,1] percentage of best individuals for current-to-p-best mutation H: int size of the memory function: function fitness function that is optimised minError: float stopping condition on function value maxGeneration: int stopping condition on max number of generation Returns ------- history: tuple tupel[0] - popDynamic\n tupel[1] - FEDynamic\n tupel[2] - FDynamic\n tupel[3] - CRDynamic\n Examples -------- >>> import numpy as np >>> def sphere(x): return np.dot(x,x) >>> maxError = -1*np.inf >>> maxGen = 10**3 >>> H = 50 >>> population = 100*np.random.rand(50,2) >>> p = 0.1 >>> (popDynamic, FEDynamic, FDynamic, CRDynamic) = L_SHADE(population, p, H, sphere, maxError, maxGen) ''' # initialisation of variables populationSize, dimension = population.shape functionValue = np.asarray([function(candidate) for candidate in population]) genCount = 1 F = 0.5 CR = 0.5 archive = np.array([population[0]]) # temorary arrays for holding the population and its function values # during a generation trailPopulation = np.copy(population) trailFunctionValue = np.copy(functionValue) # memory for control parameters mCR = 0.5*np.ones(H) mF = 0.5*np.ones(H) # k is the running memory index k = 0 # population size reduction parameter NGmin = int(np.ceil(1/p)) NGinit = populationSize popDynamic = [] FEDynamic = [] FDynamic = [] CRDynamic = [] popDynamic.append(np.copy(population)) FEDynamic.append(np.copy(functionValue)) FDynamic.append(np.copy(mF)) CRDynamic.append(np.copy(mCR)) while(genCount < maxGeneration and np.min(functionValue) > minError): # success history S for control parameters sCR = [] sF = [] sCRtemp = [] sFtemp = [] for i in range(populationSize): F = selectF(mF) sFtemp.append(F) vi = mutationCurrentToPBest1(population, archive, i, functionValue, F, p) CR = selectCR(mCR) sCRtemp.append(CR) ui = crossoverBIN(np.array([population[i]]), vi, CR) trailPopulation[i] = ui ####################################################### # for actual L-SHADE missing constraint handling here # ####################################################### trailFunctionValue[i] = function(ui) functionValueDifference = [] for i in range(populationSize): if(trailFunctionValue[i] <= functionValue[i]): # build and remove archive archLength, _ = archive.shape if (archLength >= populationSize): randIndex = np.random.randint(0, high=archLength) archive = np.delete(archive, randIndex, 0) archive = np.vstack([archive, population[i]]) # create parameter success history and weights for lehmer mean sF.append(sFtemp[i]) sCR.append(sCRtemp[i]) # equation 9 in paper functionValueDifference.append(np.abs(trailFunctionValue[i] - functionValue[i])) # perform selection population[i] = trailPopulation[i] functionValue[i] = trailFunctionValue[i] # calculate lehmer weights weights = [] sDF = np.sum(functionValueDifference) for df in functionValueDifference: if sDF == 0.0: weights.append(0) else: weights.append(df/sDF) # update parameter memory with success history if len(sCR) != 0 and len(sF) != 0: if mCR[k] == np.inf or np.max(mCR) == 0: mCR[k] = np.inf else: mCR[k] = weightedLehmermean(sCR, weights) mF[k] = weightedLehmermean(sF, weights) k += 1 if k >= H: k = 0 # perform population size reduction # calculate new population size based on the current generation count NG_1 = populationSizeReduction(genCount, maxGeneration, NGinit, NGmin) # if the new population should be smaller if NG_1 < populationSize: # delete worst individuals from the population functionValueSorted = np.argsort(functionValue) indizesToRemove = functionValueSorted[-int(populationSize-NG_1):] population = np.delete(population, indizesToRemove, 0) functionValue =
np.delete(functionValue, indizesToRemove)
numpy.delete
import tensorflow as tf import numpy as np from tqdm import trange from utils.config_manager import Config from data.datasets import TTSDataset, TTSPreprocessor from utils.decorators import ignore_exception, time_it from utils.scheduling import piecewise_linear_schedule from utils.logging_utils import SummaryManager from model.transformer_utils import create_mel_padding_mask from utils.scripts_utils import dynamic_memory_allocation, basic_train_parser from data.metadata_readers import post_processed_reader
np.random.seed(42)
numpy.random.seed
# -*- coding: utf-8 -*- """ Created on Tue Oct 27 12:29:47 2020 @author: vxr131730 """ ############################################################################### ####################### Import all the required libraries ##################### ############################################################################### import math import numpy as np from numpy import linalg as LA ############################################################################### ############################################################################### ################## UNSCENTED KALMAN FILTER IMPLEMENTATION ##################### ############################################################################### ############################################################################### class UKF: def __init__(self): # Instantiate the class variables self.zMean = 0 self.u_k = 0 self.zCovar = 0 self.n_x = 0 self.n_o = 0 self.SigmaW = 0 self.SigmaV = 0 self.CrossCor = 0 self.y_k = 0 self.L = 0 self.dT = 0 self.Wc = 0 self.Wm = 0 self.alpha = 0 self.beta = 0 self.n = 0 self.kappa = 0 self.lambda_ = 0 self.num_sigma_pts = 0 self.Tt = 0 self.knownIP = 0 self.goal_x = 0 self.goal_y = 0 ########################################################################### def Get_Weight_Matrices(self): # Initialize Van der Merwe's weighting matrix self.Wc = np.zeros((self.num_sigma_pts, 1)) self.Wm = np.zeros((self.num_sigma_pts, 1)) # Compute the Van der Merwe's weighting matrix values for i in range(self.num_sigma_pts): if i == 0: self.Wc[i,:] = self.lambda_ / (self.n + self.lambda_) + (1 - self.alpha**2 + self.beta) self.Wm[i,:] = self.lambda_ / (self.n + self.lambda_) continue self.Wc[i,:] = 1/(2*(self.n + self.lambda_)) self.Wm[i,:] = 1/(2*(self.n + self.lambda_)) ########################################################################### def Perform_Decorrelation(self): # Perform Decorrelation Scheme self.Tt = self.CrossCor @ LA.inv(self.SigmaV) # Covariance of new process noise which has 0 cross-correlation with sensor noise self.SigmaW = self.SigmaW - self.Tt @ self.SigmaV @ self.Tt.T # Fabricate the known input = Tt*y_hat self.knownIP = np.squeeze(self.Tt @ self.y_k) # self.knownIP = np.squeeze(self.Tt @ self.MeasurementModel(self.zMean).reshape(-1,1)) ########################################################################### def Generate_Sigma_Points(self): # Define the direction matrix U = LA.cholesky((self.n + self.lambda_)*self.zCovar) # Generate the sigma points using Van der Merwe algorithm # Define Place holder for all sigma points sigmaPoints = np.zeros((self.n, self.num_sigma_pts)) # First SigmaPoint is always the mean sigmaPoints[:,0] = self.zMean.T # Generate sigmapoints symmetrically around the mean for k in range(self.n): sigmaPoints[:, k+1] = sigmaPoints[:,0] + U[:, k] sigmaPoints[:, self.n+k+1] = sigmaPoints[:,0] - U[:, k] return sigmaPoints ########################################################################### def PredictionStep(self, sigmaPoints): # Get the shape of sigmaPoints ro, co = np.shape(sigmaPoints) # Create the data structure to hold the transformed points aprioriPoints = np.zeros((ro, co)) # Loop through and pass each and every sigmapoint for i in range(co): aprioriPoints[:, i] = self.NewMotionModel(sigmaPoints[:, i]) # Compute the mean and covariance of the transformed points aprioriOutput = self.ComputeStatistics(aprioriPoints, apriori_Flag = 1) # Add the aprioriPoints to output aprioriOutput["aprioriPoints"] = aprioriPoints return aprioriOutput ########################################################################### def UpdateStep(self, aprioriPoints): # Get the shape of aprioriPoints ro, M = np.shape(aprioriPoints) # Get the number of outputs num_outputs = self.n_o # Create the data structure to hold the transformed points aposterioriPoints = np.zeros((num_outputs, M)) # 4 states, 2 outputs # Loop through and pass each and every sigmapoint for i in range(M): aposterioriPoints[:, i] = self.MeasurementModel(aprioriPoints[:, i]) # Compute the mean and covariance of the transformed points aposterioriOutput = self.ComputeStatistics(aposterioriPoints, apriori_Flag = 0) # Add the aposterioriPoints to the output dictionary aposterioriOutput["aposterioriPoints"] = aposterioriPoints return aposterioriOutput ########################################################################### def NewMotionModel(self, oldState): # newState = self.MotionModel(oldState) - self.Tt @ self.MeasurementModel(oldState) + self.knownIP newState = self.MotionModel(oldState) return newState ########################################################################### def MotionModel(self, oldState): newState = oldState + [self.dT*oldState[3]*np.cos(oldState[2]), self.dT*oldState[3]*np.sin(oldState[2]), self.dT*(oldState[3]/self.L)*np.tan(self.u_k[1]), self.dT*self.u_k[0], 0, 0] return newState ########################################################################### def MeasurementModel(self, newState): """ Totally 4 outputs are being returned by the measurement model [range distance to goal bearing angle orientation with respect to goal obstacle x position * cos(6 deg) obstacle y position * cos(6 deg)] """ x_to_goal = newState[0] - self.goal_x y_to_goal = newState[1] - self.goal_y output = [math.sqrt(x_to_goal**2 + y_to_goal**2), math.atan2(y_to_goal, x_to_goal) - newState[2], newState[4]*np.sin(0.10), newState[5]*np.cos(0.10)] return output ########################################################################### def ComputeCrossCovariance(self, funParam): # Compute the crossCovarMatrix input1Shape = np.shape(funParam["input1"]) input2Shape = np.shape(funParam["input2"]) P = np.zeros((input1Shape[0], input2Shape[0])) for k in range(input1Shape[1]): diff1 = funParam["input1"][:,k] - funParam["input1Mean"] diff2 = funParam["input2"][:,k] - funParam["input2Mean"] P += funParam["weightMatrix"][k]*np.outer(diff1, diff2) return P ########################################################################### def ComputeStatistics(self, inputPoints, apriori_Flag): # Compute the weighted mean inputPointsMean = np.dot(self.Wm[:,0], inputPoints.T) # Compute the weighted covariance inputShape = np.shape(inputPoints) P =
np.zeros((inputShape[0], inputShape[0]))
numpy.zeros
import numpy as np import tensorflow as tf import dirt import skimage.io import skimage import skimage.transform import skimage.color import time import os import scipy import scipy.optimize import skimage.measure from sklearn import linear_model, datasets import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import cv2 from sklearn.utils import check_random_state, check_array, check_consistent_length from sklearn.linear_model import LinearRegression from sklearn.utils.validation import has_fit_parameter import sklearn.linear_model _dynamic_max_trials = sklearn.linear_model.ransac._dynamic_max_trials canvas_width, canvas_height = 960, 640 centre_x, centre_y = 32, 64 square_size = 16 def ransac_fit_with_weights(self, X, y, sample_weight=None, residual_threshold=None): """ Modified sklearn.linear_model.RANSACRegressor.fit() sample_weight is used in sampling base points, fitting the regressor, and calculating score for candidate model """ X = check_array(X, accept_sparse='csr') y = check_array(y, ensure_2d=False) check_consistent_length(X, y) if self.base_estimator is not None: base_estimator = clone(self.base_estimator) else: base_estimator = LinearRegression() if self.min_samples is None: # assume linear model by default min_samples = X.shape[1] + 1 elif 0 < self.min_samples < 1: min_samples = np.ceil(self.min_samples * X.shape[0]) elif self.min_samples >= 1: if self.min_samples % 1 != 0: raise ValueError("Absolute number of samples must be an " "integer value.") min_samples = self.min_samples else: raise ValueError("Value for `min_samples` must be scalar and " "positive.") if min_samples > X.shape[0]: raise ValueError("`min_samples` may not be larger than number " "of samples: n_samples = %d." % (X.shape[0])) if self.stop_probability < 0 or self.stop_probability > 1: raise ValueError("`stop_probability` must be in range [0, 1].") if residual_threshold is None: if self.residual_threshold is None: # MAD (median absolute deviation) residual_threshold = np.median(np.abs(y - np.median(y))) else: residual_threshold = self.residual_threshold if self.loss == "absolute_loss": if y.ndim == 1: loss_function = lambda y_true, y_pred: np.abs(y_true - y_pred) else: loss_function = lambda \ y_true, y_pred: np.sum(np.abs(y_true - y_pred), axis=1) elif self.loss == "squared_loss": if y.ndim == 1: loss_function = lambda y_true, y_pred: (y_true - y_pred) ** 2 else: loss_function = lambda \ y_true, y_pred: np.sum((y_true - y_pred) ** 2, axis=1) elif callable(self.loss): loss_function = self.loss else: raise ValueError( "loss should be 'absolute_loss', 'squared_loss' or a callable." "Got %s. " % self.loss) random_state = check_random_state(self.random_state) try: # Not all estimator accept a random_state base_estimator.set_params(random_state=random_state) except ValueError: pass estimator_fit_has_sample_weight = has_fit_parameter(base_estimator, "sample_weight") estimator_name = type(base_estimator).__name__ if (sample_weight is not None and not estimator_fit_has_sample_weight): raise ValueError("%s does not support sample_weight. Samples" " weights are only used for the calibration" " itself." % estimator_name) if sample_weight is not None: sample_weight = np.asarray(sample_weight) n_inliers_best = 1 score_best = -np.inf inlier_mask_best = None X_inlier_best = None y_inlier_best = None weight_inlier_best = None self.n_skips_no_inliers_ = 0 self.n_skips_invalid_data_ = 0 self.n_skips_invalid_model_ = 0 # number of data samples n_samples = X.shape[0] sample_idxs = np.arange(n_samples) n_samples, _ = X.shape self.n_trials_ = 0 max_trials = self.max_trials while self.n_trials_ < max_trials: self.n_trials_ += 1 if (self.n_skips_no_inliers_ + self.n_skips_invalid_data_ + self.n_skips_invalid_model_) > self.max_skips: break # choose random sample set #subset_idxs = sample_without_replacement(n_samples, min_samples, # random_state=random_state) # use np.random.choice here since it allows sample with prob subset_idxs = np.random.choice(n_samples, min_samples, False, sample_weight / np.sum(sample_weight)) X_subset = X[subset_idxs] y_subset = y[subset_idxs] # check if random sample set is valid if (self.is_data_valid is not None and not self.is_data_valid(X_subset, y_subset)): self.n_skips_invalid_data_ += 1 continue # fit model for current random sample set if sample_weight is None: base_estimator.fit(X_subset, y_subset) else: base_estimator.fit(X_subset, y_subset, sample_weight=sample_weight[subset_idxs]) # check if estimated model is valid if (self.is_model_valid is not None and not self.is_model_valid(base_estimator, X_subset, y_subset)): self.n_skips_invalid_model_ += 1 continue # residuals of all data for current random sample model y_pred = base_estimator.predict(X) residuals_subset = loss_function(y, y_pred) # classify data into inliers and outliers inlier_mask_subset = residuals_subset < residual_threshold n_inliers_subset = np.sum(inlier_mask_subset) # less inliers -> skip current random sample if n_inliers_subset < n_inliers_best: self.n_skips_no_inliers_ += 1 continue # extract inlier data set inlier_idxs_subset = sample_idxs[inlier_mask_subset] X_inlier_subset = X[inlier_idxs_subset] y_inlier_subset = y[inlier_idxs_subset] if sample_weight is None: weight_inlier_subset = None else: weight_inlier_subset = sample_weight[inlier_idxs_subset] # score of inlier data set score_subset = base_estimator.score(X_inlier_subset, y_inlier_subset, sample_weight[inlier_idxs_subset]) # same number of inliers but worse score -> skip current random # sample if (n_inliers_subset == n_inliers_best and score_subset < score_best): continue # save current random sample as best sample n_inliers_best = n_inliers_subset score_best = score_subset inlier_mask_best = inlier_mask_subset X_inlier_best = X_inlier_subset y_inlier_best = y_inlier_subset weight_inlier_best = weight_inlier_subset max_trials = min( max_trials, _dynamic_max_trials(n_inliers_best, n_samples, min_samples, self.stop_probability)) # break if sufficient number of inliers or score is reached if n_inliers_best >= self.stop_n_inliers or \ score_best >= self.stop_score: break # if none of the iterations met the required criteria if inlier_mask_best is None: if ((self.n_skips_no_inliers_ + self.n_skips_invalid_data_ + self.n_skips_invalid_model_) > self.max_skips): raise ValueError( "RANSAC skipped more iterations than `max_skips` without" " finding a valid consensus set. Iterations were skipped" " because each randomly chosen sub-sample failed the" " passing criteria. See estimator attributes for" " diagnostics (n_skips*).") else: raise ValueError( "RANSAC could not find a valid consensus set. All" " `max_trials` iterations were skipped because each" " randomly chosen sub-sample failed the passing criteria." " See estimator attributes for diagnostics (n_skips*).") else: if (self.n_skips_no_inliers_ + self.n_skips_invalid_data_ + self.n_skips_invalid_model_) > self.max_skips: warnings.warn("RANSAC found a valid consensus set but exited" " early due to skipping more iterations than" " `max_skips`. See estimator attributes for" " diagnostics (n_skips*).", ConvergenceWarning) # estimate final model using all inliers base_estimator.fit(X_inlier_best, y_inlier_best, weight_inlier_best) self.estimator_ = base_estimator self.inlier_mask_ = inlier_mask_best return self linear_model.RANSACRegressor.ransac_fit_with_weights = ransac_fit_with_weights def get_dirt_pixels(width=canvas_width, height=canvas_height): square_vertices = tf.constant([[-1, -1, 0, 1], [-1, 1, 0, 1], [1, 1, 0, 1], [1, -1, 0, 1]], dtype=tf.float32) #background = skimage.io.imread('/n/fs/shaderml/datas_oceanic/test_img/test_middle_ground00000.png') #background = tf.constant(skimage.img_as_float(background), dtype=tf.float32) background = tf.zeros([height, width, 3], dtype=tf.float32) camera_pos = tf.placeholder(tf.float32, 8) return dirt.rasterise( vertices=square_vertices, faces=[[0, 1, 2], [0, 2, 3]], vertex_colors=tf.ones([4, 3]), background=background, camera_pos = camera_pos, height=height, width=width, channels=3 ), camera_pos def main(): dir = '/n/fs/shaderml/deeplab-pytorch/result' highlight_dir = '/n/fs/shaderml/drone_videos/drone_frames/ocean3_00/highlight' orig_img_dir = '/n/fs/shaderml/drone_videos/drone_frames/ocean3_00' out_dir = 'horizon_optimize' #files = os.listdir(dir) #files = sorted([os.path.join(dir, file) for file in files if 'coco_stuff' not in file]) files = [os.path.join(dir, '%05d.png' % ind) for ind in range(0, 1860, 11)] #camera_pos_vals = np.load(os.path.join(dir, 'camera_pos_' + name + '.npy')) #render_t = np.load(os.path.join(dir, 'render_t_' + name + '.npy')) #nframes = camera_pos_vals.shape[0] feed_dict_arr = np.zeros(8) feed_dict_arr[1] = 200.0 feed_dict_arr[7] = 0.9 img = np.zeros([640, 960, 3]) nframes = len(files) session = tf.Session() ransac = linear_model.RANSACRegressor(stop_probability=0.995, max_trials=200) line_X = np.arange(960)[:, np.newaxis] with session.as_default(): dirt_node, camera_pos = get_dirt_pixels() for idx in range(nframes): filename = files[idx] print(filename) _, filename_short = os.path.split(filename) filename_only, _ = os.path.splitext(filename_short) orig_img_name = os.path.join(orig_img_dir, filename_short) if not os.path.exists(orig_img_name): raise orig_img = skimage.transform.resize(skimage.io.imread(orig_img_name), (img.shape[0], img.shape[1])) seg = skimage.transform.resize(skimage.io.imread(filename), (img.shape[0], img.shape[1]))[:, :, 0] is_sea_col =
np.argmin(seg, axis=0)
numpy.argmin
""" @file @brief Validates runtime for many :scikit-learn: operators. The submodule relies on :epkg:`onnxconverter_common`, :epkg:`sklearn-onnx`. """ import numpy from sklearn.base import ClusterMixin, BiclusterMixin, OutlierMixin from sklearn.base import RegressorMixin, ClassifierMixin from sklearn.calibration import CalibratedClassifierCV from sklearn.cross_decomposition import PLSSVD from sklearn.datasets import load_iris from sklearn.decomposition import LatentDirichletAllocation, NMF from sklearn.discriminant_analysis import LinearDiscriminantAnalysis, QuadraticDiscriminantAnalysis from sklearn.ensemble import ( AdaBoostRegressor, GradientBoostingRegressor, AdaBoostClassifier, BaggingClassifier, VotingClassifier, GradientBoostingClassifier, RandomForestClassifier) try: from sklearn.ensemble import StackingClassifier, StackingRegressor except ImportError: # pragma: no cover # new in 0.22 StackingClassifier, StackingRegressor = None, None from sklearn.feature_extraction import DictVectorizer, FeatureHasher from sklearn.feature_extraction.text import ( CountVectorizer, TfidfVectorizer, TfidfTransformer) from sklearn.experimental import enable_hist_gradient_boosting # pylint: disable=W0611 from sklearn.ensemble import ( HistGradientBoostingRegressor, HistGradientBoostingClassifier) from sklearn.feature_selection import ( RFE, RFECV, GenericUnivariateSelect, SelectPercentile, SelectFwe, SelectKBest, SelectFdr, SelectFpr, SelectFromModel) from sklearn.gaussian_process import GaussianProcessClassifier, GaussianProcessRegressor from sklearn.isotonic import IsotonicRegression from sklearn.linear_model import ( ARDRegression, ElasticNetCV, LarsCV, LassoCV, LassoLarsCV, LassoLarsIC, SGDRegressor, OrthogonalMatchingPursuitCV, TheilSenRegressor, BayesianRidge, MultiTaskElasticNet, MultiTaskElasticNetCV, MultiTaskLassoCV, MultiTaskLasso, PassiveAggressiveClassifier, RidgeClassifier, RidgeClassifierCV, PassiveAggressiveRegressor, HuberRegressor, LogisticRegression, SGDClassifier, LogisticRegressionCV, Perceptron) from sklearn.model_selection import GridSearchCV, RandomizedSearchCV from sklearn.multiclass import ( OneVsRestClassifier, OneVsOneClassifier, OutputCodeClassifier) from sklearn.multioutput import MultiOutputRegressor, MultiOutputClassifier from sklearn.naive_bayes import BernoulliNB, GaussianNB, MultinomialNB, ComplementNB from sklearn.neighbors import ( NearestCentroid, RadiusNeighborsClassifier, NeighborhoodComponentsAnalysis) from sklearn.preprocessing import ( LabelBinarizer, LabelEncoder, OneHotEncoder, PowerTransformer) from sklearn.semi_supervised import LabelPropagation, LabelSpreading from sklearn.svm import LinearSVC, LinearSVR, NuSVR, SVR, SVC, NuSVC from sklearn.tree import DecisionTreeRegressor, DecisionTreeClassifier, ExtraTreeClassifier from sklearn.utils import shuffle from skl2onnx.common.data_types import ( FloatTensorType, DoubleTensorType, StringTensorType, DictionaryType) from ._validate_problems_helper import ( _noshapevar, _1d_problem, text_alpha_num) def _modify_dimension(X, n_features, seed=19): """ Modifies the number of features to increase or reduce the number of features. @param X features matrix @param n_features number of features @param seed random seed (to get the same dataset at each call) @return new featurs matrix """ if n_features is None or n_features == X.shape[1]: return X if n_features < X.shape[1]: return X[:, :n_features] rstate = numpy.random.RandomState(seed) # pylint: disable=E1101 res = numpy.empty((X.shape[0], n_features), dtype=X.dtype) res[:, :X.shape[1]] = X[:, :] div = max((n_features // X.shape[1]) + 1, 2) for i in range(X.shape[1], res.shape[1]): j = i % X.shape[1] col = X[:, j] if X.dtype in (numpy.float32, numpy.float64): sigma = numpy.var(col) ** 0.5 rnd = rstate.randn(len(col)) * sigma / div col2 = col + rnd res[:, j] -= col2 / div res[:, i] = col2 elif X.dtype in (numpy.int32, numpy.int64): perm = rstate.permutation(col) h = rstate.randint(0, div) % X.shape[0] col2 = col.copy() col2[h::div] = perm[h::div] # pylint: disable=E1136 res[:, i] = col2 h = (h + 1) % X.shape[0] res[h, j] = perm[h] # pylint: disable=E1136 else: # pragma: no cover raise NotImplementedError( # pragma: no cover "Unable to add noise to a feature for this type {}".format(X.dtype)) return res ########### # datasets ########### def _problem_for_predictor_binary_classification( dtype=numpy.float32, n_features=None, add_nan=False): """ Returns *X, y, intial_types, method, node name, X runtime* for a binary classification problem. It is based on Iris dataset. """ data = load_iris() X = data.data state = numpy.random.RandomState(seed=34) # pylint: disable=E1101 rnd = state.randn(*X.shape) / 3 X += rnd X = _modify_dimension(X, n_features) y = data.target y[y == 2] = 1 if add_nan: rows = numpy.random.randint(0, X.shape[0] - 1, X.shape[0] // 3) cols = numpy.random.randint(0, X.shape[1] - 1, X.shape[0] // 3) X[rows, cols] = numpy.nan X = X.astype(dtype) y = y.astype(numpy.int64) return (X, y, [('X', X[:1].astype(dtype))], 'predict_proba', 1, X.astype(dtype)) def _problem_for_predictor_multi_classification(dtype=numpy.float32, n_features=None): """ Returns *X, y, intial_types, method, node name, X runtime* for a m-cl classification problem. It is based on Iris dataset. """ data = load_iris() X = data.data state = numpy.random.RandomState(seed=34) # pylint: disable=E1101 rnd = state.randn(*X.shape) / 3 X += rnd X = _modify_dimension(X, n_features) y = data.target X = X.astype(dtype) y = y.astype(numpy.int64) return (X, y, [('X', X[:1].astype(dtype))], 'predict_proba', 1, X.astype(dtype)) def _problem_for_predictor_multi_classification_label(dtype=numpy.float32, n_features=None): """ Returns *X, y, intial_types, method, node name, X runtime* for a m-cl classification problem. It is based on Iris dataset. """ data = load_iris() X = data.data state = numpy.random.RandomState(seed=34) # pylint: disable=E1101 rnd = state.randn(*X.shape) / 3 X += rnd X = _modify_dimension(X, n_features) y = data.target y2 = numpy.zeros((y.shape[0], 3), dtype=numpy.int64) for i, _ in enumerate(y): y2[i, _] = 1 for i in range(0, y.shape[0], 5): y2[i, (y[i] + 1) % 3] = 1 X = X.astype(dtype) y2 = y2.astype(numpy.int64) return (X, y2, [('X', X[:1].astype(dtype))], 'predict_proba', 1, X.astype(dtype)) def _problem_for_predictor_regression(many_output=False, options=None, n_features=None, nbrows=None, dtype=numpy.float32, add_nan=False, **kwargs): """ Returns *X, y, intial_types, method, name, X runtime* for a regression problem. It is based on Iris dataset. """ data = load_iris() X = data.data state = numpy.random.RandomState(seed=34) # pylint: disable=E1101 rnd = state.randn(*X.shape) / 3 X += rnd X = _modify_dimension(X, n_features) y = data.target + numpy.arange(len(data.target)) / 100 meth = 'predict' if kwargs is None else ('predict', kwargs) itt = [('X', X[:1].astype(dtype))] if n_features is not None: X = X[:, :n_features] itt = [('X', X[:1].astype(dtype))] if nbrows is not None: X = X[::nbrows, :] y = y[::nbrows] itt = [('X', X[:1].astype(dtype))] if options is not None: itt = itt, options if add_nan: rows =
numpy.random.randint(0, X.shape[0] - 1, X.shape[0] // 3)
numpy.random.randint
# coding: utf-8 import cmath import numpy as np from rcwa.common import matmul, redheffer_star_prod, get_input from rcwa.structure import HomogeneousStructure from rcwa.source import Source from rcwa._constants import UNIT_MAT_2D def save_outputs(R, T): with open('output.toml', 'w') as fid: fid.write('[R]\n00 = {:.4f}\n'.format(R)) fid.write('[T]\n00 = {:.4f}\n'.format(T)) fid.write('[R_T]\n00 = {:.4f}\n'.format(R + T)) class TMM(): '''Calculates transmission through a stack of uniform layers''' def __prepare(self, structure, source): nr1 = np.sqrt(structure.UR1*structure.ER1) self.k_inc = source.K0*nr1*\ np.array(([np.sin(source.THETA)*np.cos(source.PHI),
np.sin(source.THETA)
numpy.sin
import argparse import importlib import os import sys from datetime import datetime import numpy as np import torch from torch.autograd import Variable import provider from tensorboardX import SummaryWriter from frustum_pointnets_v1 import FPointNet from train_util import get_batch from model_util import get_loss from model_util import init_fpointnet BASE_DIR = os.path.dirname(__file__) ROOT_DIR = os.path.dirname(BASE_DIR) sys.path.append(BASE_DIR) writer = SummaryWriter('runs/exp') parser = argparse.ArgumentParser() parser.add_argument('--log_dir', default='log', help='Log dir [default: log]') parser.add_argument('--num_point', type=int, default=1024, help='Point Number [default: 2048]') parser.add_argument('--max_epoch', type=int, default=201, help='Epoch to run [default: 201]') parser.add_argument('--batch_size', type=int, default=32, help='Batch Size during training [default: 32]') parser.add_argument('--learning_rate', type=float, default=0.001, help='Initial learning rate [default: 0.001]') parser.add_argument('--momentum', type=float, default=0.9, help='Initial learning rate [default: 0.9]') parser.add_argument('--optimizer', default='adam', help='adam or momentum [default: adam]') parser.add_argument('--decay_step', type=int, default=200000, help='Decay step for lr decay [default: 200000]') parser.add_argument('--decay_rate', type=float, default=0.7, help='Decay rate for lr decay [default: 0.7]') parser.add_argument('--no_intensity', action='store_true', help='Only use XYZ for training') parser.add_argument('--restore_model_path', default=None, help='Restore model path e.g. log/model.ckpt [default: None]') parser.add_argument('--train_batch_num', default=None, help='decide how much data to train') # parse_args() 传递一组参数字符串来解析命令行,返回一个命名空间包含传递给命令的参数 FLAGS = parser.parse_args() #训练参数 EPOCH_CNT = 1 # batch_size表明这个batch中包含多少个点云数据 BATCH_SIZE = FLAGS.batch_size # num_point表明每个点云中含有多少个点 NUM_POINT = FLAGS.num_point MAX_EPOCH = FLAGS.max_epoch BASE_LEARNING_RATE = FLAGS.learning_rate # GPU_INDEX = FLAGS.gpu MOMENTUM = FLAGS.momentum OPTIMIZER = FLAGS.optimizer DECAY_STEP = FLAGS.decay_step # 初始时使用较大的学习率较快地得到较优解,随着迭代学习率呈指数逐渐减小。 # decayed_learning_rate = learning_rate*(decay_rate^(global_steps/decay_steps) DECAY_RATE = FLAGS.decay_rate NUM_CHANNEL = 3 if FLAGS.no_intensity else 4 # point feature channel NUM_CLASSES = 2 # segmentation has two classes LOG_DIR = FLAGS.log_dir #训练结果log的路径 MODEL_BASE_DIR = os.path.join(LOG_DIR,'models') if not os.path.exists(LOG_DIR): os.mkdir(LOG_DIR) LOG_FOUT = open(os.path.join(LOG_DIR, 'log_train.txt'), 'w') LOG_FOUT.write(str(FLAGS)+'\n') ################################网络参数################################## BN_INIT_DECAY = 0.5 BN_DECAY_DECAY_RATE = 0.5 BN_DECAY_DECAY_STEP = float(DECAY_STEP) BN_DECAY_CLIP = 0.99 # Load Frustum Datasets. Use default data paths. TRAIN_DATASET = provider.FrustumDataset(npoints=NUM_POINT, split='train', rotate_to_center=True, random_flip=True, random_shift=True, one_hot=True) TEST_DATASET = provider.FrustumDataset(npoints=NUM_POINT, split='val', rotate_to_center=True, one_hot=True) def log_string(out_str): LOG_FOUT.write(out_str+'\n') LOG_FOUT.flush() print(out_str) def compute_summary(end_points,labels_pl,centers_pl,heading_class_label_pl,heading_residual_label_pl,size_class_label_pl,size_residual_label_pl): ''' 计算 iou_2d, iou_3d 用 原作者提供的 numpy 版本 的操作实现可能速度会偏慢 @author chonepeiceyb :param end_points: 预测结果 :param labels_pl: (B,2) :param centers_pl: (B,3) :param heading_class_label_pl: (B,) :param heading_residual_label_pl:(B,) :param size_class_label_pl:(B,) :param size_residual_label_pl:(B,3) :return: iou2ds: (B,) birdeye view oriented 2d box ious iou3ds: (B,) 3d box ious accuracy: python float 平均预测准确度 ''' end_points_np = {} # convert tensor to numpy array for key,value in end_points.items(): end_points_np[key] = value.cpu().data.numpy() iou2ds, iou3ds = provider.compute_box3d_iou( end_points_np['center'],\ end_points_np['heading_scores'], end_points_np['heading_residuals'], \ end_points_np['size_scores'], end_points_np['size_residuals'],\ centers_pl,\ heading_class_label_pl,heading_residual_label_pl,\ size_class_label_pl,size_residual_label_pl) correct = torch.eq( torch.argmax(end_points['mask_logits'],dim=1),labels_pl.type(torch.int64)) #end_points['mask_logits'] ,(B,2,N) , 需要调 bug accuracy = torch.mean(correct.type(torch.float32)) return iou2ds,iou3ds,accuracy def train(): device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') fpointnet = FPointNet() fpointnet=fpointnet.to(device) init_fpointnet(fpointnet) optimizer = torch.optim.Adam(fpointnet.parameters(), lr=BASE_LEARNING_RATE) # for name,param in fpointnet.named_parameters(): # print(name + ':' ) # print(param.requires_grad) for epoch in range(MAX_EPOCH): print('epoch: %d' % epoch) train_one_epoch(fpointnet, device, optimizer) eval_one_epoch(fpointnet, device) # save the model every 10 epoch if (epoch+1)%10 == 0: path = os.path.join(MODEL_BASE_DIR,'fpointnet_'+str(datetime.now())+'_epoch'+str(epoch)+'.pth') torch.save(fpointnet.state_dict(),path) # save the final model path = os.path.join(MODEL_BASE_DIR, 'fpointnet_' + str(datetime.now()) + '_final' + '.pth') torch.save(fpointnet.state_dict(), path) # @torchsnooper.snoop() def train_one_epoch(fpointnet,device,optimizer): ''' @author Qiao :param fpointnet: 网络 :param device: 设备 :return: ''' global EPOCH_CNT log_string(str(datetime.now())) log_string('---- EPOCH %03d TRAINING ----' % (EPOCH_CNT)) # 按照原始数据集大小进行取值 if FLAGS.train_batch_num == None: train_idxs = np.arange(0, len(TRAIN_DATASET)) np.random.shuffle(train_idxs) #随机 num_batches = len(TRAIN_DATASET)//BATCH_SIZE else: num_batches = int(FLAGS.train_batch_num) num_batches = min(num_batches,len(TRAIN_DATASET)//BATCH_SIZE) train_idxs = np.arange(0, BATCH_SIZE*num_batches) np.random.shuffle(train_idxs) # To collect statistics total_correct = 0 total_seen = 0 loss_sum = 0 iou2ds_sum = 0 iou3ds_sum = 0 iou3d_correct_cnt = 0 # Training with batches for batch_idx in range(num_batches): start_idx = batch_idx * BATCH_SIZE end_idx = (batch_idx+1) * BATCH_SIZE batch_data, batch_label, batch_center, \ batch_hclass, batch_hres, \ batch_sclass, batch_sres, \ batch_rot_angle, batch_one_hot_vec = \ get_batch(TRAIN_DATASET, train_idxs, start_idx, end_idx, NUM_POINT, NUM_CHANNEL) pointclouds_pl = torch.from_numpy(batch_data) pointclouds_pl = pointclouds_pl.permute(0, 2, 1) pointclouds_pl = pointclouds_pl.to(device,dtype=torch.float32) one_hot_vec_pl = torch.from_numpy(batch_one_hot_vec) one_hot_vec_pl = one_hot_vec_pl.to(device,dtype=torch.float32) labels_pl = torch.from_numpy(batch_label).to(device,dtype=torch.int64) centers_pl = torch.from_numpy(batch_center).to(device,dtype=torch.float32) heading_class_label_pl = torch.from_numpy(batch_hclass).to(device,dtype=torch.int64) heading_residual_label_pl = torch.from_numpy(batch_hres).to(device,dtype=torch.float32) size_class_label_pl = torch.from_numpy(batch_sclass).to(device,dtype=torch.int64) size_residual_label_pl = torch.from_numpy(batch_sres).to(device,dtype=torch.float32) fpointnet.train() end_points = fpointnet.forward(pointclouds_pl, one_hot_vec_pl) loss, losses = get_loss(labels_pl, centers_pl,\ heading_class_label_pl, heading_residual_label_pl,\ size_class_label_pl, size_residual_label_pl, end_points) optimizer.zero_grad() loss.backward() optimizer.step() loss_val = loss.cpu().detach().numpy() logits_val = end_points['mask_logits'].cpu().detach().numpy() iou2ds,iou3ds,accuracy = compute_summary(end_points,labels_pl ,batch_center,\ batch_hclass,batch_hres,batch_sclass,batch_sres) preds_val =
np.argmax(logits_val, 1)
numpy.argmax
# -*- coding: utf-8 -*- # ProDy: A Python Package for Protein Dynamics Analysis # # Copyright (C) 2010-2012 <NAME> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/> """This module defines functions for calculating atomic properties from normal modes.""" __author__ = '<NAME>' __copyright__ = 'Copyright (C) 2010-2012 <NAME>' import time import numpy as np from prody import LOGGER from prody.atomic import AtomGroup from prody.ensemble import Ensemble, Conformation from prody.trajectory import TrajBase from nma import NMA from modeset import ModeSet from mode import VectorBase, Mode, Vector from gnm import GNMBase __all__ = ['calcCollectivity', 'calcCovariance', 'calcCrossCorr', 'calcFractVariance', 'calcSqFlucts', 'calcTempFactors', 'calcProjection', 'calcCrossProjection', 'calcPerturbResponse', ] def calcCollectivity(mode, masses=None): """Return collectivity of the mode. This function implements collectivity as defined in equation 5 of [BR95]_. If *masses* are provided, they will be incorporated in the calculation. Otherwise, atoms are assumed to have uniform masses. :arg mode: mode or vector :type mode: :class:`~.Mode` or :class:`~.Vector` :arg masses: atomic masses :type masses: :class:`numpy.ndarray`""" if not isinstance(mode, Mode): raise TypeError('mode must be a Mode instance') is3d = mode.is3d() if masses is not None: if len(masses) != mode.numAtoms(): raise ValueError('length of massesmust be equal to number of atoms') if is3d: u2in = (mode.getArrayNx3() ** 2).sum(1) / masses else: if is3d: u2in = (mode.getArrayNx3() ** 2 ).sum(1) else: u2in = (mode.getArrayNx3() ** 2 ) u2in = u2in * (1 / u2in.sum() ** 0.5) coll = np.exp(-(u2in * np.log(u2in)).sum()) / mode.numAtoms() return coll def calcFractVariance(mode): """Return fraction of variance explained by the *mode*. Fraction of variance is the ratio of the variance along a mode to the trace of the covariance matrix of the model.""" if isinstance(mode, Mode): var = mode.getVariance() trace = mode.getModel()._trace elif isinstance(mode, (ModeSet, NMA)): var = mode.getVariances() if isinstance(mode, ModeSet): trace = mode.getModel()._trace else: trace = mode._trace else: raise TypeError('mode must be a Mode instance') if trace is None: raise ValueError('modes are not calculated') return var / trace def calcProjection(ensemble, modes, rmsd=True): """Return projection of conformational deviations onto given modes. For K conformations and M modes, a (K,M) matrix is returned. :arg ensemble: an ensemble, trajectory or a conformation for which deviation(s) will be projected, or a deformation vector :type ensemble: :class:`~.Ensemble`, :class:`~.Conformation`, :class:`~.Vector`, :class:`~.Trajectory` :arg modes: up to three normal modes :type modes: :class:`~.Mode`, :class:`~.ModeSet`, :class:`~.NMA` By default root-mean-square deviation (RMSD) along the normal mode is calculated. To calculate the projection pass ``rmsd=True``. :class:`~.Vector` instances are accepted as *ensemble* argument to allow for projecting a deformation vector onto normal modes.""" if not isinstance(ensemble, (Ensemble, Conformation, Vector, TrajBase)): raise TypeError('ensemble must be Ensemble, Conformation, Vector, ' 'or a TrajBase, not {0:s}'.format(type(ensemble))) if not isinstance(modes, (NMA, ModeSet, VectorBase)): raise TypeError('rows must be NMA, ModeSet, or Mode, not {0:s}' .format(type(modes))) if not modes.is3d(): raise ValueError('modes must be 3-dimensional') if isinstance(ensemble, Vector): n_atoms = ensemble.numAtoms() else: n_atoms = ensemble.numSelected() if n_atoms != modes.numAtoms(): raise ValueError('number of atoms are not the same') if isinstance(ensemble, Vector): if not ensemble.is3d(): raise ValueError('ensemble must be a 3d vector instance') deviations = ensemble._getArray() elif isinstance(ensemble, (Ensemble, Conformation)): deviations = ensemble.getDeviations() else: nfi = ensemble.getNextIndex() ensemble.goto(0) deviations = np.array([frame.getDeviations() for frame in ensemble]) ensemble.goto(nfi) if deviations.ndim == 3: deviations = deviations.reshape((deviations.shape[0], deviations.shape[1] * 3)) elif deviations.ndim == 2: deviations = deviations.reshape((1, deviations.shape[0] * 3)) else: deviations = deviations.reshape((1, deviations.shape[0])) projection = np.dot(deviations, modes._getArray()) if rmsd: projection = (1 / (n_atoms ** 0.5)) * projection return projection def calcCrossProjection(ensemble, mode1, mode2, scale=None, **kwargs): """Return projection of conformational deviations onto modes from different models. :arg ensemble: ensemble for which deviations will be projected :type ensemble: :class:`~.Ensemble` :arg mode1: normal mode to project conformations onto :type mode1: :class:`~.Mode`, :class:`~.Vector` :arg mode2: normal mode to project conformations onto :type mode2: :class:`~.Mode`, :class:`~.Vector` :arg scale: scale width of the projection onto mode ``x`` or ``y``, best scaling factor will be calculated and printed on the console, absolute value of scalar makes the with of two projection same, sign of scalar makes the projections yield a positive correlation""" if not isinstance(ensemble, (Ensemble, Conformation, Vector, TrajBase)): raise TypeError('ensemble must be Ensemble, Conformation, Vector, ' 'or a Trajectory, not {0:s}'.format(type(ensemble))) if not isinstance(mode1, VectorBase): raise TypeError('mode1 must be a Mode instance, not {0:s}' .format(type(mode1))) if not mode1.is3d(): raise ValueError('mode1 must be 3-dimensional') if not isinstance(mode2, VectorBase): raise TypeError('mode2 must be a Mode instance, not {0:s}' .format(type(mode2))) if not mode2.is3d(): raise ValueError('mode2 must be 3-dimensional') if scale is not None: assert isinstance(scale, str), 'scale must be a string' scale = scale.lower() assert scale in ('x', 'y'), 'scale must be x or y' xcoords = calcProjection(ensemble, mode1, kwargs.get('rmsd', True)) ycoords = calcProjection(ensemble, mode2, kwargs.pop('rmsd', True)) if scale: scalar = kwargs.get('scalar', None) if scalar: assert isinstance(scalar, (float, int)), 'scalar must be a number' else: scalar = ((ycoords.max() - ycoords.min()) / (xcoords.max() - xcoords.min()) ) * np.sign(np.dot(xcoords, ycoords)) if scale == 'x': LOGGER.info('Projection onto {0:s} is scaled by {1:.2f}' .format(mode1, scalar)) else: scalar = 1 / scalar LOGGER.info('Projection onto {0:s} is scaled by {1:.2f}' .format(mode2, scalar)) if scale == 'x': xcoords = xcoords * scalar else: ycoords = ycoords * scalar return xcoords, ycoords def calcSqFlucts(modes): """Return sum of square-fluctuations for given set of normal *modes*. Square fluctuations for a single mode is obtained by multiplying the square of the mode array with the variance (:meth:`~.Mode.getVariance`) along the mode.""" if not isinstance(modes, (VectorBase, NMA, ModeSet)): raise TypeError('modes must be a Mode, NMA, or ModeSet instance, ' 'not {0:s}'.format(type(modes))) is3d = modes.is3d() if isinstance(modes, Vector): if is3d: return (modes._getArrayNx3()**2).sum(axis=1) else: return (modes._getArray() ** 2) else: sq_flucts = np.zeros(modes.numAtoms()) if isinstance(modes, VectorBase): modes = [modes] for mode in modes: if is3d: sq_flucts += ((mode._getArrayNx3()**2).sum(axis=1) * mode.getVariance()) else: sq_flucts += (mode._getArray() ** 2) * mode.getVariance() return sq_flucts def calcCrossCorr(modes, n_cpu=1): """Return cross-correlations matrix. For a 3-d model, cross-correlations matrix is an NxN matrix, where N is the number of atoms. Each element of this matrix is the trace of the submatrix corresponding to a pair of atoms. Covariance matrix may be calculated using all modes or a subset of modes of an NMA instance. For large systems, calculation of cross-correlations matrix may be time consuming. Optionally, multiple processors may be employed to perform calculations by passing ``n_cpu=2`` or more.""" if not isinstance(n_cpu, int): raise TypeError('n_cpu must be an integer') elif n_cpu < 1: raise ValueError('n_cpu must be equal to or greater than 1') if not isinstance(modes, (Mode, NMA, ModeSet)): raise TypeError('modes must be a Mode, NMA, or ModeSet instance, ' 'not {0:s}'.format(type(modes))) if modes.is3d(): model = modes if isinstance(modes, (Mode, ModeSet)): model = modes._model if isinstance(modes, (Mode)): indices = [modes.getIndex()] n_modes = 1 else: indices = modes.getIndices() n_modes = len(modes) else: n_modes = len(modes) indices = np.arange(n_modes) array = model._array n_atoms = model._n_atoms variances = model._vars if n_cpu == 1: arvar = (array[:, indices]*variances[indices]).T.reshape( (n_modes, n_atoms, 3)) array = array[:, indices].T.reshape((n_modes, n_atoms, 3)) covariance = np.tensordot(array.transpose(2, 0, 1), arvar.transpose(0, 2, 1), axes=([0, 1], [1, 0])) else: import multiprocessing n_cpu = min(multiprocessing.cpu_count(), n_cpu) queue = multiprocessing.Queue() size = n_modes / n_cpu for i in range(n_cpu): if n_cpu - i == 1: indices = modes.indices[i*size:] else: indices = modes.indices[i*size:(i+1)*size] process = multiprocessing.Process(target=_crossCorrelations, args=(queue, n_atoms, array, variances, indices)) process.start() while queue.qsize() < n_cpu: time.sleep(0.05) covariance = queue.get() while queue.qsize() > 0: covariance += queue.get() else: covariance = calcCovariance(modes) diag = np.power(covariance.diagonal(), 0.5) return covariance /
np.outer(diag, diag)
numpy.outer
#!/usr/bin/python import numpy as np import multiprocessing as mp from functools import partial # L1 = n * 2 matrix # L2 = n * 2 matrix # RF = array of recombination frequencies of size (n-1) # k = number of progenies to produce def cross2(L1, L2, RF, k): # number of columns in L1 n = L1.shape[1] # RC = 2k by n matrix # and first 0.5 probability to RF # duplicate the probabilities 2k times vertically # compare the probabilities with random 2k by n matrix # the first column means which side to choose # 0 means up and 1 means down # the rest of the columns mean if they need to change column # 0 means don't change column and 1 means change column probabilities = np.hstack((np.array([0.5]), RF)) RC = np.random.random((2*k, n))<=np.tile(probabilities, [2*k, 1]) # Cumulative products of elements along row # it shows which columns to choose in Y1 and Y2 # In fDown, 0 means up and 1 means down # In fUp, 0 means down and 1 means up cumprodRC = np.cumprod(1-2*RC, axis=1, dtype=np.int8) fDown = cumprodRC < 0 fDown = np.reshape(fDown, (2*k, n), order='F') fUp = cumprodRC > 0 fUp = np.reshape(fUp, (2*k, n), order='F') # copy the up sides of L1&L2 and combine them # copy the down sides of L1&L2 and and combine them # duplicate the combined matrix k times and # put them in a 2k by n matrices splittedL1 = np.vsplit(L1, 2) splittedL2 = np.vsplit(L2, 2) combinedUp = np.vstack((splittedL1[0], splittedL2[0])) combinedDown = np.vstack((splittedL1[1], splittedL2[1])) Y1 = np.tile(combinedUp, [k, 1]) Y2 = np.tile(combinedDown, [k, 1]) # multiple elements in Y1 and Y2 # by fUp and fDown respectively # and add them # this is the result Y = fUp*Y1 + fDown*Y2 # reshape 2k by n matrix to k by 2 by n matrix Y = np.reshape(Y, (k, 2, n), order='C') return Y # L1 = n * 2 matrix # L2 = n * 2 matrix # RF = array of recombination frequencies of size (n-1) # k = number of progenies to produce # i = current job number def cross2iterable(L1, L2, RF, k, i): print("Job " + str(i)) progenies = cross2(L1, L2, RF, k) #print("progenies.shape {}".format(progenies.shape)) return progenies # multi processing version # L1 = n * 2 matrix # L2 = n * 2 matrix # RF = array of recombination frequencies of size (n-1) # k = number of progenies to produce def cross2mp(L1, L2, RF, k): # if this value is too big, you memory cant hold # all the data and therefore the total execution time # will be very slow maxTotalJobSize = 200 # number of jobs numCores = numJobs = mp.cpu_count() numJobs = numCores # number of progenies to produce per job progenyPerJob = k//numJobs while(progenyPerJob*numCores > maxTotalJobSize): numJobs = numJobs * 2 progenyPerJob = k//numJobs #print("numJobs {}, progenyPerJob {}".format(numJobs, progenyPerJob)) theRestNum = k%numJobs print("numJobs {}, progenyPerJob {}, theRestNum {}".format(numJobs, progenyPerJob, theRestNum)) progenyList = [] # use multi-thread to calculate if (numJobs != 0): iterable = range(0, numJobs) pool = mp.Pool() func = partial(cross2iterable, L1, L2, RF, progenyPerJob) progenyList = pool.map(func, iterable) pool.close() pool.join() #print("progenyList[0].shape {}".format(progenyList[0].shape)) # convert the list to a numpy array progenies = np.array(progenyList) # convert the shape to (numJobs*progenyPerJob) by 2 by n # from numJobs by progenyPerJob by 2 by n progenies = np.reshape(progenies, (numJobs*progenyPerJob,2,L1.shape[1])) #print("progenies\n {}".format(progenies)) # do the rest if (theRestNum != 0): theRestProgenies = cross2iterable(L1,L2,RF,theRestNum,numJobs) #print("theRestProgenies\n {}".format(theRestProgenies)) progenies = np.concatenate((progenies, theRestProgenies), axis=0) #print("progenies\n {}".format(progenies)) return progenies # single processing version with memory management # L1 = n * 2 matrix # L2 = n * 2 matrix # RF = array of recombination frequencies of size (n-1) # k = number of progenies to produce def cross2sp(L1, L2, RF, k): # if this value is too big, you memory cant hold # all the data and therefore the total execution time # will be very slow maxTotalJobSize = 100 # number of jobs numCores = numJobs = mp.cpu_count() numJobs = numCores # number of progenies to produce per job progenyPerJob = k//numJobs while(progenyPerJob*numCores > maxTotalJobSize): numJobs = numJobs * 2 progenyPerJob = k//numJobs #print("numJobs {}, progenyPerJob {}".format(numJobs, progenyPerJob)) theRestNum = k%numJobs print("numJobs {}, progenyPerJob {}, theRestNum {}".format(numJobs, progenyPerJob, theRestNum)) progenyList = [] rangeNumJobs = range(numJobs) n = L1.shape[1] # use multi-thread to calculate if (numJobs != 0): for i in rangeNumJobs: progenyList.append(cross2iterable(L1,L2,RF,progenyPerJob,i)) #print("progenyList[0].shape {}".format(progenyList[0].shape)) # convert the list to a numpy array progenies = np.array(progenyList) #print(progenies.shape) # convert the shape to (numJobs*progenyPerJob) by 2 by n # from numJobs by progenyPerJob by 2 by n progenies = np.reshape(progenies, (numJobs*progenyPerJob,2,L1.shape[1])) #print("progenies\n {}".format(progenies)) # do the rest if (theRestNum != 0): theRestProgenies = cross2iterable(L1,L2,RF,theRestNum,numJobs) #print("theRestProgenies\n {}".format(theRestProgenies)) progenies =
np.concatenate((progenies, theRestProgenies), axis=0)
numpy.concatenate
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. from __future__ import division, unicode_literals import numpy as np import warnings import scipy.constants as const from monty.json import MSONable from pymatgen.analysis.structure_matcher import StructureMatcher, \ OrderDisorderElementComparator from pymatgen.core.periodic_table import get_el_sp from pymatgen.core.structure import Structure from pymatgen.io.vasp.outputs import Vasprun from pymatgen.util.coord_utils import pbc_diff """ A module to perform diffusion analyses (e.g. calculating diffusivity from mean square displacements etc.). If you use this module, please consider citing the following papers:: <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., & <NAME>. (2013). Phase stability, electrochemical stability and ionic conductivity of the Li10+-1MP2X12 (M = Ge, Si, Sn, Al or P, and X = O, S or Se) family of superionic conductors. Energy & Environmental Science, 6(1), 148. doi:10.1039/c2ee23355j <NAME>., <NAME>., & <NAME>. (2012). First Principles Study of the Li10GeP2S12 Lithium Super Ionic Conductor Material. Chemistry of Materials, 24(1), 15-17. doi:10.1021/cm203303y """ __author__ = "<NAME>, <NAME>" __version__ = "0.2" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" __status__ = "Beta" __date__ = "5/2/13" class DiffusionAnalyzer(MSONable): """ Class for performing diffusion analysis. .. attribute: diffusivity Diffusivity in cm^2 / s .. attribute: conductivity Conductivity in mS / cm .. attribute: diffusivity_components A vector with diffusivity in the a, b and c directions in cm^2 / s .. attribute: conductivity_components A vector with conductivity in the a, b and c directions in mS / cm .. attribute: diffusivity_sigma Std dev in diffusivity in cm^2 / s. Note that this makes sense only for non-smoothed analyses. .. attribute: conductivity_sigma Std dev in conductivity in mS / cm. Note that this makes sense only for non-smoothed analyses. .. attribute: diffusivity_components_sigma A vector with std dev. in diffusivity in the a, b and c directions in cm^2 / cm. Note that this makes sense only for non-smoothed analyses. .. attribute: conductivity_components_sigma A vector with std dev. in conductivity in the a, b and c directions in mS / cm. Note that this makes sense only for non-smoothed analyses. .. attribute: max_framework_displacement The maximum (drift adjusted) distance of any framework atom from its starting location in A. .. attribute: max_ion_displacements nions x 1 array of the maximum displacement of each individual ion. .. attribute: msd nsteps x 1 array of the mean square displacement of specie. .. attribute: msd_components nsteps x 3 array of the MSD in each lattice direction of specie. .. attribute: sq_disp_ions The square displacement of all ion (both specie and other ions) as a nions x nsteps array. .. attribute: dt Time coordinate array. """ def __init__(self, structure, displacements, specie, temperature, time_step, step_skip, smoothed="max", min_obs=30, avg_nsteps=1000, lattices=None): """ This constructor is meant to be used with pre-processed data. Other convenient constructors are provided as class methods (see from_vaspruns and from_files). Given a matrix of displacements (see arguments below for expected format), the diffusivity is given by:: D = 1 / 2dt * <mean square displacement> where d is the dimensionality, t is the time. To obtain a reliable diffusion estimate, a least squares regression of the MSD against time to obtain the slope, which is then related to the diffusivity. For traditional analysis, use smoothed=False and weighted=False. Args: structure (Structure): Initial structure. displacements (array): Numpy array of with shape [site, time step, axis] specie (Element/Specie): Specie to calculate diffusivity for as a String. E.g., "Li". temperature (float): Temperature of the diffusion run in Kelvin. time_step (int): Time step between measurements. step_skip (int): Sampling frequency of the displacements ( time_step is multiplied by this number to get the real time between measurements) smoothed (str): Whether to smooth the MSD, and what mode to smooth. Supported modes are: i. "max", which tries to use the maximum # of data points for each time origin, subject to a minimum # of observations given by min_obs, and then weights the observations based on the variance accordingly. This is the default. ii. "constant", in which each timestep is averaged over the number of time_steps given by min_steps. iii. None / False / any other false-like quantity. No smoothing. min_obs (int): Used with smoothed="max". Minimum number of observations to have before including in the MSD vs dt calculation. E.g. If a structure has 10 diffusing atoms, and min_obs = 30, the MSD vs dt will be calculated up to dt = total_run_time / 3, so that each diffusing atom is measured at least 3 uncorrelated times. Only applies in smoothed="max". avg_nsteps (int): Used with smoothed="constant". Determines the number of time steps to average over to get the msd for each timestep. Default of 1000 is usually pretty good. lattices (array): Numpy array of lattice matrix of every step. Used for NPT-AIMD. For NVT-AIMD, the lattice at each time step is set to the lattice in the "structure" argument. """ self.structure = structure self.disp = displacements self.specie = specie self.temperature = temperature self.time_step = time_step self.step_skip = step_skip self.min_obs = min_obs self.smoothed = smoothed self.avg_nsteps = avg_nsteps self.lattices = lattices if lattices is None: self.lattices = np.array([structure.lattice.matrix.tolist()]) indices = [] framework_indices = [] for i, site in enumerate(structure): if site.specie.symbol == specie: indices.append(i) else: framework_indices.append(i) if self.disp.shape[1] < 2: self.diffusivity = 0. self.conductivity = 0. self.diffusivity_components = np.array([0., 0., 0.]) self.conductivity_components = np.array([0., 0., 0.]) self.max_framework_displacement = 0 else: framework_disp = self.disp[framework_indices] drift = np.average(framework_disp, axis=0)[None, :, :] # drift corrected position dc = self.disp - drift nions, nsteps, dim = dc.shape if not smoothed: timesteps = np.arange(0, nsteps) elif smoothed == "constant": if nsteps <= avg_nsteps: raise ValueError('Not enough data to calculate diffusivity') timesteps = np.arange(0, nsteps - avg_nsteps) else: # limit the number of sampled timesteps to 200 min_dt = int(1000 / (self.step_skip * self.time_step)) max_dt = min(len(indices) * nsteps // self.min_obs, nsteps) if min_dt >= max_dt: raise ValueError('Not enough data to calculate diffusivity') timesteps = np.arange(min_dt, max_dt, max(int((max_dt - min_dt) / 200), 1)) dt = timesteps * self.time_step * self.step_skip # calculate the smoothed msd values msd = np.zeros_like(dt, dtype=np.double) sq_disp_ions = np.zeros((len(dc), len(dt)), dtype=np.double) msd_components = np.zeros(dt.shape + (3,)) for i, n in enumerate(timesteps): if not smoothed: dx = dc[:, i:i + 1, :] dcomponents = dc[:, i:i + 1, :] elif smoothed == "constant": dx = dc[:, i:i + avg_nsteps, :] - dc[:, 0:avg_nsteps, :] dcomponents = dc[:, i:i + avg_nsteps, :] \ - dc[:, 0:avg_nsteps, :] else: dx = dc[:, n:, :] - dc[:, :-n, :] dcomponents = dc[:, n:, :] - dc[:, :-n, :] sq_disp = dx ** 2 sq_disp_ions[:, i] = np.average(np.sum(sq_disp, axis=2), axis=1) msd[i] = np.average(sq_disp_ions[:, i][indices]) msd_components[i] = np.average(dcomponents[indices] ** 2, axis=(0, 1)) def weighted_lstsq(a, b): if smoothed == "max": # For max smoothing, we need to weight by variance. w_root = (1 / dt) ** 0.5 return np.linalg.lstsq(a * w_root[:, None], b * w_root) else: return np.linalg.lstsq(a, b) m_components = np.zeros(3) m_components_res = np.zeros(3) a = np.ones((len(dt), 2)) a[:, 0] = dt for i in range(3): (m, c), res, rank, s = weighted_lstsq(a, msd_components[:, i]) m_components[i] = max(m, 1e-15) m_components_res[i] = res[0] (m, c), res, rank, s = weighted_lstsq(a, msd) # m shouldn't be negative m = max(m, 1e-15) # factor of 10 is to convert from A^2/fs to cm^2/s # factor of 6 is for dimensionality conv_factor = get_conversion_factor(self.structure, self.specie, self.temperature) self.diffusivity = m / 60 # Calculate the error in the diffusivity using the error in the # slope from the lst sq. # Variance in slope = n * Sum Squared Residuals / (n * Sxx - Sx # ** 2) / (n-2). n = len(dt) # Pre-compute the denominator since we will use it later. # We divide dt by 1000 to avoid overflow errors in some systems ( # e.g., win). This is subsequently corrected where denom is used. denom = (n * np.sum((dt / 1000) ** 2) - np.sum(dt / 1000) ** 2) * ( n - 2) self.diffusivity_std_dev = np.sqrt(n * res[0] / denom) / 60 / 1000 self.conductivity = self.diffusivity * conv_factor self.conductivity_std_dev = self.diffusivity_std_dev * conv_factor self.diffusivity_components = m_components / 20 self.diffusivity_components_std_dev = np.sqrt( n * m_components_res / denom) / 20 / 1000 self.conductivity_components = self.diffusivity_components * \ conv_factor self.conductivity_components_std_dev = \ self.diffusivity_components_std_dev * conv_factor # Drift and displacement information. self.drift = drift self.corrected_displacements = dc self.max_ion_displacements = np.max(np.sum( dc ** 2, axis=-1) ** 0.5, axis=1) self.max_framework_displacement = \ np.max(self.max_ion_displacements[framework_indices]) self.msd = msd self.sq_disp_ions = sq_disp_ions self.msd_components = msd_components self.dt = dt self.indices = indices self.framework_indices = framework_indices def get_drift_corrected_structures(self, start=None, stop=None, step=None): """ Returns an iterator for the drift-corrected structures. Use of iterator is to reduce memory usage as # of structures in MD can be huge. You don't often need all the structures all at once. Args: start, stop, step (int): applies a start/stop/step to the iterator. Faster than applying it after generation, as it reduces the number of structures created. """ coords = np.array(self.structure.cart_coords) species = self.structure.species_and_occu lattices = self.lattices nsites, nsteps, dim = self.corrected_displacements.shape for i in range(start or 0, stop or nsteps, step or 1): latt = lattices[0] if len(lattices) == 1 else lattices[i] yield Structure( latt, species, coords + self.corrected_displacements[:, i, :], coords_are_cartesian=True) def get_summary_dict(self, include_msd_t=False): """ Provides a summary of diffusion information. Args: include_msd_t (bool): Whether to include mean square displace and time data with the data. Returns: (dict) of diffusion and conductivity data. """ d = { "D": self.diffusivity, "D_sigma": self.diffusivity_std_dev, "S": self.conductivity, "S_sigma": self.conductivity_std_dev, "D_components": self.diffusivity_components.tolist(), "S_components": self.conductivity_components.tolist(), "D_components_sigma": self.diffusivity_components_std_dev.tolist(), "S_components_sigma": self.conductivity_components_std_dev.tolist(), "specie": str(self.specie), "step_skip": self.step_skip, "time_step": self.time_step, "temperature": self.temperature, "max_framework_displacement": self.max_framework_displacement } if include_msd_t: d["msd"] = self.msd.tolist() d["msd_components"] = self.msd_components.tolist() d["dt"] = self.dt.tolist() return d def get_framework_rms_plot(self, plt=None, granularity=200, matching_s=None): """ Get the plot of rms framework displacement vs time. Useful for checking for melting, especially if framework atoms can move via paddle-wheel or similar mechanism (which would show up in max framework displacement but doesn't constitute melting). Args: plt (matplotlib.pyplot): If plt is supplied, changes will be made to an existing plot. Otherwise, a new plot will be created. granularity (int): Number of structures to match matching_s (Structure): Optionally match to a disordered structure instead of the first structure in the analyzer. Required when a secondary mobile ion is present. Notes: The method doesn't apply to NPT-AIMD simulation analysis. """ from pymatgen.util.plotting import pretty_plot if self.lattices is not None and len(self.lattices) > 1: warnings.warn("Note the method doesn't apply to NPT-AIMD " "simulation analysis!") plt = pretty_plot(12, 8, plt=plt) step = (self.corrected_displacements.shape[1] - 1) // (granularity - 1) f = (matching_s or self.structure).copy() f.remove_species([self.specie]) sm = StructureMatcher(primitive_cell=False, stol=0.6, comparator=OrderDisorderElementComparator(), allow_subset=True) rms = [] for s in self.get_drift_corrected_structures(step=step): s.remove_species([self.specie]) d = sm.get_rms_dist(f, s) if d: rms.append(d) else: rms.append((1, 1)) max_dt = (len(rms) - 1) * step * self.step_skip * self.time_step if max_dt > 100000: plot_dt = np.linspace(0, max_dt / 1000, len(rms)) unit = 'ps' else: plot_dt = np.linspace(0, max_dt, len(rms)) unit = 'fs' rms = np.array(rms) plt.plot(plot_dt, rms[:, 0], label='RMS') plt.plot(plot_dt, rms[:, 1], label='max') plt.legend(loc='best') plt.xlabel("Timestep ({})".format(unit)) plt.ylabel("normalized distance") plt.tight_layout() return plt def get_msd_plot(self, plt=None, mode="specie"): """ Get the plot of the smoothed msd vs time graph. Useful for checking convergence. This can be written to an image file. Args: plt: A plot object. Defaults to None, which means one will be generated. mode (str): Determines type of msd plot. By "species", "sites", or direction (default). """ from pymatgen.util.plotting import pretty_plot plt = pretty_plot(12, 8, plt=plt) if np.max(self.dt) > 100000: plot_dt = self.dt / 1000 unit = 'ps' else: plot_dt = self.dt unit = 'fs' if mode == "species": for sp in sorted(self.structure.composition.keys()): indices = [i for i, site in enumerate(self.structure) if site.specie == sp] sd = np.average(self.sq_disp_ions[indices, :], axis=0) plt.plot(plot_dt, sd, label=sp.__str__()) plt.legend(loc=2, prop={"size": 20}) elif mode == "sites": for i, site in enumerate(self.structure): sd = self.sq_disp_ions[i, :] plt.plot(plot_dt, sd, label="%s - %d" % ( site.specie.__str__(), i)) plt.legend(loc=2, prop={"size": 20}) else: # Handle default / invalid mode case plt.plot(plot_dt, self.msd, 'k') plt.plot(plot_dt, self.msd_components[:, 0], 'r') plt.plot(plot_dt, self.msd_components[:, 1], 'g') plt.plot(plot_dt, self.msd_components[:, 2], 'b') plt.legend(["Overall", "a", "b", "c"], loc=2, prop={"size": 20}) plt.xlabel("Timestep ({})".format(unit)) plt.ylabel("MSD ($\\AA^2$)") plt.tight_layout() return plt def plot_msd(self, mode="default"): """ Plot the smoothed msd vs time graph. Useful for checking convergence. Args: mode (str): Either "default" (the default, shows only the MSD for the diffusing specie, and its components), "ions" (individual square displacements of all ions), or "species" (mean square displacement by specie). """ self.get_msd_plot(mode=mode).show() def export_msdt(self, filename): """ Writes MSD data to a csv file that can be easily plotted in other software. Args: filename (str): Filename. Supported formats are csv and dat. If the extension is csv, a csv file is written. Otherwise, a dat format is assumed. """ fmt = "csv" if filename.lower().endswith(".csv") else "dat" delimiter = ", " if fmt == "csv" else " " with open(filename, "wt") as f: if fmt == "dat": f.write("# ") f.write(delimiter.join(["t", "MSD", "MSD_a", "MSD_b", "MSD_c"])) f.write("\n") for dt, msd, msdc in zip(self.dt, self.msd, self.msd_components): f.write(delimiter.join(["%s" % v for v in [dt, msd] + list( msdc)])) f.write("\n") @classmethod def from_structures(cls, structures, specie, temperature, time_step, step_skip, initial_disp=None, initial_structure=None, **kwargs): """ Convenient constructor that takes in a list of Structure objects to perform diffusion analysis. Args: structures ([Structure]): list of Structure objects (must be ordered in sequence of run). E.g., you may have performed sequential VASP runs to obtain sufficient statistics. specie (Element/Specie): Specie to calculate diffusivity for as a String. E.g., "Li". temperature (float): Temperature of the diffusion run in Kelvin. time_step (int): Time step between measurements. step_skip (int): Sampling frequency of the displacements ( time_step is multiplied by this number to get the real time between measurements) initial_disp (np.ndarray): Sometimes, you need to iteratively compute estimates of the diffusivity. This supplies an initial displacement that will be added on to the initial displacements. Note that this makes sense only when smoothed=False. initial_structure (Structure): Like initial_disp, this is used for iterative computations of estimates of the diffusivity. You typically need to supply both variables. This stipulates the initial structure from which the current set of displacements are computed. \\*\\*kwargs: kwargs supported by the :class:`DiffusionAnalyzer`_. Examples include smoothed, min_obs, avg_nsteps. """ p, l = [], [] for i, s in enumerate(structures): if i == 0: structure = s p.append(np.array(s.frac_coords)[:, None]) l.append(s.lattice.matrix) if initial_structure is not None: p.insert(0, np.array(initial_structure.frac_coords)[:, None]) l.insert(0, initial_structure.lattice.matrix) else: p.insert(0, p[0]) l.insert(0, l[0]) p = np.concatenate(p, axis=1) dp = p[:, 1:] - p[:, :-1] dp = dp - np.round(dp) f_disp = np.cumsum(dp, axis=1) c_disp = [np.dot(d, m) for d, m in zip(f_disp, l)] disp = np.array(c_disp) # If is NVT-AIMD, clear lattice data. if
np.array_equal(l[0], l[-1])
numpy.array_equal
import numpy as np import pandas as pd import scipy import scipy.misc from scipy.special import gammaln from scipy.special import betaln from scipy.special import digamma import remixt.utils class ProbabilityError(ValueError): def __init__(self, message, **variables): """ Error calculating a probability. Args: message (str): message detailing error KwArgs: **variables: variables to be printed """ for name, value in variables.items(): message += '\n{0}={1}'.format(name, value) ValueError.__init__(self, message) class OptimizeParameter(object): def __init__(self, name, attr, bounds, is_scalar, log_likelihood_partial=None): self.name = name self._attr = attr self._bounds = bounds self._log_likelihood_partial = log_likelihood_partial self.is_scalar = is_scalar def get_value(self): return getattr(*self._attr) def set_value(self, value): setattr(self._attr[0], self._attr[1], value) value = property(get_value, set_value) @property def length(self): if self.is_scalar: return 1 return self.value.shape[0] @property def bounds(self): if self.is_scalar: return self._bounds else: return [self._bounds] * self.length def log_likelihood_partial(self, s): return self._log_likelihood_partial(self.cn_states[s][np.newaxis, :, :]) def __call__(self, cn_states): self.cn_states = cn_states return self allele_measurement_matrix = np.array([[1, 0, 1], [0, 1, 1]]) def estimate_phi(x): """ Estimate proportion of genotypable reads. Args: x (numpy.array): major, minor, and total read counts Returns: numpy.array: estimate of proportion of genotypable reads. """ phi = x[:,0:2].sum(axis=1).astype(float) / (x[:,2].astype(float) + 1.0) return phi def proportion_measureable_matrix(phi): """ Proportion reads measureable matrix. Args: phi (numpy.array): estimate of proportion of genotypable reads. Returns: numpy.array: N * K dim array, segment to measurement transform """ return np.vstack([phi, phi, np.ones(phi.shape)]).T def expected_read_count(l, cn, h, phi): """ Calculate expected major, minor and total read counts. Args: l (numpy.array): segment lengths cn (numpy.array): copy number state h (numpy.array): haploid read depths phi (numpy.array): estimate of proportion of genotypable reads Returns: numpy.array: expected read depths """ p = proportion_measureable_matrix(phi) q = allele_measurement_matrix gamma = np.sum(cn * np.vstack([h, h]).T, axis=-2) x1 = np.dot(q.T, gamma.T).T x2 = x1 * p x3 = (x2.T * l.T).T x3 += 1e-16 for n, ell in zip(*np.where(x3 <= 0)): raise ProbabilityError('mu <= 0', n=n, cn=cn[n], l=l[n], h=h, p=p[n], mu=x3[n]) for n, ell in zip(*np.where(np.isnan(x3))): raise ProbabilityError('mu is nan', n=n, cn=cn[n], l=l[n], h=h, p=p[n], mu=x3[n]) return x3 def calculate_mean_cn(h, x, l): """ Calculate the mean raw copy number. Args: h (numpy.array): haploid read depths, h[0] for normal x (numpy.array): major, minor, and total read counts l (numpy.array): segment lengths Returns: numpy.array: N * L dim array, per segment per allele mean copy number """ phi = remixt.likelihood.estimate_phi(x) depth = x[:,0:2] / (phi * l)[:, np.newaxis] mean_cn = (depth - h[0]) / h[1:].sum() return mean_cn def calculate_mean_total_cn(h, x, l): """ Calculate the mean raw copy number. Args: h (numpy.array): haploid read depths, h[0] for normal x (numpy.array): major, minor, and total read counts l (numpy.array): segment lengths Returns: numpy.array: N * L dim array, per segment per allele mean copy number """ depth = x[:, 2] / l mean_cn = (depth - h[0]) / h[1:].sum() return mean_cn class ReadCountLikelihood(object): def __init__(self, x, l, **kwargs): """ Abstract read count likelihood model. Args: x (numpy.array): observed major, minor, and total read counts l (numpy.array): observed lengths of segments Attributes: h (numpy.array): haploid read depths, h[0] for normal phi (numpy.array): proportion genotypable reads """ self.x = x self.l = l self.param_partial_func = dict() self.param_bounds = dict() self.param_per_segment = dict() self.mask = np.array([True] * len(self.l)) def add_amplification_mask(self, cn_max): """ Add a mask for highly amplified regions. Args: cn_max (int): max unmasked dominant copy number """ dom_cn = calculate_mean_total_cn(self.h, self.x, self.l) dom_cn[np.isnan(dom_cn)] = np.inf dom_cn = np.clip(dom_cn.round().astype(int), 0, int(1e6)) self.mask &= (dom_cn <= cn_max) def add_segment_length_mask(self, min_segment_length): """ Add a mask for short segments. Args: min_segment_length (float): minimum length of modelled segments """ self.mask &= (self.l >= min_segment_length) def add_proportion_genotyped_mask(self, min_proportion_genotyped): """ Add a mask for segments with too few genotyped reads. Args: min_proportion_genotyped (float): minimum proportion genotyped reads """ p = self.x[:,:2].sum(axis=1).astype(float) / (self.x[:,2].astype(float) + 1e-16) self.mask &= (p >= min_proportion_genotyped) def _get_h(self): return self._h def _set_h(self, value): self._h = value.copy() self._h[self._h < 0.] = 0. h = property(fget=_get_h, fset=_set_h) def learn_parameters(self, x, l): """ Offline parameter learning. Args: x (numpy.array): major, minor, and total read counts l (numpy.array): segment lengths """ self.phi = estimate_phi(x) def expected_read_count(self, l, cn): """ Calculate expected major, minor and total read counts. Args: l (numpy.array): segment lengths cn (numpy.array): copy number state Returns: numpy.array: expected read depths """ h = self.h phi = self.phi return expected_read_count(l, cn, h, phi) def expected_total_read_count(self, l, cn): """ Calculate expected total read count. Args: l (numpy.array): segment lengths cn (numpy.array): copy number state Returns: numpy.array: expected total read count """ h = self.h mu = l * (h * cn.sum(axis=2)).sum(axis=1) mu += 1e-16 for n in zip(*np.where(mu <= 0)): raise ProbabilityError('mu <= 0', n=n, cn=cn[n], l=l[n], h=h, mu=mu[n]) for n in zip(*np.where(np.isnan(mu))): raise ProbabilityError('mu is nan', n=n, cn=cn[n], l=l[n], h=h, mu=mu[n]) return mu def expected_allele_ratio(self, cn): """ Calculate expected minor allele read count ratio. Args: cn (numpy.array): copy number state Returns: numpy.array: expected minor allele read count ratio """ h = self.h minor = (h * cn[:,:,1]).sum(axis=1) total = (h * cn.sum(axis=2)).sum(axis=1) p = minor / total p = np.clip(p, 1e-16, 1.-1e-16) for n in zip(*np.where((p <= 0) | (p >= 1))): raise ProbabilityError('(p <= 0) | (p >= 1)', n=n, cn=cn[n], h=h, p=p[n]) return p def _log_likelihood_post(self, ll, cn): """ Post-process likelihood Args: ll (numpy.array): log likelihood per segment cn (numpy.array): copy number state Returns: numpy.array: log likelihood per segment """ ll[np.where(np.any(cn < 0, axis=(-1, -2)))] = -np.inf ll[~self.mask] = 0.0 for n in zip(*np.where(np.isnan(ll))): raise ProbabilityError('ll is nan', n=n, x=self.x[n], l=self.l[n], cn=cn[n]) for n in zip(*np.where(np.isinf(ll))): raise ProbabilityError('ll is infinite', n=n, x=self.x[n], l=self.l[n], cn=cn[n]) return ll def _log_likelihood_partial_post(self, ll_partial, cn): """ Post-process partial derivative of log likelihood with respect to a parameter Args: ll_partial (numpy.array): partial derivative of log likelihood per segment per param cn (numpy.array): copy number state Returns: numpy.array: partial derivative of log likelihood per segment per param """ ll_partial[~self.mask, :] = 0.0 for n, idx in zip(*np.where(np.isnan(ll_partial))): raise ProbabilityError('ll derivative is nan', n=n, x=self.x[n], l=self.l[n], cn=cn[n]) for n, idx in zip(*np.where(np.isinf(ll_partial))): raise ProbabilityError('ll derivative is infinite', n=n, x=self.x[n], l=self.l[n], cn=cn[n]) return ll_partial class IndepAlleleLikelihood(ReadCountLikelihood): def __init__(self, **kwargs): """ Abstract independent allele read count likelihood model. """ super(IndepAlleleLikelihood, self).__init__(**kwargs) self.param_partial_func['h'] = self._log_likelihood_partial_h self.param_partial_func['phi'] = self._log_likelihood_partial_phi self.param_bounds['h'] = (1e-16, 10.) self.param_bounds['phi'] = (0., 1.) self.param_per_segment['h'] = False self.param_per_segment['phi'] = True def _log_likelihood_partial_h(self, x, l, cn): """ Evaluate partial derivative of log likelihood with respect to h Args: x (numpy.array): major, minor, and total read counts l (numpy.array): segment lengths cn (numpy.array): copy number state Returns: numpy.array: log likelihood derivative per segment per clone The partial derivative of the log likelihood with respect to h[m] is: sum_k a[n,k] * cn[n,m,ell] * q[ell,k] * p[n,k] * l[n] where a[n,k] is the partial derivative of p(x[n,k]|.) with respect to mu[n,k] """ partial_mu = self._log_likelihood_partial_mu(x, l, cn) p = proportion_measureable_matrix(self.phi) q = allele_measurement_matrix partial_h = np.einsum('...l,...jk,...kl,...l,...->...j', partial_mu, cn, q, p, l) return partial_h def _log_likelihood_partial_phi(self, x, l, cn): """ Evaluate partial derivative of log likelihood with respect to phi Args: x (numpy.array): major, minor, and total read counts l (numpy.array): segment lengths cn (numpy.array): copy number state Returns: numpy.array: log likelihood derivative per segment per clone The partial derivative of the log likelihood with respect to phi[n] is: sum_k a[n,k] * cn[n,m,ell] * l[n] * h[m] * I(k<>3) * I(k=ell) where a[n,k] is the partial derivative of p(x[n,k]|.) with respect to mu[n,k] """ h = self.h partial_mu = self._log_likelihood_partial_mu(x, l, cn) partial_phi = (partial_mu[:,0] * l * np.dot(cn[:,:,0], h) + partial_mu[:,1] * l * np.dot(cn[:,:,1], h)) return partial_phi[:,np.newaxis] class PoissonDistribution(object): """ Poisson distribution for read count data. """ def log_likelihood(self, x, mu): """ Calculate the poisson read count log likelihood. Args: x (numpy.array): observed read counts mu (numpy.array): expected read counts Returns: float: log likelihood The pmf of the negative binomial is: mu^x * e^-mu / x! The log likelihood is thus: x * log(mu) - mu - log(x!) """ mu[mu <= 0] = 1 ll = x * np.log(mu) - mu - gammaln(x + 1) return ll def log_likelihood_partial_mu(self, x, mu): """ Calculate the partial derivative of the poisson read count log likelihood with respect to mu Args: x (numpy.array): observed read counts mu (numpy.array): expected read counts Returns: numpy.array: log likelihood derivative The partial derivative of the log pmf of the poisson with respect to mu is: x / mu - 1 """ partial_mu = x / mu - 1. return partial_mu class PoissonLikelihood(IndepAlleleLikelihood): def __init__(self, **kwargs): """ Poisson read count likelihood model. """ self.poisson = PoissonDistribution() super(PoissonLikelihood, self).__init__(**kwargs) def _log_likelihood(self, x, l, cn): """ Calculate the poisson read count log likelihood. Args: x (numpy.array): major, minor, and total read counts l (numpy.array): segment lengths cn (numpy.array): copy number state Returns: float: log likelihood per segment """ N = x.shape[0] K = x.shape[1] mu = self.expected_read_count(l, cn) ll = np.zeros((N,)) for k in xrange(K): ll = ll + self.poisson.log_likelihood(x[:,k], mu[:,k]) return ll def _log_likelihood_partial_mu(self, x, l, cn): """ Calculate the partial derivative of the poisson read count log likelihood with respect to mu Args: x (numpy.array): major, minor, and total read counts l (numpy.array): segment lengths cn (numpy.array): copy number state Returns: numpy.array: log likelihood derivative per segment per measurement """ N = x.shape[0] K = x.shape[1] mu = self.expected_read_count(l, cn) partial_mu = np.zeros((N, K)) for k in xrange(K): partial_mu[:,k] = self.poisson.log_likelihood_partial_mu(x[:,k], mu[:,k]) return partial_mu class NegBinDistribution(object): def __init__(self, **kwargs): """ Negative binomial distribution for read count data. Attributes: r (numpy.array): negative binomial read count over-dispersion """ self.r = 500. def log_likelihood(self, x, mu): """ Calculate negative binomial read count log likelihood. Args: x (numpy.array): observed read counts mu (numpy.array): expected read counts Returns: float: log likelihood per segment The pmf of the negative binomial is: C(x + r - 1, x) * p^x * (1-p)^r where p = mu / (r + mu), with mu the mean of the distribution. The log likelihood is thus: log(G(x+r)) - log(G(x+1)) - log(G(r)) + x * log(p) + r * log(1 - p) """ nb_p = mu / (self.r + mu) nb_p[nb_p < 0.] = 0.5 nb_p[nb_p > 1.] = 0.5 ll = (gammaln(x + self.r) - gammaln(x + 1) - gammaln(self.r) + x * np.log(nb_p) + self.r * np.log(1 - nb_p)) return ll def log_likelihood_partial_mu(self, x, mu): """ Calculate the partial derivative of the negative binomial read count log likelihood with respect to mu Args: x (numpy.array): observed read counts mu (numpy.array): expected read counts Returns: numpy.array: log likelihood derivative per segment The partial derivative of the log pmf of the negative binomial with respect to mu is: x / mu - (r + x) / (r + mu) """ partial_mu = x / mu - (self.r + x) / (self.r + mu) return partial_mu def log_likelihood_partial_r(self, x, mu): """ Calculate the partial derivative of the negative binomial read count log likelihood with respect to r Args: x (numpy.array): observed read counts mu (numpy.array): expected read counts Returns: numpy.array: log likelihood derivative per segment The partial derivative of the log pmf of the negative binomial with respect to r is: digamma(r + x) - digamma(r) + log(r) + 1 - log(r + mu) - r / (r + mu) - x / (r + mu) """ r = self.r partial_r = (digamma(r + x) - digamma(r) + np.log(r) + 1. - np.log(r + mu) - r / (r + mu) - x / (r + mu)) return partial_r class NegBinMixtureDistribution(object): def __init__(self, **kwargs): """ Negative binomial 2 component mixture distribution for read count data. Attributes: r (float): negative binomial read counts over-dispersion r_noise (float): negative binomial read counts over-dispersion for noise component z (float): mixture proportion for noise compoinent """ self.negbin = NegBinDistribution() self.negbin_noise = NegBinDistribution() self.negbin_noise.r = 10. self.z = 0.01 @property def r(self): return self.negbin.r @r.setter def r(self, value): self.negbin.r = value @property def r_noise(self): return self.negbin_noise.r @r_noise.setter def r_noise(self, value): self.negbin_noise.r = value def log_likelihood(self, x, mu): """ Calculate negative binomial mixture read count log likelihood. Args: x (numpy.array): observed read counts mu (numpy.array): expected read counts Returns: float: log likelihood per segment The pmf of the negative binomial mixture is: (1 - z) * NBin(x, mu) + z * NBin(x, mu) """ ll = np.array([ np.log(1. - self.z) + self.negbin.log_likelihood(x, mu), np.log(self.z) + self.negbin_noise.log_likelihood(x, mu), ]) ll = scipy.misc.logsumexp(ll, axis=0) return ll def log_likelihood_partial_mu(self, x, mu): """ Calculate the partial derivative of the negative binomial mixture read count log likelihood with respect to mu Args: x (numpy.array): observed read counts mu (numpy.array): expected read counts Returns: numpy.array: log likelihood derivative per segment The partial derivative of the log pmf of the negative binomial with respect to mu is: x / mu - (r + x) / (r + mu) """ coeff_base = ( np.log(1 - self.z) + self.negbin.log_likelihood(x, mu) - self.log_likelihood(x, mu) ) coeff_noise = ( np.log(self.z) + self.negbin_noise.log_likelihood(x, mu) - self.log_likelihood(x, mu) ) partial_mu = ( np.exp(coeff_base) * self.negbin.log_likelihood_partial_mu(x, mu) + np.exp(coeff_noise) * self.negbin_noise.log_likelihood_partial_mu(x, mu)) return partial_mu class NegBinLikelihood(IndepAlleleLikelihood): def __init__(self, **kwargs): """ Negative binomial read count likelihood model. Attributes: r (numpy.array): negative binomial read count over-dispersion """ super(NegBinLikelihood, self).__init__(**kwargs) self.param_partial_func['r'] = self._log_likelihood_partial_r self.param_bounds['r'] = (1e-16, np.inf) self.param_per_segment['r'] = False self.negbin = [NegBinDistribution(), NegBinDistribution(), NegBinDistribution()] @property def r(self): return np.array([nb.r for nb in self.negbin]) @r.setter def r(self, value): for idx, val in enumerate(value): self.negbin[idx].r = max(0., val) def learn_parameters(self, x, l): """ Offline parameter learning. Args: x (numpy.array): observed major, minor, and total read counts l (numpy.array): observed lengths of segments """ super(NegBinLikelihood, self).learn_parameters(x, l) for k, negbin in enumerate(self.negbin): remixt.paramlearn.learn_negbin_r_adjacent(negbin, x[:,k], l) def _log_likelihood(self, x, l, cn): """ Calculate negative binomial read count log likelihood. Args: x (numpy.array): major, minor, and total read counts l (numpy.array): segment lengths cn (numpy.array): copy number state Returns: float: log likelihood per segment """ N = x.shape[0] K = x.shape[1] mu = self.expected_read_count(l, cn) ll = np.zeros((N,)) for k in xrange(K): ll = ll + self.negbin[k].log_likelihood(x[:,k], mu[:,k]) return ll def _log_likelihood_partial_mu(self, x, l, cn): """ Calculate the partial derivative of the negative binomial read count log likelihood with respect to mu Args: x (numpy.array): major, minor, and total read counts l (numpy.array): segment lengths cn (numpy.array): copy number state Returns: numpy.array: log likelihood derivative per segment per measurement """ N = x.shape[0] K = x.shape[1] mu = self.expected_read_count(l, cn) partial_mu = np.zeros((N, K)) for k in xrange(K): partial_mu[:,k] = self.negbin[k].log_likelihood_partial_mu(x[:,k], mu[:,k]) return partial_mu def _log_likelihood_partial_r(self, x, l, cn): """ Calculate the partial derivative of the negative binomial read count log likelihood with respect to r Args: x (numpy.array): major, minor, and total read counts l (numpy.array): segment lengths cn (numpy.array): copy number state Returns: numpy.array: log likelihood derivative per segment per measurement """ N = x.shape[0] K = x.shape[1] mu = self.expected_read_count(l, cn) partial_r = np.zeros((N, K)) for k in xrange(K): partial_r[:,k] = self.negbin[k].log_likelihood_partial_r(x[:,k], mu[:,k]) return partial_r class BinomialDistribution(object): def __init__(self, **kwargs): """ Binomial distribution for allele count data. """ pass def log_likelihood(self, k, n, p): """ Calculate binomial allele count log likelihood. Args: k (numpy.array): observed minor allelic read counts n (numpy.array): observed total allelic read counts p (numpy.array): expected minor allele fraction Returns: float: log likelihood per segment The pmf of the binomial is: C(n, k) * p**k * (1-p)**(n-k) The log likelihood is thus: log(G(n+1)) - log(G(k+1)) - log(G(n-k+1)) + k * log(p) + (n - k) * log(1 - p) """ ll = (gammaln(n+1) - gammaln(k+1) - gammaln(n-k+1) + k * np.log(p) + (n - k) *
np.log(1 - p)
numpy.log
#!/usr/bin/env python import collections # import itertools import numpy as np # from sklearn import linear_model as linear # for VAR # from .utils import sliding_window as window # from .utils.distance import kmeans, dists_sq # from .utils import distance as dist # from python import compress # ================================================================ shifts lut SHIFT_PAIRS_16 = [ (7, 1), # ~0 - .5 = ~-.5 (3, 1), # .125 - .5 = -.375 (2, 1), # .25 - .5 = -.25 # (4, 2), # .0625 - .25 = -.1875 (3, 2), # .125 - .5 = -.125 (4, 3), # .0625 - .125 = -.0625 (0, 0), # 1 - 1 = 0 (3, 4), # .125 - .0625 = .0625 (2, 3), # .25 - .125 - .125 (2, 4), # .25 - .0625 = .1875 (1, 2), # .5 - .25 = .25 (1, 3), # .5 - .125 = .375 (0, 1), # 1 - .5 = .5 (0, 2), # 1 - .25 = .75 (0, 3), # 1 - .125 = .875 (0, 4), # 1 - .0625 = .9375 (0, 7), # 1 - ~0 = ~1 ] # should be equivalent to `all_shifts(max_shift=5, omit_duplicates=True)` # EDIT: wait, no, not true because we have shifts of 7 at the ends SHIFT_PAIRS_26 = [ (7, 1), # ~0 - .5 = ~-.5 (5, 1), # .0625 - .5 = -.46875 # added (4, 1), # .0625 - .5 = -.4375 # added, max 4 (3, 1), # .125 - .5 = -.375 (2, 1), # .25 - .5 = -.25 (5, 2), # .03125- .25 = -.21875 (4, 2), # .0625 - .25 = -.1875 # added, max 4 (3, 2), # .125 - .25 = -.125 (5, 3), # .03125- .125 = -.09375 # added (4, 3), # .0625 - .125 = -.0625 (5, 4), # .03125- .0625 = -.03125 # added (0, 0), # 1 - 1 = 0 (4, 5), # .0625 - .03125= .03125 (3, 4), # .125 - .0625 = .0625 (3, 5), # .125 - .03125= .09375 # added (2, 3), # .25 - .125 - .125 (2, 4), # .25 - .0625 = .1875 (2, 5), # .25 - .03125= .21875 # added (1, 2), # .5 - .25 = .25 (1, 3), # .5 - .125 = .375 (1, 4), # .5 - .0625 = .4375 # added, max 4 (1, 5), # .5 - .03125= .46875 # added (0, 1), # 1 - .5 = .5 (0, 2), # 1 - .25 = .75 (0, 3), # 1 - .125 = .875 (0, 4), # 1 - .0625 = .9375 (0, 5), # 1 - .03125= .96875 # added (0, 7), # 1 - ~0 = ~1 ] def all_shifts(max_shift=-1, omit_duplicates=True): vals = {} nbits = 8 x = 1 << nbits # reference val; 256 for nbits if max_shift < 0: max_shift = nbits - 1 if omit_duplicates: vals[(0, 0)] = 0 for a in range(max_shift + 1): for b in range(max_shift + 1): if omit_duplicates and a == b: continue vals[(a, b)] = (x >> a) - (x >> b) keys, coeffs = list(zip(*list(vals.items()))) keys = np.array(keys) coeffs = np.array(coeffs) order = np.argsort(coeffs) # print "shift results:" # print keys[order] # print coeffs[order] return keys[order], coeffs[order] # okay, looks like (according to test immediately below) these values are # identical to what's in our existing LUT; this makes sense given that impls # are basically identical def _i16_for_shifts(pos_shift, neg_shift, nbits=8): start_val = 1 << nbits # 256 for nbits = 8 return (start_val >> pos_shift) - (start_val >> neg_shift) # TODO actual unit test def _test_shift_coeffs(nbits=8): shifts, shift_coeffs = all_shifts() for (pos_shift, neg_shift), coeff in zip(shifts, shift_coeffs): assert _i16_for_shifts(pos_shift, neg_shift) == coeff for val in range(-128, 128): two_shifts_val = (val >> pos_shift) - (val >> neg_shift) # ya, this fails; multiply and rshift != using shifts directly # assert (val * coeff) >> nbits == two_shifts_val # this way works; requires two multiplies though... pos_coef = 1 << (nbits - pos_shift) neg_coef = 1 << (nbits - neg_shift) pos = (val * pos_coef) >> nbits neg = (val * neg_coef) >> nbits assert pos - neg == two_shifts_val # this way also fails # pos = val * pos_coef # neg = val * neg_coef # assert (pos - neg) >> nbits == two_shifts_val # def coeff_lut(): # """create lookup table `T` such that `T[coeff]` yields the two indices # whose associated coefficients are immediately above and below `coeff`""" # shifts, shift_coeffs = all_shifts() SHIFTS, SHIFT_COEFFS = all_shifts() # ================================================================ funcs def binary_search(array, val): M = len(array) first = 0 middle = int(M / 2) last = M - 1 while (first <= last): middle_val = array[middle] if middle_val < val: first = middle + 1 elif middle_val == val: return middle else: # middle_val > val last = middle - 1 middle = int((first + last) / 2) return middle class OnlineRegressor(object): def __init__(self, block_sz=8, verbose=0, method='linreg', shifts=SHIFTS, shift_coeffs=SHIFT_COEFFS, numbits=8, ntaps=1): # self.prev0 = 0 # self.prev1 = 0 # self.mod = 1 << nbits # self.shift0 = 0 # self.shift1 = 1 self.block_sz = block_sz self.verbose = verbose self.method = method self.shifts = shifts self.shift_coeffs = shift_coeffs self.numbits = numbits self.ntaps = ntaps self.last_val = 0 self.last_delta = 0 self.coef = 0 self.coef = 256 self.counter = 0 # self.counter = 256 << (1 + self.numbits - 8) # TODO indirect to learning rate, not just 1 # noqa # self.counter = 8 << 1 # equivalent to adding 8 to round to nearest? # self.counter = self.coef self.t = 0 self.grad_counter = 0 self.offset = 0 self.offset_counter = 0 shift_by = (1 + self.numbits - 8) self.coeffs = np.zeros(self.ntaps, dtype=np.int32) + 256 self.counters = np.zeros(self.ntaps, dtype=np.int32) + (256 << shift_by) # self.approx_256_over_x = 1 self.Sxy = 0 self.Sxx = 0 self.errs = [] # print "using shifts, coeffs:" # print shifts # print shift_coeffs # for logging # self.best_idx_offset_counts = np.zeros(3, dtype=np.int64) self.best_idx_counts = np.zeros(len(self.shifts), dtype=np.int64) # counts_len = len(self.shifts) if method == 'linreg' else 512 # self.best_idx_counts = np.zeros(counts_len, dtype=np.int64) self.best_coef_counts = collections.Counter() self.best_offset_counts = collections.Counter() def feed_group(self, group): pass # TODO determine optimal filter here # errhat = a*x0 - b*x0 - a*x1 + b*x1 # = a(x0 - x1) + b(x1 - x0) # = c(x0 - x1), where c = (a - b) # # we should compute c, and find shifts (which correspond to a, b) that # approximate it well; also note that errhat is prediction of the delta # # this is just linear regression between (x0 - x1) and new val, with # some extra logic at the end to get shifts based on regression coeff # deltas; these are our target variable deltas = np.zeros(group.size, dtype=group.dtype) deltas[1:] = group[1:] - group[:-1] deltas[0] = group[0] - self.last_val self.last_val = group[-1] # deltas from previous time step; these are our indep variable diffs = np.zeros(group.size, dtype=group.dtype) diffs[1:] = deltas[:-1] diffs[0] = self.last_delta self.last_delta = deltas[-1] x = diffs y = deltas # linear regression if self.method == 'linreg': Sxy = np.sum(x * y) Sxx = np.sum(x * x) # print "x, y dtypes: ", x.dtype, y.dtype # print "Sxx, Sxy dtypes: ", Sxx.dtype, Sxy.dtype coeff = (Sxy << 8) / Sxx # shift to mirror what we'll need to do in C idx = binary_search(self.shift_coeffs, coeff) def compute_errs(x, y, shifts): predictions = (x >> shifts[0]) - (x >> shifts[1]) return y - predictions # These are commented out because, empirically, they're # *never* chosen # # best_idx_offset = 0 # # def compute_total_cost(errs, block_sz=self.block_sz): # raw_costs = compress.nbits_cost(errs) # block_costs_rows = raw_costs.reshape(-1, block_sz) # block_costs = np.max(block_costs_rows, axis=1) # return np.sum(block_costs) # # cost = compute_total_cost(errs) # if idx > 0: # errs2 = compute_errs(x, y, SHIFTS[idx - 1]) # cost2 = compute_total_cost(errs) # if cost2 < cost: # ret = errs2 # best_idx_offset = -1 # if idx < (len(SHIFTS) - 1): # errs3 = compute_errs(x, y, SHIFTS[idx + 1]) # cost3 = compute_total_cost(errs) # if cost3 < cost: # ret = errs3 # best_idx_offset = 1 # self.best_idx_offset_counts[best_idx_offset] += 1 errs = compute_errs(x, y, self.shifts[idx]) self.best_idx_counts[idx] += 1 # for logging elif self.method == 'gradient': # update coeffs using last entry in each block # learning_rate_shift = 7 # learning rate of 2^(-learning_rate_shift) # learning_rate_shift = 8 # learning rate of 2^(-learning_rate_shift) # learning_rate_shift = 12 # learning rate of 2^(-learning_rate_shift) # learning_rate_shift = 4 # learning rate of 2^(-learning_rate_shift) # learning_rate_shift = 2 # learning rate of 2^(-learning_rate_shift) predictions = (x * self.coef) >> int(min(self.numbits, 8)) for tap_idx in range(1, self.ntaps): predictions[tap_idx:] += (x[:-tap_idx] * self.coeffs[tap_idx]) predictions += self.offset errs = y - predictions for b in range(8): # for each block # only update based on a few values for efficiency which_idxs = 8 * b + np.array([3, 7]) # downsample by 4 # which_idxs = 8 * b + np.array([1, 3, 5, 7]) # downsample by 2 grads = 0 # grads = np.zeros(self.ntaps) # offsets = 0 for idx in which_idxs: xval = x[idx] # xval = x[idx] >> (self.numbits - 8) # grad = int(-errs[idx] * x[idx]) >> 8 # grad = int(-errs[idx] * x[idx]) // 256 # y0 = np.abs(self.approx_256_over_x) * np.sign(xval) # y0 = 1 + (256 - xval) >> 8 # y0 = 3 - ((3 * xval) >> 8) # grad = int(-(errs[idx] << 8) / xval) if xval != 0 else 0 # works great # self.counter -= grad # equivalent to above two lines # if self.t % 100 == 0: # print "grad:", grad # continue # # xabs = self.t # TODO rm # xabs = np.abs(xval) # if xabs == 0: # lzcnt = self.numbits # else: # lzcnt = self.numbits - 1 - int(np.log2(xabs)) # lzcnt = max(0, lzcnt - 1) # round up to nearest power of 2 # # lzcnt = min(15, lzcnt + 1) # round up to nearest power of 2 # # numerator = 1 << self.numbits # # recip = 1 << (lzcnt - 8) if lzcnt >= 8 else # # recip = np.sign(xval) << (8 + lzcnt) # shift_amt = max(0, lzcnt - (self.numbits - 8)) # usually 0, maybe 1 sometimes # recip = (1 << shift_amt) * np.sign(xval) # grad = int(-errs[idx] * recip) # # grad = int(grad / len(which_idxs)) # normal grad descent # grad = int(-errs[idx] * np.sign(xval)) # div by sqrt(hessian) # grad = int(-errs[idx] * xval) >> self.numbits # true gradient # approx newton step for log(nbits) err = errs[idx] # if False: # TODO rm # if self.numbits > 8: # grad = int(-(1 + err)) if err > 0 else int(-(err - 1)) # else: # grad = int(-err) # don't add 1 # self.grad_counter += (grad - (self.grad_counter >> 8)) # wtf this works so well for 16b, despite ignoring sign of x... # (when also only shifting counter by learning rate, not # an additional 8) # grad = -err # grad = -(err + np.sign(err)) * np.sign(xval) # grad = -err * np.sign(xval) # these both seem to work pretty well; prolly need to directly # compare them # grad = -err * np.sign(xval) # grad = -np.sign(err) * xval # significantly better than prev line grad = np.sign(err) * xval # significantly better than prev line # ^ duh; above is minimizer for L1 loss # grad = -np.sign(err) * np.sign(xval) << (self.numbits - 8) # sub_from = ((1 << self.numbits) - 1) * np.sign(xval) # approx_recip_x = sub_from - xval # grad = -np.sign(err) * approx_recip_x grads += int(grad) # grads += grad >> 1 # does this help with overflow? # simulate int8 overflow, adjusted for fact that we do 8 blocks # per group (so 1024, 2048 instead of 128, 256) mod = int(1 << self.numbits) offset = mod // 2 grads = ((grads + offset) % mod) - offset # grads = ((grads + 1024) % 2048) - 1024 # wrecks accuracy # grads = ((grads + 8192) % 16384) - 8192 # no effect self.errs.append(err) # offsets += np.sign(err) # optimize bias for l1 loss # this is the other one we should actually consider doing # # grad = int(-errs[idx] * np.sign(xval)) # # approximation of what we'd end up doing with a LUT # shift_to_just_4b = self.numbits - 4 # # y0 = ((xval >> shift_to_just_4b) + 1) << shift_to_just_4b # shifted_xval = xval >> shift_to_just_4b # if shifted_xval != 0: # y0 = int(256. / shifted_xval) << shift_to_just_4b # else: # y0 = 16*np.sign(xval) << shift_to_just_4b # # y0 = y0 * int(2 - (xval * y0 / 256)) # diverges # y0 = int(256. / xval) if xval else 0 # y0 = (1 << int(8 - np.floor(np.log2(xval)))) * np.sign(xval) # y0 = 4 * np.sign(xval) # self.approx_256_over_x = int( y0*(2 - (int(xval*y0) >> 8)) ) # noqa # doesn't work # grad = int(-errs[idx] * self.approx_256_over_x) # grad = int(-errs[idx] * y0) # grad = int(-errs[idx] * xval) # works # grad = int(-errs[idx] * 2*np.sign(xval)) # this_best_coef = self.coef - grad # self.counter += this_best_coef - self.coef # self.counter -= grad # equivalent to above two lines # self.counter -= grad >> learning_rate_shift # if self.t < 8: # if self.t % 50 == 0: # if (self.t < 5 == 0) and (b == 0): # if (self.t % 50 == 0) and (b == 0): # # print "errs: ", errs[-7], errs[-5], errs[-3], errs[-1] # print "t, b = ", self.t, b # print "errs: ", errs[-10:] # print "xs: ", x[-10:] # # print "sum(|xs|)", np.sum(np.abs(x)) # print "grads: ", grads # print "counter:", self.counter # # print "grad counter:", self.grad_counter # # # print "recip, grad: ", recip, grad # self.coef = self.counter >> min(self.t, learning_rate_shift) # self.coef = self.counter >> learning_rate_shift learning_rate_shift = 1 # learning_rate_shift = 4 # grad_learning_shift = 1 # grad_learning_shift = 4 # offset_learning_shift = 4 # compute average gradient for batch # grad = int(4 * grads / len(which_idxs)) # div by 16 grad = int(grads / len(which_idxs)) # div by 64 # grad = grads # self.grad_counter += grad - (self.grad_counter >> grad_learning_shift) # self.grad_counter += grad # # this is the pair of lines that we know works well for UCR # # self.counter -= grad self.counter += grad self.coef = self.counter >> (learning_rate_shift + (self.numbits - 8)) # self.coef = self.counter >> learning_rate_shift # self.coef -= (self.grad_counter >> grad_learning_shift) >> learning_rate_shift # learn_shift = int(min(learning_rate_shift, np.log2(self.t + 1))) # self.coef = self.counter >> (learn_shift + (self.numbits - 8)) # self.coef = self.counter >> learn_shift # for use with l1 loss # self.coef -= (self.grad_counter >> grad_learning_shift) >> learn_shift # self.coef -= (self.grad_counter >> grad_learning_shift) >> learning_rate_shift # self.coef = 192 # global soln for olive oil # quantize coeff by rounding to nearest 16; this seems to help # quite a bit, at least for stuff that really should be double # delta coded (starlight curves, presumably timestamps) # self.coef = ((self.coef + 8) >> 4) << 4 self.coef = (self.coef >> 4) << 4 # just round towards 0 # self.coef = (self.coef >> 5) << 5 # just round towards 0 # like above, but use sign since shift and unshift round towards 0 # EDIT: no apparent difference, though perhaps cuz almost nothing # actually wants a negative coef # self.coef = ((self.coef + 8 * np.sign(self.coef)) >> 4) << 4 # offset = int(offsets / len(which_idxs)) # div by 64 # self.offset_counter += offset # # self.offset = self.offset_counter >> offset_learning_shift # self.offset = 0 # offset doesn't seem to help at all # self.coef = 0 # why are estimates biased? TODO rm # self.coef = 256 # self.coef = self.counter # self.coef = np.clip(self.coef, -256, 256) # apparently important # self.coef = np.clip(self.coef, -128, 256) # apparently important # if self.t < 8: # if self.t % 100 == 0: # print "----- t = {}".format(self.t) # print "offset, offset counter: ", self.offset, self.offset_counter # # print "grad, grads sum: ", grad, grads # # print "learn shift: ", learn_shift # # print "errs[:10]: ", errs[:16] # # print "-grads[:10]: ", errs[:16] * x[:16] # # print "signed errs[:10]: ", errs[:16] * np.sign(x[:16]) # print "new coeff, grad_counter, counter = ", self.coef, self.grad_counter, self.counter # # print "new coeff, grad counter = ", self.coef, self.grad_counter # self.best_idx_counts[self.coef] += 1 # for logging self.best_coef_counts[self.coef] += 1 self.best_offset_counts[self.offset] += 1 # errs -= self.offset # do this at the end to not mess up training elif self.method == 'exact': # print "using exact method" if self.numbits <= 8: predictions = (x * self.coef) >> self.numbits else: predictions = ((x >> 8) * self.coef) errs = y - predictions learn_shift = 6 # shift = learn_shift + 2*self.numbits - 8 shift = learn_shift # only update based on a few values for efficiency start_idx = 0 if self.t > 0 else 8 for idx in np.arange(start_idx, len(x), 8): # xval = x[idx] # >> (self.numbits - 8) # yval = y[idx] # >> (self.numbits - 8) xval = x[idx] >> (self.numbits - 8) yval = y[idx] >> (self.numbits - 8) # # this way works just like global one, or maybe better # self.Sxx += xval * xval # self.Sxy += xval * yval # moving average way; seemingly works just as well # Exx = self.Sxx >> learn_shift # Exy = self.Sxy >> learn_shift Exy = self.Sxy >> shift Exx = self.Sxx >> shift # adjust_shift = 2 * diff_xx = (xval * xval) - Exx diff_xy = (xval * yval) - Exy self.Sxx += diff_xx self.Sxy += diff_xy # if min(self.Sxy, self.Sxx) >= 1024: # self.Sxx /= 2 # self.Sxy /= 2 Exy = self.Sxy >> shift Exx = self.Sxx >> shift self.coef = int((Exy << 8) / Exx) # works really well # none of this really works # # print "Exy, Exx = ", Exy, Exx # print "xval, yval: ", xval, yval # print "diff_xx, diff_xy, Exy, Exx = ", diff_xx, diff_xy, Exy, Exx # # numerator = 1 << (2 * self.numbits) # numerator = 256 # nbits = int(min(4, np.log2(Exx))) if Exx > 1 else 1 # assert numerator >= np.abs(Exx) # # print "nbits: ", nbits # recip = int((numerator >> nbits) / (Exx >> nbits)) << nbits # # recip = recip >> (2 * self.numbits - 8) # print "numerator, recip: ", numerator, recip # self.coef = int(Exy * recip) self.best_coef_counts[self.coef] += 1 self.t += 1 return errs # while (first <= last) { # if (array[middle] < search) # first = middle + 1; # else if (array[middle] == search) { # printf("%d found at location %d.\n", search, middle+1); # break; # } # else # last = middle - 1; # middle = (first + last)/2; # } def sub_online_regress(blocks, verbose=0, group_sz_blocks=8, max_shift=4, only_16_shifts=True, method='linreg', numbits=8, drop_first_half=False, **sink): # drop_first_half=True, **sink): blocks = blocks.astype(np.int32) if only_16_shifts: shifts = SHIFT_PAIRS_16 shift_coeffs = [_i16_for_shifts(*pair) for pair in shifts] else: shifts, shift_coeffs = all_shifts(max_shift=max_shift) encoder = OnlineRegressor(block_sz=blocks.shape[1], verbose=verbose, shifts=shifts, shift_coeffs=shift_coeffs, method=method, numbits=numbits) # print "using group_sz_blocks: ", group_sz_blocks # print "using method: ", method # print "using nbits: ", numbits out = np.empty(blocks.shape, dtype=np.int32) if group_sz_blocks < 1: group_sz_blocks = len(blocks) # global model ngroups = int(len(blocks) / group_sz_blocks) for g in range(ngroups): # if verbose and (g > 0) and (g % 100 == 0): # print "running on block ", g start_idx = g * group_sz_blocks end_idx = start_idx + group_sz_blocks group = blocks[start_idx:end_idx] errs = encoder.feed_group(group.ravel()) out[start_idx:end_idx] = errs.reshape(group.shape) out[end_idx:] = blocks[end_idx:] if verbose > 1: if method == 'linreg': if group_sz_blocks != len(blocks): import hipsterplot as hp # pip install hipsterplot # hp.plot(x_vals=encoder.shift_coeffs, y_vals=encoder.best_idx_counts, hp.plot(encoder.best_idx_counts, num_x_chars=len(encoder.shift_coeffs), num_y_chars=12) else: coef_idx =
np.argmax(encoder.best_idx_counts)
numpy.argmax
import numpy as np test_data_1 = np.load("cobotta_ik_jnt1_min_max.npy", allow_pickle=True) test_data_2 = np.load("cobotta_ik_jnt2_min_max.npy", allow_pickle=True) test_data_3 = np.load("cobotta_ik_jnt3_min_max.npy", allow_pickle=True) test_data_4 = np.load("cobotta_ik_jnt4_min_max.npy", allow_pickle=True) test_data_5 = np.load("cobotta_ik_jnt5_min_max.npy", allow_pickle=True) test_data_6 = np.load("cobotta_ik_jnt6_min_max.npy", allow_pickle=True) test_data_7 = np.load("cobotta_ik_jnt7_min_max.npy", allow_pickle=True) test_data_8 = np.load("cobotta_ik_jnt8_min_max.npy", allow_pickle=True) res_min_max = np.concatenate((test_data_1, test_data_2), axis=0) res_min_max = np.concatenate((res_min_max, test_data_3), axis=0) res_min_max = np.concatenate((res_min_max, test_data_4), axis=0) res_min_max = np.concatenate((res_min_max, test_data_5), axis=0) res_min_max = np.concatenate((res_min_max, test_data_6), axis=0) res_min_max =
np.concatenate((res_min_max, test_data_7), axis=0)
numpy.concatenate
import numpy as np from python_utils.mathu import quat_identity, quat_mult, vector_quat, matrix_from_quat, rodmat from scipy.spatial.transform import Rotation as R def exp_quat(v): """ See "Practical Parameterization of Rotations Using the Exponential Map" - F. <NAME> Section 3 """ ang = np.linalg.norm(v) hang = 0.5 * ang if ang < 1e-8: # Threshold probably too conservative (too low) sc = 0.5 + ang ** 2 / 48 else: sc = np.sin(hang) / ang return np.array((np.cos(hang), sc * v[0], sc * v[1], sc * v[2])) def euler_int(dt, vel, accel): return vel * dt + 0.5 * accel * dt ** 2 def so3_quat_int(quat, dang, dang_in_body): """ Uses exponential map for quaternions """ rotquat = exp_quat(dang) if dang_in_body: return quat_mult(quat, rotquat) return quat_mult(rotquat, quat) def so3_quat_naive_int(quat, dang, dang_in_body): """ Uses quaternion derivative equation and normalizes """ if dang_in_body: quat_deriv = quat_mult(quat, vector_quat(dang)) / 2.0 else: quat_deriv = quat_mult(vector_quat(dang), quat) / 2.0 quat += quat_deriv return quat / np.linalg.norm(quat) def so3_rot_int(rot, dang, dang_in_body): """ Uses exponential map for rotation matrices """ delta_rot = rodmat(dang) if dang_in_body: return rot.dot(delta_rot) return delta_rot.dot(rot) class AttitudeNoLie(object): def __init__(self, quat=quat_identity(), ang=np.zeros(3), in_body=False): self.quat = quat.copy() self.ang = ang.copy() self.in_body = in_body def step(self, dt, accel=np.zeros(3), ang_accel=np.zeros(3)): dang = euler_int(dt, self.ang, ang_accel) self.quat = so3_quat_naive_int(self.quat, dang, self.in_body) self.ang += ang_accel * dt def get_quat(self): return self.quat.copy() def get_rot(self): return matrix_from_quat(self.quat) def get_ang(self): return self.ang.copy() def set_rot(self, rot): quat = R.from_matrix(rot).as_quat() self.quat = np.array((quat[3], quat[0], quat[1], quat[2])) class Attitude(object): def __init__(self, quat=quat_identity(), ang=np.zeros(3), in_body=False): self.quat = quat.copy() self.ang = ang.copy() self.in_body = in_body def step(self, dt, accel=np.zeros(3), ang_accel=np.zeros(3)): dang = euler_int(dt, self.ang, ang_accel) self.quat = so3_quat_int(self.quat, dang, self.in_body) self.ang += ang_accel * dt def get_quat(self): return self.quat.copy() def get_rot(self): return matrix_from_quat(self.quat) def get_ang(self): return self.ang.copy() def set_rot(self, rot): quat = R.from_matrix(rot).as_quat() self.quat = np.array((quat[3], quat[0], quat[1], quat[2])) class AttitudeRot(object): def __init__(self, quat=quat_identity(), ang=np.zeros(3), in_body=False): self.rot = matrix_from_quat(quat) self.ang = ang.copy() self.in_body = in_body def step(self, dt, accel=np.zeros(3), ang_accel=
np.zeros(3)
numpy.zeros
import unittest import qteasy as qt import pandas as pd from pandas import Timestamp import numpy as np import math from numpy import int64 import itertools import datetime from qteasy.utilfuncs import list_to_str_format, regulate_date_format, time_str_format, str_to_list from qteasy.utilfuncs import maybe_trade_day, is_market_trade_day, prev_trade_day, next_trade_day from qteasy.utilfuncs import next_market_trade_day, unify, mask_to_signal, list_or_slice, labels_to_dict from qteasy.utilfuncs import weekday_name, prev_market_trade_day, is_number_like, list_truncate, input_to_list from qteasy.space import Space, Axis, space_around_centre, ResultPool from qteasy.core import apply_loop from qteasy.built_in import SelectingFinanceIndicator, TimingDMA, TimingMACD, TimingCDL, TimingTRIX from qteasy.tsfuncs import income, indicators, name_change, get_bar from qteasy.tsfuncs import stock_basic, trade_calendar, new_share, get_index from qteasy.tsfuncs import balance, cashflow, top_list, index_indicators, composite from qteasy.tsfuncs import future_basic, future_daily, options_basic, options_daily from qteasy.tsfuncs import fund_basic, fund_net_value, index_basic, stock_company from qteasy.evaluate import eval_alpha, eval_benchmark, eval_beta, eval_fv from qteasy.evaluate import eval_info_ratio, eval_max_drawdown, eval_sharp from qteasy.evaluate import eval_volatility from qteasy.tafuncs import bbands, dema, ema, ht, kama, ma, mama, mavp, mid_point from qteasy.tafuncs import mid_price, sar, sarext, sma, t3, tema, trima, wma, adx, adxr from qteasy.tafuncs import apo, bop, cci, cmo, dx, macd, macdext, aroon, aroonosc from qteasy.tafuncs import macdfix, mfi, minus_di, minus_dm, mom, plus_di, plus_dm from qteasy.tafuncs import ppo, roc, rocp, rocr, rocr100, rsi, stoch, stochf, stochrsi from qteasy.tafuncs import trix, ultosc, willr, ad, adosc, obv, atr, natr, trange from qteasy.tafuncs import avgprice, medprice, typprice, wclprice, ht_dcperiod from qteasy.tafuncs import ht_dcphase, ht_phasor, ht_sine, ht_trendmode, cdl2crows from qteasy.tafuncs import cdl3blackcrows, cdl3inside, cdl3linestrike, cdl3outside from qteasy.tafuncs import cdl3starsinsouth, cdl3whitesoldiers, cdlabandonedbaby from qteasy.tafuncs import cdladvanceblock, cdlbelthold, cdlbreakaway, cdlclosingmarubozu from qteasy.tafuncs import cdlconcealbabyswall, cdlcounterattack, cdldarkcloudcover from qteasy.tafuncs import cdldoji, cdldojistar, cdldragonflydoji, cdlengulfing from qteasy.tafuncs import cdleveningdojistar, cdleveningstar, cdlgapsidesidewhite from qteasy.tafuncs import cdlgravestonedoji, cdlhammer, cdlhangingman, cdlharami from qteasy.tafuncs import cdlharamicross, cdlhighwave, cdlhikkake, cdlhikkakemod from qteasy.tafuncs import cdlhomingpigeon, cdlidentical3crows, cdlinneck from qteasy.tafuncs import cdlinvertedhammer, cdlkicking, cdlkickingbylength from qteasy.tafuncs import cdlladderbottom, cdllongleggeddoji, cdllongline, cdlmarubozu from qteasy.tafuncs import cdlmatchinglow, cdlmathold, cdlmorningdojistar, cdlmorningstar from qteasy.tafuncs import cdlonneck, cdlpiercing, cdlrickshawman, cdlrisefall3methods from qteasy.tafuncs import cdlseparatinglines, cdlshootingstar, cdlshortline, cdlspinningtop from qteasy.tafuncs import cdlstalledpattern, cdlsticksandwich, cdltakuri, cdltasukigap from qteasy.tafuncs import cdlthrusting, cdltristar, cdlunique3river, cdlupsidegap2crows from qteasy.tafuncs import cdlxsidegap3methods, beta, correl, linearreg, linearreg_angle from qteasy.tafuncs import linearreg_intercept, linearreg_slope, stddev, tsf, var, acos from qteasy.tafuncs import asin, atan, ceil, cos, cosh, exp, floor, ln, log10, sin, sinh from qteasy.tafuncs import sqrt, tan, tanh, add, div, max, maxindex, min, minindex, minmax from qteasy.tafuncs import minmaxindex, mult, sub, sum from qteasy.history import get_financial_report_type_raw_data, get_price_type_raw_data from qteasy.history import stack_dataframes, dataframe_to_hp, HistoryPanel from qteasy.database import DataSource from qteasy.strategy import Strategy, SimpleTiming, RollingTiming, SimpleSelecting, FactoralSelecting from qteasy._arg_validators import _parse_string_kwargs, _valid_qt_kwargs from qteasy.blender import _exp_to_token, blender_parser, signal_blend class TestCost(unittest.TestCase): def setUp(self): self.amounts =
np.array([10000., 20000., 10000.])
numpy.array
#!/usr/bin/env python import sys sys.path.append(r'C:\Program Files (x86)\Keysight\SD1\Libraries\Python') from BaseDriver import LabberDriver, Error, IdError import keysightSD1 import numpy as np import os import time class Driver(LabberDriver): """ This class implements the Keysight PXI digitizer""" def performOpen(self, options={}): """Perform the operation of opening the instrument connection""" # number of demod blocks in the FPGA self.num_of_demods = 5 # self.demod_n_pts = self.num_of_demods * 15 self.demod_n_pts = 80 self.bit_stream_name = '' # set time step and resolution self.nBit = 16 self.bitRange = float(2**(self.nBit - 1) - 1) # timeout self.timeout_ms = int(1000 * self.dComCfg['Timeout']) # get PXI chassis self.chassis = int(self.dComCfg.get('PXI chassis', 1)) # create AWG instance self.dig = keysightSD1.SD_AIN() AWGPart = self.dig.getProductNameBySlot( self.chassis, int(self.comCfg.address)) self.log('Serial:', self.dig.getSerialNumberBySlot( self.chassis, int(self.comCfg.address))) if not isinstance(AWGPart, str): raise Error('Unit not available') # check that model is supported dOptionCfg = self.dInstrCfg['options'] for validId, validName in zip( dOptionCfg['model_id'], dOptionCfg['model_str']): if AWGPart.find(validId) >= 0: # id found, stop searching break else: # loop fell through, raise ID error raise IdError(AWGPart, dOptionCfg['model_id']) # set model self.setModel(validName) # sampling rate and number of channles is set by model if validName in ('M3102', 'M3302'): # 500 MHz models self.dt = 2E-9 self.nCh = 4 else: # assume 100 MHz for all other models self.dt = 10E-9 self.nCh = 4 # create list of sampled data self.lTrace = [np.array([])] * self.nCh self.demod_output_ssb = np.zeros((0,), dtype='complex') self.demod_buffer = np.zeros((0,), dtype=np.int16) self.dig.openWithSlot(AWGPart, self.chassis, int(self.comCfg.address)) # get hardware version - changes numbering of channels hw_version = self.dig.getHardwareVersion() if hw_version >= 4: # KEYSIGHT - channel numbers start with 1 self.ch_index_zero = 1 else: # SIGNADYNE - channel numbers start with 0 self.ch_index_zero = 0 self.log('HW:', hw_version) self.configure_FPGA() def configure_FPGA(self, reset=False): """Load FPGA bitstream and setup triggers""" self.fpga_config = self.getValue('FPGA Hardware') if reset or self.fpga_config == 'Only signals': bitstream = os.path.join( os.path.dirname(__file__), 'firmware_FPGAFlow_Clean_2018-05-31T22_22_11.sbp') elif self.fpga_config in ('FPGA I/Q and signals', 'Only FPGA I/Q'): bitstream = os.path.join( os.path.dirname(__file__), 'firmware_FPGAFlow_Demod_v4_IQx5_2018-09-02T19_14_50.sbp') # don't reload if correct bitstream is already loaded if bitstream == self.bit_stream_name: return if (self.dig.FPGAload(bitstream)) < 0: if self.fpga_config != 'Only signals': raise Error('FPGA not loaded, check FPGA version...') self.bit_stream_name = bitstream if self.fpga_config != 'Only signals': for n in range(self.num_of_demods): LO_freq = self.getValue('LO freq %d' % (n + 1)) self.setFPGALOfreq(n + 1, LO_freq) self.setFPGATrigger() def getHwCh(self, n): """Get hardware channel number for channel n. n starts at 0""" return n + self.ch_index_zero def performClose(self, bError=False, options={}): """Perform the close instrument connection operation""" # do not check for error if close was called with an error try: # flush all memory for n in range(self.nCh): self.log('Close ch:', n, self.dig.DAQflush(self.getHwCh(n))) # remove firmware self.configure_FPGA(reset=True) # close instrument self.dig.close() except Exception: # never return error here pass def performSetValue(self, quant, value, sweepRate=0.0, options={}): """Perform the Set Value instrument operation. This function should return the actual value set by the instrument""" # start with setting local quant value quant.setValue(value) # if changing FPGA operation, reload firmware if quant.name == 'FPGA Hardware': new_value = self.getValue('FPGA Hardware') # only reload if operation mode changed if new_value != self.fpga_config: self.configure_FPGA() # check if channel-specific, if so get channel + name if quant.name.startswith('Ch') and len(quant.name) > 6: ch = int(quant.name[2]) - 1 name = quant.name[6:] else: ch, name = None, '' if (quant.name.startswith('FPGA Voltage') or quant.name.startswith('FPGA Single-shot')): demod_num = int(quant.name[-1]) - 1 # proceed depending on command if quant.name in ('External Trig Source', 'External Trig Config', 'Trig Sync Mode'): extSource = int(self.getCmdStringFromValue('External Trig Source')) trigBehavior = int( self.getCmdStringFromValue('External Trig Config')) sync = int(self.getCmdStringFromValue('Trig Sync Mode')) self.dig.DAQtriggerExternalConfig(0, extSource, trigBehavior, sync) elif quant.name in ('Trig I/O', ): # get direction and sync from index of comboboxes direction = int(self.getCmdStringFromValue('Trig I/O')) self.dig.triggerIOconfig(direction) elif quant.name in ( 'Analog Trig Channel', 'Analog Trig Config', 'Trig Threshold'): # get trig channel trigCh = self.getValueIndex('Analog Trig Channel') mod = int(self.getCmdStringFromValue('Analog Trig Config')) threshold = self.getValue('Trig Threshold') self.dig.channelTriggerConfig(self.getHwCh(trigCh), mod, threshold) elif name in ('Range', 'Impedance', 'Coupling'): # set range, impedance, coupling at once rang = self.getRange(ch) imp = int(self.getCmdStringFromValue('Ch%d - Impedance' % (ch + 1))) coup = int(self.getCmdStringFromValue('Ch%d - Coupling' % (ch + 1))) self.dig.channelInputConfig(self.getHwCh(ch), rang, imp, coup) # FPGA configuration if quant.name.startswith('LO freq'): demod_num = int(quant.name[-1]) LO_freq = self.getValue('LO freq ' + str(demod_num)) value = self.setFPGALOfreq(demod_num, LO_freq) elif quant.name in ('Skip time', 'Integration time'): self.setFPGATrigger() return value def performGetValue(self, quant, options={}): """Perform the Set Value instrument operation. This function should return the actual value set by the instrument""" # check if channel-specific, if so get channel + name if quant.name.startswith('Ch') and len(quant.name) > 6: ch = int(quant.name[2]) - 1 name = quant.name[6:] else: ch, name = None, '' if (quant.name.startswith('FPGA Voltage') or quant.name.startswith('FPGA Single-shot')): demod_num = int(quant.name[-1]) - 1 if (name == 'Signal' or quant.name.startswith('FPGA Voltage') or quant.name.startswith('FPGA Single-shot')): if self.isHardwareLoop(options): """Get data from round-robin type averaging""" (seq_no, n_seq) = self.getHardwareLoopIndex(options) # acquisition was started when arming, just read data if name == 'Signal': return quant.getTraceDict( self.reshaped_traces[ch][seq_no], dt=self.dt) elif quant.name.startswith('FPGA Voltage I,'): return self.demod_output_I[demod_num] elif quant.name.startswith('FPGA Single-shot I,'): return quant.getTraceDict( self.demod_output_vector_I[demod_num][seq_no], dt=1) elif quant.name.startswith('FPGA Voltage Q,'): return self.demod_output_Q[demod_num] elif quant.name.startswith('FPGA Single-shot Q,'): return quant.getTraceDict( self.demod_output_vector_Q[demod_num][seq_no], dt=1) elif quant.name.startswith('FPGA Single-shot REF,'): return quant.getTraceDict( self.demod_output_vector_ref[demod_num][seq_no], dt=1) elif quant.name.startswith('FPGA Voltage NP,'): return self.demod_output_NP[demod_num] elif quant.name.startswith('FPGA Single-shot NP,'): return quant.getTraceDict( self.demod_output_vector_NP[demod_num][seq_no], dt=1) elif quant.name.startswith('FPGA Voltage,'): return self.demod_output_ssb[demod_num, :, seq_no].mean() elif quant.name.startswith('FPGA Single-shot,'): return quant.getTraceDict( self.demod_output_ssb[demod_num, :, seq_no], dt=1) # get traces if first call if self.isFirstCall(options): # don't arm and measure if in arm/trig mode, was done at arm if not self.isHardwareTrig(options): self.getTraces() # return correct data if name == 'Signal': value = quant.getTraceDict(self.lTrace[ch], dt=self.dt) elif quant.name.startswith('FPGA Voltage I,'): value = self.demod_output_I[demod_num] elif quant.name.startswith('FPGA Single-shot I,'): value = quant.getTraceDict( self.demod_output_vector_I[demod_num], dt=1) elif quant.name.startswith('FPGA Voltage Q,'): value = self.demod_output_Q[demod_num] elif quant.name.startswith('FPGA Single-shot Q,'): value = quant.getTraceDict( self.demod_output_vector_Q[demod_num], dt=1) elif quant.name.startswith('FPGA Single-shot REF,'): value = quant.getTraceDict( self.demod_output_vector_ref[demod_num], dt=1) elif quant.name.startswith('FPGA Voltage NP,'): return self.demod_output_NP[demod_num] elif quant.name.startswith('FPGA Single-shot NP,'): return quant.getTraceDict( self.demod_output_vector_NP[demod_num], dt=1) elif quant.name.startswith('FPGA Voltage,'): value = np.mean(self.demod_output_ssb[demod_num]) elif quant.name.startswith('FPGA Single-shot,'): # if no records, don't average over number of averages if self.demod_output_ssb.shape[2] <= 1: value = quant.getTraceDict( self.demod_output_ssb[demod_num, :, 0], dt=1) else: # records are being used, average over number of averages value = quant.getTraceDict( self.demod_output_ssb[demod_num].mean(0), dt=1) else: # for all others, return local value value = quant.getValue() return value def performArm(self, quant_names, options={}): """Perform the instrument arm operation""" # only arm digitizer if about to measure read-only values for name in quant_names: quant = self.getQuantity(name) if quant.isPermissionRead(): break else: # loop fell through, no read-only quantity, don't arm return # arm by calling get traces if self.isHardwareLoop(options): # in hardware looping, number of records is set by the looping (seq_no, n_seq) = self.getHardwareLoopIndex(options) # show status before starting acquisition self.reportStatus('Digitizer - Waiting for signal') # get data self.getTraces(bArm=True, bMeasure=False, n_seq=n_seq) # report arm completed, to allow client to continue self.report_arm_completed() # directly start collecting data (digitizer buffer is limited) self.getTraces(bArm=False, bMeasure=True, n_seq=n_seq) # after measurement is done, re-shape data and place in buffer self.reshaped_traces = [] for trace in self.lTrace: if len(trace) > 0: trace = trace.reshape((n_seq, trace.size // n_seq)) self.reshaped_traces.append(trace) else: self.getTraces(bArm=True, bMeasure=False) # report arm completed, to allow client to continue self.report_arm_completed() self.getTraces(bArm=False, bMeasure=True) def getTraces(self, bArm=True, bMeasure=True, n_seq=0): """Get all active traces""" # # test timing # import time # t0 = time.clock() # lT = [] # find out which traces to get lCh = [] iChMask = 0 for n in range(self.nCh): if self.fpga_config == 'Only signals': # normal operation if self.getValue('Ch%d - Enabled' % (n + 1)): lCh.append(n) iChMask += 2**n elif self.fpga_config == 'FPGA I/Q and signals': # mixed signal/demod, always enable ch 4 (used for demod) if (n == 3) or self.getValue('Ch%d - Enabled' % (n + 1)): lCh.append(n) iChMask += 2**n elif self.fpga_config == 'Only FPGA I/Q': # if only fpga demod, don't read any AWGs but ch 4 (demod) if n == 3: lCh.append(n) iChMask += 2**n else: continue # get current settings if self.fpga_config in ('Only signals', 'FPGA I/Q and signals'): nPts = int(self.getValue('Number of samples')) elif self.fpga_config == 'Only FPGA I/Q': nPts = self.demod_n_pts nCyclePerCall = int(self.getValue('Records per Buffer')) # in hardware loop mode, ignore records and use number of sequences if n_seq > 0: nSeg = n_seq else: nSeg = int(self.getValue('Number of records')) nAv = int(self.getValue('Number of averages')) # trigger delay is in 1/sample rate nTrigDelay = int(round(self.getValue('Trig Delay') / self.dt)) # special high-speed FPGA mode, don't convert, just transfer if (self.fpga_config == 'Only FPGA I/Q' and self.getValue('Hide I/Q') and not self.getValue('Convert data while streaming')): only_transfer_fgpa = True else: only_transfer_fgpa = False if bArm: # clear old data self.dig.DAQflushMultiple(iChMask) self.lTrace = [np.array([])] * self.nCh self.smsb_info_str = [] self.demod_counter = 0 # only re-allocate large output matrix if necessary (slow) if self.demod_output_ssb.size != (self.num_of_demods * nSeg * nAv): self.demod_output_ssb = np.zeros( (self.num_of_demods, nSeg * nAv), dtype='complex') else: # matrix has right size, just reshape self.demod_output_ssb = self.demod_output_ssb.reshape( (self.num_of_demods, nSeg * nAv)) # create new binary demod data buffer, if size changed buf = (nPts * nSeg * nAv) if only_transfer_fgpa else (nPts * nSeg) if self.demod_buffer.size != buf: self.demod_buffer = np.zeros(buf, dtype=np.int16) # only initiate diagnostic traces if in use if not self.getValue('Hide I/Q'): self.demod_output_vector_I = np.zeros( [self.num_of_demods, nSeg], dtype='complex') self.demod_output_I = np.zeros( self.num_of_demods, dtype='complex') self.demod_output_vector_Q = np.zeros( [self.num_of_demods, nSeg], dtype='complex') self.demod_output_Q = np.zeros( self.num_of_demods, dtype='complex') self.demod_output_vector_ref = np.zeros( [self.num_of_demods, nSeg], dtype='complex') self.demod_output_ref = np.zeros( self.num_of_demods, dtype='complex') self.demod_output_SSB = np.zeros( self.num_of_demods, dtype='complex') self.demod_output_vector_NP = np.zeros( [self.num_of_demods, nSeg]) self.demod_output_NP = np.zeros(self.num_of_demods) self.moment_I2 = np.zeros( [self.num_of_demods, nSeg], dtype='complex') self.moment_Q2 = np.zeros( [self.num_of_demods, nSeg], dtype='complex') # configure trigger for all active channels for nCh in lCh: self.lTrace[nCh] = np.zeros((nSeg * nPts)) # channel number depens on hardware version ch = self.getHwCh(nCh) # extra config for trig mode if self.getValue('Trig Mode') == 'Digital trigger': extSource = int( self.getCmdStringFromValue('External Trig Source')) trigBehavior = int( self.getCmdStringFromValue('External Trig Config')) sync = int(self.getCmdStringFromValue('Trig Sync Mode')) self.dig.DAQtriggerExternalConfig( ch, extSource, trigBehavior, sync) self.dig.DAQdigitalTriggerConfig( ch, extSource, trigBehavior) elif self.getValue('Trig Mode') == 'Analog channel': digitalTriggerMode = 0 digitalTriggerSource = 0 trigCh = self.getValueIndex('Analog Trig Channel') analogTriggerMask = 2**trigCh #analogTriggerMask = int('1111',2) self.dig.DAQdigitalTriggerConfig( ch, digitalTriggerSource, digitalTriggerMode) self.dig.DAQanalogTriggerConfig( ch, analogTriggerMask) # config daq and trig mode trigMode = int(self.getCmdStringFromValue('Trig Mode')) self.dig.DAQconfig(ch, nPts, nSeg * nAv, nTrigDelay, trigMode) # TODO change nPts # start acquiring data self.dig.DAQstartMultiple(iChMask) #self.wait(1) # lT.append('Start %.1f ms' % (1000*(time.clock()-t0))) # # return if not measure if not bMeasure: return # define number of cycles to read at a time nCycleTotal = nSeg * nAv nCall = int(np.ceil(nCycleTotal / nCyclePerCall)) lScale = [(self.getRange(ch) / self.bitRange) for ch in range(self.nCh)] # keep track of progress in percent old_percent = -1 # self.log('nCall:' + str(nCall), level = 30) # proceed depending on segment or not segment if only_transfer_fgpa: # just transfer fpga data, do conversion after to allow fast stream ch = self.getHwCh(3) count = 0 for n in range(nCall): # number of cycles for this call, could be fewer for last call nCycle = min(nCyclePerCall, nCycleTotal - (n * nCyclePerCall)) # channel number depens on hardware version data = self.DAQread(self.dig, ch, nPts * nCycle, int(3000 + self.timeout_ms / nCall)) # TODO change nPts # stop if no data if data.size == 0: return # store data in long vector, convert later self.demod_buffer[count:(count + data.size)] = data count += data.size # report progress, only report integer percent if nCall >= 1: new_percent = int(100 * n / nCall) if new_percent > old_percent: old_percent = new_percent self.reportStatus( 'Acquiring traces ({}%)'.format(new_percent) + ', FPGA Demod buffer: ' + ', '.join(self.smsb_info_str)) # break if stopped from outside if self.isStopped(): break # finally, get demod values self.getDemodValues(self.demod_buffer, nPts, nSeg, nSeg) elif nSeg <= 1: # non-segmented acquisiton for n in range(nCall): # number of cycles for this call, could be fewer for last call nCycle = min(nCyclePerCall, nCycleTotal - (n * nCyclePerCall)) # self.log('nCycle:' + str(nCycle), level = 30) # capture traces one by one for nCh in lCh: # channel number depens on hardware version ch = self.getHwCh(nCh) data = self.DAQread(self.dig, ch, nPts * nCycle, int(3000 + self.timeout_ms / nCall)) # stop if no data if data.size == 0: return # different operation for signals vs demod data if self.fpga_config == 'Only signals' or nCh < 3: # average data = data.reshape((nCycle, nPts)).mean(0) # adjust scaling to account for summing averages scale = lScale[nCh] * (nCycle / nAv) # convert to voltage, add to total average self.lTrace[nCh] += data * scale else: # for demod, immediately get demodulated values self.getDemodValues(data, nPts, nSeg, nCycle) # report progress, only report integer percent if nCall >= 1: new_percent = int(100 * n / nCall) if new_percent > old_percent: old_percent = new_percent self.reportStatus( 'Acquiring traces ({}%)'.format(new_percent) + ', FPGA Demod buffer: ' + ', '.join(self.smsb_info_str)) # break if stopped from outside if self.isStopped(): break # lT.append('N: %d, Tot %.1f ms' % (n, 1000 * (time.clock() - t0))) else: # segmented acquisition, get calls per segment (nCallSeg, extra_call) = divmod(nSeg, nCyclePerCall) # pre-calculate list of cycles/call, last call may have more cycles if nCallSeg == 0: nCallSeg = 1 lCyclesSeg = [nSeg] else: lCyclesSeg = [nCyclePerCall] * nCallSeg lCyclesSeg[-1] = nCyclePerCall + extra_call # pre-calculate scale, should include scaling for averaging lScale = np.array(lScale, dtype=float) / nAv for n in range(nAv): count = 0 # loop over number of calls per segment for m, nCycle in enumerate(lCyclesSeg): # capture traces one by one for nCh in lCh: # channel number depens on hardware version ch = self.getHwCh(nCh) data = self.DAQread(self.dig, ch, nPts * nCycle, int(3000 + self.timeout_ms / nCall)) # stop if no data if data.size == 0: return # different operation for signals vs demod data if self.fpga_config == 'Only signals' or nCh < 3: # standard operation, store data in one long vector self.lTrace[nCh][count:(count + data.size)] += \ data * lScale[nCh] else: # store raw demod data, will be extracted later self.demod_buffer[count:(count + data.size)] = data count += data.size # after one full set of records, convert demod data if self.fpga_config != 'Only signals': self.getDemodValues(self.demod_buffer, nPts, nSeg, nSeg) # report progress, only report integer percent if nAv >= 1: new_percent = int(100 * n / nAv) if new_percent > old_percent: old_percent = new_percent self.reportStatus( 'Acquiring traces ({}%)'.format(new_percent) + ', FPGA Demod buffer: ' + ', '.join(self.smsb_info_str)) # break if stopped from outside if self.isStopped(): break # at the end, convert binary data to I/Q values if self.fpga_config != 'Only signals': self.demod_output_ssb = self.demod_output_ssb.reshape( (self.num_of_demods, nAv, nSeg)) # lT.append('N: %d, Tot %.1f ms' % (n, 1000 * (time.clock() - t0))) # # log timing info # self.log(': '.join(lT)) def getRange(self, ch): """Get channel range, as voltage. Index start at 0""" rang = float(self.getCmdStringFromValue('Ch%d - Range' % (ch + 1))) # range depends on impedance if self.getValue('Ch%d - Impedance' % (ch + 1)) == 'High': rang = rang * 2 # special case if range is .25, 0.5, or 1, scale to 0.2, .4, .8 if rang < 1.1: rang *= 0.8 return rang def DAQread(self, dig, nDAQ, nPoints, timeOut): """Read data diretly to numpy array""" if dig._SD_Object__handle > 0: if nPoints > 0: data = (keysightSD1.c_short * nPoints)() nPointsOut = dig._SD_Object__core_dll.SD_AIN_DAQread( dig._SD_Object__handle, nDAQ, data, nPoints, timeOut) if nPointsOut > 0: return np.frombuffer(data, dtype=np.int16, count=nPoints) else: return np.array([], dtype=np.int16) else: return keysightSD1.SD_Error.INVALID_VALUE else: return keysightSD1.SD_Error.MODULE_NOT_OPENED def getDemodValues(self, demod_raw, nPts, nSeg, nCycle): """get Demod IQ data from Ch1/2/3 Trace""" accum_length = self.getValue('Integration time') lScale = [(self.getRange(ch) / self.bitRange) for ch in range(self.nCh)] self.smsb_info_str = [] nDemods = self.num_of_demods use_phase_ref = self.getValue('Use phase reference signal') for n in range(nDemods): y1_lsb = demod_raw[((n * 15) + 0)::nPts] y1_msb = demod_raw[((n * 15) + 1)::nPts] x1_lsb = demod_raw[((n * 15) + 2)::nPts] x1_msb = demod_raw[((n * 15) + 3)::nPts] y1x1_smsb = demod_raw[((n * 15) + 4)::nPts] x1_smsb = y1x1_smsb.astype('int8') y1_smsb = y1x1_smsb.astype('int16') >> 8 y2_lsb = demod_raw[((n * 15) + 5)::nPts] y2_msb = demod_raw[((n * 15) + 6)::nPts] x2_lsb = demod_raw[((n * 15) + 7)::nPts] x2_msb = demod_raw[((n * 15) + 8)::nPts] y2x2_smsb = demod_raw[((n * 15) + 9)::nPts] x2_smsb = y2x2_smsb.astype('int8') y2_smsb = y2x2_smsb.astype('int16') >> 8 y1_int64 = ( y1_lsb.astype('uint16') + y1_msb.astype('uint16') * (2 ** 16) + y1_smsb.astype('int8') * (2**32)) x1_int64 = ( x1_lsb.astype('uint16') + x1_msb.astype('uint16') * (2 ** 16) + x1_smsb.astype('int8') * (2**32)) y2_int64 = ( y2_lsb.astype('uint16') + y2_msb.astype('uint16') * (2 ** 16) + y2_smsb.astype('int8') * (2**32)) x2_int64 = ( x2_lsb.astype('uint16') + x2_msb.astype('uint16') * (2 ** 16) + x2_smsb.astype('int8') * (2**32)) smsb_info = [np.max(np.abs(x1_smsb)), np.max(np.abs(y1_smsb)), np.max(np.abs(x2_smsb)), np.max(np.abs(y2_smsb))] smsb_temp_info_str = str(int(max(smsb_info) / 1.24)) + '%' self.smsb_info_str.append(smsb_temp_info_str) warning_thr = 124 # warning indication that overflow can occur if np.any(np.array(smsb_info)) > warning_thr: warning_str = ( 'Warning! overflow may occur in FPGA demod block: %d, %s' % (n, str(smsb_info))) self.log(warning_str, level=30) demod_temp_I = ( (x1_int64.astype('int64') + 1j * y1_int64.astype('int64')) / 2**43 / accum_length * lScale[0]) demod_temp_Q = ( (x2_int64.astype('int64') + 1j * y2_int64.astype('int64')) / 2**43 / accum_length * lScale[1]) # store final values in large array, get indices for current call k = self.demod_counter n_values = demod_temp_I.size if self.getValue('LO freq %d' % (n + 1)) <= 0: self.demod_output_ssb[n, k:(k + n_values)] = 0.5 * ( np.real(demod_temp_I) + np.imag(demod_temp_Q) - 1j * (np.imag(demod_temp_I) - np.real(demod_temp_Q)) ) else: self.demod_output_ssb[n, k:(k + n_values)] = 0.5 * ( np.real(demod_temp_I) - np.imag(demod_temp_Q) + 1j * (np.imag(demod_temp_I) + np.real(demod_temp_Q)) ) # self.demod_output_ssb[n] = np.real(self.demod_output_vector_I[n]) - np.imag(self.demod_output_vector_Q[n]) - 1j*(np.imag(self.demod_output_vector_I[n]) + np.real(self.demod_output_vector_Q[n])) if use_phase_ref or (not self.getValue('Hide I/Q')): # extract reference signal y3_lsb = demod_raw[((n * 15) + 10)::nPts] y3_msb = demod_raw[((n * 15) + 11)::nPts] x3_lsb = demod_raw[((n * 15) + 12)::nPts] x3_msb = demod_raw[((n * 15) + 13)::nPts] y3x3_smsb = demod_raw[((n * 15) + 14)::nPts] x3_smsb = y3x3_smsb.astype('int8') y3_smsb = y3x3_smsb.astype('int16') >> 8 y3_int64 = ( y3_lsb.astype('uint16') + y3_msb.astype('uint16') * (2 ** 16) + y3_smsb.astype('int8') * (2**32)) x3_int64 = ( x3_lsb.astype('uint16') + x3_msb.astype('uint16') * (2 ** 16) + x3_smsb.astype('int8') * (2**32)) demod_temp_ref = ( (x3_int64.astype('int64') + 1j * y3_int64.astype('int64')) / 2**43 / accum_length * lScale[2]) # subtract the reference angle if use_phase_ref: ref = np.arctan2(demod_temp_ref.imag, demod_temp_ref.real) self.demod_output_ssb[n, k:(k + n_values)] /= ( np.cos(ref) - 1j * np.sin(ref)) # if advanced values not in use, don't calculate to save time if self.getValue('Hide I/Q'): continue nAv = self.getValue('Number of averages') if nSeg <= 1: demod_temp_I = demod_temp_I.reshape((nCycle, 1)).mean(0) demod_temp_Q = demod_temp_Q.reshape((nCycle, 1)).mean(0) demod_temp_ref = demod_temp_ref.reshape((nCycle, 1)).mean(0) self.demod_output_vector_I[n] += demod_temp_I / nAv * nCycle self.demod_output_vector_Q[n] += demod_temp_Q / nAv * nCycle self.demod_output_vector_ref[n] += demod_temp_ref / nAv * nCycle self.moment_I2[n] += np.power( np.abs(demod_temp_I), 2) / nAv * nCycle self.moment_Q2[n] += np.power( np.abs(demod_temp_Q), 2) / nAv * nCycle else: self.moment_I2[n] += np.power(np.abs(demod_temp_I), 2) / nAv self.moment_Q2[n] += np.power(np.abs(demod_temp_Q), 2) / nAv self.demod_output_vector_I[n] += demod_temp_I / nAv self.demod_output_vector_Q[n] += demod_temp_Q / nAv self.demod_output_vector_ref[n] += demod_temp_ref / nAv self.demod_output_I[n] = np.mean(self.demod_output_vector_I[n]) self.demod_output_Q[n] = np.mean(self.demod_output_vector_Q[n]) self.demod_output_ref[n] = np.mean(self.demod_output_vector_ref[n]) self.demod_output_vector_NP[n] = ( self.moment_I2[n] + self.moment_Q2[n]) self.demod_output_NP[n] = np.mean(self.demod_output_vector_NP[n]) self.demod_counter += n_values def setFPGALOfreq(self, demod_num, demod_LO_freq): FPGA_PcPort_channel = 0 tmp_0 = np.zeros(2, dtype=int) tmp_1 = np.zeros(2, dtype=int) tmp_2 = np.zeros(2, dtype=int) tmp_3 = np.zeros(2, dtype=int) tmp_4 = np.zeros(2, dtype=int) tmp_5 =
np.zeros(2, dtype=int)
numpy.zeros
#!/usr/bin/env python # coding: utf-8 # In[1]: import os import sys import random import gc import pickle import pandas as pd import numpy as np import matplotlib.pyplot as plt plt.style.use('seaborn-white') import seaborn as sns sns.set_style("white") get_ipython().run_line_magic('matplotlib', 'inline') from sklearn.model_selection import train_test_split from tqdm import tqdm_notebook #, tnrange #from itertools import chain from skimage.io import imread, imshow #, concatenate_images from skimage.transform import resize from skimage.morphology import label from keras.models import Model, load_model, save_model from keras.layers import Input,Dropout,BatchNormalization,Activation,Add from keras.layers.core import Lambda from keras.layers.convolutional import Conv2D, Conv2DTranspose from keras.layers.pooling import MaxPooling2D from keras.layers.merge import concatenate from keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau from keras import backend as K from keras import optimizers from keras.callbacks import Callback import keras.backend as K import numpy as np import imgaug as ia from imgaug import augmenters as iaa import tensorflow as tf from tta_wrapper import tta_segmentation from keras.preprocessing.image import array_to_img, img_to_array, load_img#,save_img import imgaug import time t_start = time.time() # In[2]: VERSION = 32 SEED = 42 FOLDS = 5 DEPTH = True basic_name = f'Unet_resnet_v{VERSION}' save_model_name = basic_name + '.model' save_model_name_lov = basic_name + '_lov.model' submission_file = basic_name + '.csv' imgaug.seed(SEED) print(save_model_name) print(save_model_name_lov) print(submission_file) # In[3]: img_size_ori = 101 img_size_target = 101 def upsample(img): if img_size_ori == img_size_target: return img return resize(img, (img_size_target, img_size_target), mode='constant', preserve_range=True) def downsample(img): if img_size_ori == img_size_target: return img return resize(img, (img_size_ori, img_size_ori), mode='constant', preserve_range=True) # In[4]: # Loading of training/testing ids and depths train_df = pd.read_csv("../data/raw/train.csv", index_col="id", usecols=[0]) depths_df = pd.read_csv("../data/raw/depths.csv", index_col="id") train_df = train_df.join(depths_df) test_df = depths_df[~depths_df.index.isin(train_df.index)] len(train_df) # In[5]: train_df["images"] = [np.array(load_img("../data/raw/train/images/{}.png".format(idx), color_mode = "grayscale",)) / 255 for idx in tqdm_notebook(train_df.index)] # In[6]: train_df["masks"] = [np.array(load_img("../data/raw/train/masks/{}.png".format(idx), color_mode = "grayscale",)) / 255 for idx in tqdm_notebook(train_df.index)] # In[7]: train_df["coverage"] = train_df.masks.map(np.sum) / pow(img_size_ori, 2) def cov_to_class(val): for i in range(0, 11): if val * 10 <= i : return i train_df["coverage_class"] = train_df.coverage.map(cov_to_class) # In[8]: SUBSET = len(train_df) train_df = train_df.head(SUBSET) len(train_df) # In[9]: def BatchActivate(x): x = BatchNormalization()(x) x = Activation('relu')(x) return x def convolution_block(x, filters, size, strides=(1,1), padding='same', activation=True): x = Conv2D(filters, size, strides=strides, padding=padding)(x) if activation == True: x = BatchActivate(x) return x def residual_block(blockInput, num_filters=16, batch_activate = False): x = BatchActivate(blockInput) x = convolution_block(x, num_filters, (3,3) ) x = convolution_block(x, num_filters, (3,3), activation=False) x = Add()([x, blockInput]) if batch_activate: x = BatchActivate(x) return x # In[10]: # Build model def build_model(input_layer, start_neurons, DropoutRatio = 0.5): # 101 -> 50 conv1 = Conv2D(start_neurons * 1, (3, 3), activation=None, padding="same")(input_layer) conv1 = residual_block(conv1,start_neurons * 1) conv1 = residual_block(conv1,start_neurons * 1, True) pool1 = MaxPooling2D((2, 2))(conv1) pool1 = Dropout(DropoutRatio/2)(pool1) # 50 -> 25 conv2 = Conv2D(start_neurons * 2, (3, 3), activation=None, padding="same")(pool1) conv2 = residual_block(conv2,start_neurons * 2) conv2 = residual_block(conv2,start_neurons * 2, True) pool2 = MaxPooling2D((2, 2))(conv2) pool2 = Dropout(DropoutRatio)(pool2) # 25 -> 12 conv3 = Conv2D(start_neurons * 4, (3, 3), activation=None, padding="same")(pool2) conv3 = residual_block(conv3,start_neurons * 4) conv3 = residual_block(conv3,start_neurons * 4, True) pool3 = MaxPooling2D((2, 2))(conv3) pool3 = Dropout(DropoutRatio)(pool3) # 12 -> 6 conv4 = Conv2D(start_neurons * 8, (3, 3), activation=None, padding="same")(pool3) conv4 = residual_block(conv4,start_neurons * 8) conv4 = residual_block(conv4,start_neurons * 8, True) pool4 = MaxPooling2D((2, 2))(conv4) pool4 = Dropout(DropoutRatio)(pool4) # Middle convm = Conv2D(start_neurons * 16, (3, 3), activation=None, padding="same")(pool4) convm = residual_block(convm,start_neurons * 16) convm = residual_block(convm,start_neurons * 16, True) # 6 -> 12 deconv4 = Conv2DTranspose(start_neurons * 8, (3, 3), strides=(2, 2), padding="same")(convm) uconv4 = concatenate([deconv4, conv4]) uconv4 = Dropout(DropoutRatio)(uconv4) uconv4 = Conv2D(start_neurons * 8, (3, 3), activation=None, padding="same")(uconv4) uconv4 = residual_block(uconv4,start_neurons * 8) uconv4 = residual_block(uconv4,start_neurons * 8, True) # 12 -> 25 #deconv3 = Conv2DTranspose(start_neurons * 4, (3, 3), strides=(2, 2), padding="same")(uconv4) deconv3 = Conv2DTranspose(start_neurons * 4, (3, 3), strides=(2, 2), padding="valid")(uconv4) uconv3 = concatenate([deconv3, conv3]) uconv3 = Dropout(DropoutRatio)(uconv3) uconv3 = Conv2D(start_neurons * 4, (3, 3), activation=None, padding="same")(uconv3) uconv3 = residual_block(uconv3,start_neurons * 4) uconv3 = residual_block(uconv3,start_neurons * 4, True) # 25 -> 50 deconv2 = Conv2DTranspose(start_neurons * 2, (3, 3), strides=(2, 2), padding="same")(uconv3) uconv2 = concatenate([deconv2, conv2]) uconv2 = Dropout(DropoutRatio)(uconv2) uconv2 = Conv2D(start_neurons * 2, (3, 3), activation=None, padding="same")(uconv2) uconv2 = residual_block(uconv2,start_neurons * 2) uconv2 = residual_block(uconv2,start_neurons * 2, True) # 50 -> 101 #deconv1 = Conv2DTranspose(start_neurons * 1, (3, 3), strides=(2, 2), padding="same")(uconv2) deconv1 = Conv2DTranspose(start_neurons * 1, (3, 3), strides=(2, 2), padding="valid")(uconv2) uconv1 = concatenate([deconv1, conv1]) uconv1 = Dropout(DropoutRatio)(uconv1) uconv1 = Conv2D(start_neurons * 1, (3, 3), activation=None, padding="same")(uconv1) uconv1 = residual_block(uconv1,start_neurons * 1) uconv1 = residual_block(uconv1,start_neurons * 1, True) #uconv1 = Dropout(DropoutRatio/2)(uconv1) #output_layer = Conv2D(1, (1,1), padding="same", activation="sigmoid")(uconv1) output_layer_noActi = Conv2D(1, (1,1), padding="same", activation=None)(uconv1) output_layer = Activation('sigmoid')(output_layer_noActi) return output_layer # In[11]: def get_iou_vector(A, B): batch_size = A.shape[0] metric = [] for batch in range(batch_size): t, p = A[batch]>0, B[batch]>0 intersection = np.logical_and(t, p) union = np.logical_or(t, p) iou = (np.sum(intersection > 0) + 1e-10 )/ (np.sum(union > 0) + 1e-10) thresholds = np.arange(0.5, 1, 0.05) s = [] for thresh in thresholds: s.append(iou > thresh) metric.append(np.mean(s)) return np.mean(metric) def my_iou_metric(label, pred): return tf.py_func(get_iou_vector, [label, pred>0.5], tf.float64) def my_iou_metric_2(label, pred): return tf.py_func(get_iou_vector, [label, pred >0], tf.float64) # In[12]: # code download from: https://github.com/bermanmaxim/LovaszSoftmax def lovasz_grad(gt_sorted): """ Computes gradient of the Lovasz extension w.r.t sorted errors See Alg. 1 in paper """ gts = tf.reduce_sum(gt_sorted) intersection = gts - tf.cumsum(gt_sorted) union = gts + tf.cumsum(1. - gt_sorted) jaccard = 1. - intersection / union jaccard = tf.concat((jaccard[0:1], jaccard[1:] - jaccard[:-1]), 0) return jaccard # --------------------------- BINARY LOSSES --------------------------- def lovasz_hinge(logits, labels, per_image=True, ignore=None): """ Binary Lovasz hinge loss logits: [B, H, W] Variable, logits at each pixel (between -\infty and +\infty) labels: [B, H, W] Tensor, binary ground truth masks (0 or 1) per_image: compute the loss per image instead of per batch ignore: void class id """ if per_image: def treat_image(log_lab): log, lab = log_lab log, lab = tf.expand_dims(log, 0), tf.expand_dims(lab, 0) log, lab = flatten_binary_scores(log, lab, ignore) return lovasz_hinge_flat(log, lab) losses = tf.map_fn(treat_image, (logits, labels), dtype=tf.float32) loss = tf.reduce_mean(losses) else: loss = lovasz_hinge_flat(*flatten_binary_scores(logits, labels, ignore)) return loss def lovasz_hinge_flat(logits, labels): """ Binary Lovasz hinge loss logits: [P] Variable, logits at each prediction (between -\infty and +\infty) labels: [P] Tensor, binary ground truth labels (0 or 1) ignore: label to ignore """ def compute_loss(): labelsf = tf.cast(labels, logits.dtype) signs = 2. * labelsf - 1. errors = 1. - logits * tf.stop_gradient(signs) errors_sorted, perm = tf.nn.top_k(errors, k=tf.shape(errors)[0], name="descending_sort") gt_sorted = tf.gather(labelsf, perm) grad = lovasz_grad(gt_sorted) #loss = tf.tensordot(tf.nn.relu(errors_sorted), tf.stop_gradient(grad), 1, name="loss_non_void") loss = tf.tensordot(tf.nn.elu(errors_sorted), tf.stop_gradient(grad), 1, name="loss_non_void") return loss # deal with the void prediction case (only void pixels) loss = tf.cond(tf.equal(tf.shape(logits)[0], 0), lambda: tf.reduce_sum(logits) * 0., compute_loss, strict=True, name="loss" ) return loss def flatten_binary_scores(scores, labels, ignore=None): """ Flattens predictions in the batch (binary case) Remove labels equal to 'ignore' """ scores = tf.reshape(scores, (-1,)) labels = tf.reshape(labels, (-1,)) if ignore is None: return scores, labels valid = tf.not_equal(labels, ignore) vscores = tf.boolean_mask(scores, valid, name='valid_scores') vlabels = tf.boolean_mask(labels, valid, name='valid_labels') return vscores, vlabels def lovasz_loss(y_true, y_pred): y_true, y_pred = K.cast(K.squeeze(y_true, -1), 'int32'), K.cast(K.squeeze(y_pred, -1), 'float32') #logits = K.log(y_pred / (1. - y_pred)) logits = y_pred #Jiaxin loss = lovasz_hinge(logits, y_true, per_image = True, ignore = None) return loss # In[13]: def predict_result(model,x_test,img_size_target): # predict both orginal and reflect x x_test_reflect = np.array([np.fliplr(x) for x in x_test]) preds_test = model.predict(x_test).reshape(-1, img_size_target, img_size_target) preds_test2_refect = model.predict(x_test_reflect).reshape(-1, img_size_target, img_size_target) preds_test += np.array([ np.fliplr(x) for x in preds_test2_refect] ) return preds_test/2 # In[14]: def add_depth_coord(images): """ Takes dataset (N, W, H, 1) returns (N, W, H, 3). """ if not DEPTH: return images assert(len(images.shape) == 4) channel1 = np.zeros_like(images) h = images.shape[1] for row, const in enumerate(np.linspace(0, 1, h)): channel1[:, row, ...] = const channel2 = images * channel1 images = np.concatenate([images, channel1, channel2], axis=-1) return images class SGDRScheduler(Callback): '''Cosine annealing learning rate scheduler with periodic restarts. # Usage ```python schedule = SGDRScheduler(min_lr=1e-5, max_lr=1e-2, steps_per_epoch=np.ceil(epoch_size/batch_size), lr_decay=0.9, cycle_length=5, mult_factor=1.5) model.fit(X_train, Y_train, epochs=100, callbacks=[schedule]) ``` # Arguments min_lr: The lower bound of the learning rate range for the experiment. max_lr: The upper bound of the learning rate range for the experiment. steps_per_epoch: Number of mini-batches in the dataset. Calculated as `np.ceil(epoch_size/batch_size)`. lr_decay: Reduce the max_lr after the completion of each cycle. Ex. To reduce the max_lr by 20% after each cycle, set this value to 0.8. cycle_length: Initial number of epochs in a cycle. mult_factor: Scale epochs_to_restart after each full cycle completion. # References Blog post: jeremyjordan.me/nn-learning-rate Original paper: http://arxiv.org/abs/1608.03983 ''' def __init__(self, min_lr, max_lr, steps_per_epoch, lr_decay=1, cycle_length=10, mult_factor=2): self.min_lr = min_lr self.max_lr = max_lr self.lr_decay = lr_decay self.batch_since_restart = 0 self.next_restart = cycle_length self.steps_per_epoch = steps_per_epoch self.cycle_length = cycle_length self.mult_factor = mult_factor self.history = {} def clr(self): '''Calculate the learning rate.''' fraction_to_restart = self.batch_since_restart / (self.steps_per_epoch * self.cycle_length) lr = self.min_lr + 0.5 * (self.max_lr - self.min_lr) * (1 + np.cos(fraction_to_restart * np.pi)) return lr def on_train_begin(self, logs={}): '''Initialize the learning rate to the minimum value at the start of training.''' logs = logs or {} K.set_value(self.model.optimizer.lr, self.max_lr) def on_batch_end(self, batch, logs={}): '''Record previous batch statistics and update the learning rate.''' logs = logs or {} self.history.setdefault('lr', []).append(K.get_value(self.model.optimizer.lr)) for k, v in logs.items(): self.history.setdefault(k, []).append(v) self.batch_since_restart += 1 K.set_value(self.model.optimizer.lr, self.clr()) def on_epoch_end(self, epoch, logs={}): '''Check for end of current cycle, apply restarts when necessary.''' if epoch + 1 == self.next_restart: self.batch_since_restart = 0 self.cycle_length = np.ceil(self.cycle_length * self.mult_factor) self.next_restart += self.cycle_length self.max_lr *= self.lr_decay self.best_weights = self.model.get_weights() def on_train_end(self, logs={}): '''Set weights to the values from the end of the most recent cycle for best performance.''' self.model.set_weights(self.best_weights) # In[15]: #Data augmentation import cv2 affine_seq = iaa.Sequential([ # General iaa.SomeOf((1, 2), [iaa.Fliplr(0.5), iaa.Affine(rotate=(-10, 10), translate_percent={"x": (-0.05, 0.05)}, mode='edge'), # iaa.CropAndPad(percent=((0.0, 0.0), (0.05, 0.0), (0.0, 0.0), (0.05, 0.0))) ]), # Deformations iaa.Sometimes(0.3, iaa.PiecewiseAffine(scale=(0.04, 0.08))), iaa.Sometimes(0.3, iaa.PerspectiveTransform(scale=(0.05, 0.1))), ], random_order=True) intensity_seq = iaa.Sequential([ iaa.Invert(0.3), iaa.Sometimes(0.3, iaa.ContrastNormalization((0.5, 1.5))), iaa.OneOf([ iaa.Noop(), iaa.Sequential([ iaa.OneOf([ iaa.Add((-10, 10)), iaa.AddElementwise((-10, 10)), iaa.Multiply((0.95, 1.05)), iaa.MultiplyElementwise((0.95, 1.05)), ]), ]), iaa.OneOf([ iaa.GaussianBlur(sigma=(0.0, 1.0)), iaa.AverageBlur(k=(2, 5)), iaa.MedianBlur(k=(3, 5)) ]) ]) ], random_order=False) def augment(x, y): sometimes = lambda aug: iaa.Sometimes(0.3, aug) seq = iaa.Sequential([ iaa.Fliplr(0.5), # horizontally flip sometimes(iaa.Add((-10, 10))), # iaa.OneOf([ # iaa.Noop(), # iaa.PerspectiveTransform(scale=(0.04, 0.08)), # iaa.Add((-10, 10)), # iaa.ContrastNormalization((0.75, 1.5)), # iaa.Emboss(alpha=(0, 1.0), strength=(0, 2.0)), # iaa.EdgeDetect(alpha=(0, 0.7)), # iaa.Noop(), # sometimes(iaa.OneOf([ # iaa.EdgeDetect(alpha=(0, 0.7)), # iaa.DirectedEdgeDetect( # alpha=(0, 0.7), direction=(0.0, 1.0) # ), # ])), # ]), #sometimes(iaa.CropAndPad( # percent=(-0.2, 0.2), # pad_mode=["reflect"] # )), # sometimes(iaa.Sequential([ # iaa.Crop(percent=(0.2), keep_size=False), # iaa.Scale({"height": img_size_target, "width": img_size_target}), # iaa.Pad(percent=(0.2), pad_mode=["reflect"]) # ])), ])._to_deterministic() images_aug_x = seq.augment_images(x) images_aug_y = seq.augment_images(y) return np.array(images_aug_x), np.array(images_aug_y) # Return augmented images/masks arrays of batch size def generator(features, labels, batch_size, repeat=1): # create empty arrays to contain batch of features and labels batch_features = np.zeros((batch_size, img_size_target, img_size_target, features.shape[3])) batch_labels = np.zeros((batch_size, img_size_target, img_size_target, labels.shape[3])) print(batch_features.shape) while True: # Fill arrays of batch size with augmented data taken randomly from full passed arrays indexes = random.sample(range(len(features)), batch_size)*repeat # Perform the exactly the same augmentation for X and y random_augmented_images, random_augmented_labels = augment(np.apply_along_axis(np.squeeze, 1, features[indexes]*255).astype(np.uint8), np.apply_along_axis(np.squeeze, 1, labels[indexes]*255).astype(np.uint8)) yield add_depth_coord(random_augmented_images/255), random_augmented_labels/255 #x_train = np.array(train_df.images.map(upsample).tolist()).reshape(-1, img_size_target, img_size_target, 3) #y_train = np.array(train_df.masks.map(upsample).tolist()).reshape(-1, img_size_target, img_size_target, 3) #x_test= np.array(test_df.images.map(upsample).tolist()).reshape(-1, img_size_target, img_size_target, 3) x_train = np.array(train_df.images.tolist()).reshape(-1, img_size_target, img_size_target, 1) y_train = np.array(train_df.masks.tolist()).reshape(-1, img_size_target, img_size_target, 1) train_cls = np.array(train_df.coverage_class) gc.collect() #x_train, y_train, train_cls = augment(train_df) # In[16]: #Score the model and do a threshold optimization by the best IoU. # src: https://www.kaggle.com/aglotero/another-iou-metric def iou_metric(y_true_in, y_pred_in, print_table=False): labels = y_true_in y_pred = y_pred_in true_objects = 2 pred_objects = 2 # if all zeros, original code generate wrong bins [-0.5 0 0.5], temp1 = np.histogram2d(labels.flatten(), y_pred.flatten(), bins=([0,0.5,1], [0,0.5, 1])) intersection = temp1[0] area_true = np.histogram(labels,bins=[0,0.5,1])[0] area_pred = np.histogram(y_pred, bins=[0,0.5,1])[0] area_true = np.expand_dims(area_true, -1) area_pred = np.expand_dims(area_pred, 0) # Compute union union = area_true + area_pred - intersection # Exclude background from the analysis intersection = intersection[1:,1:] intersection[intersection == 0] = 1e-9 union = union[1:,1:] union[union == 0] = 1e-9 # Compute the intersection over union iou = intersection / union # Precision helper function def precision_at(threshold, iou): matches = iou > threshold true_positives = np.sum(matches, axis=1) == 1 # Correct objects false_positives = np.sum(matches, axis=0) == 0 # Missed objects false_negatives = np.sum(matches, axis=1) == 0 # Extra objects tp, fp, fn =
np.sum(true_positives)
numpy.sum
#!/usr/bin/env python3 import rospy import rospkg import actionlib from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal import pathlib import onnxruntime as ort import numpy as np import cv2 from olfaction_msgs.msg import gas_sensor, anemometer import matplotlib.pyplot as plt # set initial position initial_position = (2, 14) source_position = (3, 2) # initialize path pkg_path = pathlib.Path(rospkg.RosPack().get_path('pydog_gsl')) map_path = pkg_path / 'map/occupancy.png' model_path = pkg_path / 'model/dqn.onnx' output_path = pkg_path / 'result.csv' # initialize map_grid map_grid = cv2.imread(map_path.as_posix()) map_grid = cv2.cvtColor(map_grid, cv2.COLOR_BGR2GRAY) _, map_grid = cv2.threshold(map_grid, 125, 255, cv2.THRESH_BINARY) map_grid = map_grid.astype(np.float32) map_grid /= 255.0 # onnxruntime Policy class Policy: def __init__(self, model_path: str) -> None: self.ort_sess = ort.InferenceSession(model_path) self.action_name = ['Up', 'Down', 'Left', 'Right'] def __call__(self, model_input): output = self.ort_sess.run(['output'], {'input': model_input})[0] return np.argmax(output, axis=1, keepdims=True)[0, 0] def __len__(self): return len(self.action_name) def __getitem__(self, key): return self.action_name[key] # observation matrix class ObservationMatrix: def __init__(self, map_grid, initial_position, concentration_limit=200.0) -> None: self.trajectory_matrix = np.zeros(map_grid.shape, dtype=np.float32) self.obstacle_matrix = map_grid.copy() self.concentration_matrix = np.zeros(map_grid.shape, dtype=np.float32) self.airflow_x_matrix = np.zeros(map_grid.shape, dtype=np.float32) self.airflow_y_matrix = np.zeros(map_grid.shape, dtype=np.float32) self.agent_position = [initial_position[0], initial_position[1]] self.concentration_limit = concentration_limit def get_observation(self): trajectory_matrix_pad =
np.pad(self.trajectory_matrix, (5, 5), 'constant', constant_values=0)
numpy.pad
import pickle import os import matplotlib.pyplot as plt import numpy as np def running_max_stats(scores): maxscores = np.maximum.accumulate(scores, axis=1) mean = np.mean(maxscores, axis=0) std = np.std(maxscores, axis=0) return (maxscores, mean, std) def plot_searcher_comparison(): folder_path = 'logs/searcher_comparison' searchers = ['rand', 'mcts', 'mcts_bi', 'smbo'] # searchers = ['smbo'] search_space_type = 'deepconv' num_repeats = 5 # loading the scores` m_maxscores = [] std_maxscores = [] for searcher_type in searchers: # load all the pickles rs = [] for i in xrange(num_repeats): file_name = '%s_%s_%d.pkl' % (search_space_type, searcher_type, i) file_path = os.path.join(folder_path, file_name) with open(file_path, 'rb') as f: r = pickle.load(f) rs.append(r) srch_scores = [r['scores'] for r in rs] # from pprint import pprint # print searcher_type, len(srch_scores[0]) #pprint(srch_scores) # print searcher_type, [len(scs) for scs in srch_scores] _, mean, std = running_max_stats(srch_scores) m_maxscores.append(mean) std_maxscores.append(std) def plot_comparison(k1, k2): for searcher_type, mean, std in zip(searchers, m_maxscores, std_maxscores): plt.errorbar(np.arange(k1, k2 + 1), mean[k1 - 1:k2], yerr=std[k1 - 1:k2] / np.sqrt(num_repeats), label=searcher_type) plt.legend(loc='best') plt.xlabel('Number of models evaluated') plt.ylabel('Best validation performance') # plot some different number of ranges for k1, k2 in [(1, 64), (1, 16), (4, 16), (16, 64), (6, 64)]: plot_comparison(k1, k2) plt.savefig(figs_folderpath + 'searcher_comp_%d_to_%d.pdf' % (k1, k2), bbox_inches='tight') plt.close() def compute_percentiles(scores, thresholds): scores = np.array(scores) n = float(len(scores)) percents = [(scores >= th).sum() / n for th in thresholds] return percents def plot_performance_quantiles(): folder_path = 'logs/searcher_comparison' searchers = ['rand', 'mcts', 'mcts_bi', 'smbo'] search_space_type = 'deepconv' num_repeats = 5 for searcher_type in searchers: # load all the pickles rs = [] for i in xrange(num_repeats): file_name = '%s_%s_%d.pkl' % (search_space_type, searcher_type, i) file_path = os.path.join(folder_path, file_name) with open(file_path, 'rb') as f: r = pickle.load(f) rs.append(r) percents =
np.linspace(0.0, 1.0, num=100)
numpy.linspace
""" Scripts reads in sea ice thickness data from CS-2 corrected/uncorrected and plots a trend analysis over the 2011-2017 period (April) Notes ----- Author : <NAME> Date : 16 January 2018 """ ### Import modules import numpy as np import matplotlib.pyplot as plt import matplotlib.colors as c import datetime from mpl_toolkits.basemap import Basemap import nclcmaps as ncm import cmocean import scipy.stats as sts ### Define directories directorydata = '/home/zlabe/Documents/Projects/CAAthickness/Data/' directoryfigure = '/home/zlabe/Desktop/CS2PIOMAS/Corrected/' ### Define time now = datetime.datetime.now() currentmn = str(now.month) currentdy = str(now.day) currentyr = str(now.year) currenttime = currentmn + '_' + currentdy + '_' + currentyr titletime = currentmn + '/' + currentdy + '/' + currentyr print('\n' '----Calc sea ice thickness trends - %s----\n' % titletime) ### Alott time series yearmin = 2011 yearmax = 2017 years = np.arange(yearmin,yearmax+1,1) yearsq = np.append(years,years) months = [r'April'] ### Read in data lonvals = [] latvals = [] sitp= [] situ = [] sitc = [] for i in range(years.shape[0]): filename = 'PIOMAS_CS2UC_sit_04_%s.txt' % years[i] data = np.genfromtxt(directorydata + filename,unpack=False, usecols=[0,1,2,3,4],skip_header=2) latq = data[:,0] lonq = data[:,1] sitpq = data[:,2] situq = data[:,4] sitcq = data[:,5] lonvals.append(lonq) latvals.append(latq) sitp.append(sitpq) situ.append(situq) sitc.append(sitcq) print('Completed: Read in %s data!' % years[i]) ### Appends lat/lon lonvalsn = np.append(lonvals,lonvals) latvalsn = np.append(latvals,latvals) ### Conduct a weighted average def calc_weightedAve(var,lats): """ Area weights sit array 5d [ens,year,month,lat,lon] into [ens,year,month] Parameters ---------- var : 5d,4d,3d,1d array of a gridded variable lats : 2d array of latitudes Returns ------- meanvar : weighted average for 3d,2d,1d array Usage ----- meanvar = calc_weightedAve(var,lats) """ print('\n>>> Using calc_weightedAve function!') ### Import modules import numpy as np ### Calculate weighted average for various dimensional arrays if var.ndim == 5: meanvar = np.empty((var.shape[0],var.shape[1],var.shape[2])) for ens in range(var.shape[0]): for i in range(var.shape[1]): for j in range(var.shape[2]): varq = var[ens,i,j,:,:] mask = np.isfinite(varq) & np.isfinite(lats) varmask = varq[mask] areamask = np.cos(np.deg2rad(lats[mask])) meanvar[ens,i,j] = np.nansum(varmask*areamask) \ /np.sum(areamask) elif var.ndim == 4: meanvar = np.empty((var.shape[0],var.shape[1])) for i in range(var.shape[0]): for j in range(var.shape[1]): varq = var[i,j,:,:] mask = np.isfinite(varq) & np.isfinite(lats) varmask = varq[mask] areamask = np.cos(np.deg2rad(lats[mask])) meanvar[i,j] =
np.nansum(varmask*areamask)
numpy.nansum
from numpy.testing import (assert_allclose, assert_almost_equal, assert_array_equal, assert_array_almost_equal_nulp) import numpy as np import pytest import matplotlib.mlab as mlab from matplotlib.cbook.deprecation import MatplotlibDeprecationWarning def _stride_repeat(*args, **kwargs): with pytest.warns(MatplotlibDeprecationWarning): return mlab.stride_repeat(*args, **kwargs) class TestStride: def get_base(self, x): y = x while y.base is not None: y = y.base return y def calc_window_target(self, x, NFFT, noverlap=0, axis=0): """ This is an adaptation of the original window extraction algorithm. This is here to test to make sure the new implementation has the same result. """ step = NFFT - noverlap ind = np.arange(0, len(x) - NFFT + 1, step) n = len(ind) result = np.zeros((NFFT, n)) # do the ffts of the slices for i in range(n): result[:, i] = x[ind[i]:ind[i]+NFFT] if axis == 1: result = result.T return result @pytest.mark.parametrize('shape', [(), (10, 1)], ids=['0D', '2D']) def test_stride_windows_invalid_input_shape(self, shape): x = np.arange(np.prod(shape)).reshape(shape) with pytest.raises(ValueError): mlab.stride_windows(x, 5) @pytest.mark.parametrize('n, noverlap', [(0, None), (11, None), (2, 2), (2, 3)], ids=['n less than 1', 'n greater than input', 'noverlap greater than n', 'noverlap equal to n']) def test_stride_windows_invalid_params(self, n, noverlap): x = np.arange(10) with pytest.raises(ValueError): mlab.stride_windows(x, n, noverlap) @pytest.mark.parametrize('shape', [(), (10, 1)], ids=['0D', '2D']) def test_stride_repeat_invalid_input_shape(self, shape): x = np.arange(np.prod(shape)).reshape(shape) with pytest.raises(ValueError): _stride_repeat(x, 5) @pytest.mark.parametrize('axis', [-1, 2], ids=['axis less than 0', 'axis greater than input shape']) def test_stride_repeat_invalid_axis(self, axis): x = np.array(0) with pytest.raises(ValueError): _stride_repeat(x, 5, axis=axis) def test_stride_repeat_n_lt_1_ValueError(self): x = np.arange(10) with pytest.raises(ValueError): _stride_repeat(x, 0) @pytest.mark.parametrize('axis', [0, 1], ids=['axis0', 'axis1']) @pytest.mark.parametrize('n', [1, 5], ids=['n1', 'n5']) def test_stride_repeat(self, n, axis): x = np.arange(10) y = _stride_repeat(x, n, axis=axis) expected_shape = [10, 10] expected_shape[axis] = n yr = np.repeat(np.expand_dims(x, axis), n, axis=axis) assert yr.shape == y.shape assert_array_equal(yr, y) assert tuple(expected_shape) == y.shape assert self.get_base(y) is x @pytest.mark.parametrize('axis', [0, 1], ids=['axis0', 'axis1']) @pytest.mark.parametrize('n, noverlap', [(1, 0), (5, 0), (15, 2), (13, -3)], ids=['n1-noverlap0', 'n5-noverlap0', 'n15-noverlap2', 'n13-noverlapn3']) def test_stride_windows(self, n, noverlap, axis): x = np.arange(100) y = mlab.stride_windows(x, n, noverlap=noverlap, axis=axis) expected_shape = [0, 0] expected_shape[axis] = n expected_shape[1 - axis] = 100 // (n - noverlap) yt = self.calc_window_target(x, n, noverlap=noverlap, axis=axis) assert yt.shape == y.shape assert_array_equal(yt, y) assert tuple(expected_shape) == y.shape assert self.get_base(y) is x @pytest.mark.parametrize('axis', [0, 1], ids=['axis0', 'axis1']) def test_stride_windows_n32_noverlap0_unflatten(self, axis): n = 32 x = np.arange(n)[np.newaxis] x1 = np.tile(x, (21, 1)) x2 = x1.flatten() y = mlab.stride_windows(x2, n, axis=axis) if axis == 0: x1 = x1.T assert y.shape == x1.shape assert_array_equal(y, x1) def test_stride_ensure_integer_type(self): N = 100 x = np.full(N + 20, np.nan) y = x[10:-10] y[:] = 0.3 # previous to #3845 lead to corrupt access y_strided = mlab.stride_windows(y, n=33, noverlap=0.6) assert_array_equal(y_strided, 0.3) # previous to #3845 lead to corrupt access y_strided = mlab.stride_windows(y, n=33.3, noverlap=0) assert_array_equal(y_strided, 0.3) # even previous to #3845 could not find any problematic # configuration however, let's be sure it's not accidentally # introduced y_strided = _stride_repeat(y, n=33.815) assert_array_equal(y_strided, 0.3) def _apply_window(*args, **kwargs): with pytest.warns(MatplotlibDeprecationWarning): return mlab.apply_window(*args, **kwargs) class TestWindow: def setup(self): np.random.seed(0) n = 1000 self.sig_rand = np.random.standard_normal(n) + 100. self.sig_ones = np.ones(n) def check_window_apply_repeat(self, x, window, NFFT, noverlap): """ This is an adaptation of the original window application algorithm. This is here to test to make sure the new implementation has the same result. """ step = NFFT - noverlap ind = np.arange(0, len(x) - NFFT + 1, step) n = len(ind) result = np.zeros((NFFT, n)) if np.iterable(window): windowVals = window else: windowVals = window(np.ones(NFFT, x.dtype)) # do the ffts of the slices for i in range(n): result[:, i] = windowVals * x[ind[i]:ind[i]+NFFT] return result def test_window_none_rand(self): res = mlab.window_none(self.sig_ones) assert_array_equal(res, self.sig_ones) def test_window_none_ones(self): res = mlab.window_none(self.sig_rand) assert_array_equal(res, self.sig_rand) def test_window_hanning_rand(self): targ = np.hanning(len(self.sig_rand)) * self.sig_rand res = mlab.window_hanning(self.sig_rand) assert_allclose(targ, res, atol=1e-06) def test_window_hanning_ones(self): targ = np.hanning(len(self.sig_ones)) res = mlab.window_hanning(self.sig_ones) assert_allclose(targ, res, atol=1e-06) def test_apply_window_1D_axis1_ValueError(self): x = self.sig_rand window = mlab.window_hanning with pytest.raises(ValueError): _apply_window(x, window, axis=1, return_window=False) def test_apply_window_1D_els_wrongsize_ValueError(self): x = self.sig_rand window = mlab.window_hanning(np.ones(x.shape[0]-1)) with pytest.raises(ValueError): _apply_window(x, window) def test_apply_window_0D_ValueError(self): x = np.array(0) window = mlab.window_hanning with pytest.raises(ValueError): _apply_window(x, window, axis=1, return_window=False) def test_apply_window_3D_ValueError(self): x = self.sig_rand[np.newaxis][np.newaxis] window = mlab.window_hanning with pytest.raises(ValueError): _apply_window(x, window, axis=1, return_window=False) def test_apply_window_hanning_1D(self): x = self.sig_rand window = mlab.window_hanning window1 = mlab.window_hanning(np.ones(x.shape[0])) y, window2 = _apply_window(x, window, return_window=True) yt = window(x) assert yt.shape == y.shape assert x.shape == y.shape assert_allclose(yt, y, atol=1e-06) assert_array_equal(window1, window2) def test_apply_window_hanning_1D_axis0(self): x = self.sig_rand window = mlab.window_hanning y = _apply_window(x, window, axis=0, return_window=False) yt = window(x) assert yt.shape == y.shape assert x.shape == y.shape assert_allclose(yt, y, atol=1e-06) def test_apply_window_hanning_els_1D_axis0(self): x = self.sig_rand window = mlab.window_hanning(np.ones(x.shape[0])) window1 = mlab.window_hanning y = _apply_window(x, window, axis=0, return_window=False) yt = window1(x) assert yt.shape == y.shape assert x.shape == y.shape assert_allclose(yt, y, atol=1e-06) def test_apply_window_hanning_2D_axis0(self): x = np.random.standard_normal([1000, 10]) + 100. window = mlab.window_hanning y = _apply_window(x, window, axis=0, return_window=False) yt = np.zeros_like(x) for i in range(x.shape[1]): yt[:, i] = window(x[:, i]) assert yt.shape == y.shape assert x.shape == y.shape assert_allclose(yt, y, atol=1e-06) def test_apply_window_hanning_els1_2D_axis0(self): x = np.random.standard_normal([1000, 10]) + 100. window = mlab.window_hanning(np.ones(x.shape[0])) window1 = mlab.window_hanning y = _apply_window(x, window, axis=0, return_window=False) yt = np.zeros_like(x) for i in range(x.shape[1]): yt[:, i] = window1(x[:, i]) assert yt.shape == y.shape assert x.shape == y.shape assert_allclose(yt, y, atol=1e-06) def test_apply_window_hanning_els2_2D_axis0(self): x = np.random.standard_normal([1000, 10]) + 100. window = mlab.window_hanning window1 = mlab.window_hanning(np.ones(x.shape[0])) y, window2 = _apply_window(x, window, axis=0, return_window=True) yt = np.zeros_like(x) for i in range(x.shape[1]): yt[:, i] = window1*x[:, i] assert yt.shape == y.shape assert x.shape == y.shape assert_allclose(yt, y, atol=1e-06) assert_array_equal(window1, window2) def test_apply_window_hanning_els3_2D_axis0(self): x = np.random.standard_normal([1000, 10]) + 100. window = mlab.window_hanning window1 = mlab.window_hanning(np.ones(x.shape[0])) y, window2 = _apply_window(x, window, axis=0, return_window=True) yt = _apply_window(x, window1, axis=0, return_window=False) assert yt.shape == y.shape assert x.shape == y.shape assert_allclose(yt, y, atol=1e-06) assert_array_equal(window1, window2) def test_apply_window_hanning_2D_axis1(self): x = np.random.standard_normal([10, 1000]) + 100. window = mlab.window_hanning y = _apply_window(x, window, axis=1, return_window=False) yt = np.zeros_like(x) for i in range(x.shape[0]): yt[i, :] = window(x[i, :]) assert yt.shape == y.shape assert x.shape == y.shape assert_allclose(yt, y, atol=1e-06) def test_apply_window_hanning_2D_els1_axis1(self): x = np.random.standard_normal([10, 1000]) + 100. window = mlab.window_hanning(np.ones(x.shape[1])) window1 = mlab.window_hanning y = _apply_window(x, window, axis=1, return_window=False) yt = np.zeros_like(x) for i in range(x.shape[0]): yt[i, :] = window1(x[i, :]) assert yt.shape == y.shape assert x.shape == y.shape assert_allclose(yt, y, atol=1e-06) def test_apply_window_hanning_2D_els2_axis1(self): x = np.random.standard_normal([10, 1000]) + 100. window = mlab.window_hanning window1 = mlab.window_hanning(np.ones(x.shape[1])) y, window2 = _apply_window(x, window, axis=1, return_window=True) yt = np.zeros_like(x) for i in range(x.shape[0]): yt[i, :] = window1 * x[i, :] assert yt.shape == y.shape assert x.shape == y.shape assert_allclose(yt, y, atol=1e-06) assert_array_equal(window1, window2) def test_apply_window_hanning_2D_els3_axis1(self): x = np.random.standard_normal([10, 1000]) + 100. window = mlab.window_hanning window1 = mlab.window_hanning(np.ones(x.shape[1])) y = _apply_window(x, window, axis=1, return_window=False) yt = _apply_window(x, window1, axis=1, return_window=False) assert yt.shape == y.shape assert x.shape == y.shape assert_allclose(yt, y, atol=1e-06) def test_apply_window_stride_windows_hanning_2D_n13_noverlapn3_axis0(self): x = self.sig_rand window = mlab.window_hanning yi = mlab.stride_windows(x, n=13, noverlap=2, axis=0) y = _apply_window(yi, window, axis=0, return_window=False) yt = self.check_window_apply_repeat(x, window, 13, 2) assert yt.shape == y.shape assert x.shape != y.shape assert_allclose(yt, y, atol=1e-06) def test_apply_window_hanning_2D_stack_axis1(self): ydata = np.arange(32) ydata1 = ydata+5 ydata2 = ydata+3.3 ycontrol1 = _apply_window(ydata1, mlab.window_hanning) ycontrol2 = mlab.window_hanning(ydata2) ydata = np.vstack([ydata1, ydata2]) ycontrol = np.vstack([ycontrol1, ycontrol2]) ydata = np.tile(ydata, (20, 1)) ycontrol = np.tile(ycontrol, (20, 1)) result = _apply_window(ydata, mlab.window_hanning, axis=1, return_window=False) assert_allclose(ycontrol, result, atol=1e-08) def test_apply_window_hanning_2D_stack_windows_axis1(self): ydata = np.arange(32) ydata1 = ydata+5 ydata2 = ydata+3.3 ycontrol1 = _apply_window(ydata1, mlab.window_hanning) ycontrol2 = mlab.window_hanning(ydata2) ydata = np.vstack([ydata1, ydata2]) ycontrol = np.vstack([ycontrol1, ycontrol2]) ydata = np.tile(ydata, (20, 1)) ycontrol = np.tile(ycontrol, (20, 1)) result = _apply_window(ydata, mlab.window_hanning, axis=1, return_window=False) assert_allclose(ycontrol, result, atol=1e-08) def test_apply_window_hanning_2D_stack_windows_axis1_unflatten(self): n = 32 ydata = np.arange(n) ydata1 = ydata+5 ydata2 = ydata+3.3 ycontrol1 = _apply_window(ydata1, mlab.window_hanning) ycontrol2 = mlab.window_hanning(ydata2) ydata = np.vstack([ydata1, ydata2]) ycontrol = np.vstack([ycontrol1, ycontrol2]) ydata = np.tile(ydata, (20, 1)) ycontrol = np.tile(ycontrol, (20, 1)) ydata = ydata.flatten() ydata1 = mlab.stride_windows(ydata, 32, noverlap=0, axis=0) result = _apply_window(ydata1, mlab.window_hanning, axis=0, return_window=False) assert_allclose(ycontrol.T, result, atol=1e-08) class TestDetrend: def setup(self): np.random.seed(0) n = 1000 x = np.linspace(0., 100, n) self.sig_zeros = np.zeros(n) self.sig_off = self.sig_zeros + 100. self.sig_slope = np.linspace(-10., 90., n) self.sig_slope_mean = x - x.mean() sig_rand = np.random.standard_normal(n) sig_sin = np.sin(x*2*np.pi/(n/100)) sig_rand -= sig_rand.mean() sig_sin -= sig_sin.mean() self.sig_base = sig_rand + sig_sin self.atol = 1e-08 def test_detrend_none_0D_zeros(self): input = 0. targ = input mlab.detrend_none(input) assert input == targ def test_detrend_none_0D_zeros_axis1(self): input = 0. targ = input mlab.detrend_none(input, axis=1) assert input == targ def test_detrend_str_none_0D_zeros(self): input = 0. targ = input mlab.detrend(input, key='none') assert input == targ def test_detrend_detrend_none_0D_zeros(self): input = 0. targ = input mlab.detrend(input, key=mlab.detrend_none) assert input == targ def test_detrend_none_0D_off(self): input = 5.5 targ = input mlab.detrend_none(input) assert input == targ def test_detrend_none_1D_off(self): input = self.sig_off targ = input res = mlab.detrend_none(input) assert_array_equal(res, targ) def test_detrend_none_1D_slope(self): input = self.sig_slope targ = input res = mlab.detrend_none(input) assert_array_equal(res, targ) def test_detrend_none_1D_base(self): input = self.sig_base targ = input res = mlab.detrend_none(input) assert_array_equal(res, targ) def test_detrend_none_1D_base_slope_off_list(self): input = self.sig_base + self.sig_slope + self.sig_off targ = input.tolist() res = mlab.detrend_none(input.tolist()) assert res == targ def test_detrend_none_2D(self): arri = [self.sig_base, self.sig_base + self.sig_off, self.sig_base + self.sig_slope, self.sig_base + self.sig_off + self.sig_slope] input = np.vstack(arri) targ = input res = mlab.detrend_none(input) assert_array_equal(res, targ) def test_detrend_none_2D_T(self): arri = [self.sig_base, self.sig_base + self.sig_off, self.sig_base + self.sig_slope, self.sig_base + self.sig_off + self.sig_slope] input = np.vstack(arri) targ = input res = mlab.detrend_none(input.T) assert_array_equal(res.T, targ) def test_detrend_mean_0D_zeros(self): input = 0. targ = 0. res = mlab.detrend_mean(input) assert_almost_equal(res, targ) def test_detrend_str_mean_0D_zeros(self): input = 0. targ = 0. res = mlab.detrend(input, key='mean') assert_almost_equal(res, targ) def test_detrend_detrend_mean_0D_zeros(self): input = 0. targ = 0. res = mlab.detrend(input, key=mlab.detrend_mean) assert_almost_equal(res, targ) def test_detrend_mean_0D_off(self): input = 5.5 targ = 0. res = mlab.detrend_mean(input) assert_almost_equal(res, targ) def test_detrend_str_mean_0D_off(self): input = 5.5 targ = 0. res = mlab.detrend(input, key='mean') assert_almost_equal(res, targ) def test_detrend_detrend_mean_0D_off(self): input = 5.5 targ = 0. res = mlab.detrend(input, key=mlab.detrend_mean) assert_almost_equal(res, targ) def test_detrend_mean_1D_zeros(self): input = self.sig_zeros targ = self.sig_zeros res = mlab.detrend_mean(input)
assert_allclose(res, targ, atol=self.atol)
numpy.testing.assert_allclose
""" File: encoders.py Author: Team ohia.ai Description: Generalized encoder classes with a consistent Sklearn-like API """ import time import numpy as np import pandas as pd from statsmodels.distributions.empirical_distribution import ECDF from sklearn.linear_model import Ridge from scipy.stats import rankdata def run_length_encoding(im): pixels = im.flatten(order = 'F') pixels = np.concatenate([[0], pixels, [0]]) runs = np.where(pixels[1:] != pixels[:-1])[0] + 1 runs[1::2] -= runs[::2] return ' '.join(str(x) for x in runs) class RunLengthEncoder(object): """Run length encoding of a binary array.""" def __init__(self, order='C', one_indexing=False): """ order: {'K', 'A', 'C', 'F'}, optional Passed to the numpy.flatten function. one_indexing: bool, optional If True then start indexing at 1 (rather than 0). The default is False. """ self._one_indexing = one_indexing self._order = order def encode(self, x: np.ndarray) -> str: """Run length encoding of a binary array. Args: x: numpy.array Binary input array. Returns: rle_str: Run length encoded values. Indexs and lengths are space delimited. """ pixels = x.flatten(order = self._order) pixels = np.concatenate([[0], pixels, [0]]) runs = np.where(pixels[1:] != pixels[:-1])[0] + self._one_indexing runs[1::2] -= runs[::2] return ' '.join(str(x) for x in runs) def decode(self, rle_str: str, shape: tuple) -> np.ndarray: """Decoding of a run length encoded array. Args: rle_str: str run-length string (space delimited) shape: tuple size (height,width) of array to return Returns: x: binary array of size `shape` """ s = rle_str.split() starts, lengths = [np.asarray(x, dtype=int) for x in (s[0:][::2], s[1:][::2])] starts -= self._one_indexing ends = starts + lengths img = np.zeros(shape[0]*shape[1], dtype=np.uint8) for lo, hi in zip(starts, ends): img[lo:hi] = 1 return img.reshape(shape, order=self._order) class FastLabelEncoder(): """Map categorical variable into {0, 1, ..., n_categories}. Note: https://stackoverflow.com/questions/45321999/how-can-i-optimize-label-encoding-for-large-data-sets-sci-kit-learn?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa """ def __init__(self): self.lookup = None def fit(self, x): labels = np.unique(x, return_inverse=True)[1] self.lookup = dict(zip(x, labels)) def transform(self, x): return np.vectorize(self.lookup.get)(x) def fit_transform(self, x): self.fit(x) return self.transform(x) class MeanImputer(): """Single column mean imputation """ def __inti__(self): self.replace_value = None def fit(self, x): self.replace_value = np.mean(x[np.isfinite(x)]) def transform(self, x): y = x.copy() y[~np.isfinite(x)] = self.replace_value return y def fit_transform(self, x): self.fit(x) return self.transform(x) class BinEncoder(): """Bin a numeric variable into {0, 1, ...n_bins-1}. """ def __init__(self, n_bins=100): self.n_bins = n_bins self.ecdf = None def fit(self, x): """Calculate empirical CDF Args: x (array): input array """ self.ecdf = ECDF(x) def transform(self, x): """Transform using empirical CDF Args: x (array): array to transform """ return np.ceil(self.n_bins*self.ecdf(x)).astype(np.int) def fit_transform(self, x): """Calculate and Transform using empirical CDF Args: x (array): array to transform """ self.fit(x) return self.transform(x) class RankEncoder(): """Map an ordinal variable into {0, 1, ...n_unique} The order of the variable is preserved. """ def __init__(self): self.lookup = None def fit(self, x): x = np.unique(np.array(x)) r = rankdata(x).astype(np.int) self.lookup = dict(zip(x, r)) def transform(self, x): x = np.array(x) return
np.vectorize(self.lookup.get)
numpy.vectorize
"""Model Objects and ML algorithm serialisation.""" import os import pickle import warnings import logging from itertools import chain from functools import partial from os.path import join, isdir, abspath import numpy as np from revrand import StandardLinearModel, GeneralisedLinearModel from revrand.basis_functions import LinearBasis, RandomRBF, \ RandomLaplace, RandomCauchy, RandomMatern32, RandomMatern52 from revrand.btypes import Parameter, Positive from revrand.likelihoods import Gaussian from revrand.optimize import Adam from revrand.utils import atleast_list from scipy.integrate import fixed_quad from scipy.stats import norm from sklearn.base import BaseEstimator, RegressorMixin from sklearn.svm import SVR, SVC from sklearn.ensemble import (RandomForestRegressor as RFR, RandomForestClassifier as RFC, GradientBoostingClassifier) from sklearn.linear_model import ARDRegression, LogisticRegression from sklearn.tree import DecisionTreeRegressor, ExtraTreeRegressor from sklearn.neighbors import KNeighborsRegressor from sklearn.preprocessing import LabelEncoder from sklearn.kernel_approximation import RBFSampler from xgboost import XGBRegressor from uncoverml import mpiops from uncoverml.interpolate import SKLearnNearestNDInterpolator, \ SKLearnLinearNDInterpolator, SKLearnRbf, SKLearnCT from uncoverml.cubist import Cubist from uncoverml.cubist import MultiCubist from uncoverml.transforms import target as transforms warnings.filterwarnings("ignore", category=DeprecationWarning) # # Module constants # log = logging.getLogger(__name__) QUADORDER = 5 # Order of quadrature used for transforming probabilistic vals # # Mixin classes for providing pipeline compatibility to revrand # class BasisMakerMixin(): """ Mixin class for easily creating approximate kernel functions for revrand. This is primarily used for the approximate Gaussian process algorithms. """ def fit(self, X, y, *args, **kwargs): self._make_basis(X) return super().fit(X, y, *args, **kwargs) # args for GLMs def _store_params(self, kernel, regulariser, nbases, lenscale, ard): self.kernel = kernel self.nbases = nbases self.ard = ard self.lenscale = lenscale if np.isscalar(lenscale) \ else np.asarray(lenscale) self.regulariser = Parameter(regulariser, Positive()) def _make_basis(self, X): D = X.shape[1] lenscale = self.lenscale if self.ard and D > 1: lenscale = np.ones(D) * lenscale lenscale_init = Parameter(lenscale, Positive()) gpbasis = basismap[self.kernel](Xdim=X.shape[1], nbases=self.nbases, lenscale=lenscale_init, regularizer=self.regulariser) self.basis = gpbasis + LinearBasis() class PredictDistMixin(): """ Mixin class for providing a ``predict_dist`` method to the StandardLinearModel class in revrand. """ def predict_dist(self, X, interval=0.95, *args, **kwargs): """ Predictive mean and variance for a probabilistic regressor. Parameters ---------- X: ndarray (Ns, d) array query dataset (Ns samples, d dimensions). interval: float, optional The percentile confidence interval (e.g. 95%) to return. fields: dict, optional dictionary of fields parsed from the shape file. ``indicator_field`` should be a key in this dictionary. If this is not present, then a Gaussian likelihood will be used for all predictions. The only time this may be input if for cross validation. Returns ------- Ey: ndarray The expected value of ys for the query inputs, X of shape (Ns,). Vy: ndarray The expected variance of ys (excluding likelihood noise terms) for the query inputs, X of shape (Ns,). ql: ndarray The lower end point of the interval with shape (Ns,) qu: ndarray The upper end point of the interval with shape (Ns,) """ Ey, Vy = self.predict_moments(X, *args, **kwargs) ql, qu = norm.interval(interval, loc=Ey, scale=np.sqrt(Vy)) return Ey, Vy, ql, qu class GLMPredictDistMixin(): """ Mixin class for providing a ``predict_dist`` method to the GeneralisedLinearModel class in revrand. This is especially for use with Gaussian likelihood models. """ def predict_dist(self, X, interval=0.95, *args, **kwargs): """ Predictive mean and variance for a probabilistic regressor. Parameters ---------- X: ndarray (Ns, d) array query dataset (Ns samples, d dimensions). interval: float, optional The percentile confidence interval (e.g. 95%) to return. fields: dict, optional dictionary of fields parsed from the shape file. ``indicator_field`` should be a key in this dictionary. If this is not present, then a Gaussian likelihood will be used for all predictions. The only time this may be input if for cross validation. Returns ------- Ey: ndarray The expected value of ys for the query inputs, X of shape (Ns,). Vy: ndarray The expected variance of ys (excluding likelihood noise terms) for the query inputs, X of shape (Ns,). ql: ndarray The lower end point of the interval with shape (Ns,) qu: ndarray The upper end point of the interval with shape (Ns,) """ Ey, Vy = self.predict_moments(X, *args, **kwargs) Vy += self.like_hypers_ ql, qu = norm.interval(interval, loc=Ey, scale=np.sqrt(Vy)) return Ey, Vy, ql, qu class MutualInfoMixin(): """ Mixin class for providing predictive entropy reduction functionality to the StandardLinearModel class (only). """ def entropy_reduction(self, X): """ Predictice entropy reduction (a.k.a mutual information). Estimate the reduction in the posterior distribution's entropy (i.e. model uncertainty reduction) as a result of including a particular observation. Parameters ---------- X: ndarray (Ns, d) array query dataset (Ns samples, d dimensions). Returns ------- MI: ndarray Prediction of mutual information (expected reduiction in posterior entrpy) assocated with each query input. The units are 'nats', and the shape of the returned array is (Ns,). """ Phi = self.basis.transform(X, *atleast_list(self.hypers_)) pCp = [p.dot(self.covariance_).dot(p.T) for p in Phi] MI = 0.5 * (np.log(self.var_ +
np.array(pCp)
numpy.array
from sysu_dataset import SYSU import numpy as np import scipy import itertools import cv2 import torch from torch.utils.data import Dataset import torchvision.transforms as transforms from config import * vox_size=54 all_tups = np.array(list(itertools.product(range(vox_size), repeat=2))) rot_array =
np.arange(vox_size*vox_size)
numpy.arange
#!/usr/bin/env python # stdlib imports import os.path import sys # third party imports from openquake.hazardlib.geo.utils import OrthographicProjection from openquake.hazardlib.gsim.abrahamson_2014 import AbrahamsonEtAl2014 from openquake.hazardlib.gsim.berge_thierry_2003 \ import BergeThierryEtAl2003SIGMA import numpy as np import pandas as pd import pytest import time # local imports from shakelib.distance import Distance from shakelib.distance import get_distance from shakelib.rupture.gc2 import _computeGC2 from shakelib.rupture.origin import Origin from shakelib.rupture.point_rupture import PointRupture from shakelib.rupture.quad_rupture import QuadRupture from shakelib.sites import Sites from impactutils.time.ancient_time import HistoricTime do_tests = True homedir = os.path.dirname(os.path.abspath(__file__)) # where is this script? shakedir = os.path.abspath(os.path.join(homedir, '..', '..')) sys.path.insert(0, shakedir) def test_san_fernando(): # This is a challenging rupture due to overlapping and discordant # segments, as brought up by <NAME>. Our initial # implementation put the origin on the wrong side of the rupture. x0 = np.array([7.1845, 7.8693]) y0 = np.array([-10.3793, -16.2096]) z0 = np.array([3.0000, 0.0000]) x1 =
np.array([-7.8506, -7.5856])
numpy.array
import itertools import os, random import statistics import matplotlib import matplotlib.pyplot as plt from analyze_entropy import comp_entropy from analyze_prob_attn import compute_idf, get_ban_positions # from data_collection import CUR_DIR, PROB_META_DIR, spec_name, MODEL_NAME, DATA_NAME from util import convert_enc_attn, parse_arg from matplotlib.ticker import (MultipleLocator, FormatStrFormatter, AutoMinorLocator) font_size = 14 matplotlib.font_manager._rebuild() GLOBAL_FIGURE_WIDTH = 8 dpi = 800 # plt.rcParams["font.weight"] = "light" plt.rcParams.update({'font.size': 14}) plt.rcParams['font.family'] = 'DejaVu Sans' dir_datadrive = '/mnt/data0/jcxu/data/prob_gpt' # Density: x: entropy, two plots: is bigram or not FIG_SIZE_x = GLOBAL_FIGURE_WIDTH def get_ys(t, logits, BOS_token=0): # for one time step, get the tokens last_inp, cur_inp, cur_pred, and next_pred cur_pred = logits[t] try: next_pred = logits[t + 1] except IndexError: next_pred = None if t - 2 >= 0: last_inp = logits[t - 2] elif t - 2 == -1: last_inp = BOS_token else: last_inp = None if t - 1 >= 0: cur_inp = logits[t - 1] elif t - 1 == -1: cur_inp = BOS_token else: cur_inp = None return last_inp, cur_inp, cur_pred, next_pred from collections import Counter def truncate_attention_cell(attn_distb, input_doc, idf_ban_pos, tgt_prob_mass=0.9) -> Counter: # for each attention distribution, remove the idf ban tokens (positions), get the accumulated prob up to prob_mass. # return sorts = np.argsort(attn_distb, axis=-1, kind=None, order=None)[::-1] cum_prob_mass = 0 cnt = Counter() for topk in sorts: prob_mass = attn_distb[topk] cum_prob_mass += prob_mass if topk not in idf_ban_pos: cnt[input_doc[topk]] = prob_mass if cum_prob_mass > tgt_prob_mass or prob_mass < 0.01: break return cnt def _y_entropy_step(attn_lle, input_doc, idf_ban_pos): num_layer, num_head, src_len = attn_lle.shape all_attns = Counter() for l in range(num_layer): for h in range(num_head): cell_attn = truncate_attention_cell(attn_lle[l][h], input_doc, idf_ban_pos=idf_ban_pos) all_attns = all_attns + cell_attn return all_attns def retrieve_tok_val(cnter, token): try: v = cnter[token] except: v = 0 return v import matplotlib import matplotlib.pyplot as plt def plot_hist(val_ent_pairs, title): weights = [p[0] for p in val_ent_pairs] xs = [p[1] for p in val_ent_pairs] plt.hist(xs, bins=20, weights=weights, density=True) plt.xlabel('Pred Ent') plt.ylabel('Cum Attn') plt.title(title) plt.grid(True) plt.show() import seaborn as sns def get_statistics(matrix): result = [0 for _ in range(len(matrix))] for idx, row in enumerate(matrix): try: m = statistics.mean(row) except: m = 0 print("NO DATA!") result[idx] = m return result def proceed_data(segs, val_ent_pairs, step_size=0.5): cat_bins = [[[] for _ in range(segs)] for _ in range(5)] for p in val_ent_pairs: last_inp, cur_inp, cur_pred, next_pred, pred_ent, atte_ent = p # attn_val, ent, attn_e = p[0], p[1], p[2] cat = int(pred_ent // step_size) try: cat_bins[0][cat].append(last_inp) cat_bins[1][cat].append(cur_inp) cat_bins[2][cat].append(cur_pred) cat_bins[3][cat].append(next_pred) cat_bins[4][cat].append(atte_ent) except: pass last_inp_mean = get_statistics(cat_bins[0]) cur_inp_mean = get_statistics(cat_bins[1]) cur_pred_mean = get_statistics(cat_bins[2]) next_pred_mean = get_statistics(cat_bins[3]) atte_ent_mean = get_statistics(cat_bins[4]) return last_inp_mean, cur_inp_mean, cur_pred_mean, next_pred_mean, atte_ent_mean def read_stack_data(last_inp_mean, cur_inp_mean, cur_pred_mean, next_pred_mean, seps=10): bar0 = last_inp_mean bar1 = cur_inp_mean bar2 = cur_pred_mean bar3 = next_pred_mean from operator import add bar01 = np.add(bar0, bar1).tolist() bar012 = np.add(bar01, bar2).tolist() # x = list(range(10)) return bar0, bar1, bar2, bar3, bar01, bar012 def plot_single_line(this_fig, spec_config, input_data, step_size=0.5, ent_max=5, show_x_ticks=False, show_y_ticks=True, data_name="", model_name="", ymin=2, ymax=5): segs = np.arange(0, ent_max, step_size).tolist() # colorblind = sns.color_palette("coolwarm", 10)[::-1] last_inp_mean, cur_inp_mean, cur_pred_mean, next_pred_mean, atte_ent_mean = input_data axes = this_fig.add_subplot(spec_config) sns.lineplot(x=list(np.arange(0, 5, step_size)), y=atte_ent_mean, markers=True, dashes=False) # axes = sns.boxplot(x=x, y=y, palette=colorblind, showfliers=False) axes.xaxis.set_major_locator(MultipleLocator(1)) axes.xaxis.set_major_formatter(FormatStrFormatter('%d')) # For the minor ticks, use no labels; default NullFormatter. axes.xaxis.set_minor_locator(MultipleLocator(0.5)) # axes.get_ylim() # axes.set_ylim(ymin, ymax) if show_x_ticks: # x_vals = [m * step_size for m in xticks] # axes.set_xticklabels(x_vals, rotation='vertical')center pass else: plt.setp(axes.get_xticklabels(), visible=False) # if not show_y_ticks: # plt.setp(axes.get_yticklabels(), visible=False) if data_name != "": axes.set_ylabel(data_name) else: axes.set_ylabel("") if model_name != "": axes.set_title(model_name) return axes def plot_single_box(this_fig, spec_config, input_data, step_size=0.5, ent_max=5, show_x_ticks=False, show_y_ticks=True, ylim=0.8, data_name="", model_name="", show_legend=False): segs = np.arange(0, ent_max, step_size).tolist() # colorblind = sns.color_palette("coolwarm", 10)[::-1] last_inp_mean, cur_inp_mean, cur_pred_mean, next_pred_mean, atte_ent_mean = input_data bar0, bar1, bar2, bar3, bar01, bar012 = read_stack_data(last_inp_mean, cur_inp_mean, cur_pred_mean, next_pred_mean) colorblind = sns.color_palette("coolwarm", 4) # colorblind = sns.color_palette("Set2") # colorblind = sns.color_palette() catnames = ['$y_{t-2}$', '$y_{t-1}$', '$y_{t}$', '$y_{t+1}$'] linewidth = 1.5 axes = this_fig.add_subplot(spec_config) x = list(np.arange(0, 5, 0.5)) axes.bar(x, bar0, color=colorblind[0], # edgecolor=colorblind[0],linewidth=linewidth, label=catnames[0], width=step_size, # hatch='/' ) axes.bar(x, bar1, bottom=bar0, # edgecolor='white', linewidth=1, label=catnames[1], width=step_size, # hatch='-', facecolor=colorblind[1], # histtype='step', facecolor='g', # alpha=0.75 # ,hatch='-' ) axes.bar(x, bar2, bottom=bar01, # edgecolor=colorblind[3], linewidth=0, label=catnames[2], width=step_size, facecolor=colorblind[3], # histtype='step', # hatch='|' # ,hatch='|' ) axes.bar(x, bar3, bottom=bar012, color=colorblind[2], label=catnames[3], width=step_size, # edgecolor=colorblind[2], linewidth=linewidth, # hatch='\\' ) # axes = sns.boxplot(x=x, y=y, palette=colorblind, showfliers=False) axes.xaxis.set_major_locator(MultipleLocator(1)) axes.xaxis.set_major_formatter(FormatStrFormatter('%d')) if show_legend: axes.legend(ncol=2, frameon=False) # For the minor ticks, use no labels; default NullFormatter. axes.xaxis.set_minor_locator(MultipleLocator(0.5)) axes.set_ylim(0, ylim) if show_x_ticks: # x_vals = [m * step_size for m in xticks] # axes.set_xticklabels(x_vals, rotation='vertical')center pass else: plt.setp(axes.get_xticklabels(), visible=False) if not show_y_ticks: plt.setp(axes.get_yticklabels(), visible=False) if data_name != "": axes.set_ylabel(data_name) else: axes.set_ylabel("") if model_name != "": axes.set_title(model_name) return axes def plot_box(val_ent_pairs, title=None, step_size=.25): # max_pred_ent = max([p[1] for p in val_ent_pairs]) # segs = np.linspace(0, max_pred_ent + 0.1, num=20).tolist() segs = np.arange(0, 8, step_size).tolist() colorblind = sns.color_palette("coolwarm", 10)[::-1] bins = [[] for _ in range(len(segs))] x, y = [], [] for p in val_ent_pairs: v, ent = p[0], p[1] cat = int(ent // step_size) try: bins[cat].append(v) x.append(cat) y.append(v) except: pass fig1, ax1 = plt.subplots() ax1.set_title(title) ax1 = sns.violinplot(x=x, y=y, cut=0, palette=colorblind, inner='quartile') # ax1.set_xticks( np.arange(0, 8, step_size).tolist()) # ax1.set_xticklabels(np.arange(0, 8, step_size).tolist()) return ax1 def plot_single_scatter(val_ent_pairs, title): y_attn_frac = [m[0] for m in val_ent_pairs] x_pred_ent = [m[1] for m in val_ent_pairs] ax = sns.jointplot(x=x_pred_ent, y=y_attn_frac, kind="hex", color="#4CB391") # ax = sns.scatterplot(x=x_pred_ent,y=y_attn_frac) # # sns.histplot(x=x_pred_ent, y=y_attn_frac, bins=50, pthresh=.1, cmap="mako") # sns.kdeplot(x=x_pred_ent, y=y_attn_frac, levels=5,linewidths=1) # ax.set_title(title) plt.show() return ax def analyze_attention_y_entropy(max_time_step, attn_tlle, pred_distribution, input_doc, ban_positions, logits, nuc, top_p): # T = attn_tlle.shape[0] # data_pairs = [[], [], [], []] data = [] for t in range(max_time_step): try: t_pred_ent = comp_entropy(pred_distribution[t], nuc, top_p) last_inp, cur_inp, cur_pred, next_pred = get_ys(t, logits) all_attns_counter = _y_entropy_step(attn_tlle[t], input_doc, ban_positions) total_attn_val = sum(all_attns_counter.values()) all_attention = list(all_attns_counter.values()) np_attn = np.asarray(all_attention) / total_attn_val attn_ent = comp_entropy(np_attn) last_inp_val = retrieve_tok_val(all_attns_counter, last_inp) cur_inp_val = retrieve_tok_val(all_attns_counter, cur_inp) cur_pred_val = retrieve_tok_val(all_attns_counter, cur_pred) next_pred_val = retrieve_tok_val(all_attns_counter, next_pred) # data_pairs[0].append((last_inp_val / total_attn_val, t_pred_ent)) # data_pairs[1].append((cur_inp_val / total_attn_val, t_pred_ent)) # data_pairs[2].append((cur_pred_val / total_attn_val, t_pred_ent)) data.append((last_inp_val / total_attn_val, cur_inp_val / total_attn_val, cur_pred_val / total_attn_val, next_pred_val / total_attn_val, t_pred_ent, attn_ent)) except: pass # data_pairs[3].append((next_pred_val / total_attn_val, t_pred_ent)) return data import pickle import numpy as np from scipy.stats import entropy import matplotlib.gridspec as gridspec import multiprocessing def detect_useless_ids(indices): last = -100 good_indices = [] for x in indices: if x - 5 > last: last = x good_indices.append(x) else: break return good_indices def process_data_single(args, f, eos_token_ids): print("running") BOS_TOKEN = 0 with open(os.path.join(args.cur_dir, f), 'rb') as fd: data = pickle.load(fd) attentions, pred_distb, logits, input_doc = data['attentions'], data['pred_distributions'], data['logits'], \ data['input_doc'] timesteps = len(attentions) attentions_tlle = convert_enc_attn(attentions, merge_layer_head=False) # T,L,L,E attention_tle = convert_enc_attn(attentions, merge_layer_head=True) # T,L,E document_len = input_doc.shape[0] input_doc = input_doc.astype(np.int).tolist() logits = logits.tolist() indices = [i for i, x in enumerate(logits) if x in eos_token_ids] good_indices = detect_useless_ids(indices) if good_indices: max_t = good_indices[-1] else: max_t = attentions_tlle.shape[0] # dec_inp_logits = [BOS_TOKEN] + logits[:-1] pred_distb = np.exp(pred_distb) # time step, vocab size # pred_ent = entropy(pred_distb, axis=-1) idf_flag = compute_idf(attention_tle[:max_t]) # E ban_positions = get_ban_positions(idf_flag) # ban_positions = [] data_pairs = analyze_attention_y_entropy(max_t, attentions_tlle, pred_distb, input_doc, ban_positions, logits, args.nucleus, args.nuc_prob) return data_pairs from itertools import product def plot_stack_vocab(cnndm_peg, xsum_peg, cnndm_bart, xsum_bart): fig = plt.figure(figsize=(FIG_SIZE_x, FIG_SIZE_x - 4)) spec2 = gridspec.GridSpec(ncols=2, nrows=2, figure=fig) plot_single_box(this_fig=fig, spec_config=spec2[0, 0], input_data=cnndm_peg, show_x_ticks=False, show_y_ticks=True, data_name="CNN/DM", model_name="PEGASUS", ylim=0.7) plot_single_box(this_fig=fig, spec_config=spec2[0, 1], input_data=cnndm_bart, show_x_ticks=False, show_y_ticks=False, model_name="BART", ylim=0.7) plot_single_box(this_fig=fig, spec_config=spec2[1, 0], input_data=xsum_peg, show_x_ticks=True, show_y_ticks=True, data_name='XSum', ylim=0.4) plot_single_box(this_fig=fig, spec_config=spec2[1, 1], input_data=xsum_bart, show_x_ticks=True, show_y_ticks=False, ylim=0.4, show_legend=True) fig.text(0.5, 0.01, 'Prediction Entropy', ha='center', fontsize=font_size) fig.text(0.0, 0.5, 'Vocab Projected Attention', va='center', rotation='vertical', fontsize=font_size) fig.tight_layout() plt.savefig(f"x_pred_ent_y_attn_frac.pdf", dpi=dpi, bbox_inches='tight') plt.show() plt.close() def run_one_fig(spec, args, num_samples=300): print(f"--{spec}--") CUR_DIR = os.path.join(args.prob_meta_dir, spec) args.cur_dir = CUR_DIR files = os.listdir(CUR_DIR) random.shuffle(files) files = files[:num_samples] BOS_TOKEN = 0 print(args.spec_name) if 'pegasus' in args.model_name: from transformers import PegasusTokenizer bpe_tokenizer = PegasusTokenizer.from_pretrained(args.model_name) EOS_TOK_IDs = [106, bpe_tokenizer.eos_token_id, 2] # <n> elif 'gpt' in args.model_name: from transformers import GPT2Tokenizer bpe_tokenizer = GPT2Tokenizer.from_pretrained('gpt2') EOS_TOK_IDs = [bpe_tokenizer.eos_token_id] elif 'bart' in args.model_name: from transformers import BartTokenizer bpe_tokenizer = BartTokenizer.from_pretrained(args.model_name) EOS_TOK_IDs = [bpe_tokenizer.eos_token_id] else: raise NotImplementedError # process_data_single(args, files[0], eos_token_ids=EOS_TOK_IDs) len_samples = len(files) cpu_cnt = multiprocessing.cpu_count() with multiprocessing.Pool(processes=cpu_cnt) as pool: results = pool.starmap(process_data_single, zip([args] * len_samples, files, [EOS_TOK_IDs] * len_samples)) output = list(itertools.chain.from_iterable(results)) print(f"Samples: {len(output)}") output = proceed_data(10, output) return output def plot_ant_entropy(cnndm_peg, xsum_peg, cnndm_bart, xsum_bart): fig = plt.figure(figsize=(FIG_SIZE_x, FIG_SIZE_x - 5)) step_size = 0.5 d = {'PEG$_{C}$': cnndm_peg[-1], 'PEG-X': xsum_peg[-1], 'BART-C': cnndm_bart[-1], 'BART-X': xsum_bart[-1], } # df = pd.DataFrame(data=d) ax = fig.add_subplot(1, 1, 1) # line1 = sns.lineplot(x=list(np.arange(0, 5, step_size)), y=cnndm_peg[-1], label='PEG$_{C}$', markers='x') plt.plot(list(np.arange(0, 5, step_size)), cnndm_peg[-1], label='PEG$_{C}$', marker='+', # color='k' ) plt.plot(list(np.arange(0, 5, step_size)), xsum_peg[-1], label='PEG$_{X}$', marker='x', # color='k' ) plt.plot(list(
np.arange(0, 5, step_size)
numpy.arange
import numpy as np from tqdm import tqdm def new_process(raw_data): transform_data = [] for i, data in enumerate(tqdm(raw_data)): # if i < 5494: # continue trans_data = ntu_tranform_skeleton(data['input']) transform_data.append({'label': data['label'], 'input': trans_data}) return transform_data def ntu_tranform_skeleton(test): """ :param test: frames of skeleton within a video sample """ remove_frame = False test = np.asarray(test) transform_test = [] d = test[0, 0:3] v1 = test[0, 1 * 3:1 * 3 + 3] - test[0, 0 * 3:0 * 3 + 3] v1 = v1 / np.linalg.norm(v1) v2_ = test[0, 12 * 3:12 * 3 + 3] - test[0, 16 * 3:16 * 3 + 3] if np.equal(np.sum(v2_), 0): v2_ += 1e-6 proj_v2_v1 = np.dot(v1.T, v2_) * v1 / np.linalg.norm(v1) v2 = v2_ - np.squeeze(proj_v2_v1) v2 = v2 / np.linalg.norm(v2) v3 = np.cross(v2, v1) / np.linalg.norm(np.cross(v2, v1)) v1 = np.reshape(v1, (3, 1)) v2 = np.reshape(v2, (3, 1)) v3 =
np.reshape(v3, (3, 1))
numpy.reshape
import time from absl import app, flags, logging from absl.flags import FLAGS import cv2 import tensorflow as tf from models import ( YoloV3, YoloV3Tiny ) from dataset import transform_images from utils import draw_outputs from iou_tracker import track_iou import numpy as np flags.DEFINE_string('classes', './coco.names', 'path to classes file') flags.DEFINE_string('weights', './yolov3.tf', 'path to weights file') flags.DEFINE_boolean('tiny', False, 'yolov3 or yolov3-tiny') flags.DEFINE_integer('size', 416, 'resize images to') flags.DEFINE_string('video', './video.mp4', 'path to video file or number for webcam)') flags.DEFINE_string('output', 'output.mp4', 'path to output video') flags.DEFINE_string('output_format', 'MP4V', 'codec used in VideoWriter when saving video to file') flags.DEFINE_integer('num_classes', 80, 'number of classes in the model') # track_iou parameters flags.DEFINE_float('sigma_l', 0.2, 'sigma_l for low iou') flags.DEFINE_float('sigma_h', 0.9, 'sigma high') flags.DEFINE_float('sigma_iou', 0.8, 'IOU for tracking') flags.DEFINE_integer('t_min', 4, 'min number of frames to track') def proj3DWorld(p, n, delta): # remember to import numpy delta = np.array([delta]) rho = np.array(np.concatenate([n, delta], axis=0)) P = -(delta*p)/np.dot((np.array(np.concatenate([p, [0]], axis=-1))), rho) return P def main(_argv): physical_devices = tf.config.experimental.list_physical_devices('GPU') for physical_device in physical_devices: tf.config.experimental.set_memory_growth(physical_device, True) if FLAGS.tiny: yolo = YoloV3Tiny(classes=FLAGS.num_classes) else: yolo = YoloV3(classes=FLAGS.num_classes) yolo.load_weights(FLAGS.weights) logging.info('weights loaded') class_names = [c.strip() for c in open(FLAGS.classes).readlines()] logging.info('classes loaded') times = [] try: vid = cv2.VideoCapture(int(FLAGS.video)) except: vid = cv2.VideoCapture(FLAGS.video) if FLAGS.output: # by default VideoCapture returns float instead of int width = int(vid.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(vid.get(cv2.CAP_PROP_FRAME_HEIGHT)) fps = int(vid.get(cv2.CAP_PROP_FPS)) codec = cv2.VideoWriter_fourcc(*FLAGS.output_format) output = cv2.VideoWriter(FLAGS.output, codec, fps, (width, height)) info_moving = 1 frame_num = 1 det_frames_stack = [] W = width H = height u = np.array([(444-W/2), (-(26-H/2)), 1]) v = np.array([(530-W/2), (-(22-H/2)), 1]) f = np.sqrt(
np.dot(u, v)
numpy.dot
""" Detect Cube Sat and Processing Plant artifacts """ from datetime import timedelta import os from io import StringIO import cv2 import numpy as np from osgar.node import Node from osgar.bus import BusShutdownException g_mask = None MIN_CYAN_COUNT = 300 def count_mask(mask): """Count statistics and bounding box for given image mask""" count = int(mask.sum()) if count == 0: return count, None, None, None, None # argmax for mask finds the first True value x_min = (mask.argmax(axis=0) != 0).argmax() x_max = mask.shape[1] - np.flip((mask.argmax(axis=0) != 0), axis=0).argmax() - 1 w = (mask.shape[1] - np.flip((mask.argmax(axis=0) != 0), axis=0).argmax() - (mask.argmax(axis=0) != 0).argmax()) h = (mask.shape[0] - np.flip((mask.argmax(axis=1) != 0), axis=0).argmax() - (mask.argmax(axis=1) != 0).argmax()) return count, w, h, x_min, x_max def count_cyan(img, filtered=False, stdout=None): # NASA SRC logo color is #007DBD or (0,125,189) # assume valid colors are between that and lighter #E5F2F8 (229, 242, 248) (given the illumination) # valid rgb: ratios for r,g,b must be similar, ie for any given pixel, each r,g,b must in the same place between both end rgb values # r ratio = (r - 0) / (229 - 0) # g ratio = (g - 125) / (242 - 125) # b ratio = (b - 189) / (248 - 189) b = img[:,:,0] g = img[:,:,1] r = img[:,:,2] mask = np.logical_and((r - 0) / (229 - 0) < 1, np.logical_and(abs(((r - 0) / (229 - 0)) - ((g - 125) / (242 - 125))) < 0.2 , abs(((b - 189) / (248 - 189)) - ((g - 125) / (242 - 125))) < 0.2)) not_mask =
np.logical_not(mask)
numpy.logical_not
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import numpy as np import math import onnx from onnx import helper, TensorProto, mapping import torch import torchvision import topi import topi.testing import tvm from tvm import te from tvm import relay from tvm.contrib import graph_runtime from tvm.relay.testing.config import ctx_list import scipy def get_input_data_shape_dict(graph_def, input_data): if isinstance(input_data, list): input_names = {} shape_dict = {} for i, _ in enumerate(input_data): input_names[i] = graph_def.graph.input[i].name shape_dict[input_names[i]] = input_data[i].shape else: input_names = graph_def.graph.input[0].name shape_dict = {input_names: input_data.shape} return input_names, shape_dict def get_tvm_output_with_vm(graph_def, input_data, target, ctx, opset=None): """ Generic function to execute and get tvm output with vm executor""" _, shape_dict = get_input_data_shape_dict(graph_def, input_data) mod, params = relay.frontend.from_onnx(graph_def, shape_dict, opset=opset) ex = relay.create_executor('vm', mod=mod, ctx=ctx, target=target) indata = tvm.nd.array(input_data) result = ex.evaluate()(indata) return result.asnumpy() def get_tvm_output(graph_def, input_data, target, ctx, output_shape=None, output_dtype='float32', opset=None): """ Generic function to execute and get tvm output""" target = 'llvm' input_names, shape_dict = get_input_data_shape_dict(graph_def, input_data) mod, params = relay.frontend.from_onnx(graph_def, shape_dict, opset=opset) with tvm.transform.PassContext(opt_level=1): graph, lib, params = relay.build(mod, target, params=params) ctx = tvm.cpu(0) m = graph_runtime.create(graph, lib, ctx) # set inputs if isinstance(input_data, list): for i, e in enumerate(input_names): # Its possible for some onnx inputs to not be needed in the tvm # module, confirm its present before setting. try: m.set_input(input_names[i], tvm.nd.array( input_data[i].astype(input_data[i].dtype))) except: continue else: m.set_input(input_names, tvm.nd.array( input_data.astype(input_data.dtype))) m.set_input(**params) # execute m.run() # get outputs if isinstance(output_shape, list) and isinstance(output_dtype, list): tvm_output_list = [] for i, _ in enumerate(output_shape): tvm_output = m.get_output(i) tvm_output_list.append(tvm_output.asnumpy()) return tvm_output_list else: tvm_output = m.get_output(0) return tvm_output.asnumpy() def get_onnxruntime_output(model, inputs, dtype='float32'): import onnxruntime.backend rep = onnxruntime.backend.prepare(model, 'CPU') if isinstance(inputs, list) and len(inputs) > 1: ort_out = rep.run(inputs) else: x = inputs.astype(dtype) ort_out = rep.run(x)[0] return ort_out def verify_onnx_forward_impl(graph_file, data_shape, out_shape): dtype = 'float32' x = np.random.uniform(size=data_shape) model = onnx.load_model(graph_file) c2_out = get_onnxruntime_output(model, x, dtype) for target, ctx in ctx_list(): tvm_out = get_tvm_output(model, x, target, ctx, out_shape, dtype) tvm.testing.assert_allclose(c2_out, tvm_out, rtol=1e-5, atol=1e-5) def test_reshape(): in_shape = (4, 3, 3, 4) ref_shape = (6, 2, 4, 3) ref_array = np.array(ref_shape) ref_node = onnx.helper.make_node('Constant', inputs=[], outputs=['ref_in'], value=onnx.helper.make_tensor(name='const_tensor', data_type=onnx.TensorProto.INT32, dims=ref_array.shape, vals=ref_array.flatten().astype(int))) reshape_node = helper.make_node("Reshape", ["in", "ref_in"], ["out"]) graph = helper.make_graph([ref_node, reshape_node], "reshape_test", inputs=[helper.make_tensor_value_info("in", TensorProto.FLOAT, list(in_shape))], outputs=[helper.make_tensor_value_info("out", TensorProto.FLOAT, list(ref_shape))]) model = helper.make_model(graph, producer_name='reshape_test') for target, ctx in ctx_list(): x = np.random.uniform(size=in_shape).astype('int32') tvm_out = get_tvm_output(model, x, target, ctx, ref_shape, 'float32') tvm.testing.assert_allclose(ref_shape, tvm_out.shape) def test_expand(): def _test_expand(name, data, shape, ref_data): shape_array = np.array(shape) shape_node = onnx.helper.make_node('Constant', inputs=[], outputs=['shape'], value=onnx.helper.make_tensor(name = 'const_tensor', data_type = onnx.TensorProto.INT32, dims = shape_array.shape, vals = shape_array.flatten().astype('int32'))) expand_node = helper.make_node("Expand", ["in", "shape"], ["out"]) graph = helper.make_graph([shape_node, expand_node], "expand_test", inputs = [helper.make_tensor_value_info("in", TensorProto.FLOAT, list(data.shape))], outputs = [helper.make_tensor_value_info("out", TensorProto.FLOAT, list(ref_data.shape))]) model = helper.make_model(graph, producer_name=name) for target, ctx in ctx_list(): tvm_out = get_tvm_output(model, data, target, ctx, ref_data.shape, 'float32') tvm.testing.assert_allclose(ref_data, tvm_out) in_shape = (3, 1) shape = (3, 4) data = np.random.uniform(size=in_shape).astype(np.float32) ref_data = np.tile(data, 4) _test_expand('expand_with_dim_unchanged_test', data, shape, ref_data) in_shape = (3, 1) shape = (2, 1, 6) data = np.random.uniform(size=in_shape).astype(np.float32) ref_data = data * np.ones(shape, dtype=np.float32) _test_expand('expand_with_dim_changed_test', data, shape, ref_data) def verify_depth_to_space(inshape, outshape, mode, blockSize): node = onnx.helper.make_node('DepthToSpace', inputs=['x'], outputs=['y'], blocksize=blockSize) graph = helper.make_graph([node], "depth_to_space_test", inputs=[helper.make_tensor_value_info("x", TensorProto.FLOAT, list(inshape))], outputs=[helper.make_tensor_value_info("y", TensorProto.FLOAT, list(outshape))]) model = helper.make_model(graph, producer_name='depth_to_space_test') for target, ctx in ctx_list(): x = np.random.uniform(size=inshape).astype('float32') tvm_out = get_tvm_output(model, x, target, ctx, outshape, 'float32') onnx_out = get_onnxruntime_output(model, x, 'float32') tvm.testing.assert_allclose(onnx_out, tvm_out) def test_depth_to_space(): # current onnx.checker use OpSet-1 version of DepthToSpace, which doesn't have a mode argument. # TO-DO, we can add mode arguement to test CRD mode and DCR mode # in the future when we update to a newer onnx version. verify_depth_to_space((1, 8, 2, 3), (1, 2, 4, 6), mode="CRD", blockSize=2) def verify_space_to_depth(inshape, outshape, blockSize): node = onnx.helper.make_node('SpaceToDepth', inputs=['x'], outputs=['y'], blocksize=blockSize) graph = helper.make_graph([node], "space_to_depth_test", inputs=[helper.make_tensor_value_info("x", TensorProto.FLOAT, list(inshape))], outputs=[helper.make_tensor_value_info("y", TensorProto.FLOAT, list(outshape))]) model = helper.make_model(graph, producer_name='space_to_depth_test') for target, ctx in ctx_list(): x = np.random.uniform(size=inshape).astype('float32') tvm_out = get_tvm_output(model, x, target, ctx, outshape, 'float32') onnx_out = get_onnxruntime_output(model, x, 'float32') tvm.testing.assert_allclose(onnx_out, tvm_out) def test_space_to_depth(): verify_space_to_depth((1, 1, 4, 6), (1, 4, 2, 3), 2) def test_shape(): in_shape = (4, 3, 3, 4) ref_shape = (6, 2, 4, 3) ref_array = np.array(ref_shape) ref_node = onnx.helper.make_node('Constant', inputs=[], outputs=['ref_in'], value=onnx.helper.make_tensor(name='const_tensor', data_type=onnx.TensorProto.INT32, dims=ref_array.shape, vals=ref_array.flatten().astype(int))) reshape_node = helper.make_node("Reshape", ["in", "ref_in"], ["out"]) shape_node = helper.make_node("Shape", ['out'], ['final_out']) graph = helper.make_graph([ref_node, reshape_node, shape_node], "shape_test", inputs=[helper.make_tensor_value_info("in", TensorProto.FLOAT, list(in_shape))], outputs=[helper.make_tensor_value_info("final_out", TensorProto.FLOAT, list(ref_shape))]) model = helper.make_model(graph, producer_name='shape_test') for target, ctx in ctx_list(): x = np.random.uniform(size=in_shape).astype('int32') tvm_out = get_tvm_output(model, x, target, ctx, ref_shape, 'int32') tvm.testing.assert_allclose(ref_shape, tvm_out) def _test_power_iteration(x_shape, y_shape): if isinstance(y_shape, int): y_shape = [y_shape] x = np.random.uniform(size=x_shape).astype(np.float32) y = np.random.uniform(size=y_shape).astype(np.float32) np_res = np.power(x, y).astype(np.float32) res = helper.make_node("Pow", ['x', 'y'], ['out']) graph = helper.make_graph([res], 'power_test', inputs=[helper.make_tensor_value_info("x", TensorProto.FLOAT, list(x_shape)), helper.make_tensor_value_info("y", TensorProto.FLOAT, list(y_shape))], outputs=[helper.make_tensor_value_info("out", TensorProto.FLOAT, list(np_res.shape))]) model = helper.make_model(graph, producer_name='power_test') for target, ctx in ctx_list(): tvm_out = get_tvm_output(model, [x, y], target, ctx, np_res.shape) tvm.testing.assert_allclose(np_res, tvm_out, rtol=1e-5, atol=1e-5) def test_power(): _test_power_iteration((1, 3), (1)) _test_power_iteration((2, 3), (2, 3)) _test_power_iteration((2, 3), (1, 3)) def test_squeeze(): in_shape = (1, 3, 1, 3, 1, 1) out_shape = (3, 3) y = helper.make_node("Squeeze", ['in'], ['out'], axes=[0, 2, 4, 5]) graph = helper.make_graph([y], 'squeeze_test', inputs=[helper.make_tensor_value_info("in", TensorProto.FLOAT, list(in_shape))], outputs=[helper.make_tensor_value_info("out", TensorProto.FLOAT, list(out_shape))]) model = helper.make_model(graph, producer_name='squeeze_test') for target, ctx in ctx_list(): x = np.random.uniform(size=in_shape).astype('float32') tvm_out = get_tvm_output(model, x, target, ctx, out_shape, 'float32') tvm.testing.assert_allclose(out_shape, tvm_out.shape) def test_flatten(): in_shape = (1, 3, 4, 4) axis = 1 ref_shape = (1, 48) flatten_node = helper.make_node("Flatten", ["in"], ["out"], axis=axis) graph = helper.make_graph([flatten_node], "flatten_test", inputs=[helper.make_tensor_value_info("in", TensorProto.FLOAT, list(in_shape))], outputs=[helper.make_tensor_value_info("out", TensorProto.FLOAT, list(ref_shape))]) model = helper.make_model(graph, producer_name='flatten_test') for target, ctx in ctx_list(): x = np.random.uniform(size=in_shape).astype('int32') tvm_out = get_tvm_output(model, x, target, ctx, ref_shape, 'float32') tvm.testing.assert_allclose(ref_shape, tvm_out.shape) def test_unsqueeze(): in_shape = (3, 3) axis = (0, 3, 4) out_shape = (1, 3, 3, 1, 1) y = helper.make_node("Unsqueeze", ['in'], ['out'], axes=list(axis)) graph = helper.make_graph([y], 'squeeze_test', inputs=[helper.make_tensor_value_info("in", TensorProto.FLOAT, list(in_shape))], outputs=[helper.make_tensor_value_info("out", TensorProto.FLOAT, list(out_shape))]) model = helper.make_model(graph, producer_name='squeeze_test') for target, ctx in ctx_list(): x = np.random.uniform(size=in_shape).astype('float32') tvm_out = get_tvm_output(model, x, target, ctx, out_shape, 'float32') tvm.testing.assert_allclose(out_shape, tvm_out.shape) def verify_gather(in_shape, indices, axis, dtype): x = np.random.uniform(size=in_shape).astype(dtype) indices = np.array(indices, dtype="int32") out_np = np.take(x, indices, axis=axis) y = helper.make_node("Gather", ['in', 'indices'], ['out'], axis=axis) graph = helper.make_graph([y], 'gather_test', inputs=[helper.make_tensor_value_info("in", TensorProto.FLOAT, list(in_shape)), helper.make_tensor_value_info("indices", TensorProto.INT32, list(indices.shape))], outputs=[helper.make_tensor_value_info("out", TensorProto.FLOAT, list(out_np.shape))]) model = helper.make_model(graph, producer_name='gather_test') for target, ctx in ctx_list(): tvm_out = get_tvm_output( model, [x, indices], target, ctx, out_np.shape) tvm.testing.assert_allclose(out_np, tvm_out) def test_gather(): verify_gather((4,), [1], 0, 'int32') verify_gather((1, 4), [0], 0, 'int32') verify_gather((4,), [[[1, 0], [0, 1]]], 0, 'float32') verify_gather((2, 2), [[[1, 0], [0, 1]]], 1, 'int32') verify_gather((3, 3, 3), [[[1, 0]]], -1, 'int32') verify_gather((4, 3, 5, 6), [[2, 1, 0, 0]], 0, 'float32') def verify_scatter(in_shape, indices, axis): x = np.random.uniform(size=in_shape).astype("float32") indices = np.array(indices, dtype="int32") updates = np.random.uniform(size=indices.shape).astype("float32") y = helper.make_node("ScatterElements", ['data', 'indices', 'updates'], ['output'], axis=axis) graph = helper.make_graph([y], 'scatter_test', inputs=[helper.make_tensor_value_info("data", TensorProto.FLOAT, list(in_shape)), helper.make_tensor_value_info("indices", TensorProto.INT32, list(indices.shape)), helper.make_tensor_value_info("updates", TensorProto.FLOAT, list(indices.shape))], outputs=[helper.make_tensor_value_info("output", TensorProto.FLOAT, list(in_shape))]) model = helper.make_model(graph, producer_name='scatter_test') onnx_out = get_onnxruntime_output(model, [x, indices, updates]) for target, ctx in ctx_list(): tvm_out = get_tvm_output( model, [x, indices, updates], target, ctx, onnx_out[0].shape) tvm.testing.assert_allclose(onnx_out[0], tvm_out) def test_scatter(): verify_scatter((4,), [1], 0) verify_scatter((1, 4), [[0]], 0) verify_scatter((4,), [2, 3], 0) verify_scatter((2, 2), [[1, 0], [0, 1]], 1) verify_scatter((3, 3, 3), [[[-1, -3]]], -1) verify_scatter((4, 3, 5, 6), [[[[2, 1, 0, 0]]]], 0) def _test_slice_iteration_v1(indata, outdata, starts, ends, axes=None): if axes: y = helper.make_node( "Slice", ['in'], ['out'], axes=axes, starts=starts, ends=ends) else: y = helper.make_node( "Slice", ['in'], ['out'], starts=starts, ends=ends) graph = helper.make_graph([y], 'slice_test', inputs=[helper.make_tensor_value_info("in", TensorProto.FLOAT, list(indata.shape))], outputs=[helper.make_tensor_value_info("out", TensorProto.FLOAT, list(outdata.shape))]) model = helper.make_model(graph, producer_name='slice_test') for target, ctx in ctx_list(): tvm_out = get_tvm_output( model, indata, target, ctx, outdata.shape, 'float32', opset=1) tvm.testing.assert_allclose(outdata, tvm_out) def _test_slice_iteration_v10(indata, outdata, starts, ends, axes=None): if isinstance(starts, int): starts = (starts, ) if isinstance(ends, int): ends = (ends, ) if isinstance(axes, int): axes = (axes, ) starts = np.asarray(starts) ends = np.asarray(ends) inputs = [ helper.make_tensor_value_info("data", TensorProto.FLOAT, list(indata.shape)), helper.make_tensor_value_info("starts", TensorProto.INT32, list(starts.shape)), helper.make_tensor_value_info("ends", TensorProto.INT32, list(ends.shape)) ] initializer = [ helper.make_tensor("starts", TensorProto.INT32, list(starts.shape), starts), helper.make_tensor("ends", TensorProto.INT32, list(ends.shape), ends) ] if axes: axes = np.asarray(axes) y = helper.make_node("Slice", ["data", "starts", "ends", "axes"], ["out"]) inputs.append( helper.make_tensor_value_info("axes", TensorProto.INT32, list(axes.shape))) initializer.append( helper.make_tensor("axes", TensorProto.INT32, list(axes.shape), axes)) else: y = helper.make_node("Slice", ["data", "starts", "ends"], ["out"]) graph = helper.make_graph([y], 'slice_test', inputs=inputs, outputs=[ helper.make_tensor_value_info( "out", TensorProto.FLOAT, list(outdata.shape)) ], initializer=initializer) model = helper.make_model(graph, producer_name='slice_test') for target, ctx in ctx_list(): tvm_out = get_tvm_output(model, indata, target, ctx, outdata.shape, 'float32', opset=10) tvm.testing.assert_allclose(outdata, tvm_out) def test_slice(): x = np.random.randn(20, 10, 5).astype(np.float32) _test_slice_iteration_v1(x, x[0:3, 0:10], (0, 0), (3, 10), (0, 1)) _test_slice_iteration_v1(x, x[:, :, 3:4], (0, 0, 3), (20, 10, 4)) _test_slice_iteration_v1(x, x[:, 1:1000], (1), (1000), (1)) _test_slice_iteration_v1(x, x[:, 0:-1], (0), (-1), (1)) _test_slice_iteration_v10(x, x[0:3, 0:10], (0, 0), (3, 10), (0, 1)) _test_slice_iteration_v10(x, x[:, :, 3:4], (0, 0, 3), (20, 10, 4)) _test_slice_iteration_v10(x, x[:, 1:1000], (1), (1000), (1)) _test_slice_iteration_v10(x, x[:, 0:-1], (0), (-1), (1)) def _test_onnx_op_elementwise(inshape, outfunc, npargs, dtype, opname, kwargs): indata = np.random.uniform(-1, 1, size=inshape).astype(dtype) outdata = outfunc(indata, **npargs) y = helper.make_node(opname, ['in'], ['out'], **kwargs) graph = helper.make_graph([y], opname+'_test', inputs=[helper.make_tensor_value_info("in", TensorProto.FLOAT, list(indata.shape))], outputs=[helper.make_tensor_value_info("out", TensorProto.FLOAT, list(outdata.shape))]) model = helper.make_model(graph, producer_name=opname+'_test') for target, ctx in ctx_list(): tvm_out = get_tvm_output( model, indata, target, ctx, outdata.shape, dtype) tvm.testing.assert_allclose(outdata, tvm_out) def test_floor(): _test_onnx_op_elementwise((2, 4, 5, 6), np.floor, {}, 'float32', 'Floor', {}) def test_ceil(): _test_onnx_op_elementwise((2, 4, 5, 6), np.ceil, {}, 'float32', 'Ceil', {}) def test_clip(): _test_onnx_op_elementwise((2, 4, 5, 6), np.clip, {'a_min': -1.0, 'a_max': 1.0}, 'float32', 'Clip', {'min': -1.0, 'max': 1.0}) def test_round(): _test_onnx_op_elementwise((2, 4, 5, 6), np.round, {}, 'float32', 'Round', {}) def _test_finite_ops(inshape, outfunc, npargs, dtype, opname, kwargs): indata = np.random.choice(a=[np.nan, np.inf, -np.inf, 0.5, 1.0, 0], size=inshape).astype(dtype) outdata = outfunc(indata, **npargs) y = helper.make_node(opname, ['in'], ['out'], **kwargs) graph = helper.make_graph([y], opname+'_test', inputs=[helper.make_tensor_value_info("in", TensorProto.FLOAT, list(indata.shape))], outputs=[helper.make_tensor_value_info("out", TensorProto.BOOL, list(outdata.shape))]) model = helper.make_model(graph, producer_name=opname+'_test') for target, ctx in ctx_list(): tvm_out = get_tvm_output( model, indata, target, ctx, outdata.shape, dtype) tvm.testing.assert_allclose(outdata, tvm_out) def test_isinf(): _test_finite_ops((2, 4, 5, 6), np.isinf, {}, 'float32', 'IsInf', {}) def test_isnan(): _test_finite_ops((2, 4, 5, 6), np.isnan, {}, 'float32', 'IsNaN', {}) def verify_gather_nd(in_shape, indices, dtype): x = np.random.uniform(size=in_shape).astype(dtype) indices = np.array(indices, dtype="int32") out_np = topi.testing.gather_nd_python(x, indices) y = helper.make_node("GatherND", ['in', 'indices'], ['out']) graph = helper.make_graph([y], 'gather_test', inputs=[helper.make_tensor_value_info("in", TensorProto.FLOAT, list(in_shape)), helper.make_tensor_value_info("indices", TensorProto.INT32, list(indices.shape))], outputs=[helper.make_tensor_value_info("out", TensorProto.FLOAT, list(out_np.shape))]) model = helper.make_model(graph, producer_name='gather_test') for target, ctx in ctx_list(): tvm_out = get_tvm_output( model, [x, indices], target, ctx, out_np.shape) tvm.testing.assert_allclose(out_np, tvm_out) def test_gather_nd(): verify_gather_nd((2, 2), [[0,0],[1,1]], 'int32') verify_gather_nd((3, 3, 3), [[0,1],[1,0]] , 'float32') verify_gather_nd((4, 3, 5, 6), [[2, 1, 0, 0]], 'float32') def test_onehot(): indices_shape = [10] indices_array = np.random.randint( low=0, high=9, size=indices_shape, dtype='int32') depth = 10 values = np.asarray([0, 1]) out_np = np.eye(depth)[indices_array.reshape(-1)] onehot_node = helper.make_node( "OneHot", ["indices", "depth", "values"], ["out"]) graph = helper.make_graph([onehot_node], "onehot_test", inputs=[helper.make_tensor_value_info("indices", TensorProto.INT32, indices_shape), helper.make_tensor_value_info("depth", TensorProto.INT32, [1]), helper.make_tensor_value_info("values", TensorProto.INT32, values.shape)], initializer=[helper.make_tensor("depth", TensorProto.INT32, [1], [depth]), helper.make_tensor("values", TensorProto.INT32, values.shape, values)], outputs=[helper.make_tensor_value_info("out", TensorProto.INT32, out_np.shape)]) model = helper.make_model(graph, producer_name="onehot_test") for target, ctx in ctx_list(): tvm_out = get_tvm_output( model, [indices_array], target, ctx, out_np.shape) tvm.testing.assert_allclose(out_np, tvm_out, rtol=1e-5, atol=1e-5) def test_matmul(): a_shape = (4, 3) b_shape = (3, 4) a_array = np.random.uniform(size=a_shape).astype('float32') b_array = np.random.uniform(size=b_shape).astype('float32') out_np = np.matmul(a_array, b_array) mul_node = helper.make_node("MatMul", ["a", "b"], ["out"]) graph = helper.make_graph([mul_node], "matmul_test", inputs=[helper.make_tensor_value_info("a", TensorProto.FLOAT, list(a_shape)), helper.make_tensor_value_info("b", TensorProto.FLOAT, list(b_shape))], outputs=[helper.make_tensor_value_info("out", TensorProto.FLOAT, list(out_np.shape))]) model = helper.make_model(graph, producer_name='matmul_test') for target, ctx in ctx_list(): tvm_out = get_tvm_output( model, [a_array, b_array], target, ctx, out_np.shape) tvm.testing.assert_allclose(out_np, tvm_out, rtol=1e-5, atol=1e-5) def verify_batch_matmul(a_shape, b_shape): a_array = np.random.uniform(size=a_shape).astype('float32') b_array = np.random.uniform(size=b_shape).astype('float32') out_np = np.matmul(a_array, b_array) mul_node = helper.make_node("MatMul", ["a", "b"], ["out"]) graph = helper.make_graph([mul_node], "matmul_test", inputs=[helper.make_tensor_value_info("a", TensorProto.FLOAT, list(a_shape)), helper.make_tensor_value_info("b", TensorProto.FLOAT, list(b_shape))], outputs=[helper.make_tensor_value_info("out", TensorProto.FLOAT, list(out_np.shape))]) model = helper.make_model(graph, producer_name='matmul_test') for target, ctx in ctx_list(): tvm_out = get_tvm_output( model, [a_array, b_array], target, ctx, out_np.shape) tvm.testing.assert_allclose(out_np, tvm_out, rtol=1e-5, atol=1e-5) def test_batch_matmul(): verify_batch_matmul((2, 3, 4, 3), (2, 3, 3, 4)) verify_batch_matmul((2, 4, 3), (3, 4)) verify_batch_matmul((2, 3, 4, 3), (3, 4)) def verify_lrn(shape, nsize, dtype, alpha=None, beta=None, bias=None): in_array = np.random.uniform(size=shape).astype(dtype) if alpha == None and beta == None and bias == None: alpha = 0.0001 beta = 0.75 bias = 1.0 node = onnx.helper.make_node( 'LRN', inputs=['in'], outputs=['out'], size=nsize) else: node = onnx.helper.make_node('LRN', inputs=['in'], outputs=['out'], alpha=alpha, beta=beta, bias=bias, size=nsize) graph = helper.make_graph([node], "lrn_test", inputs=[helper.make_tensor_value_info( "in", TensorProto.FLOAT, list(shape))], outputs=[helper.make_tensor_value_info("out", TensorProto.FLOAT, list(shape))]) model = helper.make_model(graph, producer_name='lrn_test') def _get_python_lrn(): square_sum = np.zeros(shape).astype(dtype) for n, c, h, w in np.ndindex(in_array.shape): square_sum[n, c, h, w] = sum(in_array[n, max(0, c - int(math.floor((nsize - 1) / 2))): min(5, c + int(math.ceil((nsize - 1) / 2)) + 1), h, w] ** 2) py_out = in_array / ((bias + (alpha / nsize) * square_sum) ** beta) return py_out for target, ctx in ctx_list(): input_name = model.graph.input[0].name py_out = _get_python_lrn() tvm_out = get_tvm_output( model, in_array, target, ctx, py_out.shape, 'float32') tvm.testing.assert_allclose(py_out, tvm_out, rtol=1e-5, atol=1e-5) def test_lrn(): verify_lrn((5, 5, 5, 5), 3, 'float32') verify_lrn((5, 5, 5, 5), 3, 'float32', alpha=0.0002, beta=0.5, bias=2.0) def verify_instance_norm(shape, axis=1): def _get_python_instance_norm(x, gamma, beta, epsilon=1e-5): dims_x = len(x.shape) axis = tuple(range(2, dims_x)) mean = np.mean(x, axis=axis, keepdims=True) var = np.var(x, axis=axis, keepdims=True) dim_ones = (1,) * (dims_x - 2) gamma = gamma.reshape(-1, *dim_ones) beta = beta.reshape(-1, *dim_ones) return gamma * (x - mean) / np.sqrt(var + epsilon) + beta x = np.random.randn(*shape).astype(np.float32) gamma = np.random.randn(shape[1]).astype(np.float32) beta = np.random.randn(shape[1]).astype(np.float32) epsilon = 1e-5 y = _get_python_instance_norm(x, gamma, beta, epsilon).astype(np.float32) node = onnx.helper.make_node( 'InstanceNormalization', inputs=['x', 'gamma', 'beta'], outputs=['y'], epsilon=epsilon, ) graph = helper.make_graph([node], "instance_norm_test", inputs=[helper.make_tensor_value_info("x", TensorProto.FLOAT, list(shape)), helper.make_tensor_value_info( "gamma", TensorProto.FLOAT, (shape[1],)), helper.make_tensor_value_info("beta", TensorProto.FLOAT, (shape[1],))], outputs=[helper.make_tensor_value_info("y", TensorProto.FLOAT, list(shape))]) model = helper.make_model(graph, producer_name='instance_norm_test') for target, ctx in ctx_list(): tvm_out = get_tvm_output( model, [x, gamma, beta], target, ctx, shape, 'float32') tvm.testing.assert_allclose(y, tvm_out, rtol=1e-5, atol=1e-5) def test_instance_norm(): verify_instance_norm((2, 3, 4, 5)) verify_instance_norm((32, 64, 80, 64)) verify_instance_norm((8, 6, 5)) verify_instance_norm((8, 7, 6, 5, 4)) def _test_upsample_nearest(): scale = 2 in_shape = (1, 1, 3, 3) out_shape = (1, 1, 3*scale, 3*scale) y = helper.make_node("Upsample", ['in'], [ 'out'], mode='nearest', scales=[1.0, 1.0, 2.0, 2.0]) in_array = np.random.uniform(size=in_shape).astype(np.float32) out_array = topi.testing.upsampling_python( in_array, (scale, scale), "NCHW") graph = helper.make_graph([y], 'upsample_nearest_test', inputs=[helper.make_tensor_value_info( "in", TensorProto.FLOAT, list(in_shape))], outputs=[helper.make_tensor_value_info("out", TensorProto.FLOAT, list(out_shape))]) model = helper.make_model(graph, producer_name='upsample_nearest_test') for target, ctx in ctx_list(): tvm_out = get_tvm_output( model, in_array, target, ctx, out_shape, 'float32') tvm.testing.assert_allclose(out_array, tvm_out) def _test_upsample3d_nearest(): scale = 2 in_shape = (1, 1, 3, 3, 3) out_shape = (1, 1, 3*scale, 3*scale, 3*scale) y = helper.make_node("Upsample", ['in'], [ 'out'], mode='nearest', scales=[1.0, 1.0, 2.0, 2.0, 2.0]) in_array = np.random.uniform(size=in_shape).astype(np.float32) out_array = topi.testing.upsampling3d_python( in_array, (scale, scale, scale), "NCDHW") graph = helper.make_graph([y], 'upsample_nearest_test', inputs=[helper.make_tensor_value_info( "in", TensorProto.FLOAT, list(in_shape))], outputs=[helper.make_tensor_value_info("out", TensorProto.FLOAT, list(out_shape))]) model = helper.make_model(graph, producer_name='upsample_nearest_test') for target, ctx in ctx_list(): tvm_out = get_tvm_output( model, in_array, target, ctx, out_shape, 'float32') tvm.testing.assert_allclose(out_array, tvm_out) def _test_upsample_bilinear(): scale = 2 in_shape = (1, 1, 3, 3) out_shape = (1, 1, 3*scale, 3*scale) y = helper.make_node("Upsample", ['in'], [ 'out'], mode='linear', scales=[1.0, 1.0, 2.0, 2.0]) in_array = np.random.uniform(size=in_shape).astype(np.float32) out_array = topi.testing.bilinear_resize_python( in_array, (3*scale, 3*scale), "NCHW") graph = helper.make_graph([y], 'upsample_bilinear_test', inputs=[helper.make_tensor_value_info( "in", TensorProto.FLOAT, list(in_shape))], outputs=[helper.make_tensor_value_info("out", TensorProto.FLOAT, list(out_shape))]) model = helper.make_model(graph, producer_name='upsample_bilinear_test') for target, ctx in ctx_list(): tvm_out = get_tvm_output( model, in_array, target, ctx, out_shape, 'float32') tvm.testing.assert_allclose(out_array, tvm_out, rtol=1e-5, atol=1e-5) def _test_upsample_bilinear_opset9(): scale = 2 in_shape = (1, 1, 3, 3) out_shape = (1, 1, 3*scale, 3*scale) y = helper.make_node("Upsample", ['in', 'scales'], ['out'], mode='linear') scales = [1, 1, 2, 2] in_array = np.random.uniform(size=in_shape).astype(np.float32) out_array = topi.testing.bilinear_resize_python( in_array, (3*scale, 3*scale), "NCHW") ref_node = helper.make_node('Constant', inputs=[], outputs=['const'], value=onnx.helper.make_tensor(name='const_tensor', data_type=TensorProto.FLOAT, dims=scales, vals=np.random.random(scales).flatten().astype(float))) shape_node = helper.make_node("Shape", ['const'], ['scales']) graph = helper.make_graph([ref_node, shape_node, y], 'upsample_bilinear_opset9_test', inputs=[helper.make_tensor_value_info( "in", TensorProto.FLOAT, list(in_shape))], outputs=[helper.make_tensor_value_info("out", TensorProto.FLOAT, list(out_shape))]) model = helper.make_model( graph, producer_name='upsample_bilinear_opset9_test') for target, ctx in ctx_list(): tvm_out = get_tvm_output( model, in_array, target, ctx, out_shape, 'float32') tvm.testing.assert_allclose(out_array, tvm_out, rtol=1e-5, atol=1e-5) def _test_upsample3d_trilinear(): scale = 2 in_shape = (1, 1, 3, 3, 3) out_shape = (1, 1, 3*scale, 3*scale, 3*scale) y = helper.make_node("Upsample", ['in', 'scales'], ['out'], mode='linear') scales = [1.0, 1.0, 2.0, 2.0, 2.0] in_array = np.random.uniform(size=in_shape).astype(np.float32) out_array = topi.testing.trilinear_resize3d_python( in_array, (3*scale, 3*scale, 3*scale), "NCDHW", coordinate_transformation_mode="half_pixel") ref_array = np.array(scales) ref_node = helper.make_node('Constant', inputs=[], outputs=['scales'], value=onnx.helper.make_tensor(name='const_tensor', data_type=TensorProto.FLOAT, dims=ref_array.shape, vals=ref_array.flatten().astype(float))) graph = helper.make_graph([ref_node, y], 'upsample_trilinear_test', inputs=[helper.make_tensor_value_info( "in", TensorProto.FLOAT, list(in_shape))], outputs=[helper.make_tensor_value_info("out", TensorProto.FLOAT, list(out_shape))]) model = helper.make_model( graph, producer_name='upsample_trilinear_test') for target, ctx in ctx_list(): tvm_out = get_tvm_output( model, in_array, target, ctx, out_shape, 'float32') tvm.testing.assert_allclose(out_array, tvm_out, rtol=1e-5, atol=1e-5) def test_upsample(): _test_upsample_nearest() _test_upsample_bilinear() _test_upsample_bilinear_opset9() _test_upsample3d_nearest() _test_upsample3d_trilinear() def _test_softmax(inshape, axis): opname = 'Softmax' indata = np.random.uniform(size=inshape).astype(np.float32) outshape = inshape outdata = topi.testing.softmax_python(indata) if isinstance(axis, int): y = helper.make_node(opname, ['in'], ['out'], axis=axis) elif axis is None: y = helper.make_node(opname, ['in'], ['out']) graph = helper.make_graph([y], opname+'_test', inputs=[helper.make_tensor_value_info("in", TensorProto.FLOAT, list(indata.shape))], outputs=[helper.make_tensor_value_info("out", TensorProto.FLOAT, list(outdata.shape))]) model = helper.make_model(graph, producer_name=opname+'_test') for target, ctx in ctx_list(): tvm_out = get_tvm_output( model, indata, target, ctx, outshape, 'float32') tvm.testing.assert_allclose(outdata, tvm_out, rtol=1e-5, atol=1e-5) def test_softmax(): _test_softmax((1, 10), None) _test_softmax((1, 10), 1) def verify_min(input_dim): dtype = 'float32' a_np1 = np.random.uniform(size=input_dim).astype(dtype) a_np2 = np.random.uniform(size=input_dim).astype(dtype) a_np3 = np.random.uniform(size=input_dim).astype(dtype) b_np = np.min((a_np1, a_np2, a_np3), axis=0) min_node = helper.make_node("Min", ["a_np1", "a_np2", "a_np3"], ["out"]) graph = helper.make_graph([min_node], "Min_test", inputs=[helper.make_tensor_value_info("a_np1", TensorProto.FLOAT, list(input_dim)), helper.make_tensor_value_info("a_np2", TensorProto.FLOAT, list(input_dim)), helper.make_tensor_value_info("a_np3", TensorProto.FLOAT, list(input_dim))], outputs=[helper.make_tensor_value_info("out", TensorProto.FLOAT, list(b_np.shape))]) model = helper.make_model(graph, producer_name='Min_test') for target, ctx in ctx_list(): tvm_out = get_tvm_output( model, [a_np1, a_np2, a_np3], target, ctx, b_np.shape) tvm.testing.assert_allclose(b_np, tvm_out, rtol=1e-5, atol=1e-5) def test_forward_min(): verify_min((1, 3, 20, 20)) verify_min((20, 20)) def verify_max(input_dim): dtype = 'float32' a_np1 = np.random.uniform(size=input_dim).astype(dtype) a_np2 = np.random.uniform(size=input_dim).astype(dtype) a_np3 = np.random.uniform(size=input_dim).astype(dtype) b_np = np.max((a_np1, a_np2, a_np3), axis=0) max_node = helper.make_node("Max", ["a_np1", "a_np2", "a_np3"], ["out"]) graph = helper.make_graph([max_node], "Max_test", inputs=[helper.make_tensor_value_info("a_np1", TensorProto.FLOAT, list(input_dim)), helper.make_tensor_value_info("a_np2", TensorProto.FLOAT, list(input_dim)), helper.make_tensor_value_info("a_np3", TensorProto.FLOAT, list(input_dim))], outputs=[helper.make_tensor_value_info("out", TensorProto.FLOAT, list(b_np.shape))]) model = helper.make_model(graph, producer_name='Max_test') for target, ctx in ctx_list(): tvm_out = get_tvm_output( model, [a_np1, a_np2, a_np3], target, ctx, b_np.shape) tvm.testing.assert_allclose(b_np, tvm_out, rtol=1e-5, atol=1e-5) def test_forward_max(): verify_max((1, 3, 20, 20)) verify_max((20, 20)) def verify_mean(input_dim): dtype = 'float32' a_np1 = np.random.uniform(size=input_dim).astype(dtype) a_np2 = np.random.uniform(size=input_dim).astype(dtype) a_np3 = np.random.uniform(size=input_dim).astype(dtype) b_np = np.mean((a_np1, a_np2, a_np3), axis=0) mean_node = helper.make_node("Mean", ["a_np1", "a_np2", "a_np3"], ["out"]) graph = helper.make_graph([mean_node], "Mean_test", inputs=[helper.make_tensor_value_info("a_np1", TensorProto.FLOAT, list(input_dim)), helper.make_tensor_value_info("a_np2", TensorProto.FLOAT, list(input_dim)), helper.make_tensor_value_info("a_np3", TensorProto.FLOAT, list(input_dim))], outputs=[helper.make_tensor_value_info("out", TensorProto.FLOAT, list(b_np.shape))]) model = helper.make_model(graph, producer_name='Mean_test') for target, ctx in ctx_list(): tvm_out = get_tvm_output( model, [a_np1, a_np2, a_np3], target, ctx, b_np.shape) tvm.testing.assert_allclose(b_np, tvm_out, rtol=1e-5, atol=1e-5) def test_forward_mean(): verify_mean((1, 3, 20, 20)) verify_mean((20, 20)) def verify_hardsigmoid(input_dim, alpha, beta): dtype = 'float32' a_np1 = np.random.uniform(size=input_dim).astype(dtype) b_np = np.clip(a_np1 * alpha + beta, 0, 1) hardsigmoid_node = helper.make_node("HardSigmoid", ["a_np1"], [ "out"], alpha=alpha, beta=beta) graph = helper.make_graph([hardsigmoid_node], "HardSigmoid_test", inputs=[helper.make_tensor_value_info("a_np1", TensorProto.FLOAT, list(input_dim))], outputs=[helper.make_tensor_value_info("out", TensorProto.FLOAT, list(b_np.shape))]) model = helper.make_model(graph, producer_name='HardSigmoid_test') for target, ctx in ctx_list(): tvm_out = get_tvm_output(model, [a_np1], target, ctx, b_np.shape) tvm.testing.assert_allclose(b_np, tvm_out, rtol=1e-5, atol=1e-5) def test_forward_hardsigmoid(): verify_hardsigmoid((1, 3, 20, 20), 0.5, 0.6) verify_hardsigmoid((20, 20), 0.3, 0.4) def verify_argmin(input_dim, axis=None, keepdims=None): def _argmin_numpy(data, axis=0, keepdims=True): result = np.argmin(data, axis=axis) if (keepdims == 1): result = np.expand_dims(result, axis) return result.astype(data.dtype) a_np1 = np.random.uniform(-10, 10, input_dim).astype(np.int32) if keepdims is None and axis is None: b_np = _argmin_numpy(a_np1) node = onnx.helper.make_node('ArgMin', inputs=['a_np1'], outputs=['out']) elif axis is None: b_np = _argmin_numpy(a_np1, keepdims=keepdims) node = onnx.helper.make_node('ArgMin', inputs=['a_np1'], outputs=['out'], keepdims=keepdims) elif keepdims is None: b_np = _argmin_numpy(a_np1, axis=axis) node = onnx.helper.make_node('ArgMin', inputs=['a_np1'], outputs=['out'], axis=axis) else: b_np = _argmin_numpy(a_np1, axis=axis, keepdims=keepdims) node = onnx.helper.make_node('ArgMin', inputs=['a_np1'], outputs=['out'], axis=axis, keepdims=keepdims) graph = helper.make_graph([node], "argmin_test", inputs=[helper.make_tensor_value_info("a_np1", TensorProto.INT32, list(a_np1.shape))], outputs=[helper.make_tensor_value_info("out", TensorProto.INT32, list(b_np.shape))]) model = helper.make_model(graph, producer_name='argmin_test') for target, ctx in ctx_list(): tvm_out = get_tvm_output( model, [a_np1], target, ctx, b_np.shape, b_np.dtype) tvm.testing.assert_allclose(b_np, tvm_out, rtol=1e-5, atol=1e-5) def verify_argmax(input_dim, axis=None, keepdims=None): def _argmax_numpy(data, axis=0, keepdims=True): result = np.argmax(data, axis=axis) if (keepdims == 1): result = np.expand_dims(result, axis) return result.astype(data.dtype) a_np1 = np.random.uniform(-10, 10, input_dim).astype(np.int32) if keepdims is None and axis is None: b_np = _argmax_numpy(a_np1) node = onnx.helper.make_node('ArgMax', inputs=['a_np1'], outputs=['out']) elif axis is None: b_np = _argmax_numpy(a_np1, keepdims=keepdims) node = onnx.helper.make_node('ArgMax', inputs=['a_np1'], outputs=['out'], keepdims=keepdims) elif keepdims is None: b_np = _argmax_numpy(a_np1, axis=axis) node = onnx.helper.make_node('ArgMax', inputs=['a_np1'], outputs=['out'], axis=axis) else: b_np = _argmax_numpy(a_np1, axis=axis, keepdims=keepdims) node = onnx.helper.make_node('ArgMax', inputs=['a_np1'], outputs=['out'], axis=axis, keepdims=keepdims) graph = helper.make_graph([node], "argmax_test", inputs=[helper.make_tensor_value_info("a_np1", TensorProto.INT32, list(a_np1.shape))], outputs=[helper.make_tensor_value_info("out", TensorProto.INT32, list(b_np.shape))]) model = helper.make_model(graph, producer_name='argmax_test') for target, ctx in ctx_list(): tvm_out = get_tvm_output( model, [a_np1], target, ctx, b_np.shape, b_np.dtype) tvm.testing.assert_allclose(b_np, tvm_out, rtol=1e-5, atol=1e-5) def test_forward_arg_min_max(): '''Verify argmin and argmax''' verify_argmin([3, 4, 4]) verify_argmax([3, 4, 4]) verify_argmin([3, 4, 4], axis=1) verify_argmax([3, 4, 4], axis=0) verify_argmin([3, 4, 4], keepdims=0) verify_argmax([3, 4, 4], keepdims=1) for axis in [None, 0, 1, 2]: for keepdims in [None, True, False]: verify_argmin([3, 4, 4], axis, keepdims) verify_argmax([3, 4, 4], axis, keepdims) def verify_constantofshape(input_dim, value, dtype): out = np.empty(shape=input_dim, dtype=dtype) out.fill(value) fill_node = helper.make_node("ConstantOfShape", ["input"], ["output"], value=helper.make_tensor( 'value', mapping.NP_TYPE_TO_TENSOR_TYPE[np.dtype(dtype)], (1, ), (value, ))) inputs = [ helper.make_tensor_value_info("input", TensorProto.FLOAT, input_dim) ] graph = helper.make_graph( [fill_node], "fill_test", inputs, outputs=[ helper.make_tensor_value_info("output", TensorProto.FLOAT, list(out.shape)) ], initializer=[ helper.make_tensor("input", TensorProto.INT32, (len(input_dim), ), input_dim) ]) model = helper.make_model(graph, producer_name='fill_test') for target, ctx in ctx_list(): tvm_out = get_tvm_output(model, [], target, ctx, out.shape) tvm.testing.assert_allclose(out, tvm_out, rtol=1e-5, atol=1e-5) def test_constantofshape(): verify_constantofshape((2, 3, 4, 5), 10, 'float32') verify_constantofshape((3, 3), 0, 'int32') verify_constantofshape((1, 2, 3), -1, 'float32') def verify_pad(indata, pads, mode='constant', value=0.0): indata = np.array(indata).astype(np.float32) # numpy expect result len_dim = len(pads) // 2 np_pads = [(pads[i], pads[i+len_dim]) for i in range(len_dim)] # onnx graph if mode in ['edge', 'reflect']: outdata = np.pad(indata, pad_width=np_pads, mode=mode) node = helper.make_node( 'Pad', inputs=['input'], outputs=['output'], mode=mode, pads=pads, ) else: outdata = np.pad(indata, pad_width=np_pads, mode='constant', constant_values=value) node = helper.make_node( 'Pad', inputs=['input'], outputs=['output'], mode='constant', pads=pads, value=value ) graph = helper.make_graph([node], 'pad_test', inputs=[helper.make_tensor_value_info("input", TensorProto.FLOAT, list(indata.shape))], outputs=[helper.make_tensor_value_info("output", TensorProto.FLOAT, list(outdata.shape))]) model = helper.make_model(graph, producer_name='pad_test') # tvm result for target, ctx in ctx_list(): tvm_out = get_tvm_output( model, indata, target, ctx, outdata.shape, 'float32', opset=2) tvm.testing.assert_allclose(outdata, tvm_out, rtol=1e-5, atol=1e-5) def verify_pad_v11(indata, pads, mode='constant', value=0.0): indata = np.array(indata).astype(np.float32) # numpy expect result len_dim = len(pads) // 2 np_pads = [(pads[i], pads[i+len_dim]) for i in range(len_dim)] pads = np.array(pads) # onnx graph if mode in ['edge', 'reflect']: inputs = [indata, pads] outdata = np.pad(indata, pad_width=np_pads, mode=mode) node = helper.make_node( 'Pad', inputs=['input', 'pads'], outputs=['output'], mode=mode ) graph = helper.make_graph([node], 'pad_test', inputs=[helper.make_tensor_value_info("input", TensorProto.FLOAT, list(indata.shape)), helper.make_tensor_value_info("pads", TensorProto.INT64,(len(pads),))], initializer=[helper.make_tensor("pads", TensorProto.INT64, (len(pads),), pads)], outputs=[helper.make_tensor_value_info("output", TensorProto.FLOAT, list(outdata.shape))]) else: inputs = [indata, pads, np.array([value])] outdata = np.pad(indata, pad_width=np_pads, mode='constant', constant_values=value) node = helper.make_node( 'Pad', inputs=['input', 'pads', 'constant_value'], outputs=['output'], mode='constant' ) graph = helper.make_graph([node], 'pad_test', inputs=[helper.make_tensor_value_info("input", TensorProto.FLOAT, list(indata.shape)), helper.make_tensor_value_info("pads", TensorProto.INT64,(len(pads),)), helper.make_tensor_value_info("constant_value", TensorProto.INT64,(1,)), ], initializer=[helper.make_tensor("pads", TensorProto.INT64, (len(pads),), pads), helper.make_tensor("constant_value", TensorProto.FLOAT, (1,), [value])], outputs=[helper.make_tensor_value_info("output", TensorProto.FLOAT, list(outdata.shape))]) model = helper.make_model(graph, producer_name='pad_test') # tvm result for target, ctx in ctx_list(): tvm_out = get_tvm_output( model, inputs, target, ctx, outdata.shape, 'float32', opset=11) tvm.testing.assert_allclose(outdata, tvm_out, rtol=1e-5, atol=1e-5) def test_pad(): verify_pad(np.random.randn(2, 2).astype( np.float32), [0, 1, 0, 0], 'constant', 0.0) verify_pad(np.random.randn(2, 3).astype( np.float32), [1, 0, 0, 1], 'constant', 0.0) verify_pad(np.random.randn(3, 2).astype( np.float32), [0, 0, 1, 0], 'constant', 5.0) verify_pad(np.random.randn(1, 3, 4, 5).astype( np.float32), [0, 0, 1, 1, 0, 0, 1, 1], 'edge') verify_pad(np.random.randn(1, 3, 4, 5).astype( np.float32), [0, 0, 1, 1, 0, 0, 1, 1], 'reflect') verify_pad_v11(np.random.randn(2, 2).astype( np.float32), [0, 1, 0, 0], 'constant', 0.0) verify_pad_v11(np.random.randn(2, 3).astype( np.float32), [1, 0, 0, 1], 'constant', 0.0) verify_pad_v11(np.random.randn(3, 2).astype( np.float32), [0, 0, 1, 0], 'constant', 5.0) verify_pad_v11(np.random.randn(1, 3, 4, 5).astype( np.float32), [0, 0, 1, 1, 0, 0, 1, 1], 'edge') verify_pad_v11(np.random.randn(1, 3, 4, 5).astype( np.float32), [0, 0, 1, 1, 0, 0, 1, 1], 'reflect') def verify_reduce_func(func, data, axis, keepdims): inshape = data.shape outshape = np.sum(data, axis=axis, keepdims=keepdims == 1).shape if axis: node = onnx.helper.make_node(func, inputs=['x'], outputs=['y'], axes=axis, keepdims=keepdims) else: node = onnx.helper.make_node(func, inputs=['x'], outputs=['y'], keepdims=keepdims) graph = helper.make_graph([node], "reduce_test", inputs=[helper.make_tensor_value_info("x", TensorProto.FLOAT, list(inshape))], outputs=[helper.make_tensor_value_info("y", TensorProto.FLOAT, list(outshape))]) model = helper.make_model(graph, producer_name='reduce_test') onnx_out = get_onnxruntime_output(model, data, 'float32') for target, ctx in ctx_list(): tvm_out = get_tvm_output(model, data, target, ctx, outshape, 'float32') tvm.testing.assert_allclose(onnx_out, tvm_out, rtol=1e-5, atol=1e-5) def test_all_reduce_funcs(): funcs = ["ReduceMax", "ReduceMean", "ReduceMin", "ReduceProd", "ReduceSum", 'ReduceSumSquare', "ReduceLogSum", "ReduceLogSumExp", "ReduceL1", "ReduceL2"] for func in funcs: for keepdims in [True, False]: verify_reduce_func(func, np.random.randn(3, 2, 2).astype(np.float32), axis=None, keepdims=keepdims) verify_reduce_func(func, np.random.randn(3, 2, 3).astype(np.float32), axis=None, keepdims=keepdims) verify_reduce_func(func, np.random.randn(3, 3, 3).astype(np.float32), axis=(1,), keepdims=keepdims) verify_reduce_func(func, np.random.randn(3, 3, 3, 1).astype(np.float32), axis=(1, 2), keepdims=keepdims) verify_reduce_func(func, np.random.randn(3, 3, 3, 1).astype(np.float32), axis=(1,), keepdims=keepdims) verify_reduce_func(func, np.random.randn(1, 3, 4, 1).astype(np.float32), axis=(1,), keepdims=keepdims) def verify_split(indata, outdatas, split, axis=0): indata = np.array(indata).astype(np.float32) outdatas = [np.array(o).astype(np.float32) for o in outdatas] if split: split_index = range(len(split)) else: split_index = range(len(outdatas)) node = helper.make_node( 'Split', inputs=['input'], outputs=['output_{}'.format(i) for i in range(len(split_index))], axis=axis, split=split ) graph = helper.make_graph([node], 'split_test', inputs=[helper.make_tensor_value_info("input", TensorProto.FLOAT, list(indata.shape))], outputs=[helper.make_tensor_value_info("output_{}".format(i), TensorProto.FLOAT, list(outdatas[i].shape)) for i in range(len(split_index)) ]) model = helper.make_model(graph, producer_name='split_test') for target, ctx in ctx_list(): output_shape = [o.shape for o in outdatas] output_type = ['float32', 'float32', 'float32'] tvm_out = get_tvm_output( model, indata, target, ctx, output_shape, output_type) for o, t in zip(outdatas, tvm_out): tvm.testing.assert_allclose(o, t) def test_split(): # 1D verify_split([1., 2., 3., 4., 5., 6.], [ [1., 2.], [3., 4.], [5., 6.]], [2, 2, 2], 0) verify_split([1., 2., 3., 4., 5., 6.], [ [1., 2.], [3.], [4., 5., 6.]], [2, 1, 3], 0) # 2D verify_split([[1., 2., 3., 4.], [7., 8., 9., 10.]], [[[1., 2.], [7., 8.]], [[3., 4.], [9., 10.]]], [2, 2], 1) # Split evenly (unstack) verify_split([1, 2, 3], [[1], [2], [3]], False) def test_binary_ops(): in_shape = (1, 2, 3, 3) dtype = "float32" out_shape = in_shape def verify_binary_ops(op, x, y, out_np, x_name='in1', y_name='in2', broadcast=None): if broadcast is None: z = helper.make_node(op, [x_name, y_name], ['out']) else: z = helper.make_node(op, [x_name, y_name], ['out'], broadcast=1) graph = helper.make_graph([z], '_test', inputs=[helper.make_tensor_value_info(x_name, TensorProto.FLOAT, list(in_shape)), helper.make_tensor_value_info(y_name, TensorProto.FLOAT, list(in_shape))], outputs=[helper.make_tensor_value_info("out", TensorProto.FLOAT, list(out_shape))]) model = helper.make_model(graph, producer_name='_test') for target, ctx in ctx_list(): tvm_out = get_tvm_output(model, [x, y], target, ctx) tvm.testing.assert_allclose(out_np, tvm_out, rtol=1e-5, atol=1e-5) x = np.random.uniform(size=in_shape).astype(dtype) y = np.random.uniform(size=in_shape).astype(dtype) z = np.random.uniform(size=(3,)).astype(dtype) verify_binary_ops("Add", x, y, x + y, broadcast=None) verify_binary_ops("Add", x, z, x + z, broadcast=True) verify_binary_ops("Sub", x, y, x - y, broadcast=None) verify_binary_ops("Sub", x, z, x - z, broadcast=True) verify_binary_ops("Mul", x, y, x * y, broadcast=None) verify_binary_ops("Mul", x, z, x * z, broadcast=True) verify_binary_ops("Mul", x, x, x * x, x_name='in1', y_name='in1', broadcast=None) verify_binary_ops("Div", x, y, x / y, broadcast=None) verify_binary_ops("Div", x, z, x / z, broadcast=True) verify_binary_ops("Sum", x, y, x + y, broadcast=None) verify_binary_ops("Greater", x, y, x > y, broadcast=True) verify_binary_ops("Less", x, y, x < y, broadcast=True) verify_binary_ops("Equal", x, y, x == y, broadcast=True) def test_single_ops(): in_shape = (1, 2, 3, 3) dtype = "float32" out_shape = in_shape def verify_single_ops(op, x, out_np, rtol=1e-5, atol=1e-5): z = helper.make_node(op, ['in1'], ['out']) graph = helper.make_graph([z], '_test', inputs=[helper.make_tensor_value_info("in1", TensorProto.FLOAT, list(in_shape)), ], outputs=[helper.make_tensor_value_info("out", TensorProto.FLOAT, list(out_shape))]) model = helper.make_model(graph, producer_name='_test') for target, ctx in ctx_list(): tvm_out = get_tvm_output(model, [x], target, ctx) tvm.testing.assert_allclose(out_np, tvm_out, rtol=rtol, atol=atol) x = np.random.uniform(size=in_shape).astype(dtype) verify_single_ops("Neg", x, -x) verify_single_ops("Abs", x, np.abs(x)) verify_single_ops("Reciprocal", x, 1/x) verify_single_ops("Sqrt", x, np.sqrt(x)) verify_single_ops("Relu", x, np.maximum(x, 0)) verify_single_ops("Exp", x, np.exp(x)) verify_single_ops("Log", x, np.log(x)) verify_single_ops("Log", x, np.log(x)) verify_single_ops("ACos", x, np.arccos(x)) verify_single_ops("ACosh", x, np.arccosh(x)) verify_single_ops("ASin", x, np.arcsin(x)) verify_single_ops("ASinh", x, np.arcsinh(x)) verify_single_ops("ATan", x, np.arctan(x)) verify_single_ops("ATanh", x, np.arctanh(x)) verify_single_ops("Cos", x, np.cos(x)) verify_single_ops("Cosh", x, np.cosh(x)) verify_single_ops("Sin", x, np.sin(x)) verify_single_ops("Sinh", x, np.sinh(x)) verify_single_ops("Tan", x, np.tan(x)) verify_single_ops("Tanh", x, np.tanh(x)) verify_single_ops("Sigmoid", x, 1 / (1 + np.exp(-x))) verify_single_ops("Softsign", x, x / (1 + np.abs(x))) verify_single_ops("SoftPlus", x, np.log(1 + np.exp(x))) def test_leaky_relu(): def leaky_relu_x(x, alpha): return np.where(x >= 0, x, x * alpha) _test_onnx_op_elementwise((2, 4, 5, 6), leaky_relu_x, {'alpha': 0.25}, 'float32', 'LeakyRelu', {'alpha': 0.25}) def test_elu(): def elu_x(x, alpha): return np.where(x > 0, x, alpha * (np.exp(x) - 1.0)) _test_onnx_op_elementwise((2, 4, 5, 6), elu_x, {'alpha': 0.25}, 'float32', 'Elu', {'alpha': 0.25}) def test_selu(): def selu_x(x, alpha, gamma): return gamma * np.where(x > 0, x, alpha * (np.exp(x) - 1.0)) _test_onnx_op_elementwise((2, 4, 5, 6), selu_x, {'alpha': 0.25, 'gamma': 0.3}, 'float32', 'Selu', {'alpha': 0.25, 'gamma': 0.3}) def test_prelu(): def verify_prelu(x_shape, a_shape): node = helper.make_node('PRelu', inputs=['X', 'slope'], outputs=['Y']) graph = helper.make_graph([node], "prelu_test", inputs=[helper.make_tensor_value_info("X", TensorProto.FLOAT, list(x_shape)), helper.make_tensor_value_info("slope", TensorProto.FLOAT, list(a_shape))], outputs=[helper.make_tensor_value_info("Y", TensorProto.FLOAT, list(x_shape))]) model = helper.make_model(graph, producer_name='prelu_test') indata = np.random.uniform(-10, 10, x_shape).astype(np.float32) slopedata = np.random.uniform(-10, 10, a_shape).astype(np.float32) onnx_out = get_onnxruntime_output(model, [indata, slopedata]) for target, ctx in [('llvm', tvm.cpu())]: tvm_out = get_tvm_output(model, [indata, slopedata], target, ctx, list(x_shape), output_dtype='float32') tvm.testing.assert_allclose(onnx_out[0], tvm_out, rtol=1e-05, atol=1e-05) verify_prelu([3,4,5,6], [1, 4, 1, 1]) verify_prelu([1,8,5,6], [1, 8, 1, 1]) verify_prelu([2,12,16,16], [1, 12, 1, 1]) def test_ThresholdedRelu(): def ThresholdedRelu_x(x, alpha): out_np = np.clip(x, alpha, np.inf) out_np[out_np == alpha] = 0 return out_np _test_onnx_op_elementwise((2, 4, 5, 6), ThresholdedRelu_x, {'alpha': 0.25}, 'float32', 'ThresholdedRelu', {'alpha': 0.25}) def test_ScaledTanh(): def ScaledTanh_x(x, alpha, beta): return alpha * np.tanh(beta * x) _test_onnx_op_elementwise((2, 4, 5, 6), ScaledTanh_x, {'alpha': 0.25, 'beta': 0.3}, 'float32', 'ScaledTanh', {'alpha': 0.25, 'beta': 0.3}) def test_ParametricSoftplus(): def ParametricSoftplus_x(x, alpha, beta): return alpha * np.log(np.exp(beta * x) + 1) _test_onnx_op_elementwise((2, 4, 5, 6), ParametricSoftplus_x, {'alpha': 0.25, 'beta': 0.3}, 'float32', 'ParametricSoftplus', {'alpha': 0.25, 'beta': 0.3}) def test_Scale(): def Scale_x(x, scale): return scale * x _test_onnx_op_elementwise((2, 4, 5, 6), Scale_x, {'scale': 0.25}, 'float32', 'Scale', {'scale': 0.25}) def test_LogSoftmax(): _test_onnx_op_elementwise((1, 4), topi.testing.log_softmax_python, {}, 'float32', 'LogSoftmax', {'axis': 1}) def check_torch_conversion(model, input_size): dummy_input = torch.randn(*input_size) file_name = '{}.onnx'.format(model.__name__) # Set verbose=True for more output torch.onnx.export(model(), dummy_input, file_name, export_params=True, verbose=False) onnx_model = onnx.load(file_name) for target, ctx in ctx_list(): input_data = np.random.uniform(size=input_size).astype('int32') c2_out = get_onnxruntime_output(onnx_model, input_data) tvm_out = get_tvm_output(onnx_model, input_data, target, ctx) tvm.testing.assert_allclose(c2_out, tvm_out) def test_resnet(): check_torch_conversion(torchvision.models.resnet18, (1, 3, 224, 224)) # check_torch_conversion(torchvision.models.resnet101, (1,3,224,224)) # def test_alexnet(): # Torch's ONNX export does not support the adaptive pooling used by AlexNet? # check_torch_conversion(torchvision.models.alexnet, (1,3,224,224)) # Torch's ONNX export does not support the adaptive pooling used by vgg16? # def test_vgg16(): # check_torch_conversion(torchvision.models.vgg16, (1,3,224,224)) # TODO(@jroesch): Update Torch + ONNX to support this import. # def test_squeezenet(): # # Torch's ONNX export does not support the max pooling used by Squezenet # check_torch_conversion(torchvision.models.squeezenet1_0, (1,3,224,224)) def test_densenet(): check_torch_conversion(torchvision.models.densenet161, (1, 3, 224, 224)) def test_inception(): check_torch_conversion(torchvision.models.inception_v3, (1, 3, 224, 224)) # TODO(@jroesch): Update Torch + ONNX to support this import. # def test_googlenet(): # check_torch_conversion(torchvision.models.googlenet, (1,3,224,224)) # TODO(@jroesch): Update Torch + ONNX to support this import. # def test_shufflenetv2(): # check_torch_conversion(torchvision.models.shufflenetv2, (1,3,224,224)) def test_sign(): def Sign_x(x): return np.sign(x) _test_onnx_op_elementwise((3, 4, 5, 6), Sign_x, {}, 'float32', 'Sign', {}) def verify_not(indata, dtype): x = indata.astype(dtype) outdata = np.logical_not(x) node = helper.make_node('Not', inputs=['in'], outputs=['out'],) graph = helper.make_graph([node], 'not_test', inputs=[helper.make_tensor_value_info( "in", TensorProto.BOOL, list(x.shape))], outputs=[helper.make_tensor_value_info("out", TensorProto.BOOL, list(outdata.shape))]) model = helper.make_model(graph, producer_name='not_test') for target, ctx in ctx_list(): tvm_out = get_tvm_output(model, [x], target, ctx, outdata.shape) tvm.testing.assert_allclose(outdata, tvm_out) def test_not(): # 2d verify_not(indata=(np.random.randn(3, 4) > 0), dtype=bool) # 3d verify_not(indata=(np.random.randn(3, 4, 5) > 0), dtype=bool) # 4d verify_not(indata=(np.random.randn(3, 4, 5, 6) > 0), dtype=bool) def verify_and(indata, dtype): x = indata[0].astype(dtype) y = indata[1].astype(dtype) outdata = np.logical_and(x, y) node = helper.make_node('And', inputs=['in1', 'in2'], outputs=['out'], ) graph = helper.make_graph([node], 'and_test', inputs=[helper.make_tensor_value_info("in1", TensorProto.BOOL, list(x.shape)), helper.make_tensor_value_info("in2", TensorProto.BOOL, list(y.shape))], outputs=[helper.make_tensor_value_info("out", TensorProto.BOOL, list(outdata.shape))]) model = helper.make_model(graph, producer_name='and_test') for target, ctx in ctx_list(): tvm_out = get_tvm_output(model, [x, y], target, ctx, outdata.shape) tvm.testing.assert_allclose(outdata, tvm_out) def test_and(): # 2d x = (np.random.randn(3, 4) > 0) y = (np.random.randn(3, 4) > 0) verify_and(indata=[x, y], dtype=bool) # 3d x = (np.random.randn(3, 4, 5) > 0) y = (np.random.randn(3, 4, 5) > 0) verify_and(indata=[x, y], dtype=bool) # 4d x = (np.random.randn(3, 4, 5, 6) > 0) y = (np.random.randn(3, 4, 5, 6) > 0) verify_and(indata=[x, y], dtype=bool) # 3d vs 1d x = (np.random.randn(3, 4, 5) > 0) y = (np.random.randn(5) > 0) verify_and(indata=[x, y], dtype=bool) # 3d vs 2d x = (np.random.randn(3, 4, 5) > 0) y = (np.random.randn(4, 5) > 0) verify_and(indata=[x, y], dtype=bool) def verify_tile_v1(indata, outdata, **kwargs): node = helper.make_node('Tile', inputs=['in'], outputs=['out'], **kwargs) graph = helper.make_graph([node], 'tile_test', inputs=[helper.make_tensor_value_info( "in", TensorProto.FLOAT, list(indata.shape))], outputs=[helper.make_tensor_value_info("out", TensorProto.FLOAT, list(outdata.shape))]) model = helper.make_model(graph, producer_name='tile_test') for target, ctx in ctx_list(): tvm_out = get_tvm_output( model, [indata], target, ctx, outdata.shape, opset=1) tvm.testing.assert_allclose(outdata, tvm_out) def verify_tile_v6(indata, repeats, outdata): node = helper.make_node('Tile', inputs=['input', 'repeats'], outputs=['out']) graph = helper.make_graph( [node], 'tile_test', inputs=[ helper.make_tensor_value_info("input", TensorProto.FLOAT, list(indata.shape)), helper.make_tensor_value_info("repeats", TensorProto.INT64, list(repeats.shape)) ], outputs=[ helper.make_tensor_value_info("out", TensorProto.FLOAT, list(outdata.shape)) ], initializer=[ helper.make_tensor("repeats", TensorProto.INT64, list(repeats.shape), repeats) ]) model = helper.make_model(graph, producer_name='tile_test') for target, ctx in ctx_list(): tvm_out = get_tvm_output(model, [indata], target, ctx, outdata.shape, opset=6) tvm.testing.assert_allclose(outdata, tvm_out) def test_tile(): 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) verify_tile_v1(x, z, repeats=repeats) verify_tile_v6(x, repeats, z) def verify_erf(indata, outdata): node = helper.make_node('Erf', inputs=['in'], outputs=['out']) graph = helper.make_graph([node], 'erf_test', inputs=[helper.make_tensor_value_info( 'in', TensorProto.FLOAT, list(indata.shape))], outputs=[helper.make_tensor_value_info('out', TensorProto.FLOAT, list(outdata.shape))]) model = helper.make_model(graph, producer_name='erf_test') for target, ctx in ctx_list(): tvm_out = get_tvm_output(model, [indata], target, ctx, outdata.shape) tvm.testing.assert_allclose(outdata, tvm_out) def test_erf(): x = np.random.rand(2, 3, 4, 6).astype(np.float32) z = scipy.special.erf(x) verify_erf(x, z) def verify_where(condition, x, y, dtype, outdata): node = helper.make_node('Where', inputs=['condition', 'x', 'y'], outputs=['out']) graph = helper.make_graph([node], 'where_test', inputs=[helper.make_tensor_value_info('condition', TensorProto.BOOL, list(condition.shape)), helper.make_tensor_value_info('x', dtype, list(x.shape)), helper.make_tensor_value_info('y', dtype, list(y.shape))], outputs=[helper.make_tensor_value_info('out', dtype, list(outdata.shape))]) model = helper.make_model(graph, producer_name='where_test') for target, ctx in ctx_list(): tvm_out = get_tvm_output(model, [condition, x, y], target, ctx, outdata.shape) tvm.testing.assert_allclose(outdata, tvm_out) def test_where(): condition = np.array([[1, 0], [1, 1]], dtype=np.bool) x = np.array([[1, 2], [3, 4]], dtype=np.int64) y = np.array([[9, 8], [7, 6]], dtype=np.int64) outdata = np.where(condition, x, y) verify_where(condition, x, y, TensorProto.INT64, outdata) x = np.array([[1, 2], [3, 4]], dtype=np.float32) y = np.array([[9, 8], [7, 6]], dtype=np.float32) outdata = np.where(condition, x, y) verify_where(condition, x, y, TensorProto.FLOAT, outdata) x = np.array(1, dtype=np.float32) y = np.array([2], dtype=np.float32) outdata = np.where(condition, x, y) verify_where(condition, x, y, TensorProto.FLOAT, outdata) x = np.array([2], dtype=np.float32) y = np.array(1, dtype=np.float32) outdata = np.where(condition, x, y) verify_where(condition, x, y, TensorProto.FLOAT, outdata) condition = np.array(1, dtype=np.bool) x = np.array([[1, 2], [3, 4]], dtype=np.float32) y = np.array([[5, 6], [7, 8]], dtype=np.float32) outdata = np.where(condition, x, y) verify_where(condition, x, y, TensorProto.FLOAT, outdata) x = np.array([[1, 2], [3, 4]], dtype=np.float32) y = np.array([[1], [7]], dtype=np.float32) outdata = np.where(condition, x, y) verify_where(condition, x, y, TensorProto.FLOAT, outdata) def verify_or(indata, dtype): x = indata[0].astype(dtype) y = indata[1].astype(dtype) outdata = np.logical_or(x, y) node = helper.make_node('Or', inputs=['in1', 'in2'], outputs=['out'], ) graph = helper.make_graph([node], 'or_test', inputs=[helper.make_tensor_value_info("in1", TensorProto.BOOL, list(x.shape)), helper.make_tensor_value_info("in2", TensorProto.BOOL, list(y.shape))], outputs=[helper.make_tensor_value_info("out", TensorProto.BOOL, list(outdata.shape))]) model = helper.make_model(graph, producer_name='or_test') for target, ctx in ctx_list(): tvm_out = get_tvm_output(model, [x, y], target, ctx, outdata.shape) tvm.testing.assert_allclose(outdata, tvm_out) def test_or(): # 2d x = (np.random.randn(3, 4) > 0) y = (np.random.randn(3, 4) > 0) verify_or(indata=[x, y], dtype=bool) # 3d x = (np.random.randn(3, 4, 5) > 0) y = (np.random.randn(3, 4, 5) > 0) verify_or(indata=[x, y], dtype=bool) # 4d x = (np.random.randn(3, 4, 5, 6) > 0) y = (np.random.randn(3, 4, 5, 6) > 0) verify_or(indata=[x, y], dtype=bool) # 3d vs 1d x = (np.random.randn(3, 4, 5) > 0) y = (np.random.randn(5) > 0) verify_or(indata=[x, y], dtype=bool) # 3d vs 2d x = (np.random.randn(3, 4, 5) > 0) y = (np.random.randn(4, 5) > 0) verify_or(indata=[x, y], dtype=bool) def test_batch_norm(): def verify_batch_norm(in_shape): batchnorm = onnx.helper.make_node('BatchNormalization', inputs=["x", "scale", "B", "mean", "var"], outputs=['Y']) graph = helper.make_graph([batchnorm], "batchnorm_test", inputs=[helper.make_tensor_value_info("x", TensorProto.FLOAT, list(in_shape)), helper.make_tensor_value_info("scale", TensorProto.FLOAT, [in_shape[1]]), helper.make_tensor_value_info("B", TensorProto.FLOAT, [in_shape[1]]), helper.make_tensor_value_info("mean", TensorProto.FLOAT, [in_shape[1]]), helper.make_tensor_value_info("var", TensorProto.FLOAT, [in_shape[1]]), ], outputs=[helper.make_tensor_value_info("Y", TensorProto.FLOAT, list(in_shape))]) model = helper.make_model(graph, producer_name='batchnorm_test') for target, ctx in ctx_list(): x = np.random.uniform(size=in_shape).astype('float32') scale = np.random.uniform(size=in_shape[1]).astype('float32') b = np.random.uniform(size=in_shape[1]).astype('float32') mean = np.random.uniform(size=in_shape[1]).astype('float32') var = np.random.uniform(size=in_shape[1]).astype('float32') onnx_out = get_onnxruntime_output(model, [x, scale, b, mean, var], 'float32')[0] tvm_out = get_tvm_output(model, [x, scale, b, mean, var], target, ctx, in_shape, 'float32') tvm.testing.assert_allclose(onnx_out, tvm_out, rtol=1e-5, atol=1e-5) verify_batch_norm([1, 3, 224, 224]) verify_batch_norm([1, 3, 24, 24]) verify_batch_norm([16, 3, 24, 24]) verify_batch_norm([16, 16, 24, 24]) verify_batch_norm([16, 16, 10, 10]) def test_batch_norm_dynamic_subgraph(): def verify_batch_norm_dynamic_subgraph(in_shape, o_shape): batchnorm = onnx.helper.make_node('BatchNormalization', inputs=["x", "scale", "B", "mean", "var"], outputs=['Y']) shape_node = helper.make_node("Shape", ['Y'], ['shape']) reshape_node = helper.make_node("Reshape", ["in", "shape"], ["out"]) graph = helper.make_graph([batchnorm, shape_node, reshape_node], "batchnorm_test", inputs=[helper.make_tensor_value_info("x", TensorProto.FLOAT, list(in_shape)), helper.make_tensor_value_info("in", TensorProto.FLOAT, list(o_shape)), helper.make_tensor_value_info("scale", TensorProto.FLOAT, [in_shape[1]]), helper.make_tensor_value_info("B", TensorProto.FLOAT, [in_shape[1]]), helper.make_tensor_value_info("mean", TensorProto.FLOAT, [in_shape[1]]), helper.make_tensor_value_info("var", TensorProto.FLOAT, [in_shape[1]]), ], outputs=[helper.make_tensor_value_info("out", TensorProto.FLOAT, list(in_shape))]) model = helper.make_model(graph, producer_name='batchnorm_test') for target, ctx in ctx_list(): x = np.random.uniform(size=in_shape).astype('float32') inp = np.random.uniform(size=o_shape).astype('float32') scale = np.random.uniform(size=in_shape[1]).astype('float32') b = np.random.uniform(size=in_shape[1]).astype('float32') mean = np.random.uniform(size=in_shape[1]).astype('float32') var = np.random.uniform(size=in_shape[1]).astype('float32') onnx_out = get_onnxruntime_output(model, [x, inp, scale, b, mean, var], 'float32')[0] tvm_out = get_tvm_output(model, [x, inp, scale, b, mean, var], target, ctx, in_shape, 'float32') tvm.testing.assert_allclose(onnx_out, tvm_out, rtol=1e-5, atol=1e-5) verify_batch_norm_dynamic_subgraph([16, 16, 10, 10], [160, 160]) def verify_conv(x_shape, w_shape, y_shape, padding, kernel_shape, strides, dilations, auto_pad="NOTSET", unset_pad=False): if unset_pad: node = helper.make_node('Conv', inputs=['x', 'W'], outputs=['y'], kernel_shape=kernel_shape, # Default values for other attributes: strides=strides, dilations=dilations, # groups=1 ) elif padding is None: node = helper.make_node('Conv', inputs=['x', 'W'], outputs=['y'], kernel_shape=kernel_shape, # Default values for other attributes: strides=strides, dilations=dilations, # groups=1 auto_pad=auto_pad) else: node = helper.make_node('Conv', inputs=['x', 'W'], outputs=['y'], kernel_shape=kernel_shape, # Default values for other attributes: strides=strides, dilations=dilations, # groups=1 pads=padding) graph = helper.make_graph([node], 'conv_test', inputs=[helper.make_tensor_value_info("x", TensorProto.FLOAT, list(x_shape)), helper.make_tensor_value_info("W", TensorProto.FLOAT, list(w_shape))], outputs=[helper.make_tensor_value_info("y", TensorProto.FLOAT, list(y_shape))]) model = helper.make_model(graph, producer_name='conv_test') for target, ctx in ctx_list(): x = np.random.uniform(size=x_shape).astype('float32') W = np.random.uniform(size=w_shape).astype('float32') tvm_out = get_tvm_output(model, [x, W], target, ctx, y_shape) onnx_out = get_onnxruntime_output(model, [x, W], 'float32')[0] tvm.testing.assert_allclose(onnx_out, tvm_out, rtol=1e-5, atol=1e-5) def test_conv(): def repeat(N, D): return tuple([N for _ in range(D)]) for D in [1, 2, 3]: # Convolution with padding verify_conv((1, 1) + repeat(5, D), (1, 1) + repeat(3, D), (1, 1) + repeat(5, D), 2 * repeat(1, D), repeat(3, D), repeat(1, D), repeat(1, D)) # Convolution without padding verify_conv((1, 1) + repeat(5, D), (1, 1) + repeat(3, D), (1, 1) + repeat(3, D), 2 * repeat(0, D), repeat(3, D), repeat(1, D), repeat(1, D)) # Convolution with autopadding verify_conv((1, 1) + repeat(5, D), (1, 1) + repeat(3, D), (1, 1) + repeat(5, D), None, repeat(3, D), repeat(1, D), repeat(1, D), auto_pad="SAME_UPPER") # Convolution with unset padding verify_conv((1, 1) + repeat(5, D), (1, 1) + repeat(3, D), (1, 1) + repeat(3, D), 2 * repeat(0, D), repeat(3, D), repeat(1, D), repeat(1, D), True) # Convolution with non uniform stride verify_conv((1, 1) + repeat(5, D), (1, 1) + repeat(3, D), (1, 1) + repeat(3, D), None, repeat(3, D), repeat(2, D), repeat(1, D), auto_pad="SAME_UPPER") # Convolution with dilation verify_conv((1, 1) + repeat(5, D), (1, 1) + repeat(3, D), (1, 1) + repeat(5, D), 2 * repeat(2, D), repeat(3, D), repeat(1, D), repeat(2, D)) def verify_convtranspose(x_shape, w_shape, y_shape, p): node = onnx.helper.make_node("ConvTranspose", inputs=["x", "W"], outputs=['y'], strides=[3, 2], group=1, kernel_shape=[3, 3], pads=p) graph = helper.make_graph([node], 'verify_convtranspose_test', inputs=[helper.make_tensor_value_info("x", TensorProto.FLOAT, list(x_shape)), helper.make_tensor_value_info("W", TensorProto.FLOAT, list(w_shape))], outputs=[helper.make_tensor_value_info("y", TensorProto.FLOAT, list(y_shape))]) model = helper.make_model(graph, producer_name='convtranspose_trest') for target, ctx in ctx_list(): x = np.random.uniform(size=x_shape).astype('float32') W = np.random.uniform(size=w_shape).astype('float32') tvm_out = get_tvm_output(model, [x, W], target, ctx, y_shape) onnx_out = get_onnxruntime_output(model, [x, W], 'float32')[0] tvm.testing.assert_allclose(onnx_out, tvm_out, rtol=1e-5, atol=1e-5) def test_convtranspose(): # Convolution Transpose with padding # (1, 1, 3, 3) input tensor # (1, 2, 3, 3) tensor for convolution weights # (1, 2, 7, 3) output tensor # [1, 2, 1, 2] list for pads verify_convtranspose((1, 1, 3, 3), (1, 2, 3, 3), (1, 2, 7, 3), [1, 2, 1, 2]) def test_unsqueeze_constant(): from torch.nn import Linear, Sequential, Module class Flatten(Module): def forward(self, input): return input.view(input.size(0), -1) import tempfile with tempfile.NamedTemporaryFile() as fp: file_name = fp.name input_size = (1, 16, 32, 32) dummy_input = torch.randn(*input_size) layer = Sequential(Flatten(), Linear(16 * 32 * 32, 64)) torch.onnx.export(layer, dummy_input, file_name, export_params=True) onnx_model = onnx.load(file_name) relay.frontend.from_onnx(onnx_model, {'0': input_size}) def verify_pooling(x_shape, kernel_shape, strides, pads, out_shape, mode, auto_pad="NOTSET"): x_np = np.random.uniform(size=x_shape).astype('float32') if mode == 'max': node_type = "MaxPool" elif mode == 'average': node_type = "AveragePool" else: raise ValueError("Pool method {} is not supported.".format(mode)) pool_node = helper.make_node( node_type, inputs=["x"], outputs=["y"], kernel_shape=kernel_shape, strides=strides) if pads is None: pad_attr = helper.make_attribute('auto_pad', auto_pad) else: pad_attr = helper.make_attribute('pads', pads) pool_node.attribute.append(pad_attr) if mode == 'max': storage_attr = helper.make_attribute('storage_order', 0) pool_node.attribute.append(storage_attr) graph = helper.make_graph([pool_node], "pooling_test", inputs=[helper.make_tensor_value_info("x", TensorProto.FLOAT, list(x_shape))], outputs=[helper.make_tensor_value_info("y", TensorProto.FLOAT, list(out_shape))]) model = helper.make_model(graph, producer_name='pooling_test') for target, ctx in ctx_list(): onnx_out = get_onnxruntime_output(model, x_np, 'float32') tvm_out = get_tvm_output( model, [x_np], target, ctx, out_shape) tvm.testing.assert_allclose(onnx_out, tvm_out, rtol=1e-5, atol=1e-5) def test_pooling(): for mode in ['max', 'average']: # Pool1D verify_pooling(x_shape=[1, 1, 32], kernel_shape=[3], strides=[1], pads=[1, 1], out_shape=[1, 1, 32], mode=mode) # Pool2D verify_pooling(x_shape=[1, 1, 32, 32], kernel_shape=[3, 3], strides=[1, 1], pads=[1, 1, 1, 1], out_shape=[1, 1, 32, 32], mode=mode) # Pool1D with stride verify_pooling(x_shape=[1, 1, 32], kernel_shape=[3], strides=[2], pads=[1, 1], out_shape=[1, 1, 16], mode=mode) # Pool2D with stride verify_pooling(x_shape=[1, 1, 32, 32], kernel_shape=[3, 3], strides=[2, 2], pads=[1, 1, 1, 1], out_shape=[1, 1, 16, 16], mode=mode) # Pool1D with stride and autopadding verify_pooling(x_shape=[1, 1, 32], kernel_shape=[3], strides=[2], pads=None, out_shape=[1, 1, 16], mode=mode, auto_pad='SAME_UPPER') # Pool2D with stride and autopadding verify_pooling(x_shape=[1, 1, 32, 32], kernel_shape=[3, 3], strides=[2, 2], pads=None, out_shape=[1, 1, 16, 16], mode=mode, auto_pad='SAME_UPPER') # Pool3D with stride verify_pooling(x_shape=[1, 1, 32, 32, 32], kernel_shape=[3, 3, 3], strides=[2, 2, 2], pads=[1, 1, 1, 1, 1, 1], out_shape=[1, 1, 16, 16, 16], mode=mode) # Pool3D with stride and autopadding verify_pooling(x_shape=[1, 1, 32, 32, 32], kernel_shape=[3, 3, 3], strides=[2, 2, 2], pads=None, out_shape=[1, 1, 16, 16, 16], mode=mode, auto_pad='SAME_UPPER') def verify_mod(x_shape, y_shape, fmod, dtype='float32'): x_np = np.random.uniform(size=x_shape).astype(dtype) y_np = np.random.uniform(size=y_shape).astype(dtype) y_np = np.where(y_np==0, 1, y_np) #remove 0's to avoid division by zero error if fmod: np_out = np.fmod(x_np, y_np) else: np_out = np.mod(x_np, y_np) out_shape = np_out.shape mod_node = helper.make_node("Mod", inputs=["x", "y"], outputs=["z"], fmod=fmod) onnx_dtype = TensorProto.FLOAT if dtype == "float32" else TensorProto.INT32 graph = helper.make_graph([mod_node], "mod_test", inputs=[helper.make_tensor_value_info("x", onnx_dtype, list(x_shape)), helper.make_tensor_value_info("y", onnx_dtype, list(y_shape))], outputs=[helper.make_tensor_value_info("z", onnx_dtype, list(out_shape))]) model = helper.make_model(graph, producer_name='mod_test') for target, ctx in ctx_list(): tvm_out = get_tvm_output( model, [x_np, y_np], target, ctx, out_shape) tvm.testing.assert_allclose(np_out, tvm_out, rtol=1e-5, atol=1e-5) def test_mod(): # Mod verify_mod(x_shape=[1, 32, 32], y_shape=[1, 32, 32], fmod=0) verify_mod(x_shape=[1, 32, 32], y_shape=[1, 1, 32], fmod=0, dtype="int32") # fmod verify_mod(x_shape=[1, 1, 32], y_shape=[1, 32, 32], fmod=1) verify_mod(x_shape=[1, 32, 32], y_shape=[1, 32, 32], fmod=1, dtype="int32") def verify_xor(x_shape, y_shape): x_np = np.random.choice(a=[False, True], size=x_shape).astype("bool") y_np = np.random.choice(a=[False, True], size=y_shape).astype("bool") np_out = np.logical_xor(x_np, y_np) out_shape = np_out.shape xor_node = helper.make_node("Xor", inputs=["x", "y"], outputs=["z"]) onnx_dtype = TensorProto.BOOL graph = helper.make_graph([xor_node], "xor_test", inputs=[helper.make_tensor_value_info("x", onnx_dtype, list(x_shape)), helper.make_tensor_value_info("y", onnx_dtype, list(y_shape))], outputs=[helper.make_tensor_value_info("z", onnx_dtype, list(out_shape))]) model = helper.make_model(graph, producer_name='xor_test') for target, ctx in ctx_list(): tvm_out = get_tvm_output( model, [x_np, y_np], target, ctx, out_shape) tvm.testing.assert_allclose(np_out, tvm_out, rtol=1e-5, atol=1e-5) def test_xor(): # XOR verify_xor(x_shape=[1, 32, 32], y_shape=[1, 32, 32]) # Xor broadcast verify_xor(x_shape=[1, 32, 32], y_shape=[1, 1, 32]) def verify_max_roi_pool(x_shape, rois_shape, pooled_shape, spatial_scale, out_shape): x_np = np.random.uniform(size=x_shape).astype('float32') rois_np = np.random.uniform(size=rois_shape).astype('float32') if spatial_scale is None: pool_node = helper.make_node("MaxRoiPool", inputs=["x", "rois"], outputs=["y"], pooled_shape=pooled_shape) else: pool_node = helper.make_node("MaxRoiPool", inputs=["x", "rois"], outputs=["y"], pooled_shape=pooled_shape, spatial_scale=spatial_scale) graph = helper.make_graph([pool_node], "pool_test", inputs=[helper.make_tensor_value_info("x", TensorProto.FLOAT, list(x_shape)), helper.make_tensor_value_info("rois", TensorProto.FLOAT, list(rois_shape))], outputs=[helper.make_tensor_value_info("y", TensorProto.FLOAT, list(out_shape))]) model = helper.make_model(graph, producer_name='pool_test') onnx_out = get_onnxruntime_output(model, [x_np, rois_np], 'float32')[0] for target, ctx in ctx_list(): tvm_out = get_tvm_output( model, [x_np, rois_np], target, ctx, out_shape) tvm.testing.assert_allclose(onnx_out, tvm_out, rtol=1e-5, atol=1e-5) def test_max_roi_pool(): verify_max_roi_pool(x_shape=[1, 3, 6, 6], rois_shape=[3, 5], pooled_shape=[1, 1], spatial_scale=None, out_shape=[3, 3, 1, 1]) verify_max_roi_pool(x_shape=[1, 3, 10, 10], rois_shape=[4, 5], pooled_shape=[2, 2], spatial_scale=2.0, out_shape=[4, 3, 2, 2]) def verify_lppool(x_shape, kernel_shape, p, strides, pads, out_shape, auto_pad="NOTSET"): x_np = np.random.uniform(size=x_shape).astype('float32') if pads is None: pool_node = helper.make_node("LpPool", inputs=["x"], outputs=["y"], kernel_shape=kernel_shape, p = p, auto_pad=auto_pad, strides=strides) else: pool_node = helper.make_node("LpPool", inputs=["x"], outputs=["y"], kernel_shape=kernel_shape, p = p, pads=pads, strides=strides) graph = helper.make_graph([pool_node], "lppool_test", inputs=[helper.make_tensor_value_info("x", TensorProto.FLOAT, list(x_shape))], outputs=[helper.make_tensor_value_info("y", TensorProto.FLOAT, list(out_shape))]) model = helper.make_model(graph, producer_name='lppool_test') for target, ctx in ctx_list(): onnx_out = get_onnxruntime_output(model, x_np, 'float32') tvm_out = get_tvm_output( model, [x_np], target, ctx, out_shape) tvm.testing.assert_allclose(onnx_out, tvm_out, rtol=1e-5, atol=1e-5) def test_lppool(): # Pool1D verify_lppool(x_shape=[1, 1, 32], kernel_shape=[3], p=2, strides=[1], pads=[1, 1], out_shape=[1, 1, 32]) # Pool2D verify_lppool(x_shape=[1, 1, 32, 32], kernel_shape=[3, 3], p=2, strides=[1, 1], pads=[1, 1, 1, 1], out_shape=[1, 1, 32, 32]) # Pool1D with stride verify_lppool(x_shape=[1, 1, 32], kernel_shape=[3], p=2, strides=[2], pads=[1, 1], out_shape=[1, 1, 16]) # Pool2D with stride verify_lppool(x_shape=[1, 1, 32, 32], kernel_shape=[3, 3], p=2, strides=[2, 2], pads=[1, 1, 1, 1], out_shape=[1, 1, 16, 16]) # Pool1D with stride and autopadding verify_lppool(x_shape=[1, 1, 32], kernel_shape=[3], p=2, strides=[2], pads=None, out_shape=[1, 1, 16], auto_pad='SAME_UPPER') # Pool2D with stride and autopadding verify_lppool(x_shape=[1, 1, 32, 32], kernel_shape=[3, 3], p=2, strides=[2, 2], pads=None, out_shape=[1, 1, 16, 16], auto_pad='SAME_UPPER') # Pool3D with stride verify_lppool(x_shape=[1, 1, 32, 32, 32], kernel_shape=[3, 3, 3], p=2, strides=[2, 2, 2], pads=[1, 1, 1, 1, 1, 1], out_shape=[1, 1, 16, 16, 16]) # Pool3D with stride and autopadding verify_lppool(x_shape=[1, 1, 32, 32, 32], kernel_shape=[3, 3, 3], p=2, strides=[2, 2, 2], pads=None, out_shape=[1, 1, 16, 16, 16], auto_pad='SAME_UPPER') def verify_lstm(seq_length, batch_size, input_size, hidden_size, use_bias=False, activations=None, alphas=None, betas=None, use_initial_state=False, use_peep=False): x_np = np.random.uniform(size=(seq_length, batch_size, input_size)).astype('float32') w_np = np.random.uniform(size=(1, 4 * hidden_size, input_size)).astype('float32') r_np = np.random.uniform(size=(1, 4 * hidden_size, hidden_size)).astype('float32') input_names = ["X", "W", "R"] input_tensors = [ helper.make_tensor_value_info("X", TensorProto.FLOAT, list(x_np.shape)), helper.make_tensor_value_info("W", TensorProto.FLOAT, list(w_np.shape)), helper.make_tensor_value_info("R", TensorProto.FLOAT, list(r_np.shape)) ] input_values = [x_np, w_np, r_np] if use_bias: b_np = np.random.uniform(size=(1, 8 * hidden_size)).astype('float32') input_names.append("B") input_tensors.append( helper.make_tensor_value_info("B", TensorProto.FLOAT, [1, 8 * hidden_size])) input_values.append(b_np) if use_initial_state: assert use_bias == True, "Initial states must have bias specified." sequence_np = np.repeat(seq_length, batch_size).astype('int32') input_names.append("sequence_lens") input_tensors.append(helper.make_tensor_value_info("sequence_lens", TensorProto.INT32, [batch_size])) input_values.append(sequence_np) initial_h_np = np.random.uniform(size=(1, batch_size, hidden_size)).astype('float32') input_names.append("initial_h") input_tensors.append( helper.make_tensor_value_info("initial_h", TensorProto.FLOAT, [1, batch_size, hidden_size])) input_values.append(initial_h_np) initial_c_np = np.random.uniform(size=(1, batch_size, hidden_size)).astype('float32') input_names.append("initial_c") input_tensors.append( helper.make_tensor_value_info("initial_c", TensorProto.FLOAT, [1, batch_size, hidden_size])) input_values.append(initial_c_np) if use_peep: assert use_initial_state == True, "Peepholes require initial state to be specified." p_np = np.random.uniform(size=(1, 3 * hidden_size)).astype('float32') input_names.append("P") input_tensors.append( helper.make_tensor_value_info("P", TensorProto.FLOAT, [1, 3 * hidden_size])) input_values.append(p_np) Y_shape = [seq_length, 1, batch_size, hidden_size] Y_h_shape = [1, batch_size, hidden_size] Y_c_shape = [1, batch_size, hidden_size] if activations is None: lstm_node = helper.make_node( 'LSTM', inputs=input_names, outputs=["Y", "Y_h", "Y_c"], hidden_size=hidden_size) elif alphas is None: lstm_node = helper.make_node( 'LSTM', inputs=input_names, outputs=["Y", "Y_h", "Y_c"], hidden_size=hidden_size, activations=activations) else: lstm_node = helper.make_node( 'LSTM', inputs=input_names, outputs=["Y", "Y_h", "Y_c"], hidden_size=hidden_size, activations=activations, activation_alpha=alphas, activation_beta=betas) graph = helper.make_graph([lstm_node], "lstm_test", inputs=input_tensors, outputs=[ helper.make_tensor_value_info("Y", TensorProto.FLOAT, list(Y_shape)), helper.make_tensor_value_info("Y_h", TensorProto.FLOAT, list(Y_h_shape)), helper.make_tensor_value_info("Y_c", TensorProto.FLOAT, list(Y_c_shape)) ]) model = helper.make_model(graph, producer_name='lstm_test') for target, ctx in ctx_list(): onnx_out = get_onnxruntime_output(model, input_values, 'float32') tvm_out = get_tvm_output( model, input_values, target, ctx, [Y_shape, Y_h_shape, Y_c_shape], output_dtype=['float32', 'float32', 'float32']) for o_out, t_out in zip(onnx_out, tvm_out): tvm.testing.assert_allclose(o_out, t_out, rtol=5e-3, atol=5e-3) def test_lstm(): # No bias. verify_lstm(seq_length=2, batch_size=1, input_size=16, hidden_size=32, use_bias=False) # large batch. verify_lstm(seq_length=4, batch_size=8, input_size=16, hidden_size=32, use_bias=True) # Non power of two. verify_lstm(seq_length=3, batch_size=3, input_size=16, hidden_size=40, use_bias=True) # Long sequence. verify_lstm(seq_length=8, batch_size=1, input_size=16, hidden_size=32, use_bias=True) # Large hidden. verify_lstm(seq_length=2, batch_size=1, input_size=16, hidden_size=128, use_bias=True) # Large input. verify_lstm(seq_length=2, batch_size=1, input_size=64, hidden_size=32, use_bias=True) # Different activation testing. # Default value hardsigmoid. verify_lstm( seq_length=2, batch_size=1, input_size=16, hidden_size=32, use_bias=False, activations=['HardSigmoid', 'Tanh', 'Tanh']) # Multiple parameterized activations. verify_lstm( seq_length=2, batch_size=1, input_size=16, hidden_size=32, use_bias=False, activations=['HardSigmoid', 'LeakyRelu', 'Tanh'], alphas=[2.0, 0.5], betas=[.3]) # All parameterized with new Affine activation. verify_lstm( seq_length=2, batch_size=1, input_size=16, hidden_size=32, use_bias=False, activations=['HardSigmoid', 'LeakyRelu', 'Affine'], alphas=[2.0, 0.5, 0.8], betas=[.3, 0.1]) # Testing with initial state and peepholes verify_lstm( seq_length=2, batch_size=1, input_size=16, hidden_size=32, use_bias=True, use_initial_state=True) verify_lstm( seq_length=2, batch_size=1, input_size=16, hidden_size=32, use_bias=True, use_initial_state=True, use_peep=True) def test_resize(): def make_constant_node(name, data_type, dims, vals): return helper.make_node('Constant', inputs=[], outputs=[name], value=helper.make_tensor(name=name, data_type=data_type, dims=dims, vals=vals)) def verify(ishape, oshape, scales, mode, coord_trans): nodes = [ make_constant_node('roi', onnx.TensorProto.FLOAT, (0,), []), make_constant_node('scales', onnx.TensorProto.FLOAT, (len(scales),), scales) ] input_names = ['X', 'roi', 'scales'] if oshape != []: nodes.append(make_constant_node('sizes', onnx.TensorProto.INT64, (len(oshape),), oshape)) input_names.append('sizes') nodes.append(helper.make_node( 'Resize', inputs=input_names, outputs=['Y'], mode=mode, coordinate_transformation_mode=coord_trans )) if oshape == []: oshape = [round(dim * scale) for (dim, scale) in zip(ishape, scales)] graph = helper.make_graph(nodes, "resize_test", inputs=[helper.make_tensor_value_info("X", TensorProto.FLOAT, ishape)], outputs=[helper.make_tensor_value_info("Y", TensorProto.FLOAT, oshape)]) model = helper.make_model(graph, producer_name='resize_test') for target, ctx in ctx_list(): x = np.random.uniform(size=ishape).astype('float32') onnx_out = get_onnxruntime_output(model, x, 'float32') tvm_out = get_tvm_output(model, x, target, ctx, oshape, 'float32', opset=11) tvm.testing.assert_allclose(onnx_out, tvm_out, rtol=1e-05, atol=1e-05) # upsampling verify([1, 16, 32, 32], [1, 16, 64, 64], [], "nearest", "asymmetric") verify([1, 16, 32, 32], [1, 16, 64, 64], [], "linear", "align_corners") verify([1, 16, 32, 32], [1, 16, 64, 64], [], "linear", "half_pixel") # downsampling verify([1, 16, 32, 32], [1, 16, 16, 16], [], "nearest", "asymmetric") verify([1, 16, 32, 32], [1, 16, 16, 16], [], "linear", "align_corners") verify([1, 16, 32, 32], [1, 16, 16, 16], [], "linear", "half_pixel") # scales are specified instead of sizes verify([1, 16, 32, 32], [], [1, 1, 2, 2], "nearest", "asymmetric") verify([1, 16, 32, 32], [], [1, 1, 0.5, 0.5], "linear", "half_pixel") def test_nonzero(): def verify_nonzero(indata, outdata, dtype): node = helper.make_node('NonZero', inputs=['X'], outputs=['Y'],) graph = helper.make_graph([node], "nonzero_test", inputs=[helper.make_tensor_value_info("X", TensorProto.INT64, list(indata.shape))], outputs=[helper.make_tensor_value_info("Y", TensorProto.INT64, list(outdata.shape))]) model = helper.make_model(graph, producer_name='nonzero_test') onnx_out = get_onnxruntime_output(model, indata, dtype) for target, ctx in [('llvm', tvm.cpu())]: tvm_out = get_tvm_output_with_vm(model, indata, target, ctx, opset=9) tvm.testing.assert_allclose(onnx_out, tvm_out, rtol=1e-05, atol=1e-05) input_data = np.array([[1, 0], [1, 1]], dtype=np.int64) result = np.array((np.nonzero(input_data))) # expected output [[0, 1, 1], [0, 0, 1]] verify_nonzero(input_data, result, dtype=np.int64) input_data = np.array([[3, 0, 0], [0, 4, 0], [5, 6, 0]], dtype=np.int64) result = np.array((np.nonzero(input_data))) # expected output [[0, 1, 2, 2], [0, 1, 0, 1]] verify_nonzero(input_data, result, dtype=np.int64) def test_topk(): def verify_topk(input_dims, K, axis=-1): output_dims = list(input_dims) output_dims[axis] = K node = helper.make_node('TopK', inputs=['X', 'K'], outputs=['Values', 'Indicies'], axis=axis) graph = helper.make_graph([node], "topk_test", inputs=[helper.make_tensor_value_info("X", TensorProto.FLOAT, list(input_dims)), helper.make_tensor_value_info("K", TensorProto.INT64, [1,])], initializer=[helper.make_tensor("K", TensorProto.INT64, [1], [K])], outputs=[helper.make_tensor_value_info("Values", TensorProto.FLOAT, output_dims), helper.make_tensor_value_info("Indicies", TensorProto.INT64, output_dims)]) model = helper.make_model(graph, producer_name='topk_test') indata = np.random.uniform(-10, 10, input_dims).astype(np.float32) onnx_out = get_onnxruntime_output(model, [indata, k]) for target, ctx in [('llvm', tvm.cpu())]: tvm_out = get_tvm_output(model, indata, target, ctx, [output_dims, output_dims], output_dtype=['float32', 'int64']) tvm.testing.assert_allclose(onnx_out, tvm_out, rtol=1e-05, atol=1e-05) for n in [12, 32]: for shape in [[n], [n, n], [n, n, n]]: for k in [1, 5, 10]: verify_topk(shape, k) verify_topk([n, n, n], 5, 0) verify_topk([n, n, n], 5, 1) verify_topk([n, n, n], 5, 2) def test_roi_align(): def verify_roi_align(input_dims, num_roi, output_height, output_width, sampling_ratio=0, spatial_scale=1.0): output_dims = [num_roi, input_dims[1], output_height, output_width] node = helper.make_node('RoiAlign', inputs=['X', 'rois', 'batch_indicies'], outputs=['Y'], mode="avg", output_height=output_height, output_width=output_width, sampling_ratio=sampling_ratio, spatial_scale=spatial_scale, ) graph = helper.make_graph([node], "roialign_test", inputs=[helper.make_tensor_value_info("X", TensorProto.FLOAT, list(input_dims)), helper.make_tensor_value_info( "rois", TensorProto.FLOAT, [num_roi, 4]), helper.make_tensor_value_info( "batch_indicies", TensorProto.INT64, [num_roi, ]), ], outputs=[helper.make_tensor_value_info("Y", TensorProto.FLOAT, output_dims)]) model = helper.make_model(graph, producer_name='roialign_test') np_data =
np.random.uniform(size=input_dims)
numpy.random.uniform
# -*- coding: utf-8 -*- """Symbolic Fourier Approximation (SFA) Transformer. Configurable SFA transform for discretising time series into words. """ __author__ = ["<NAME>", "<NAME>"] __all__ = ["SFA"] import math import sys import warnings import numpy as np import pandas as pd from joblib import Parallel, delayed from numba import NumbaTypeSafetyWarning, njit, types from numba.typed import Dict from sklearn.feature_selection import f_classif from sklearn.preprocessing import KBinsDiscretizer from sklearn.tree import DecisionTreeClassifier from sktime.transformations.base import _PanelToPanelTransformer from sktime.utils.validation.panel import check_X # The binning methods to use: equi-depth, equi-width, information gain or kmeans binning_methods = {"equi-depth", "equi-width", "information-gain", "kmeans"} # TODO remove imag-part from dc-component component class SFA(_PanelToPanelTransformer): """Symbolic Fourier Approximation (SFA) Transformer. Overview: for each series: run a sliding window across the series for each window shorten the series with DFT discretise the shortened series into bins set by MFC form a word from these discrete values by default SFA produces a single word per series (window_size=0) if a window is used, it forms a histogram of counts of words. Parameters ---------- word_length: int, default = 8 length of word to shorten window to (using PAA) alphabet_size: int, default = 4 number of values to discretise each value to window_size: int, default = 12 size of window for sliding. Input series length for whole series transform norm: boolean, default = False mean normalise words by dropping first fourier coefficient binning_method: {"equi-depth", "equi-width", "information-gain", "kmeans"}, default="equi-depth" the binning method used to derive the breakpoints. anova: boolean, default = False If True, the Fourier coefficient selection is done via a one-way ANOVA test. If False, the first Fourier coefficients are selected. Only applicable if labels are given bigrams: boolean, default = False whether to create bigrams of SFA words skip_grams: boolean, default = False whether to create skip-grams of SFA words remove_repeat_words: boolean, default = False whether to use numerosity reduction (default False) levels: int, default = 1 Number of spatial pyramid levels save_words: boolean, default = False whether to save the words generated for each series (default False) return_pandas_data_series: boolean, default = False set to true to return Pandas Series as a result of transform. setting to true reduces speed significantly but is required for automatic test. n_jobs: int, optional, default = 1 The number of jobs to run in parallel for both `transform`. ``-1`` means using all processors. Attributes ---------- words: [] breakpoints: = [] num_insts = 0 num_atts = 0 References ---------- .. [1] Schäfer, Patrick, and <NAME>. "SFA: a symbolic fourier approximation and index for similarity search in high dimensional datasets." Proceedings of the 15th international conference on extending database technology. 2012. """ _tags = {"univariate-only": True} def __init__( self, word_length=8, alphabet_size=4, window_size=12, norm=False, binning_method="equi-depth", anova=False, bigrams=False, skip_grams=False, remove_repeat_words=False, levels=1, lower_bounding=True, save_words=False, keep_binning_dft=False, return_pandas_data_series=False, use_fallback_dft=False, typed_dict=False, n_jobs=1, ): self.words = [] self.breakpoints = [] # we cannot select more than window_size many letters in a word offset = 2 if norm else 0 self.dft_length = window_size - offset if anova is True else word_length # make dft_length an even number (same number of reals and imags) self.dft_length = self.dft_length + self.dft_length % 2 self.support = np.array(list(range(word_length))) self.word_length = word_length self.alphabet_size = alphabet_size self.window_size = window_size self.lower_bounding = lower_bounding self.inverse_sqrt_win_size = ( 1.0 / math.sqrt(window_size) if not lower_bounding else 1.0 ) self.norm = norm self.remove_repeat_words = remove_repeat_words self.save_words = save_words self.keep_binning_dft = keep_binning_dft self.binning_dft = None self.levels = levels self.binning_method = binning_method self.anova = anova self.bigrams = bigrams self.skip_grams = skip_grams self.return_pandas_data_series = return_pandas_data_series self.use_fallback_dft = ( use_fallback_dft if word_length < window_size - offset else True ) self.typed_dict = typed_dict self.n_jobs = n_jobs self.n_instances = 0 self.series_length = 0 self.letter_bits = 0 self.letter_max = 0 self.word_bits = 0 self.max_bits = 0 self.level_bits = 0 self.level_max = 0 super(SFA, self).__init__() def fit(self, X, y=None): """Calculate word breakpoints using MCB or IGB. Parameters ---------- X : pandas DataFrame or 3d numpy array, input time series. y : array_like, target values (optional, ignored). Returns ------- self: object """ if self.alphabet_size < 2: raise ValueError("Alphabet size must be an integer greater than 2") if self.word_length < 1: raise ValueError("Word length must be an integer greater than 1") if self.binning_method == "information-gain" and y is None: raise ValueError( "Class values must be provided for information gain binning" ) if self.binning_method not in binning_methods: raise TypeError("binning_method must be one of: ", binning_methods) self.letter_bits = math.ceil(math.log2(self.alphabet_size)) self.letter_max = pow(2, self.letter_bits) - 1 self.word_bits = self.word_length * self.letter_bits self.max_bits = ( self.word_bits * 2 if self.bigrams or self.skip_grams else self.word_bits ) if self.typed_dict and self.max_bits > 64: raise ValueError( "Typed Dictionaries can only handle 64 bit words. " "ceil(log2(alphabet_size)) * word_length must be less than or equal " "to 64." "With bi-grams or skip-grams enabled, this bit limit is 32." ) if self.typed_dict and self.levels > 15: raise ValueError( "Typed Dictionaries can only handle 15 levels " "(this is way to many anyway)." ) X = check_X(X, enforce_univariate=True, coerce_to_numpy=True) X = X.squeeze(1) if self.levels > 1: quadrants = 0 for i in range(self.levels): quadrants += pow(2, i) self.level_bits = math.ceil(math.log2(quadrants)) self.level_max = pow(2, self.level_bits) - 1 self.n_instances, self.series_length = X.shape self.breakpoints = self._binning(X, y) self._is_fitted = True return self def transform(self, X, y=None): """Transform data into SFA words. Parameters ---------- X : pandas DataFrame or 3d numpy array, input time series. y : array_like, target values (optional, ignored). Returns ------- List of dictionaries containing SFA words """ self.check_is_fitted() X = check_X(X, enforce_univariate=True, coerce_to_numpy=True) X = X.squeeze(1) with warnings.catch_warnings(): warnings.simplefilter("ignore", category=NumbaTypeSafetyWarning) transform = Parallel(n_jobs=self.n_jobs)( delayed(self._transform_case)( X[i, :], supplied_dft=self.binning_dft[i] if self.keep_binning_dft else None, ) for i in range(X.shape[0]) ) dim, words = zip(*transform) if self.save_words: self.words = list(words) # cant pickle typed dict if self.typed_dict and self.n_jobs != 1: nl = [None] * len(dim) for i, pdict in enumerate(dim): ndict = ( Dict.empty( key_type=types.UniTuple(types.int64, 2), value_type=types.uint32 ) if self.levels > 1 else Dict.empty(key_type=types.int64, value_type=types.uint32) ) for key, val in pdict.items(): ndict[key] = val nl[i] = pdict dim = nl bags = pd.DataFrame() if self.return_pandas_data_series else [None] bags[0] = list(dim) return bags def _transform_case(self, X, supplied_dft=None): if supplied_dft is None: dfts = self._mft(X) else: dfts = supplied_dft if self.typed_dict: bag = ( Dict.empty( key_type=types.UniTuple(types.int64, 2), value_type=types.uint32 ) if self.levels > 1 else Dict.empty(key_type=types.int64, value_type=types.uint32) ) else: bag = {} last_word = -1 repeat_words = 0 words = ( np.zeros(dfts.shape[0], dtype=np.int64) if self.word_bits <= 64 else [0 for _ in range(dfts.shape[0])] ) for window in range(dfts.shape[0]): word_raw = ( SFA._create_word( dfts[window], self.word_length, self.alphabet_size, self.breakpoints, self.letter_bits, ) if self.word_bits <= 64 else self._create_word_large( dfts[window], ) ) words[window] = word_raw repeat_word = ( self._add_to_pyramid( bag, word_raw, last_word, window - int(repeat_words / 2) ) if self.levels > 1 else self._add_to_bag(bag, word_raw, last_word) ) if repeat_word: repeat_words += 1 else: last_word = word_raw repeat_words = 0 if self.bigrams: if window - self.window_size >= 0: bigram = self._create_bigram_words( word_raw, words[window - self.window_size] ) if self.levels > 1: if self.typed_dict: bigram = (bigram, -1) else: bigram = (bigram << self.level_bits) | 0 bag[bigram] = bag.get(bigram, 0) + 1 if self.skip_grams: # creates skip-grams, skipping every (s-1)-th word in-between for s in range(2, 4): if window - s * self.window_size >= 0: skip_gram = self._create_bigram_words( word_raw, words[window - s * self.window_size] ) if self.levels > 1: if self.typed_dict: skip_gram = (skip_gram, -1) else: skip_gram = (skip_gram << self.level_bits) | 0 bag[skip_gram] = bag.get(skip_gram, 0) + 1 # cant pickle typed dict if self.typed_dict and self.n_jobs != 1: pdict = dict() for key, val in bag.items(): pdict[key] = val bag = pdict return [ pd.Series(bag) if self.return_pandas_data_series else bag, words if self.save_words else [], ] def _binning(self, X, y=None): num_windows_per_inst = math.ceil(self.series_length / self.window_size) dft = np.array( [ self._binning_dft(X[i, :], num_windows_per_inst) for i in range(self.n_instances) ] ) if self.keep_binning_dft: self.binning_dft = dft dft = dft.reshape(len(X) * num_windows_per_inst, self.dft_length) if y is not None: y = np.repeat(y, num_windows_per_inst) if self.anova and y is not None: non_constant = np.where( ~np.isclose(dft.var(axis=0), np.zeros_like(dft.shape[1])) )[0] # select word-length many indices with best f-score if self.word_length <= non_constant.size: f, _ = f_classif(dft[:, non_constant], y) self.support = non_constant[
np.argsort(-f)
numpy.argsort
"""General ROM utilities <NAME>, 14 Feb 2018 """ import warnings import numpy as np import scipy.linalg as scalg # from IPython import embed import sharpy.linear.src.libsparse as libsp import sharpy.linear.src.libss as libss def balreal_direct_py(A, B, C, DLTI=True, Schur=False, full_outputs=False): r""" Find balanced realisation of continuous (``DLTI = False``) and discrete (``DLTI = True``) time of LTI systems using scipy libraries. The function proceeds to achieve balanced realisation of the state-space system by first solving the Lyapunov equations. They are solved using Barlets-Stewart algorithm for Sylvester equation, which is based on A matrix Schur decomposition. .. math:: \mathbf{A\,W_c + W_c\,A^T + B\,B^T} &= 0 \\ \mathbf{A^T\,W_o + W_o\,A + C^T\,C} &= 0 to obtain the reachability and observability gramians, which are positive definite matrices. Then, the gramians are decomposed into their Cholesky factors such that: .. math:: \mathbf{W_c} &= \mathbf{Q_c\,Q_c^T} \\ \mathbf{W_o} &= \mathbf{Q_o\,Q_o^T} A singular value decomposition (SVD) of the product of the Cholesky factors is performed .. math:: (\mathbf{Q_o^T\,Q_c}) = \mathbf{U\,\Sigma\,V^*} The singular values are then used to build the transformation matrix :math:`\mathbf{T}` .. math:: \mathbf{T} &= \mathbf{Q_c\,V\,\Sigma}^{-1/2} \\ \mathbf{T}^{-1} &= \mathbf{\Sigma}^{-1/2}\,\mathbf{U^T\,Q_o^T} The balanced system is therefore of the form: .. math:: \mathbf{A_b} &= \mathbf{T\,A\,T^{-1}} \\ \mathbf{B_b} &= \mathbf{T\,B} \\ \mathbf{C_b} &= \mathbf{C\,T^{-1}} \\ \mathbf{D_b} &= \mathbf{D} Warnings: This function may be less computationally efficient than the ``balreal`` Matlab implementation and does not offer the option to bound the realisation in frequency and time. Notes: Lyapunov equations are solved using Barlets-Stewart algorithm for Sylvester equation, which is based on A matrix Schur decomposition. Args: A (np.ndarray): Plant Matrix B (np.ndarray): Input Matrix C (np.ndarray): Output Matrix DLTI (bool): Discrete time state-space flag Schur (bool): Use Schur decomposition to solve the Lyapunov equations Returns: tuple of np.ndarrays: Tuple of the form ``(S, T, Tinv)`` containing: - Singular values in diagonal matrix (``S``) - Transformation matrix (``T``). - Inverse transformation matrix(``Tinv``). References: Anthoulas, A.C.. Approximation of Large Scale Dynamical Systems. Chapter 7. Advances in Design and Control. SIAM. 2005. """ ### select solver for Lyapunov equation # Notation reminder: # scipy: A X A.T - X = -Q # contr: A W A.T - W = - B B.T # obser: A.T W A - W = - C.T C if DLTI: sollyap = scalg.solve_discrete_lyapunov else: sollyap = scalg.solve_lyapunov # solve Lyapunov if Schur: # decompose A Atri, U = scalg.schur(A) # solve Lyapunov BBtri = np.dot(U.T, np.dot(B, np.dot(B.T, U))) CCtri = np.dot(U.T, np.dot(C.T, np.dot(C, U))) Wctri = sollyap(Atri, BBtri) Wotri = sollyap(Atri.T, CCtri) # reconstruct Wo,Wc Wc = np.dot(U, np.dot(Wctri, U.T)) Wo = np.dot(U, np.dot(Wotri, U.T)) else: Wc = sollyap(A, np.dot(B, B.T)) Wo = sollyap(A.T, np.dot(C.T, C)) # Choleski factorisation: W=Q Q.T # Qc = scalg.cholesky(Wc).T # Qo = scalg.cholesky(Wo).T # build M matrix and SVD # M = np.dot(Qo.T, Qc) # U, s, Vh = scalg.svd(M) # S = np.diag(s) # Sinv = np.diag(1. / s) # V = Vh.T # Build transformation matrices # T = np.dot(Qc, np.dot(V, np.sqrt(Sinv))) # Tinv = np.dot(np.sqrt(Sinv), np.dot(U.T, Qo.T)) # return S, T, Tinv ### Find transformation matrices # avoid Cholevski - unstable hsv_sq, Tinv = np.linalg.eig(np.dot(Wc, Wo)) T = np.linalg.inv(Tinv) # sort iisort = np.argsort(hsv_sq)[::-1] hsv = np.sqrt(hsv_sq[iisort]) T = T[:, iisort] Tinv = Tinv[iisort, :] if full_outputs is False: return hsv, T, Tinv else: # get square-root factors UT, QoT = scalg.qr(np.dot(np.diag(np.sqrt(hsv)), Tinv), pivoting=False) Vh, QcT = scalg.qr(np.dot(T, np.diag(np.sqrt(hsv))).T, pivoting=False) return hsv, UT.T, Vh, QcT.T, QoT.T def balreal_iter(A, B, C, lowrank=True, tolSmith=1e-10, tolSVD=1e-6, kmin=None, tolAbs=False, Print=False, outFacts=False): """ Find balanced realisation of DLTI system. Notes: Lyapunov equations are solved using iterative squared Smith algorithm, in its low or full rank version. These implementations are as per the low_rank_smith and smith_iter functions respectively but, for computational efficiency, the iterations are rewritten here so as to solve for the observability and controllability Gramians contemporary. - Exploiting sparsity: This algorithm is not ideal to exploit sparsity. However, the following strategies are implemented: - if the A matrix is provided in sparse format, the powers of A will be calculated exploiting sparsity UNTIL the number of non-zero elements is below 15% the size of A. Upon this threshold, the cost of the matrix multiplication rises dramatically, and A is hence converted to a dense numpy array. """ ### Solve Lyapunov equations # Notation reminder: # scipy: A X A.T - X = -Q # contr: A W A.T - W = - B B.T # obser: A.T W A - W = - C.T C # low-rank smith: A.T X A - X = -Q Q.T # matrices size N = A.shape[0] rC = B.shape[1] rO = C.shape[0] if lowrank: # low-rank square-Smith iteration (with SVD) # initialise smith iteration DeltaNorm = 1e6 # error DeltaNormNext = DeltaNorm ** 2 # error expected at next iter kk = 0 Qck = B Qok = C.T if Print: print('Iter\tMaxZ\t|\trank_c\trank_o\tA size') while DeltaNorm > tolSmith and DeltaNormNext > 1e-3 * tolSmith: ###### controllability ### compute Ak^2 * Qck # (future: use block Arnoldi) Qcright = libsp.dot(A, Qck) MaxZhere = np.max(np.abs(Qcright)) ### enlarge Z matrices Qck = np.concatenate((Qck, Qcright), axis=1) Qcright = None rC = Qck.shape[1] if kmin == None or kmin < rC: ### "cheap" SVD truncation Uc, svc = scalg.svd(Qck, full_matrices=False, overwrite_a=True, lapack_driver='gesdd')[:2] # import scipy.linalg.interpolative as sli # Ucnew,svcnew,temp=sli.svd(Qck,tolSVD) if tolAbs: rcmax = np.sum(svc > tolSVD) else: rcmax = np.sum(svc > tolSVD * svc[0]) if kmin != None: rC = max(rcmax, kmin) else: rC = rcmax Qck = Uc[:, :rC] * svc[:rC] # free memory Uc = None Qcright = None ###### observability ### compute Ak^2 * Qok # (future: use block Arnoldi) Qoright = np.transpose(libsp.dot(Qok.T, A)) DeltaNorm = max(MaxZhere, np.max(np.abs(Qoright))) ### enlarge Z matrices Qok = np.concatenate((Qok, Qoright), axis=1) Qoright = None rO = Qok.shape[1] if kmin == None or kmin < rO: ### "cheap" SVD truncation Uo, svo = scalg.svd(Qok, full_matrices=False)[:2] if tolAbs: romax = np.sum(svo > tolSVD) else: romax = np.sum(svo > tolSVD * svo[0]) if kmin != None: rO = max(romax, kmin) else: rO = romax Qok = Uo[:, :rO] * svo[:rO] Uo = None ##### Prepare next time step if Print: print('%.3d\t%.2e\t%.5d\t%.5d\t%.5d' % (kk, DeltaNorm, rC, rO, N)) DeltaNormNext = DeltaNorm ** 2 if DeltaNorm > tolSmith and DeltaNormNext > 1e-3 * tolSmith: # compute power if type(A) is libsp.csc_matrix: A = A.dot(A) # check sparsity if A.size > 0.15 * N ** 2: A = A.toarray() elif type(A) is np.ndarray: A = np.linalg.matrix_power(A, 2) else: raise NameError('Type of A not supported') ### update kk = kk + 1 A = None else: # full-rank squared smith iteration (with Cholevsky) raise NameError('Use balreal_iter_old instead!') # find min size (only if iter used) cc, co = Qck.shape[1], Qok.shape[1] if Print: print('cc=%.2d, co=%.2d' % (cc, co)) print('rank(Zc)=%.4d\trank(Zo)=%.4d' % (rcmax, romax)) # build M matrix and SVD M = libsp.dot(Qok.T, Qck) U, s, Vh = scalg.svd(M, full_matrices=False) if outFacts: return s, Qck, Qok else: sinv = s ** (-0.5) T = libsp.dot(Qck, Vh.T * sinv) Tinv = np.dot((U * sinv).T, Qok.T) if Print: print('rank(Zc)=%.4d\trank(Zo)=%.4d' % (rcmax, romax)) return s, T, Tinv, rcmax, romax def balreal_iter_old(A, B, C, lowrank=True, tolSmith=1e-10, tolSVD=1e-6, kmax=None, tolAbs=False): """ Find balanced realisation of DLTI system. Notes: Lyapunov equations are solved using iterative squared Smith algorithm, in its low or full rank version. These implementations are as per the low_rank_smith and smith_iter functions respectively but, for computational efficiency,, the iterations are rewritten here so as to solve for the observability and controllability Gramians contemporary. """ ### Solve Lyapunov equations # Notation reminder: # scipy: A X A.T - X = -Q # contr: A W A.T - W = - B B.T # obser: A.T W A - W = - C.T C # low-rank smith: A.T X A - X = -Q Q.T if lowrank: # low-rank square-Smith iteration (with SVD) # matrices size N = A.shape[0] rB = B.shape[1] rC = C.shape[0] # initialise smith iteration DeltaNorm = 1e6 print('Iter\tMaxZhere') kk = 0 Apow = A Qck = B Qok = C.T while DeltaNorm > tolSmith: ### compute products Ak^2 * Zk ### (use block Arnoldi) Qcright = np.dot(Apow, Qck) Qoright = np.dot(Apow.T, Qok) Apow = np.dot(Apow, Apow) ### enlarge Z matrices Qck = np.concatenate((Qck, Qcright), axis=1) Qok = np.concatenate((Qok, Qoright), axis=1) ### check convergence without reconstructing the added term MaxZhere = max(np.max(np.abs(Qoright)), np.max(np.abs(Qcright))) print('%.4d\t%.3e' % (kk, MaxZhere)) DeltaNorm = MaxZhere # fixed columns chopping if kmax is None: # cheap SVD truncation if Qck.shape[1] > .4 * N or Qok.shape[1] > .4 * N: Uc, svc = scalg.svd(Qck, full_matrices=False)[:2] Uo, svo = scalg.svd(Qok, full_matrices=False)[:2] if tolAbs: rcmax = np.sum(svc > tolSVD) romax = np.sum(svo > tolSVD) else: rcmax = np.sum(svc > tolSVD * svc[0]) romax = np.sum(svo > tolSVD * svo[0]) pmax = max(rcmax, romax) Qck = Uc[:, :pmax] * svc[:pmax] Qok = Uo[:, :pmax] * svo[:pmax] # Qck_old=np.dot(Uc[:,:pmax],np.diag(svc[:pmax])) # Qok_old=np.dot(Uo[:,:pmax],np.diag(svo[:pmax])) # Qck=np.dot(Uc[:,:rcmax],np.diag(svc[:rcmax])) # Qok=np.dot(Uo[:,:romax],np.diag(svo[:romax])) else: if Qck.shape[1] > kmax: Uc, svc = scalg.svd(Qck, full_matrices=False)[:2] Qck = Uc[:, :kmax] * svc[:kmax] if Qok.shape[1] > kmax: Uo, svo = scalg.svd(Qok, full_matrices=False)[:2] Qok = Uo[:, :kmax] * svo[:kmax] ### update kk = kk + 1 del Apow Qc, Qo = Qck, Qok else: # full-rank squared smith iteration (with Cholevsky) # first iteration Wc = np.dot(B, B.T) Wo = np.dot(C.T, C) Apow = A AXAobs = np.dot(np.dot(A.T, Wo), A) AXActrl = np.dot(np.dot(A, Wc), A.T) DeltaNorm = max(np.max(np.abs(AXAobs)), np.max(np.abs(AXActrl))) kk = 1 print('Iter\tRes') while DeltaNorm > tolSmith: kk = kk + 1 # update Wo = Wo + AXAobs Wc = Wc + AXActrl # incremental Apow = np.dot(Apow, Apow) AXAobs = np.dot(np.dot(Apow.T, Wo), Apow) AXActrl = np.dot(np.dot(Apow, Wc), Apow.T) DeltaNorm = max(np.max(np.abs(AXAobs)), np.max(np.abs(AXActrl))) print('%.4d\t%.3e' % (kk, DeltaNorm)) # final update (useless in very low tolerance) Wo = Wo + AXAobs Wc = Wc + AXActrl # Choleski factorisation: W=Q Q.T. If unsuccessful, directly solve # eigenvalue problem Qc = scalg.cholesky(Wc).T Qo = scalg.cholesky(Wo).T # # eigenvalues are normalised by one, hence Tinv and T matrices # # here are not scaled # ssq,Tinv,T=scalg.eig(np.dot(Wc,Wo),left=True,right=True) # Tinv=Tinv.T # #Tinv02=Tinv02.T # S=np.diag(np.sqrt(ssq)) # return S,T,Tinv # find min size (only if iter used) cc, co = Qc.shape[1], Qo.shape[1] cmin = min(cc, co) print('cc=%.2d, co=%.2d' % (cc, co)) # build M matrix and SVD M = np.dot(Qo.T, Qc) # ### not optimised # U,s,Vh=scalg.svd(M,full_matrices=True) # U,Vh,s=U[:,:cmin],Vh[:cmin,:],s[:cmin] # S=np.diag(s) # Sinv=np.diag(1./s) # V=Vh.T # # Build transformation matrices # T=np.dot(Qc,np.dot(V,np.sqrt(Sinv))) # Tinv=np.dot(np.sqrt(Sinv),np.dot(U.T,Qo.T)) ### optimised U, s, Vh = scalg.svd(M, full_matrices=True) # as M is square, full_matrices has no effect sinv = s ** (-0.5) T = np.dot(Qc, Vh.T * sinv) Tinv = np.dot((U * sinv).T, Qo.T) return s, T, Tinv def smith_iter(S, T, tol=1e-8, Square=True): """ Solves the Stein equation S.T X S - X = -T by mean of Smith or squared-Smith algorithm. Note that a solution X exists only if the eigenvalues of S are stricktly smaller than one, and the algorithm will not converge otherwise. The algorithm can not exploit sparsity, hence, while convergence can be improved for very large matrices, it can not be employed if matrices are too large to be stored in memory. Ref. Penzt, "A cyclic low-rank Smith method for large sparse Lyapunov equations", 2000. """ N = S.shape[0] if Square: # first iteration X = T Spow = S STXS = np.dot(np.dot(S.T, X), S) DeltaNorm = np.max(np.abs(STXS)) # # second iteration: # # can be removed using Spow=np.dot(Spow,Spow) # X=X+STXS # S=np.dot(S,S) # Spow=S # STXS=np.dot(np.dot(Spow.T,X),Spow) # DeltaNorm=np.max(np.abs(STXS)) counter = 1 print('Iter\tRes') while DeltaNorm > tol: counter = counter + 1 # update X = X + STXS # incremental # Spow=np.dot(Spow,S) # use this if uncomment second iter Spow = np.dot(Spow, Spow) STXS = np.dot(np.dot(Spow.T, X), Spow) DeltaNorm = np.max(np.abs(STXS)) print('%.4d\t%.3e' % (counter, DeltaNorm)) else: # first iteration X = T Spow = S STTS = np.dot(np.dot(Spow.T, T), Spow) DeltaNorm = np.max(np.abs(STTS)) counter = 1 print('Iter\tRes') while DeltaNorm > tol: counter = counter + 1 # update X = X + STTS # incremental Spow = np.dot(Spow, S) STTS = np.dot(np.dot(Spow.T, T), Spow) DeltaNorm = np.max(np.abs(STTS)) print('%.4d\t%.3e' % (counter, DeltaNorm)) print('Error %.2e achieved after %.4d iteration!' % (DeltaNorm, counter)) return X def res_discrete_lyap(A, Q, Z, Factorised=True): """ Provides residual of discrete Lyapunov equation: A.T X A - X = -Q Q.T If Factorised option is true, X=Z*Z.T otherwise X=Z is chosen. Reminder: contr: A W A.T - W = - B B.T obser: A.T W A - W = - C.T C """ if Factorised: X = np.dot(Z, Z.T) else: X = Z R = np.dot(A.T, np.dot(X, A)) - X + np.dot(Q, Q.T) resinf = np.max(np.abs(R)) return resinf def low_rank_smith(A, Q, tol=1e-10, Square=True, tolSVD=1e-12, tolAbs=False, kmax=None, fullOut=True, Convergence='Zk'): """ Low-rank smith algorithm for Stein equation A.T X A - X = -Q Q.T The algorithm can only be used if T is symmetric positive-definite, but this is not checked in this routine for computational performance. The solution X is provided in its factorised form: X=Z Z.T As in the most general case, a solution X exists only if the eigenvalues of S are stricktly smaller than one, and the algorithm will not converge otherwise. The algorithm can not exploits parsity, hence, while convergence can be improved for very large matrices, it can not be employed if matrices are too large to be stored in memory. Parameters: - tol: tolerance for stopping convergence of Smith algorithm - Square: if true the squared-Smith algorithm is used - tolSVD: tolerance for reduce Z matrix based on singular values - kmax: if given, the Z matrix is forced to have size kmax - tolAbs: if True, the tolerance - fullOut: not implemented - Convergence: 'Zk','res'. - If 'Zk' the iteration is stopped when the inf norm of the incremental matrix goes below tol. - If 'res' the residual of the Lyapunov equation is computed. This strategy may fail to converge if kmax is too low or tolSVD too large! Ref. <NAME>, <NAME> and <NAME>, "On the squared Smith method for large-scale Stein equations", 2014. """ N = A.shape[0] ncol = Q.shape[1] AT = A.T DeltaNorm = 1e6 print('Iter\tMaxZhere') kk = 0 SvList = [] ZcColList = [] if Square: # ------------------------------------------------- squared iter Zk = Q while DeltaNorm > tol: ### compute product Ak^2 * Zk ### use block Arnoldi ## too expensive!! # Zright=Zk # for ii in range(2**kk): # Zright=np.dot(AT,Zright) Zright = np.dot(AT, Zk) AT = np.dot(AT, AT) ### enlarge Z matrix Zk = np.concatenate((Zk, Zright), axis=1) ### check convergence if Convergence == 'Zk': ### check convergence without reconstructing the added term MaxZhere = np.max(np.abs(Zright)) print('%.4d\t%.3e' % (kk, MaxZhere)) DeltaNorm = MaxZhere elif Convergence == 'res': ### check convergence through residual resinf = res_discrete_lyap(A, Q, Zk, Factorised=True) print('%.4d\t%.3e\t%.3e' % (kk, MaxZhere, resinf)) DeltaNorm = resinf # cheap SVD truncation U, sv, Vh = scalg.svd(Zk, full_matrices=False) # embed() if kmax == None: if tolAbs: pmax = np.sum(sv > tolSVD) else: pmax = np.sum(sv > tolSVD * sv[0]) else: pmax = kmax Ut = U[:, :pmax] svt = sv[:pmax] # Vht=Vh[:pmax,:] # Zkrec=np.dot(Ut,np.dot(np.diag(svt),Vht)) Zk = np.dot(Ut, np.diag(svt)) ### update kk = kk + 1 else: # -------------------------------------------------------- smith iter raise NameError( 'Smith method without SVD will lead to extremely large matrices') Zk = [] Zk.append(Q) while DeltaNorm > tol: Zk.append(np.dot(AT, Zk[-1])) kk = kk + 1 # check convergence without reconstructing Z*Z.T MaxZhere = np.max(np.abs(Zk[-1])) print('%.4d\t%.3e' % (kk, MaxZhere)) DeltaNorm = MaxZhere Zk = np.concatenate(tuple(Zk), axis=1) return Zk ### utilities for balfreq def get_trapz_weights(k0, kend, Nk, knyq=False): """ Returns uniform frequency grid (kv of length Nk) and weights (wv) for Gramians integration using trapezoidal rule. If knyq is True, it is assumed that kend is also the Nyquist frequency. """ assert k0 >= 0. and kend >= 0., 'Frequencies must be positive!' dk = (kend - k0) / (Nk - 1.) kv = np.linspace(k0, kend, Nk) wv = np.ones((Nk,)) * dk * np.sqrt(2) if k0 / (kend - k0) < 1e-10: wv[0] = .5 * dk else: wv[0] = dk / np.sqrt(2) if knyq: wv[-1] = .5 * dk else: wv[-1] = dk / np.sqrt(2) return kv, wv def get_gauss_weights(k0, kend, Npart, order): """ Returns gauss-legendre frequency grid (kv of length Npart*order) and weights (wv) for Gramians integration. The integration grid is divided into Npart partitions, and in each of them integration is performed using a Gauss-Legendre quadrature of order order. Note: integration points are never located at k0 or kend, hence there is no need for special treatment as in (for e.g.) a uniform grid case (see get_unif_weights) """ if Npart == 1: # get gauss normalised coords and weights xad, wad = np.polynomial.legendre.leggauss(order) krange = kend - k0 kv = .5 * (k0 + kend) + .5 * krange * xad wv = wad * (.5 * krange) * np.sqrt(2) print('partitioning: %.3f to %.3f' % (k0, kend)) else: kv = np.zeros((Npart * order,)) wv = np.zeros((Npart * order,)) dk_part = (kend - k0) / Npart for ii in range(Npart): k0_part = k0 + ii * dk_part kend_part = k0_part + dk_part iivec = range(order * ii, order * (ii + 1)) kv[iivec], wv[iivec] = get_gauss_weights(k0_part, kend_part, Npart=1, order=order) return kv, wv def balfreq(SS, DictBalFreq): """ Method for frequency limited balancing. The Observability and controllability Gramians over the frequencies kv are solved in factorised form. Balanced modes are then obtained with a square-root method. Details: * Observability and controllability Gramians are solved in factorised form through explicit integration. The number of integration points determines both the accuracy and the maximum size of the balanced model. * Stability over all (Nb) balanced states is achieved if: a. one of the Gramian is integrated through the full Nyquist range b. the integration points are enough. Input: - DictBalFreq: dictionary specifying integration method with keys: - ``frequency``: defines limit frequencies for balancing. The balanced model will be accurate in the range ``[0,F]``, where ``F`` is the value of this key. Note that ``F`` units must be consistent with the units specified in the ``self.ScalingFacts`` dictionary. - ``method_low``: ``['gauss','trapz']`` specifies whether to use gauss quadrature or trapezoidal rule in the low-frequency range ``[0,F]``. - ``options_low``: options to use for integration in the low-frequencies. These depend on the integration scheme (See below). - ``method_high``: method to use for integration in the range [F,F_N], where F_N is the Nyquist frequency. See 'method_low'. - ``options_high``: options to use for integration in the high-frequencies. - ``check_stability``: if True, the balanced model is truncated to eliminate unstable modes - if any is found. Note that very accurate balanced model can still be obtained, even if high order modes are unstable. Note that this option is overridden if "" - ``get_frequency_response``: if True, the function also returns the frequency response evaluated at the low-frequency range integration points. If True, this option also allows to automatically tune the balanced model. Future options: - Ncpu: for parallel run The following integration schemes are available: - ``trapz``: performs integration over equally spaced points using trapezoidal rule. It accepts options dictionaries with keys: - ``points``: number of integration points to use (including domain boundary) - ``gauss`` performs gauss-lobotto quadrature. The domain can be partitioned in Npart sub-domain in which the gauss-lobotto quadrature of order Ord can be applied. A total number of Npart*Ord points is required. It accepts options dictionaries of the form: - ``partitions``: number of partitions - ``order``: quadrature order. Examples: The following dictionary >>> DictBalFreq={'frequency': 1.2, >>> 'method_low': 'trapz', >>> 'options_low': {'points': 12}, >>> 'method_high': 'gauss', >>> 'options_high': {'partitions': 2, 'order': 8}, >>> 'check_stability': True } balances the state-space model in the frequency range [0, 1.2] using: a. 12 equally-spaced points integration of the Gramians in the low-frequency range [0,1.2] and b. A 2 Gauss-Lobotto 8-th order quadratures of the controllability Gramian in the high-frequency range. A total number of 28 integration points will be required, which will result into a balanced model with number of states >>> min{ 2*28* number_inputs, 2*28* number_outputs } The model is finally truncated so as to retain only the first Ns stable modes. """ ### check input dictionary if 'frequency' not in DictBalFreq: raise NameError('Solution dictionary must include the "frequency" key') if 'method_low' not in DictBalFreq: warnings.warn('Setting default options for low-frequency integration') DictBalFreq['method_low'] = 'trapz' DictBalFreq['options_low'] = {'points': 12} if 'method_high' not in DictBalFreq: warnings.warn('Setting default options for high-frequency integration') DictBalFreq['method_high'] = 'gauss' DictBalFreq['options_high'] = {'partitions': 2, 'order': 8} if 'check_stability' not in DictBalFreq: DictBalFreq['check_stability'] = True if 'output_modes' not in DictBalFreq: DictBalFreq['output_modes'] = True if 'get_frequency_response' not in DictBalFreq: DictBalFreq['get_frequency_response'] = False ### get integration points and weights # Nyquist frequency kn = np.pi / SS.dt Opt = DictBalFreq['options_low'] if DictBalFreq['method_low'] == 'trapz': kv_low, wv_low = get_trapz_weights(0., DictBalFreq['frequency'], Opt['points'], False) elif DictBalFreq['method_low'] == 'gauss': kv_low, wv_low = get_gauss_weights(0., DictBalFreq['frequency'], Opt['partitions'], Opt['order']) else: raise NameError( 'Invalid value %s for key "method_low"' % DictBalFreq['method_low']) Opt = DictBalFreq['options_high'] if DictBalFreq['method_high'] == 'trapz': if Opt['points'] == 0: warnings.warn('You have chosen no points in high frequency range!') kv_high, wv_high = [], [] else: kv_high, wv_high = get_trapz_weights(DictBalFreq['frequency'], kn, Opt['points'], True) elif DictBalFreq['method_high'] == 'gauss': if Opt['order'] * Opt['partitions'] == 0: warnings.warn('You have chosen no points in high frequency range!') kv_high, wv_high = [], [] else: kv_high, wv_high = get_gauss_weights(DictBalFreq['frequency'], kn, Opt['partitions'], Opt['order']) else: raise NameError( 'Invalid value %s for key "method_high"' % DictBalFreq['method_high']) ### -------------------------------------------------- loop frequencies ### merge vectors Nk_low = len(kv_low) kvdt = np.concatenate((kv_low, kv_high)) * SS.dt wv = np.concatenate((wv_low, wv_high)) * SS.dt zv = np.cos(kvdt) + 1.j * np.sin(kvdt) Eye = libsp.eye_as(SS.A) Zc = np.zeros((SS.states, 2 * SS.inputs * len(kvdt)), ) Zo = np.zeros((SS.states, 2 * SS.outputs * Nk_low), ) if DictBalFreq['get_frequency_response']: Yfreq = np.empty((SS.outputs, SS.inputs, Nk_low,), dtype=np.complex_) kv = kv_low for kk in range(len(kvdt)): zval = zv[kk] Intfact = wv[kk] # integration factor Qctrl = Intfact * libsp.solve(zval * Eye - SS.A, SS.B) kkvec = range(2 * kk * SS.inputs, 2 * (kk + 1) * SS.inputs) Zc[:, kkvec[:SS.inputs]] = Qctrl.real Zc[:, kkvec[SS.inputs:]] = Qctrl.imag ### ----- frequency response if DictBalFreq['get_frequency_response'] and kk < Nk_low: Yfreq[:, :, kk] = (1. / Intfact) * \ libsp.dot(SS.C, Qctrl, type_out=np.ndarray) + SS.D ### ----- observability if kk >= Nk_low: continue Qobs = Intfact * libsp.solve(np.conj(zval) * Eye - SS.A.T, SS.C.T) kkvec = range(2 * kk * SS.outputs, 2 * (kk + 1) * SS.outputs) Zo[:, kkvec[:SS.outputs]] = Intfact * Qobs.real Zo[:, kkvec[SS.outputs:]] = Intfact * Qobs.imag # delete full matrices Kernel = None Qctrl = None Qobs = None # LRSQM (optimised) U, hsv, Vh = scalg.svd(np.dot(Zo.T, Zc), full_matrices=False) sinv = hsv ** (-0.5) T = np.dot(Zc, Vh.T * sinv) Ti = np.dot((U * sinv).T, Zo.T) # Zc,Zo=None,None ### build frequency balanced model Ab = libsp.dot(Ti, libsp.dot(SS.A, T)) Bb = libsp.dot(Ti, SS.B) Cb = libsp.dot(SS.C, T) SSb = libss.ss(Ab, Bb, Cb, SS.D, dt=SS.dt) ### Eliminate unstable modes - if any: if DictBalFreq['check_stability']: for nn in range(1, len(hsv) + 1): eigs_trunc = scalg.eigvals(SSb.A[:nn, :nn]) eigs_trunc_max = np.max(np.abs(eigs_trunc)) if eigs_trunc_max > 1. - 1e-16: SSb.truncate(nn - 1) hsv = hsv[:nn - 1] T = T[:, :nn - 1] Ti = Ti[:nn - 1, :] break outs = (SSb, hsv) if DictBalFreq['output_modes']: outs += (T, Ti, Zc, Zo, U, Vh) return outs def modred(SSb, N, method='residualisation'): """ Produces a reduced order model with N states from balanced or modal system SSb. Both "truncation" and "residualisation" methods are employed. Note: - this method is designed for small size systems, i.e. a deep copy of SSb is produced by default. """ assert method in ['residualisation', 'realisation', 'truncation'], \ "method must be equal to 'residualisation' or 'truncation'!" assert SSb.dt is not None, 'SSb is not a DLTI!' Nb = SSb.A.shape[0] if Nb == N: SSrom = libss.ss(SSb.A, SSb.B, SSb.C, SSb.D, dt=SSb.dt) return SSrom A11 = SSb.A[:N, :N] B11 = SSb.B[:N, :] C11 = SSb.C[:, :N] D = SSb.D if method is 'truncation': SSrom = libss.ss(A11, B11, C11, D, dt=SSb.dt) else: Nb = SSb.A.shape[0] IA22inv = -SSb.A[N:, N:].copy() eevec = range(Nb - N) IA22inv[eevec, eevec] += 1. IA22inv = scalg.inv(IA22inv, overwrite_a=True) SSrom = libss.ss( A11 + np.dot(SSb.A[:N, N:],
np.dot(IA22inv, SSb.A[N:, :N])
numpy.dot
import os import cv2 import random import numpy as np from SOLO.visualize import visualize from SOLO.preprocess.flag import flag from preprocess.find_folder import find_folder from SOLO.preprocess.augmentation import augment, augment_flip from SOLO.preprocess.solo_labelgen import file_reader, label_generator, grid_generator f = flag() target_size = f.target_size dataset_directory = '../../EgoGesture Dataset/' label_directory = '../../EgoGesture Dataset/label/' folders = ['SingleOne', 'SingleTwo', 'SingleThree', 'SingleFour', 'SingleFive', 'SingleSix', 'SingleSeven', 'SingleEight', 'SingleNine', 'SingleGood', 'SingleBad'] label = {} for folder in folders: label[folder] = file_reader(folder) def train_generator(steps_per_epoch, sample_per_batch): train_image_files = [] for folder in folders: train_image_files = train_image_files + os.listdir(dataset_directory + folder) for i in range(0, 15): random.shuffle(train_image_files) print('Training Dataset Size: ', len(train_image_files)) while True: for i in range(0, steps_per_epoch): x_batch = [] y_batch = [] start = i * sample_per_batch for n in range(start, start + sample_per_batch): image_name = train_image_files[n] folder_name = find_folder(image_name) image = cv2.imread(dataset_directory + folder_name + '/' + image_name) image = cv2.resize(image, (target_size, target_size)) obj_box = label_generator(image_name=image_name, file=label.get(folder_name)) # 01: original image x_batch.append(image) output = grid_generator(obj_box=obj_box) y_batch.append(output) # visualize(image=image, output=output) # 02: original image + augment image_aug, bbox_aug = augment(image=image, bbox=obj_box) x_batch.append(image_aug) output = grid_generator(obj_box=bbox_aug) y_batch.append(output) # visualize(image=image_aug, output=output) x_batch = np.asarray(x_batch) x_batch = x_batch.astype('float32') x_batch = x_batch / 255.0 y_batch = np.asarray(y_batch) yield (x_batch, y_batch) def valid_generator(steps_per_epoch, sample_per_batch): dataset_directory = '../EgoGesture Dataset/Valid/' train_image_files = os.listdir(dataset_directory) for i in range(0, 10): random.shuffle(train_image_files) while True: for i in range(0, steps_per_epoch): x_batch = [] y_batch = [] start = i * sample_per_batch for n in range(start, start + sample_per_batch): image_name = train_image_files[n] folder_name = find_folder(image_name) image = cv2.imread(dataset_directory + folder_name + '/' + image_name) image = cv2.resize(image, (416, 416)) obj_box = label_generator(image_name=image_name, file=label.get(folder_name)) # 01: original image x_batch.append(image) output = grid_generator(obj_box=obj_box) y_batch.append(output) # visualize(image=image, output=output) # 02: flip image image_flip, bbox_flip = augment_flip(image=image, bbox=obj_box) x_batch.append(image_flip) y_batch.append(grid_generator(obj_box=bbox_flip)) x_batch = np.asarray(x_batch) x_batch = x_batch.astype('float32') x_batch = x_batch / 255.0 y_batch =
np.asarray(y_batch)
numpy.asarray
import numpy as np import os import re import requests import sys import time from netCDF4 import Dataset import pandas as pd from bs4 import BeautifulSoup from tqdm import tqdm # setup constants used to access the data from the different M2M interfaces BASE_URL = 'https://ooinet.oceanobservatories.org/api/m2m/' # base M2M URL SENSOR_URL = '12576/sensor/inv/' # Sensor Information # setup access credentials AUTH = ['OOIAPI-853A3LA6QI3L62', '<KEY>'] def M2M_Call(uframe_dataset_name, start_date, end_date): options = '?beginDT=' + start_date + '&endDT=' + end_date + '&format=application/netcdf' r = requests.get(BASE_URL + SENSOR_URL + uframe_dataset_name + options, auth=(AUTH[0], AUTH[1])) if r.status_code == requests.codes.ok: data = r.json() else: return None # wait until the request is completed print('Waiting for OOINet to process and prepare data request, this may take up to 20 minutes') url = [url for url in data['allURLs'] if re.match(r'.*async_results.*', url)][0] check_complete = url + '/status.txt' with tqdm(total=400, desc='Waiting') as bar: for i in range(400): r = requests.get(check_complete) bar.update(1) if r.status_code == requests.codes.ok: bar.n = 400 bar.last_print_n = 400 bar.refresh() print('\nrequest completed in %f minutes.' % elapsed) break else: time.sleep(3) elapsed = (i * 3) / 60 return data def M2M_Files(data, tag=''): """ Use a regex tag combined with the results of the M2M data request to collect the data from the THREDDS catalog. Collected data is gathered into an xarray dataset for further processing. :param data: JSON object returned from M2M data request with details on where the data is to be found for download :param tag: regex tag to use in discriminating the data files, so we only collect the correct ones :return: the collected data as an xarray dataset """ # Create a list of the files from the request above using a simple regex as a tag to discriminate the files url = [url for url in data['allURLs'] if re.match(r'.*thredds.*', url)][0] files = list_files(url, tag) return files def list_files(url, tag=''): """ Function to create a list of the NetCDF data files in the THREDDS catalog created by a request to the M2M system. :param url: URL to user's THREDDS catalog specific to a data request :param tag: regex pattern used to distinguish files of interest :return: list of files in the catalog with the URL path set relative to the catalog """ page = requests.get(url).text soup = BeautifulSoup(page, 'html.parser') pattern = re.compile(tag) return [node.get('href') for node in soup.find_all('a', text=pattern)] def M2M_Data(nclist,variables): thredds = 'https://opendap.oceanobservatories.org/thredds/dodsC/ooi/' #nclist is going to contain more than one url eventually for jj in range(len(nclist)): url=nclist[jj] url=url[25:] dap_url = thredds + url + '#fillmismatch' openFile = Dataset(dap_url,'r') for ii in range(len(variables)): dum = openFile.variables[variables[ii].name] variables[ii].data = np.append(variables[ii].data, dum[:].data) tmp = variables[0].data/60/60/24 time_converted = pd.to_datetime(tmp, unit='D', origin=pd.Timestamp('1900-01-01')) return variables, time_converted class var(object): def __init__(self): """A Class that generically holds data with a variable name and the units as attributes""" self.name = '' self.data = np.array([]) self.units = '' def __repr__(self): return_str = "name: " + self.name + '\n' return_str += "units: " + self.units + '\n' return_str += "data: size: " + str(self.data.shape) return return_str class structtype(object): def __init__(self): """ A class that imitates a Matlab structure type """ self._data = [] def __getitem__(self, index): """implement index behavior in the struct""" if index == len(self._data): self._data.append(var()) return self._data[index] def __len__(self): return len(self._data) def M2M_URLs(platform_name,node,instrument_class,method): var_list = structtype() #MOPAK if platform_name == 'CE01ISSM' and node == 'BUOY' and instrument_class == 'MOPAK' and method == 'Telemetered': uframe_dataset_name = 'CE01ISSM/SBD17/01-MOPAK0000/telemetered/mopak_o_dcl_accel' var_list[0].name = 'time' var_list[0].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' elif platform_name == 'CE02SHSM' and node == 'BUOY' and instrument_class == 'MOPAK' and method == 'Telemetered': uframe_dataset_name = 'CE02SHSM/SBD11/01-MOPAK0000/telemetered/mopak_o_dcl_accel' var_list[0].name = 'time' var_list[0].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' elif platform_name == 'CE04OSSM' and node == 'BUOY' and instrument_class == 'MOPAK' and method == 'Telemetered': uframe_dataset_name = 'CE04OSSM/SBD11/01-MOPAK0000/telemetered/mopak_o_dcl_accel' var_list[0].name = 'time' var_list[0].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' elif platform_name == 'CE06ISSM' and node == 'BUOY' and instrument_class == 'MOPAK' and method == 'Telemetered': uframe_dataset_name = 'CE06ISSM/SBD17/01-MOPAK0000/telemetered/mopak_o_dcl_accel' var_list[0].name = 'time' var_list[0].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' elif platform_name == 'CE07SHSM' and node == 'BUOY' and instrument_class == 'MOPAK' and method == 'Telemetered': uframe_dataset_name = 'CE07SHSM/SBD11/01-MOPAK0000/telemetered/mopak_o_dcl_accel' var_list[0].name = 'time' var_list[0].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' elif platform_name == 'CE09OSSM' and node == 'BUOY' and instrument_class == 'MOPAK' and method == 'Telemetered': uframe_dataset_name = 'CE09OSSM/SBD11/01-MOPAK0000/telemetered/mopak_o_dcl_accel' var_list[0].name = 'time' var_list[0].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' elif platform_name == 'CE09OSPM' and node == 'BUOY' and instrument_class == 'MOPAK' and method == 'Telemetered': uframe_dataset_name = 'CE09OSPM/SBS01/01-MOPAK0000/telemetered/mopak_o_dcl_accel' var_list[0].name = 'time' var_list[0].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' #METBK elif platform_name == 'CE02SHSM' and node == 'BUOY' and instrument_class == 'METBK1' and method == 'Telemetered': uframe_dataset_name = 'CE02SHSM/SBD11/06-METBKA000/telemetered/metbk_a_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'sea_surface_temperature' var_list[2].name = 'sea_surface_conductivity' var_list[3].name = 'met_salsurf' var_list[4].name = 'met_windavg_mag_corr_east' var_list[5].name = 'met_windavg_mag_corr_north' var_list[6].name = 'barometric_pressure' var_list[7].name = 'air_temperature' var_list[8].name = 'relative_humidity' var_list[9].name = 'longwave_irradiance' var_list[10].name = 'shortwave_irradiance' var_list[11].name = 'precipitation' var_list[12].name = 'met_heatflx_minute' var_list[13].name = 'met_latnflx_minute' var_list[14].name = 'met_netlirr_minute' var_list[15].name = 'met_sensflx_minute' var_list[16].name = 'eastward_velocity' var_list[17].name = 'northward_velocity' var_list[18].name = 'met_spechum' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[8].data = np.array([]) var_list[9].data = np.array([]) var_list[10].data = np.array([]) var_list[11].data = np.array([]) var_list[12].data = np.array([]) var_list[13].data = np.array([]) var_list[14].data = np.array([]) var_list[15].data = np.array([]) var_list[16].data = np.array([]) var_list[17].data = np.array([]) var_list[18].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'S/m' var_list[3].units = 'unitless' var_list[4].units = 'm/s' var_list[5].units = 'm/s' var_list[6].units = 'mbar' var_list[7].units = 'degC' var_list[8].units = '#' var_list[9].units = 'W/m' var_list[10].units = 'W/m' var_list[11].units = 'mm' var_list[12].units = 'W/m' var_list[13].units = 'W/m' var_list[14].units = 'W/m' var_list[15].units = 'W/m' var_list[16].units = 'm/s' var_list[17].units = 'm/s' var_list[18].units = 'g/kg' elif platform_name == 'CE04OSSM' and node == 'BUOY' and instrument_class == 'METBK1' and method == 'Telemetered': uframe_dataset_name = 'CE04OSSM/SBD11/06-METBKA000/telemetered/metbk_a_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'sea_surface_temperature' var_list[2].name = 'sea_surface_conductivity' var_list[3].name = 'met_salsurf' var_list[4].name = 'met_windavg_mag_corr_east' var_list[5].name = 'met_windavg_mag_corr_north' var_list[6].name = 'barometric_pressure' var_list[7].name = 'air_temperature' var_list[8].name = 'relative_humidity' var_list[9].name = 'longwave_irradiance' var_list[10].name = 'shortwave_irradiance' var_list[11].name = 'precipitation' var_list[12].name = 'met_heatflx_minute' var_list[13].name = 'met_latnflx_minute' var_list[14].name = 'met_netlirr_minute' var_list[15].name = 'met_sensflx_minute' var_list[16].name = 'eastward_velocity' var_list[17].name = 'northward_velocity' var_list[18].name = 'met_spechum' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[8].data = np.array([]) var_list[9].data = np.array([]) var_list[10].data = np.array([]) var_list[11].data = np.array([]) var_list[12].data = np.array([]) var_list[13].data = np.array([]) var_list[14].data = np.array([]) var_list[15].data = np.array([]) var_list[16].data = np.array([]) var_list[17].data = np.array([]) var_list[18].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'S/m' var_list[3].units = 'unitless' var_list[4].units = 'm/s' var_list[5].units = 'm/s' var_list[6].units = 'mbar' var_list[7].units = 'degC' var_list[8].units = '#' var_list[9].units = 'W/m' var_list[10].units = 'W/m' var_list[11].units = 'mm' var_list[12].units = 'W/m' var_list[13].units = 'W/m' var_list[14].units = 'W/m' var_list[15].units = 'W/m' var_list[16].units = 'm/s' var_list[17].units = 'm/s' var_list[18].units = 'g/kg' elif platform_name == 'CE07SHSM' and node == 'BUOY' and instrument_class == 'METBK1' and method == 'Telemetered': uframe_dataset_name = 'CE07SHSM/SBD11/06-METBKA000/telemetered/metbk_a_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'sea_surface_temperature' var_list[2].name = 'sea_surface_conductivity' var_list[3].name = 'met_salsurf' var_list[4].name = 'met_windavg_mag_corr_east' var_list[5].name = 'met_windavg_mag_corr_north' var_list[6].name = 'barometric_pressure' var_list[7].name = 'air_temperature' var_list[8].name = 'relative_humidity' var_list[9].name = 'longwave_irradiance' var_list[10].name = 'shortwave_irradiance' var_list[11].name = 'precipitation' var_list[12].name = 'met_heatflx_minute' var_list[13].name = 'met_latnflx_minute' var_list[14].name = 'met_netlirr_minute' var_list[15].name = 'met_sensflx_minute' var_list[16].name = 'eastward_velocity' var_list[17].name = 'northward_velocity' var_list[18].name = 'met_spechum' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[8].data = np.array([]) var_list[9].data = np.array([]) var_list[10].data = np.array([]) var_list[11].data = np.array([]) var_list[12].data = np.array([]) var_list[13].data = np.array([]) var_list[14].data = np.array([]) var_list[15].data = np.array([]) var_list[16].data = np.array([]) var_list[17].data = np.array([]) var_list[18].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'S/m' var_list[3].units = 'unitless' var_list[4].units = 'm/s' var_list[5].units = 'm/s' var_list[6].units = 'mbar' var_list[7].units = 'degC' var_list[8].units = '#' var_list[9].units = 'W/m' var_list[10].units = 'W/m' var_list[11].units = 'mm' var_list[12].units = 'W/m' var_list[13].units = 'W/m' var_list[14].units = 'W/m' var_list[15].units = 'W/m' var_list[16].units = 'm/s' var_list[17].units = 'm/s' var_list[18].units = 'g/kg' elif platform_name == 'CE09OSSM' and node == 'BUOY' and instrument_class == 'METBK1' and method == 'Telemetered': uframe_dataset_name = 'CE09OSSM/SBD11/06-METBKA000/telemetered/metbk_a_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'sea_surface_temperature' var_list[2].name = 'sea_surface_conductivity' var_list[3].name = 'met_salsurf' var_list[4].name = 'met_windavg_mag_corr_east' var_list[5].name = 'met_windavg_mag_corr_north' var_list[6].name = 'barometric_pressure' var_list[7].name = 'air_temperature' var_list[8].name = 'relative_humidity' var_list[9].name = 'longwave_irradiance' var_list[10].name = 'shortwave_irradiance' var_list[11].name = 'precipitation' var_list[12].name = 'met_heatflx_minute' var_list[13].name = 'met_latnflx_minute' var_list[14].name = 'met_netlirr_minute' var_list[15].name = 'met_sensflx_minute' var_list[16].name = 'eastward_velocity' var_list[17].name = 'northward_velocity' var_list[18].name = 'met_spechum' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[8].data = np.array([]) var_list[9].data = np.array([]) var_list[10].data = np.array([]) var_list[11].data = np.array([]) var_list[12].data = np.array([]) var_list[13].data = np.array([]) var_list[14].data = np.array([]) var_list[15].data = np.array([]) var_list[16].data = np.array([]) var_list[17].data = np.array([]) var_list[18].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'S/m' var_list[3].units = 'unitless' var_list[4].units = 'm/s' var_list[5].units = 'm/s' var_list[6].units = 'mbar' var_list[7].units = 'degC' var_list[8].units = '#' var_list[9].units = 'W/m' var_list[10].units = 'W/m' var_list[11].units = 'mm' var_list[12].units = 'W/m' var_list[13].units = 'W/m' var_list[14].units = 'W/m' var_list[15].units = 'W/m' var_list[16].units = 'm/s' var_list[17].units = 'm/s' var_list[18].units = 'g/kg' #FLORT elif platform_name == 'CE01ISSM' and node == 'NSIF' and instrument_class == 'FLORT' and method == 'Telemetered': uframe_dataset_name = 'CE01ISSM/RID16/02-FLORTD000/telemetered/flort_sample' var_list[0].name = 'time' var_list[1].name = 'seawater_scattering_coefficient' var_list[2].name = 'fluorometric_chlorophyll_a' var_list[3].name = 'fluorometric_cdom' var_list[4].name = 'total_volume_scattering_coefficient' var_list[5].name = 'optical_backscatter' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm-1' var_list[2].units = 'ug/L' var_list[3].units = 'ppb' var_list[4].units = 'm-1 sr-1' var_list[5].units = 'm-1' elif platform_name == 'CE01ISSM' and node == 'BUOY' and instrument_class == 'FLORT' and method == 'Telemetered': uframe_dataset_name = 'CE01ISSM/SBD17/06-FLORTD000/telemetered/flort_sample' var_list[0].name = 'time' var_list[1].name = 'seawater_scattering_coefficient' var_list[2].name = 'fluorometric_chlorophyll_a' var_list[3].name = 'fluorometric_cdom' var_list[4].name = 'total_volume_scattering_coefficient' var_list[5].name = 'optical_backscatter' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm-1' var_list[2].units = 'ug/L' var_list[3].units = 'ppb' var_list[4].units = 'm-1 sr-1' var_list[5].units = 'm-1' elif platform_name == 'CE06ISSM' and node == 'NSIF' and instrument_class == 'FLORT' and method == 'Telemetered': uframe_dataset_name = 'CE06ISSM/RID16/02-FLORTD000/telemetered/flort_sample' var_list[0].name = 'time' var_list[1].name = 'seawater_scattering_coefficient' var_list[2].name = 'fluorometric_chlorophyll_a' var_list[3].name = 'fluorometric_cdom' var_list[4].name = 'total_volume_scattering_coefficient' var_list[5].name = 'optical_backscatter' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm-1' var_list[2].units = 'ug/L' var_list[3].units = 'ppb' var_list[4].units = 'm-1 sr-1' var_list[5].units = 'm-1' elif platform_name == 'CE06ISSM' and node == 'BUOY' and instrument_class == 'FLORT' and method == 'Telemetered': uframe_dataset_name = 'CE06ISSM/SBD17/06-FLORTD000/telemetered/flort_sample' var_list[0].name = 'time' var_list[1].name = 'seawater_scattering_coefficient' var_list[2].name = 'fluorometric_chlorophyll_a' var_list[3].name = 'fluorometric_cdom' var_list[4].name = 'total_volume_scattering_coefficient' var_list[5].name = 'optical_backscatter' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm-1' var_list[2].units = 'ug/L' var_list[3].units = 'ppb' var_list[4].units = 'm-1 sr-1' var_list[5].units = 'm-1' elif platform_name == 'CE02SHSM' and node == 'NSIF' and instrument_class == 'FLORT' and method == 'Telemetered': uframe_dataset_name = 'CE02SHSM/RID27/02-FLORTD000/telemetered/flort_sample' var_list[0].name = 'time' var_list[1].name = 'seawater_scattering_coefficient' var_list[2].name = 'fluorometric_chlorophyll_a' var_list[3].name = 'fluorometric_cdom' var_list[4].name = 'total_volume_scattering_coefficient' var_list[5].name = 'optical_backscatter' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm-1' var_list[2].units = 'ug/L' var_list[3].units = 'ppb' var_list[4].units = 'm-1 sr-1' var_list[5].units = 'm-1' elif platform_name == 'CE07SHSM' and node == 'NSIF' and instrument_class == 'FLORT' and method == 'Telemetered': uframe_dataset_name = 'CE07SHSM/RID27/02-FLORTD000/telemetered/flort_sample' var_list[0].name = 'time' var_list[1].name = 'seawater_scattering_coefficient' var_list[2].name = 'fluorometric_chlorophyll_a' var_list[3].name = 'fluorometric_cdom' var_list[4].name = 'total_volume_scattering_coefficient' var_list[5].name = 'optical_backscatter' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm-1' var_list[2].units = 'ug/L' var_list[3].units = 'ppb' var_list[4].units = 'm-1 sr-1' var_list[5].units = 'm-1' elif platform_name == 'CE04OSSM' and node == 'NSIF' and instrument_class == 'FLORT' and method == 'Telemetered': uframe_dataset_name = 'CE04OSSM/RID27/02-FLORTD000/telemetered/flort_sample' var_list[0].name = 'time' var_list[1].name = 'seawater_scattering_coefficient' var_list[2].name = 'fluorometric_chlorophyll_a' var_list[3].name = 'fluorometric_cdom' var_list[4].name = 'total_volume_scattering_coefficient' var_list[5].name = 'optical_backscatter' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm-1' var_list[2].units = 'ug/L' var_list[3].units = 'ppb' var_list[4].units = 'm-1 sr-1' var_list[5].units = 'm-1' elif platform_name == 'CE09OSSM' and node == 'NSIF' and instrument_class == 'FLORT' and method == 'Telemetered': uframe_dataset_name = 'CE09OSSM/RID27/02-FLORTD000/telemetered/flort_sample' var_list[0].name = 'time' var_list[1].name = 'seawater_scattering_coefficient' var_list[2].name = 'fluorometric_chlorophyll_a' var_list[3].name = 'fluorometric_cdom' var_list[4].name = 'total_volume_scattering_coefficient' var_list[5].name = 'optical_backscatter' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm-1' var_list[2].units = 'ug/L' var_list[3].units = 'ppb' var_list[4].units = 'm-1 sr-1' var_list[5].units = 'm-1' elif platform_name == 'CE09OSPM' and node == 'PROFILER' and instrument_class == 'FLORT' and method == 'Telemetered': uframe_dataset_name = 'CE09OSPM/WFP01/04-FLORTK000/telemetered/flort_sample' var_list[0].name = 'time' var_list[1].name = 'seawater_scattering_coefficient' var_list[2].name = 'fluorometric_chlorophyll_a' var_list[3].name = 'fluorometric_cdom' var_list[4].name = 'total_volume_scattering_coefficient' var_list[5].name = 'optical_backscatter' var_list[6].name = 'int_ctd_pressure' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm-1' var_list[2].units = 'ug/L' var_list[3].units = 'ppb' var_list[4].units = 'm-1 sr-1' var_list[5].units = 'm-1' var_list[6].units = 'dbar' #FDCHP elif platform_name == 'CE02SHSM' and node == 'BUOY' and instrument_class == 'FDCHP' and method == 'Telemetered': uframe_dataset_name = 'CE02SHSM/SBD12/08-FDCHPA000/telemetered/fdchp_a_dcl_instrument' var_list[0].name = 'time' var_list[0].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' #DOSTA elif platform_name == 'CE01ISSM' and node == 'NSIF' and instrument_class == 'DOSTA' and method == 'Telemetered': uframe_dataset_name = 'CE01ISSM/RID16/03-DOSTAD000/telemetered/dosta_abcdjm_ctdbp_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'dissolved_oxygen' var_list[2].name = 'dosta_ln_optode_oxygen' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'umol/kg' var_list[2].units = 'umol/L' elif platform_name == 'CE02SHSM' and node == 'NSIF' and instrument_class == 'DOSTA' and method == 'Telemetered': uframe_dataset_name = 'CE02SHSM/RID27/04-DOSTAD000/telemetered/dosta_abcdjm_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'dissolved_oxygen' var_list[2].name = 'estimated_oxygen_concentration' var_list[3].name = 'optode_temperature' var_list[4].name = 'dosta_abcdjm_cspp_tc_oxygen' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'umol/kg' var_list[2].units = 'umol/L' var_list[3].units = 'degC' var_list[4].units = 'umol/L' elif platform_name == 'CE04OSSM' and node == 'NSIF' and instrument_class == 'DOSTA' and method == 'Telemetered': uframe_dataset_name = 'CE04OSSM/RID27/04-DOSTAD000/telemetered/dosta_abcdjm_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'dissolved_oxygen' var_list[2].name = 'estimated_oxygen_concentration' var_list[3].name = 'optode_temperature' var_list[4].name = 'dosta_abcdjm_cspp_tc_oxygen' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'umol/kg' var_list[2].units = 'umol/L' var_list[3].units = 'degC' var_list[4].units = 'umol/L' elif platform_name == 'CE06ISSM' and node == 'NSIF' and instrument_class == 'DOSTA' and method == 'Telemetered': uframe_dataset_name = 'CE06ISSM/RID16/03-DOSTAD000/telemetered/dosta_abcdjm_ctdbp_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'dissolved_oxygen' var_list[2].name = 'dosta_ln_optode_oxygen' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'umol/kg' var_list[2].units = 'umol/L' elif platform_name == 'CE07SHSM' and node == 'NSIF' and instrument_class == 'DOSTA' and method == 'Telemetered': uframe_dataset_name = 'CE07SHSM/RID27/04-DOSTAD000/telemetered/dosta_abcdjm_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'dissolved_oxygen' var_list[2].name = 'estimated_oxygen_concentration' var_list[3].name = 'optode_temperature' var_list[4].name = 'dosta_abcdjm_cspp_tc_oxygen' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'umol/kg' var_list[2].units = 'umol/L' var_list[3].units = 'degC' var_list[4].units = 'umol/L' elif platform_name == 'CE09OSSM' and node == 'NSIF' and instrument_class == 'DOSTA' and method == 'Telemetered': uframe_dataset_name = 'CE09OSSM/RID27/04-DOSTAD000/telemetered/dosta_abcdjm_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'dissolved_oxygen' var_list[2].name = 'estimated_oxygen_concentration' var_list[3].name = 'optode_temperature' var_list[4].name = 'dosta_abcdjm_cspp_tc_oxygen' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'umol/kg' var_list[2].units = 'umol/L' var_list[3].units = 'degC' var_list[4].units = 'umol/L' elif platform_name == 'CE01ISSM' and node == 'MFN' and instrument_class == 'DOSTA' and method == 'Telemetered': uframe_dataset_name = 'CE01ISSM/MFD37/03-DOSTAD000/telemetered/dosta_abcdjm_ctdbp_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'dissolved_oxygen' var_list[2].name = 'dosta_ln_optode_oxygen' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'umol/kg' var_list[2].units = 'umol/L' elif platform_name == 'CE06ISSM' and node == 'MFN' and instrument_class == 'DOSTA' and method == 'Telemetered': uframe_dataset_name = 'CE06ISSM/MFD37/03-DOSTAD000/telemetered/dosta_abcdjm_ctdbp_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'dissolved_oxygen' var_list[2].name = 'dosta_ln_optode_oxygen' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'umol/kg' var_list[2].units = 'umol/L' elif platform_name == 'CE07SHSM' and node == 'MFN' and instrument_class == 'DOSTA' and method == 'Telemetered': uframe_dataset_name = 'CE07SHSM/MFD37/03-DOSTAD000/telemetered/dosta_abcdjm_ctdbp_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'dissolved_oxygen' var_list[2].name = 'dosta_ln_optode_oxygen' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'umol/kg' var_list[2].units = 'umol/L' elif platform_name == 'CE09OSSM' and node == 'MFN' and instrument_class == 'DOSTA' and method == 'Telemetered': uframe_dataset_name = 'CE09OSSM/MFD37/03-DOSTAD000/telemetered/dosta_abcdjm_ctdbp_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'dissolved_oxygen' var_list[2].name = 'dosta_ln_optode_oxygen' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'umol/kg' var_list[2].units = 'umol/L' elif platform_name == 'CE09OSPM' and node == 'PROFILER' and instrument_class == 'DOSTA' and method == 'Telemetered': uframe_dataset_name = 'CE09OSPM/WFP01/02-DOFSTK000/telemetered/dofst_k_wfp_instrument' var_list[0].name = 'time' var_list[1].name = 'dofst_k_oxygen_l2' var_list[2].name = 'dofst_k_oxygen' var_list[3].name = 'int_ctd_pressure' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'umol/kg' var_list[2].units = 'Hz' var_list[3].units = 'dbar' #ADCP elif platform_name == 'CE02SHSM' and node == 'NSIF' and instrument_class == 'ADCP' and method == 'Telemetered': uframe_dataset_name = 'CE02SHSM/RID26/01-ADCPTA000/telemetered/adcp_velocity_earth' var_list[0].name = 'time' var_list[1].name = 'bin_depths' var_list[2].name = 'heading' var_list[3].name = 'pitch' var_list[4].name = 'roll' var_list[5].name = 'eastward_seawater_velocity' var_list[6].name = 'northward_seawater_velocity' var_list[7].name = 'upward_seawater_velocity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'meters' var_list[2].units = 'deci-degrees' var_list[3].units = 'deci-degrees' var_list[4].units = 'deci-degrees' var_list[5].units = 'm/s' var_list[6].units = 'm/s' var_list[7].units = 'm/s' elif platform_name == 'CE04OSSM' and node == 'NSIF' and instrument_class == 'ADCP' and method == 'Telemetered': uframe_dataset_name = 'CE04OSSM/RID26/01-ADCPTC000/telemetered/adcp_velocity_earth' var_list[0].name = 'time' var_list[1].name = 'bin_depths' var_list[2].name = 'heading' var_list[3].name = 'pitch' var_list[4].name = 'roll' var_list[5].name = 'eastward_seawater_velocity' var_list[6].name = 'northward_seawater_velocity' var_list[7].name = 'upward_seawater_velocity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'meters' var_list[2].units = 'deci-degrees' var_list[3].units = 'deci-degrees' var_list[4].units = 'deci-degrees' var_list[5].units = 'm/s' var_list[6].units = 'm/s' var_list[7].units = 'm/s' elif platform_name == 'CE07SHSM' and node == 'NSIF' and instrument_class == 'ADCP' and method == 'Telemetered': uframe_dataset_name = 'CE07SHSM/RID26/01-ADCPTA000/telemetered/adcp_velocity_earth' var_list[0].name = 'time' var_list[1].name = 'bin_depths' var_list[2].name = 'heading' var_list[3].name = 'pitch' var_list[4].name = 'roll' var_list[5].name = 'eastward_seawater_velocity' var_list[6].name = 'northward_seawater_velocity' var_list[7].name = 'upward_seawater_velocity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'meters' var_list[2].units = 'deci-degrees' var_list[3].units = 'deci-degrees' var_list[4].units = 'deci-degrees' var_list[5].units = 'm/s' var_list[6].units = 'm/s' var_list[7].units = 'm/s' elif platform_name == 'CE09OSSM' and node == 'NSIF' and instrument_class == 'ADCP' and method == 'Telemetered': uframe_dataset_name = 'CE09OSSM/RID26/01-ADCPTC000/telemetered/adcp_velocity_earth' var_list[0].name = 'time' var_list[1].name = 'bin_depths' var_list[2].name = 'heading' var_list[3].name = 'pitch' var_list[4].name = 'roll' var_list[5].name = 'eastward_seawater_velocity' var_list[6].name = 'northward_seawater_velocity' var_list[7].name = 'upward_seawater_velocity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'meters' var_list[2].units = 'deci-degrees' var_list[3].units = 'deci-degrees' var_list[4].units = 'deci-degrees' var_list[5].units = 'm/s' var_list[6].units = 'm/s' var_list[7].units = 'm/s' elif platform_name == 'CE01ISSM' and node == 'MFN' and instrument_class == 'ADCP' and method == 'Telemetered': uframe_dataset_name = 'CE01ISSM/MFD35/04-ADCPTM000/telemetered/adcp_velocity_earth' var_list[0].name = 'time' var_list[1].name = 'bin_depths' var_list[2].name = 'heading' var_list[3].name = 'pitch' var_list[4].name = 'roll' var_list[5].name = 'eastward_seawater_velocity' var_list[6].name = 'northward_seawater_velocity' var_list[7].name = 'upward_seawater_velocity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'meters' var_list[2].units = 'deci-degrees' var_list[3].units = 'deci-degrees' var_list[4].units = 'deci-degrees' var_list[5].units = 'm/s' var_list[6].units = 'm/s' var_list[7].units = 'm/s' elif platform_name == 'CE06ISSM' and node == 'MFN' and instrument_class == 'ADCP' and method == 'Telemetered': uframe_dataset_name = 'CE06ISSM/MFD35/04-ADCPTM000/telemetered/adcp_velocity_earth' var_list[0].name = 'time' var_list[1].name = 'bin_depths' var_list[2].name = 'heading' var_list[3].name = 'pitch' var_list[4].name = 'roll' var_list[5].name = 'eastward_seawater_velocity' var_list[6].name = 'northward_seawater_velocity' var_list[7].name = 'upward_seawater_velocity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'meters' var_list[2].units = 'deci-degrees' var_list[3].units = 'deci-degrees' var_list[4].units = 'deci-degrees' var_list[5].units = 'm/s' var_list[6].units = 'm/s' var_list[7].units = 'm/s' elif platform_name == 'CE07SHSM' and node == 'MFN' and instrument_class == 'ADCP' and method == 'Telemetered': uframe_dataset_name = 'CE07SHSM/MFD35/04-ADCPTC000/telemetered/adcp_velocity_earth' var_list[0].name = 'time' var_list[1].name = 'bin_depths' var_list[2].name = 'heading' var_list[3].name = 'pitch' var_list[4].name = 'roll' var_list[5].name = 'eastward_seawater_velocity' var_list[6].name = 'northward_seawater_velocity' var_list[7].name = 'upward_seawater_velocity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'meters' var_list[2].units = 'deci-degrees' var_list[3].units = 'deci-degrees' var_list[4].units = 'deci-degrees' var_list[5].units = 'm/s' var_list[6].units = 'm/s' var_list[7].units = 'm/s' elif platform_name == 'CE09OSSM' and node == 'MFN' and instrument_class == 'ADCP' and method == 'Telemetered': uframe_dataset_name = 'CE09OSSM/MFD35/04-ADCPSJ000/telemetered/adcp_velocity_earth' var_list[0].name = 'time' var_list[1].name = 'bin_depths' var_list[2].name = 'heading' var_list[3].name = 'pitch' var_list[4].name = 'roll' var_list[5].name = 'eastward_seawater_velocity' var_list[6].name = 'northward_seawater_velocity' var_list[7].name = 'upward_seawater_velocity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'meters' var_list[2].units = 'deci-degrees' var_list[3].units = 'deci-degrees' var_list[4].units = 'deci-degrees' var_list[5].units = 'm/s' var_list[6].units = 'm/s' var_list[7].units = 'm/s' #ZPLSC elif platform_name == 'CE01ISSM' and node == 'MFN' and instrument_class == 'ZPLSC' and method == 'Telemetered': uframe_dataset_name = 'CE01ISSM/MFD37/07-ZPLSCC000/telemetered/zplsc_c_instrument' var_list[0].name = 'time' var_list[0].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' elif platform_name == 'CE06ISSM' and node == 'MFN' and instrument_class == 'ZPLSC' and method == 'Telemetered': uframe_dataset_name = 'CE06ISSM/MFD37/07-ZPLSCC000/telemetered/zplsc_c_instrument' var_list[0].name = 'time' var_list[0].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' elif platform_name == 'CE07SHSM' and node == 'MFN' and instrument_class == 'ZPLSC' and method == 'Telemetered': uframe_dataset_name = 'CE07SHSM/MFD37/07-ZPLSCC000/telemetered/zplsc_c_instrument' var_list[0].name = 'time' var_list[0].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' elif platform_name == 'CE09OSSM' and node == 'MFN' and instrument_class == 'ZPLSC' and method == 'Telemetered': uframe_dataset_name = 'CE09OSSM/MFD37/07-ZPLSCC000/telemetered/zplsc_c_instrument' var_list[0].name = 'time' var_list[0].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' elif platform_name == 'CE01ISSM' and node == 'MFN' and instrument_class == 'ZPLSC' and method == 'RecoveredHost': uframe_dataset_name = 'CE01ISSM/MFD37/07-ZPLSCC000/recovered_host/zplsc_c_instrument' var_list[0].name = 'time' var_list[0].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' elif platform_name == 'CE06ISSM' and node == 'MFN' and instrument_class == 'ZPLSC' and method == 'RecoveredHost': uframe_dataset_name = 'CE06ISSM/MFD37/07-ZPLSCC000/recovered_host/zplsc_c_instrument' var_list[0].name = 'time' var_list[0].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' elif platform_name == 'CE07SHSM' and node == 'MFN' and instrument_class == 'ZPLSC' and method == 'RecoveredHost': uframe_dataset_name = 'CE07SHSM/MFD37/07-ZPLSCC000/recovered_host/zplsc_c_instrument' var_list[0].name = 'time' var_list[0].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' elif platform_name == 'CE09OSSM' and node == 'MFN' and instrument_class == 'ZPLSC' and method == 'RecoveredHost': uframe_dataset_name = 'CE09OSSM/MFD37/07-ZPLSCC000/recovered_host/zplsc_c_instrument' var_list[0].name = 'time' var_list[0].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' #WAVSS elif platform_name == 'CE02SHSM' and node == 'BUOY' and instrument_class == 'WAVSS_Stats' and method == 'Telemetered': uframe_dataset_name = 'CE02SHSM/SBD12/05-WAVSSA000/telemetered/wavss_a_dcl_statistics' var_list[0].name = 'time' var_list[1].name = 'number_zero_crossings' var_list[2].name = 'average_wave_height' var_list[3].name = 'mean_spectral_period' var_list[4].name = 'max_wave_height' var_list[5].name = 'significant_wave_height' var_list[6].name = 'significant_period' var_list[7].name = 'wave_height_10' var_list[8].name = 'wave_period_10' var_list[9].name = 'mean_wave_period' var_list[10].name = 'peak_wave_period' var_list[11].name = 'wave_period_tp5' var_list[12].name = 'wave_height_hmo' var_list[13].name = 'mean_direction' var_list[14].name = 'mean_spread' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[8].data = np.array([]) var_list[9].data = np.array([]) var_list[10].data = np.array([]) var_list[11].data = np.array([]) var_list[12].data = np.array([]) var_list[13].data = np.array([]) var_list[14].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'counts' var_list[2].units = 'm' var_list[3].units = 'sec' var_list[4].units = 'm' var_list[5].units = 'm' var_list[6].units = 'sec' var_list[7].units = 'm' var_list[8].units = 'sec' var_list[9].units = 'sec' var_list[10].units = 'sec' var_list[11].units = 'sec' var_list[12].units = 'm' var_list[13].units = 'degrees' var_list[14].units = 'degrees' elif platform_name == 'CE04OSSM' and node == 'BUOY' and instrument_class == 'WAVSS_Stats' and method == 'Telemetered': uframe_dataset_name = 'CE04OSSM/SBD12/05-WAVSSA000/telemetered/wavss_a_dcl_statistics' var_list[0].name = 'time' var_list[1].name = 'number_zero_crossings' var_list[2].name = 'average_wave_height' var_list[3].name = 'mean_spectral_period' var_list[4].name = 'max_wave_height' var_list[5].name = 'significant_wave_height' var_list[6].name = 'significant_period' var_list[7].name = 'wave_height_10' var_list[8].name = 'wave_period_10' var_list[9].name = 'mean_wave_period' var_list[10].name = 'peak_wave_period' var_list[11].name = 'wave_period_tp5' var_list[12].name = 'wave_height_hmo' var_list[13].name = 'mean_direction' var_list[14].name = 'mean_spread' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[8].data = np.array([]) var_list[9].data = np.array([]) var_list[10].data = np.array([]) var_list[11].data = np.array([]) var_list[12].data = np.array([]) var_list[13].data = np.array([]) var_list[14].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'counts' var_list[2].units = 'm' var_list[3].units = 'sec' var_list[4].units = 'm' var_list[5].units = 'm' var_list[6].units = 'sec' var_list[7].units = 'm' var_list[8].units = 'sec' var_list[9].units = 'sec' var_list[10].units = 'sec' var_list[11].units = 'sec' var_list[12].units = 'm' var_list[13].units = 'degrees' var_list[14].units = 'degrees' elif platform_name == 'CE07SHSM' and node == 'BUOY' and instrument_class == 'WAVSS_Stats' and method == 'Telemetered': uframe_dataset_name = 'CE07SHSM/SBD12/05-WAVSSA000/telemetered/wavss_a_dcl_statistics' var_list[0].name = 'time' var_list[1].name = 'number_zero_crossings' var_list[2].name = 'average_wave_height' var_list[3].name = 'mean_spectral_period' var_list[4].name = 'max_wave_height' var_list[5].name = 'significant_wave_height' var_list[6].name = 'significant_period' var_list[7].name = 'wave_height_10' var_list[8].name = 'wave_period_10' var_list[9].name = 'mean_wave_period' var_list[10].name = 'peak_wave_period' var_list[11].name = 'wave_period_tp5' var_list[12].name = 'wave_height_hmo' var_list[13].name = 'mean_direction' var_list[14].name = 'mean_spread' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[8].data = np.array([]) var_list[9].data = np.array([]) var_list[10].data = np.array([]) var_list[11].data = np.array([]) var_list[12].data = np.array([]) var_list[13].data = np.array([]) var_list[14].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'counts' var_list[2].units = 'm' var_list[3].units = 'sec' var_list[4].units = 'm' var_list[5].units = 'm' var_list[6].units = 'sec' var_list[7].units = 'm' var_list[8].units = 'sec' var_list[9].units = 'sec' var_list[10].units = 'sec' var_list[11].units = 'sec' var_list[12].units = 'm' var_list[13].units = 'degrees' var_list[14].units = 'degrees' elif platform_name == 'CE09OSSM' and node == 'BUOY' and instrument_class == 'WAVSS_Stats' and method == 'Telemetered': uframe_dataset_name = 'CE09OSSM/SBD12/05-WAVSSA000/telemetered/wavss_a_dcl_statistics' var_list[0].name = 'time' var_list[1].name = 'number_zero_crossings' var_list[2].name = 'average_wave_height' var_list[3].name = 'mean_spectral_period' var_list[4].name = 'max_wave_height' var_list[5].name = 'significant_wave_height' var_list[6].name = 'significant_period' var_list[7].name = 'wave_height_10' var_list[8].name = 'wave_period_10' var_list[9].name = 'mean_wave_period' var_list[10].name = 'peak_wave_period' var_list[11].name = 'wave_period_tp5' var_list[12].name = 'wave_height_hmo' var_list[13].name = 'mean_direction' var_list[14].name = 'mean_spread' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[8].data = np.array([]) var_list[9].data = np.array([]) var_list[10].data = np.array([]) var_list[11].data = np.array([]) var_list[12].data = np.array([]) var_list[13].data = np.array([]) var_list[14].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'counts' var_list[2].units = 'm' var_list[3].units = 'sec' var_list[4].units = 'm' var_list[5].units = 'm' var_list[6].units = 'sec' var_list[7].units = 'm' var_list[8].units = 'sec' var_list[9].units = 'sec' var_list[10].units = 'sec' var_list[11].units = 'sec' var_list[12].units = 'm' var_list[13].units = 'degrees' var_list[14].units = 'degrees' #VELPT elif platform_name == 'CE01ISSM' and node == 'BUOY' and instrument_class == 'VELPT' and method == 'Telemetered': uframe_dataset_name = 'CE01ISSM/SBD17/04-VELPTA000/telemetered/velpt_ab_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'eastward_velocity' var_list[2].name = 'northward_velocity' var_list[3].name = 'upward_velocity' var_list[4].name = 'heading_decidegree' var_list[5].name = 'roll_decidegree' var_list[6].name = 'pitch_decidegree' var_list[7].name = 'temperature_centidegree' var_list[8].name = 'pressure_mbar' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[8].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm/s' var_list[2].units = 'm/s' var_list[3].units = 'm/s' var_list[4].units = 'deci-degrees' var_list[5].units = 'deci-degrees' var_list[6].units = 'deci-degrees' var_list[7].units = '0.01degC' var_list[8].units = '0.001dbar' elif platform_name == 'CE02SHSM' and node == 'BUOY' and instrument_class == 'VELPT' and method == 'Telemetered': uframe_dataset_name = 'CE02SHSM/SBD11/04-VELPTA000/telemetered/velpt_ab_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'eastward_velocity' var_list[2].name = 'northward_velocity' var_list[3].name = 'upward_velocity' var_list[4].name = 'heading_decidegree' var_list[5].name = 'roll_decidegree' var_list[6].name = 'pitch_decidegree' var_list[7].name = 'temperature_centidegree' var_list[8].name = 'pressure_mbar' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[8].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm/s' var_list[2].units = 'm/s' var_list[3].units = 'm/s' var_list[4].units = 'deci-degrees' var_list[5].units = 'deci-degrees' var_list[6].units = 'deci-degrees' var_list[7].units = '0.01degC' var_list[8].units = '0.001dbar' elif platform_name == 'CE04OSSM' and node == 'BUOY' and instrument_class == 'VELPT' and method == 'Telemetered': uframe_dataset_name = 'CE04OSSM/SBD11/04-VELPTA000/telemetered/velpt_ab_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'eastward_velocity' var_list[2].name = 'northward_velocity' var_list[3].name = 'upward_velocity' var_list[4].name = 'heading_decidegree' var_list[5].name = 'roll_decidegree' var_list[6].name = 'pitch_decidegree' var_list[7].name = 'temperature_centidegree' var_list[8].name = 'pressure_mbar' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[8].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm/s' var_list[2].units = 'm/s' var_list[3].units = 'm/s' var_list[4].units = 'deci-degrees' var_list[5].units = 'deci-degrees' var_list[6].units = 'deci-degrees' var_list[7].units = '0.01degC' var_list[8].units = '0.001dbar' elif platform_name == 'CE06ISSM' and node == 'BUOY' and instrument_class == 'VELPT' and method == 'Telemetered': uframe_dataset_name = 'CE06ISSM/SBD17/04-VELPTA000/telemetered/velpt_ab_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'eastward_velocity' var_list[2].name = 'northward_velocity' var_list[3].name = 'upward_velocity' var_list[4].name = 'heading_decidegree' var_list[5].name = 'roll_decidegree' var_list[6].name = 'pitch_decidegree' var_list[7].name = 'temperature_centidegree' var_list[8].name = 'pressure_mbar' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[8].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm/s' var_list[2].units = 'm/s' var_list[3].units = 'm/s' var_list[4].units = 'deci-degrees' var_list[5].units = 'deci-degrees' var_list[6].units = 'deci-degrees' var_list[7].units = '0.01degC' var_list[8].units = '0.001dbar' elif platform_name == 'CE07SHSM' and node == 'BUOY' and instrument_class == 'VELPT' and method == 'Telemetered': uframe_dataset_name = 'CE07SHSM/SBD11/04-VELPTA000/telemetered/velpt_ab_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'eastward_velocity' var_list[2].name = 'northward_velocity' var_list[3].name = 'upward_velocity' var_list[4].name = 'heading_decidegree' var_list[5].name = 'roll_decidegree' var_list[6].name = 'pitch_decidegree' var_list[7].name = 'temperature_centidegree' var_list[8].name = 'pressure_mbar' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[8].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm/s' var_list[2].units = 'm/s' var_list[3].units = 'm/s' var_list[4].units = 'deci-degrees' var_list[5].units = 'deci-degrees' var_list[6].units = 'deci-degrees' var_list[7].units = '0.01degC' var_list[8].units = '0.001dbar' elif platform_name == 'CE09OSSM' and node == 'BUOY' and instrument_class == 'VELPT' and method == 'Telemetered': uframe_dataset_name = 'CE09OSSM/SBD11/04-VELPTA000/telemetered/velpt_ab_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'eastward_velocity' var_list[2].name = 'northward_velocity' var_list[3].name = 'upward_velocity' var_list[4].name = 'heading_decidegree' var_list[5].name = 'roll_decidegree' var_list[6].name = 'pitch_decidegree' var_list[7].name = 'temperature_centidegree' var_list[8].name = 'pressure_mbar' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[8].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm/s' var_list[2].units = 'm/s' var_list[3].units = 'm/s' var_list[4].units = 'deci-degrees' var_list[5].units = 'deci-degrees' var_list[6].units = 'deci-degrees' var_list[7].units = '0.01degC' var_list[8].units = '0.001dbar' elif platform_name == 'CE01ISSM' and node == 'NSIF' and instrument_class == 'VELPT' and method == 'Telemetered': uframe_dataset_name = 'CE01ISSM/RID16/04-VELPTA000/telemetered/velpt_ab_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'eastward_velocity' var_list[2].name = 'northward_velocity' var_list[3].name = 'upward_velocity' var_list[4].name = 'heading_decidegree' var_list[5].name = 'roll_decidegree' var_list[6].name = 'pitch_decidegree' var_list[7].name = 'temperature_centidegree' var_list[8].name = 'pressure_mbar' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[8].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm/s' var_list[2].units = 'm/s' var_list[3].units = 'm/s' var_list[4].units = 'deci-degrees' var_list[5].units = 'deci-degrees' var_list[6].units = 'deci-degrees' var_list[7].units = '0.01degC' var_list[8].units = '0.001dbar' elif platform_name == 'CE02SHSM' and node == 'NSIF' and instrument_class == 'VELPT' and method == 'Telemetered': uframe_dataset_name = 'CE02SHSM/RID26/04-VELPTA000/telemetered/velpt_ab_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'eastward_velocity' var_list[2].name = 'northward_velocity' var_list[3].name = 'upward_velocity' var_list[4].name = 'heading_decidegree' var_list[5].name = 'roll_decidegree' var_list[6].name = 'pitch_decidegree' var_list[7].name = 'temperature_centidegree' var_list[8].name = 'pressure_mbar' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[8].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm/s' var_list[2].units = 'm/s' var_list[3].units = 'm/s' var_list[4].units = 'deci-degrees' var_list[5].units = 'deci-degrees' var_list[6].units = 'deci-degrees' var_list[7].units = '0.01degC' var_list[8].units = '0.001dbar' elif platform_name == 'CE04OSSM' and node == 'NSIF' and instrument_class == 'VELPT' and method == 'Telemetered': uframe_dataset_name = 'CE04OSSM/RID26/04-VELPTA000/telemetered/velpt_ab_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'eastward_velocity' var_list[2].name = 'northward_velocity' var_list[3].name = 'upward_velocity' var_list[4].name = 'heading_decidegree' var_list[5].name = 'roll_decidegree' var_list[6].name = 'pitch_decidegree' var_list[7].name = 'temperature_centidegree' var_list[8].name = 'pressure_mbar' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[8].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm/s' var_list[2].units = 'm/s' var_list[3].units = 'm/s' var_list[4].units = 'deci-degrees' var_list[5].units = 'deci-degrees' var_list[6].units = 'deci-degrees' var_list[7].units = '0.01degC' var_list[8].units = '0.001dbar' elif platform_name == 'CE06ISSM' and node == 'NSIF' and instrument_class == 'VELPT' and method == 'Telemetered': uframe_dataset_name = 'CE06ISSM/RID16/04-VELPTA000/telemetered/velpt_ab_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'eastward_velocity' var_list[2].name = 'northward_velocity' var_list[3].name = 'upward_velocity' var_list[4].name = 'heading_decidegree' var_list[5].name = 'roll_decidegree' var_list[6].name = 'pitch_decidegree' var_list[7].name = 'temperature_centidegree' var_list[8].name = 'pressure_mbar' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[8].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm/s' var_list[2].units = 'm/s' var_list[3].units = 'm/s' var_list[4].units = 'deci-degrees' var_list[5].units = 'deci-degrees' var_list[6].units = 'deci-degrees' var_list[7].units = '0.01degC' var_list[8].units = '0.001dbar' elif platform_name == 'CE07SHSM' and node == 'NSIF' and instrument_class == 'VELPT' and method == 'Telemetered': uframe_dataset_name = 'CE07SHSM/RID26/04-VELPTA000/telemetered/velpt_ab_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'eastward_velocity' var_list[2].name = 'northward_velocity' var_list[3].name = 'upward_velocity' var_list[4].name = 'heading_decidegree' var_list[5].name = 'roll_decidegree' var_list[6].name = 'pitch_decidegree' var_list[7].name = 'temperature_centidegree' var_list[8].name = 'pressure_mbar' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[8].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm/s' var_list[2].units = 'm/s' var_list[3].units = 'm/s' var_list[4].units = 'deci-degrees' var_list[5].units = 'deci-degrees' var_list[6].units = 'deci-degrees' var_list[7].units = '0.01degC' var_list[8].units = '0.001dbar' elif platform_name == 'CE09OSSM' and node == 'NSIF' and instrument_class == 'VELPT' and method == 'Telemetered': uframe_dataset_name = 'CE09OSSM/RID26/04-VELPTA000/telemetered/velpt_ab_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'eastward_velocity' var_list[2].name = 'northward_velocity' var_list[3].name = 'upward_velocity' var_list[4].name = 'heading_decidegree' var_list[5].name = 'roll_decidegree' var_list[6].name = 'pitch_decidegree' var_list[7].name = 'temperature_centidegree' var_list[8].name = 'pressure_mbar' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[8].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm/s' var_list[2].units = 'm/s' var_list[3].units = 'm/s' var_list[4].units = 'deci-degrees' var_list[5].units = 'deci-degrees' var_list[6].units = 'deci-degrees' var_list[7].units = '0.01degC' var_list[8].units = '0.001dbar' #PCO2W elif platform_name == 'CE01ISSM' and node == 'NSIF' and instrument_class == 'PCO2W' and method == 'Telemetered': uframe_dataset_name = 'CE01ISSM/RID16/05-PCO2WB000/telemetered/pco2w_abc_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'pco2w_thermistor_temperature' var_list[2].name = 'pco2_seawater' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'uatm' elif platform_name == 'CE01ISSM' and node == 'MFN' and instrument_class == 'PCO2W' and method == 'Telemetered': uframe_dataset_name = 'CE01ISSM/MFD35/05-PCO2WB000/telemetered/pco2w_abc_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'pco2w_thermistor_temperature' var_list[2].name = 'pco2_seawater' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'uatm' elif platform_name == 'CE06ISSM' and node == 'NSIF' and instrument_class == 'PCO2W' and method == 'Telemetered': uframe_dataset_name = 'CE06ISSM/RID16/05-PCO2WB000/telemetered/pco2w_abc_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'pco2w_thermistor_temperature' var_list[2].name = 'pco2_seawater' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'uatm' elif platform_name == 'CE06ISSM' and node == 'MFN' and instrument_class == 'PCO2W' and method == 'Telemetered': uframe_dataset_name = 'CE06ISSM/MFD35/05-PCO2WB000/telemetered/pco2w_abc_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'pco2w_thermistor_temperature' var_list[2].name = 'pco2_seawater' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'uatm' elif platform_name == 'CE07SHSM' and node == 'MFN' and instrument_class == 'PCO2W' and method == 'Telemetered': uframe_dataset_name = 'CE07SHSM/MFD35/05-PCO2WB000/telemetered/pco2w_abc_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'pco2w_thermistor_temperature' var_list[2].name = 'pco2_seawater' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'uatm' elif platform_name == 'CE09OSSM' and node == 'MFN' and instrument_class == 'PCO2W' and method == 'Telemetered': uframe_dataset_name = 'CE09OSSM/MFD35/05-PCO2WB000/telemetered/pco2w_abc_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'pco2w_thermistor_temperature' var_list[2].name = 'pco2_seawater' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'uatm' #PHSEN elif platform_name == 'CE01ISSM' and node == 'NSIF' and instrument_class == 'PHSEN' and method == 'Telemetered': uframe_dataset_name = 'CE01ISSM/RID16/06-PHSEND000/telemetered/phsen_abcdef_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'phsen_thermistor_temperature' var_list[2].name = 'phsen_abcdef_ph_seawater' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' elif platform_name == 'CE02SHSM' and node == 'NSIF' and instrument_class == 'PHSEN' and method == 'Telemetered': uframe_dataset_name = 'CE02SHSM/RID26/06-PHSEND000/telemetered/phsen_abcdef_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'phsen_thermistor_temperature' var_list[2].name = 'phsen_abcdef_ph_seawater' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' elif platform_name == 'CE04OSSM' and node == 'NSIF' and instrument_class == 'PHSEN' and method == 'Telemetered': uframe_dataset_name = 'CE04OSSM/RID26/06-PHSEND000/telemetered/phsen_abcdef_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'phsen_thermistor_temperature' var_list[2].name = 'phsen_abcdef_ph_seawater' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' elif platform_name == 'CE06ISSM' and node == 'NSIF' and instrument_class == 'PHSEN' and method == 'Telemetered': uframe_dataset_name = 'CE06ISSM/RID16/06-PHSEND000/telemetered/phsen_abcdef_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'phsen_thermistor_temperature' var_list[2].name = 'phsen_abcdef_ph_seawater' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' elif platform_name == 'CE07SHSM' and node == 'NSIF' and instrument_class == 'PHSEN' and method == 'Telemetered': uframe_dataset_name = 'CE07SHSM/RID26/06-PHSEND000/telemetered/phsen_abcdef_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'phsen_thermistor_temperature' var_list[2].name = 'phsen_abcdef_ph_seawater' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' elif platform_name == 'CE09OSSM' and node == 'NSIF' and instrument_class == 'PHSEN' and method == 'Telemetered': uframe_dataset_name = 'CE09OSSM/RID26/06-PHSEND000/telemetered/phsen_abcdef_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'phsen_thermistor_temperature' var_list[2].name = 'phsen_abcdef_ph_seawater' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' elif platform_name == 'CE01ISSM' and node == 'MFN' and instrument_class == 'PHSEN' and method == 'Telemetered': uframe_dataset_name = 'CE01ISSM/MFD35/06-PHSEND000/telemetered/phsen_abcdef_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'phsen_thermistor_temperature' var_list[2].name = 'phsen_abcdef_ph_seawater' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' elif platform_name == 'CE06ISSM' and node == 'MFN' and instrument_class == 'PHSEN' and method == 'Telemetered': uframe_dataset_name = 'CE06ISSM/MFD35/06-PHSEND000/telemetered/phsen_abcdef_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'phsen_thermistor_temperature' var_list[2].name = 'phsen_abcdef_ph_seawater' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' elif platform_name == 'CE07SHSM' and node == 'MFN' and instrument_class == 'PHSEN' and method == 'Telemetered': uframe_dataset_name = 'CE07SHSM/MFD35/06-PHSEND000/telemetered/phsen_abcdef_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'phsen_thermistor_temperature' var_list[2].name = 'phsen_abcdef_ph_seawater' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' elif platform_name == 'CE09OSSM' and node == 'MFN' and instrument_class == 'PHSEN' and method == 'Telemetered': uframe_dataset_name = 'CE09OSSM/MFD35/06-PHSEND000/telemetered/phsen_abcdef_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'phsen_thermistor_temperature' var_list[2].name = 'phsen_abcdef_ph_seawater' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' #SPKIR elif platform_name == 'CE01ISSM' and node == 'NSIF' and instrument_class == 'SPKIR' and method == 'Telemetered': uframe_dataset_name = 'CE01ISSM/RID16/08-SPKIRB000/telemetered/spkir_abj_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'spkir_abj_cspp_downwelling_vector' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'uW cm-2 nm-1' elif platform_name == 'CE02SHSM' and node == 'NSIF' and instrument_class == 'SPKIR' and method == 'Telemetered': uframe_dataset_name = 'CE02SHSM/RID26/08-SPKIRB000/telemetered/spkir_abj_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'spkir_abj_cspp_downwelling_vector' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'uW cm-2 nm-1' elif platform_name == 'CE04OSSM' and node == 'NSIF' and instrument_class == 'SPKIR' and method == 'Telemetered': uframe_dataset_name = 'CE04OSSM/RID26/08-SPKIRB000/telemetered/spkir_abj_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'spkir_abj_cspp_downwelling_vector' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'uW cm-2 nm-1' elif platform_name == 'CE06ISSM' and node == 'NSIF' and instrument_class == 'SPKIR' and method == 'Telemetered': uframe_dataset_name = 'CE06ISSM/RID16/08-SPKIRB000/telemetered/spkir_abj_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'spkir_abj_cspp_downwelling_vector' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'uW cm-2 nm-1' elif platform_name == 'CE07SHSM' and node == 'NSIF' and instrument_class == 'SPKIR' and method == 'Telemetered': uframe_dataset_name = 'CE07SHSM/RID26/08-SPKIRB000/telemetered/spkir_abj_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'spkir_abj_cspp_downwelling_vector' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'uW cm-2 nm-1' elif platform_name == 'CE09OSSM' and node == 'NSIF' and instrument_class == 'SPKIR' and method == 'Telemetered': uframe_dataset_name = 'CE09OSSM/RID26/08-SPKIRB000/telemetered/spkir_abj_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'spkir_abj_cspp_downwelling_vector' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'uW cm-2 nm-1' #PRESF elif platform_name == 'CE01ISSM' and node == 'MFN' and instrument_class == 'PRESF' and method == 'Telemetered': uframe_dataset_name = 'CE01ISSM/MFD35/02-PRESFA000/telemetered/presf_abc_dcl_tide_measurement' var_list[0].name = 'time' var_list[1].name = 'abs_seafloor_pressure' var_list[2].name = 'seawater_temperature' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'dbar' var_list[2].units = 'degC' elif platform_name == 'CE06ISSM' and node == 'MFN' and instrument_class == 'PRESF' and method == 'Telemetered': uframe_dataset_name = 'CE06ISSM/MFD35/02-PRESFA000/telemetered/presf_abc_dcl_tide_measurement' var_list[0].name = 'time' var_list[1].name = 'abs_seafloor_pressure' var_list[2].name = 'seawater_temperature' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'dbar' var_list[2].units = 'degC' elif platform_name == 'CE07SHSM' and node == 'MFN' and instrument_class == 'PRESF' and method == 'Telemetered': uframe_dataset_name = 'CE07SHSM/MFD35/02-PRESFB000/telemetered/presf_abc_dcl_tide_measurement' var_list[0].name = 'time' var_list[1].name = 'abs_seafloor_pressure' var_list[2].name = 'seawater_temperature' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'dbar' var_list[2].units = 'degC' elif platform_name == 'CE09OSSM' and node == 'MFN' and instrument_class == 'PRESF' and method == 'Telemetered': uframe_dataset_name = 'CE09OSSM/MFD35/02-PRESFC000/telemetered/presf_abc_dcl_tide_measurement' var_list[0].name = 'time' var_list[1].name = 'abs_seafloor_pressure' var_list[2].name = 'seawater_temperature' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'dbar' var_list[2].units = 'degC' #CTDBP elif platform_name == 'CE01ISSM' and node == 'NSIF' and instrument_class == 'CTD' and method == 'Telemetered': uframe_dataset_name = 'CE01ISSM/RID16/03-CTDBPC000/telemetered/ctdbp_cdef_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'temp' var_list[2].name = 'practical_salinity' var_list[3].name = 'density' var_list[4].name = 'pressure' var_list[5].name = 'conductivity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' var_list[3].units = 'kg/m3' var_list[4].units = 'dbar' var_list[5].units = 'S/m' elif platform_name == 'CE01ISSM' and node == 'MFN' and instrument_class == 'CTD' and method == 'Telemetered': uframe_dataset_name = 'CE01ISSM/MFD37/03-CTDBPC000/telemetered/ctdbp_cdef_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'temp' var_list[2].name = 'practical_salinity' var_list[3].name = 'density' var_list[4].name = 'pressure' var_list[5].name = 'conductivity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' var_list[3].units = 'kg/m3' var_list[4].units = 'dbar' var_list[5].units = 'S/m' elif platform_name == 'CE01ISSM' and node == 'BUOY' and instrument_class == 'CTD' and method == 'Telemetered': uframe_dataset_name = 'CE01ISSM/SBD17/06-CTDBPC000/telemetered/ctdbp_cdef_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'temp' var_list[2].name = 'practical_salinity' var_list[3].name = 'density' var_list[4].name = 'pressure' var_list[5].name = 'conductivity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' var_list[3].units = 'kg/m3' var_list[4].units = 'dbar' var_list[5].units = 'S/m' elif platform_name == 'CE06ISSM' and node == 'NSIF' and instrument_class == 'CTD' and method == 'Telemetered': uframe_dataset_name = 'CE06ISSM/RID16/03-CTDBPC000/telemetered/ctdbp_cdef_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'temp' var_list[2].name = 'practical_salinity' var_list[3].name = 'density' var_list[4].name = 'pressure' var_list[5].name = 'conductivity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' var_list[3].units = 'kg/m3' var_list[4].units = 'dbar' var_list[5].units = 'S/m' elif platform_name == 'CE06ISSM' and node == 'MFN' and instrument_class == 'CTD' and method == 'Telemetered': uframe_dataset_name = 'CE06ISSM/MFD37/03-CTDBPC000/telemetered/ctdbp_cdef_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'temp' var_list[2].name = 'practical_salinity' var_list[3].name = 'density' var_list[4].name = 'pressure' var_list[5].name = 'conductivity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' var_list[3].units = 'kg/m3' var_list[4].units = 'dbar' var_list[5].units = 'S/m' elif platform_name == 'CE06ISSM' and node == 'BUOY' and instrument_class == 'CTD' and method == 'Telemetered': uframe_dataset_name = 'CE06ISSM/SBD17/06-CTDBPC000/telemetered/ctdbp_cdef_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'temp' var_list[2].name = 'practical_salinity' var_list[3].name = 'density' var_list[4].name = 'pressure' var_list[5].name = 'conductivity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' var_list[3].units = 'kg/m3' var_list[4].units = 'dbar' var_list[5].units = 'S/m' elif platform_name == 'CE02SHSM' and node == 'NSIF' and instrument_class == 'CTD' and method == 'Telemetered': uframe_dataset_name = 'CE02SHSM/RID27/03-CTDBPC000/telemetered/ctdbp_cdef_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'temp' var_list[2].name = 'practical_salinity' var_list[3].name = 'density' var_list[4].name = 'pressure' var_list[5].name = 'conductivity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' var_list[3].units = 'kg/m3' var_list[4].units = 'dbar' var_list[5].units = 'S/m' elif platform_name == 'CE07SHSM' and node == 'NSIF' and instrument_class == 'CTD' and method == 'Telemetered': uframe_dataset_name = 'CE07SHSM/RID27/03-CTDBPC000/telemetered/ctdbp_cdef_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'temp' var_list[2].name = 'practical_salinity' var_list[3].name = 'density' var_list[4].name = 'pressure' var_list[5].name = 'conductivity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' var_list[3].units = 'kg/m3' var_list[4].units = 'dbar' var_list[5].units = 'S/m' elif platform_name == 'CE04OSSM' and node == 'NSIF' and instrument_class == 'CTD' and method == 'Telemetered': uframe_dataset_name = 'CE04OSSM/RID27/03-CTDBPC000/telemetered/ctdbp_cdef_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'temp' var_list[2].name = 'practical_salinity' var_list[3].name = 'density' var_list[4].name = 'pressure' var_list[5].name = 'conductivity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' var_list[3].units = 'kg/m3' var_list[4].units = 'dbar' var_list[5].units = 'S/m' elif platform_name == 'CE09OSSM' and node == 'NSIF' and instrument_class == 'CTD' and method == 'Telemetered': uframe_dataset_name = 'CE09OSSM/RID27/03-CTDBPC000/telemetered/ctdbp_cdef_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'temp' var_list[2].name = 'practical_salinity' var_list[3].name = 'density' var_list[4].name = 'pressure' var_list[5].name = 'conductivity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' var_list[3].units = 'kg/m3' var_list[4].units = 'dbar' var_list[5].units = 'S/m' elif platform_name == 'CE07SHSM' and node == 'MFN' and instrument_class == 'CTD' and method == 'Telemetered': uframe_dataset_name = 'CE07SHSM/MFD37/03-CTDBPC000/telemetered/ctdbp_cdef_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'temp' var_list[2].name = 'practical_salinity' var_list[3].name = 'density' var_list[4].name = 'pressure' var_list[5].name = 'conductivity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' var_list[3].units = 'kg/m3' var_list[4].units = 'dbar' var_list[5].units = 'S/m' elif platform_name == 'CE09OSSM' and node == 'MFN' and instrument_class == 'CTD' and method == 'Telemetered': uframe_dataset_name = 'CE09OSSM/MFD37/03-CTDBPE000/telemetered/ctdbp_cdef_dcl_instrument' var_list[0].name = 'time' var_list[1].name = 'temp' var_list[2].name = 'practical_salinity' var_list[3].name = 'density' var_list[4].name = 'pressure' var_list[5].name = 'conductivity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' var_list[3].units = 'kg/m3' var_list[4].units = 'dbar' var_list[5].units = 'S/m' #VEL3D elif platform_name == 'CE01ISSM' and node == 'MFN' and instrument_class == 'VEL3D' and method == 'Telemetered': uframe_dataset_name = 'CE01ISSM/MFD35/01-VEL3DD000/telemetered/vel3d_cd_dcl_velocity_data' var_list[0].name = 'time' var_list[1].name = 'vel3d_c_eastward_turbulent_velocity' var_list[2].name = 'vel3d_c_northward_turbulent_velocity' var_list[3].name = 'vel3d_c_upward_turbulent_velocity' var_list[4].name = 'seawater_pressure_mbar' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm/s' var_list[2].units = 'm/s' var_list[3].units = 'm/s' var_list[4].units = '0.001dbar' elif platform_name == 'CE06ISSM' and node == 'MFN' and instrument_class == 'VEL3D' and method == 'Telemetered': uframe_dataset_name = 'CE06ISSM/MFD35/01-VEL3DD000/telemetered/vel3d_cd_dcl_velocity_data' var_list[0].name = 'time' var_list[1].name = 'vel3d_c_eastward_turbulent_velocity' var_list[2].name = 'vel3d_c_northward_turbulent_velocity' var_list[3].name = 'vel3d_c_upward_turbulent_velocity' var_list[4].name = 'seawater_pressure_mbar' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm/s' var_list[2].units = 'm/s' var_list[3].units = 'm/s' var_list[4].units = '0.001dbar' elif platform_name == 'CE07SHSM' and node == 'MFN' and instrument_class == 'VEL3D' and method == 'Telemetered': uframe_dataset_name = 'CE07SHSM/MFD35/01-VEL3DD000/telemetered/vel3d_cd_dcl_velocity_data' var_list[0].name = 'time' var_list[1].name = 'vel3d_c_eastward_turbulent_velocity' var_list[2].name = 'vel3d_c_northward_turbulent_velocity' var_list[3].name = 'vel3d_c_upward_turbulent_velocity' var_list[4].name = 'seawater_pressure_mbar' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm/s' var_list[2].units = 'm/s' var_list[3].units = 'm/s' var_list[4].units = '0.001dbar' elif platform_name == 'CE09OSSM' and node == 'MFN' and instrument_class == 'VEL3D' and method == 'Telemetered': uframe_dataset_name = 'CE09OSSM/MFD35/01-VEL3DD000/telemetered/vel3d_cd_dcl_velocity_data' var_list[0].name = 'time' var_list[1].name = 'vel3d_c_eastward_turbulent_velocity' var_list[2].name = 'vel3d_c_northward_turbulent_velocity' var_list[3].name = 'vel3d_c_upward_turbulent_velocity' var_list[4].name = 'seawater_pressure_mbar' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm/s' var_list[2].units = 'm/s' var_list[3].units = 'm/s' var_list[4].units = '0.001dbar' #VEL3DK elif platform_name == 'CE09OSPM' and node == 'PROFILER' and instrument_class == 'VEL3D' and method == 'Telemetered': uframe_dataset_name = 'CE09OSPM/WFP01/01-VEL3DK000/telemetered/vel3d_k_wfp_stc_instrument' var_list[0].name = 'time' var_list[1].name = 'vel3d_k_eastward_velocity' var_list[2].name = 'vel3d_k_northward_velocity' var_list[3].name = 'vel3d_k_upward_velocity' var_list[4].name = 'vel3d_k_heading' var_list[5].name = 'vel3d_k_pitch' var_list[6].name = 'vel3d_k_roll' var_list[7].name = 'int_ctd_pressure' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm/s' var_list[2].units = 'm/s' var_list[3].units = 'm/s' var_list[4].units = 'ddegrees' var_list[5].units = 'ddegrees' var_list[6].units = 'ddegrees' var_list[7].units = 'dbar' elif platform_name == 'CE09OSPM' and node == 'PROFILER' and instrument_class == 'CTD' and method == 'Telemetered': uframe_dataset_name = 'CE09OSPM/WFP01/03-CTDPFK000/telemetered/ctdpf_ckl_wfp_instrument' var_list[0].name = 'time' var_list[1].name = 'ctdpf_ckl_seawater_temperature' var_list[2].name = 'practical_salinity' var_list[3].name = 'density' var_list[4].name = 'ctdpf_ckl_seawater_pressure' var_list[5].name = 'ctdpf_ckl_seawater_conductivity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' var_list[3].units = 'kg/m3' var_list[4].units = 'dbar' var_list[5].units = 'S/m' #PCO2A elif platform_name == 'CE02SHSM' and node == 'BUOY' and instrument_class == 'PCO2A' and method == 'Telemetered': uframe_dataset_name = 'CE02SHSM/SBD12/04-PCO2AA000/telemetered/pco2a_a_dcl_instrument_water' var_list[0].name = 'time' var_list[1].name = 'partial_pressure_co2_ssw' var_list[2].name = 'partial_pressure_co2_atm' var_list[3].name = 'pco2_co2flux' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'uatm' var_list[2].units = 'uatm' var_list[3].units = 'mol m-2 s-1' elif platform_name == 'CE04OSSM' and node == 'BUOY' and instrument_class == 'PCO2A' and method == 'Telemetered': uframe_dataset_name = 'CE04OSSM/SBD12/04-PCO2AA000/telemetered/pco2a_a_dcl_instrument_water' var_list[0].name = 'time' var_list[1].name = 'partial_pressure_co2_ssw' var_list[2].name = 'partial_pressure_co2_atm' var_list[3].name = 'pco2_co2flux' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'uatm' var_list[2].units = 'uatm' var_list[3].units = 'mol m-2 s-1' elif platform_name == 'CE07SHSM' and node == 'BUOY' and instrument_class == 'PCO2A' and method == 'Telemetered': uframe_dataset_name = 'CE07SHSM/SBD12/04-PCO2AA000/telemetered/pco2a_a_dcl_instrument_water' var_list[0].name = 'time' var_list[1].name = 'partial_pressure_co2_ssw' var_list[2].name = 'partial_pressure_co2_atm' var_list[3].name = 'pco2_co2flux' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'uatm' var_list[2].units = 'uatm' var_list[3].units = 'mol m-2 s-1' elif platform_name == 'CE09OSSM' and node == 'BUOY' and instrument_class == 'PCO2A' and method == 'Telemetered': uframe_dataset_name = 'CE09OSSM/SBD12/04-PCO2AA000/telemetered/pco2a_a_dcl_instrument_water' var_list[0].name = 'time' var_list[1].name = 'partial_pressure_co2_ssw' var_list[2].name = 'partial_pressure_co2_atm' var_list[3].name = 'pco2_co2flux' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'uatm' var_list[2].units = 'uatm' var_list[3].units = 'mol m-2 s-1' #PARAD elif platform_name == 'CE09OSPM' and node == 'PROFILER' and instrument_class == 'PARAD' and method == 'Telemetered': uframe_dataset_name = 'CE09OSPM/WFP01/05-PARADK000/telemetered/parad_k__stc_imodem_instrument' var_list[0].name = 'time' var_list[1].name = 'parad_k_par' var_list[2].name = 'int_ctd_pressure' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'umol photons m-2 s-1' var_list[2].units = 'dbar' #OPTAA elif platform_name == 'CE01ISSM' and node == 'NSIF' and instrument_class == 'OPTAA' and method == 'Telemetered': uframe_dataset_name = 'CE01ISSM/RID16/01-OPTAAD000/telemetered/optaa_dj_dcl_instrument' var_list[0].name = 'time' var_list[0].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' elif platform_name == 'CE02SHSM' and node == 'NSIF' and instrument_class == 'OPTAA' and method == 'Telemetered': uframe_dataset_name = 'CE02SHSM/RID27/01-OPTAAD000/telemetered/optaa_dj_dcl_instrument' var_list[0].name = 'time' var_list[0].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' elif platform_name == 'CE04OSSM' and node == 'NSIF' and instrument_class == 'OPTAA' and method == 'Telemetered': uframe_dataset_name = 'CE04OSSM/RID27/01-OPTAAD000/telemetered/optaa_dj_dcl_instrument' var_list[0].name = 'time' var_list[0].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' elif platform_name == 'CE06ISSM' and node == 'NSIF' and instrument_class == 'OPTAA' and method == 'Telemetered': uframe_dataset_name = 'CE06ISSM/RID16/01-OPTAAD000/telemetered/optaa_dj_dcl_instrument' var_list[0].name = 'time' var_list[0].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' elif platform_name == 'CE07SHSM' and node == 'NSIF' and instrument_class == 'OPTAA' and method == 'Telemetered': uframe_dataset_name = 'CE07SHSM/RID27/01-OPTAAD000/telemetered/optaa_dj_dcl_instrument' var_list[0].name = 'time' var_list[0].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' elif platform_name == 'CE09OSSM' and node == 'NSIF' and instrument_class == 'OPTAA' and method == 'Telemetered': uframe_dataset_name = 'CE09OSSM/RID27/01-OPTAAD000/telemetered/optaa_dj_dcl_instrument' var_list[0].name = 'time' var_list[0].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' elif platform_name == 'CE01ISSM' and node == 'MFN' and instrument_class == 'OPTAA' and method == 'Telemetered': uframe_dataset_name = 'CE01ISSM/MFD37/01-OPTAAD000/telemetered/optaa_dj_dcl_instrument' var_list[0].name = 'time' var_list[0].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' elif platform_name == 'CE06ISSM' and node == 'MFN' and instrument_class == 'OPTAA' and method == 'Telemetered': uframe_dataset_name = 'CE06ISSM/MFD37/01-OPTAAD000/telemetered/optaa_dj_dcl_instrument' var_list[0].name = 'time' var_list[0].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' elif platform_name == 'CE07SHSM' and node == 'MFN' and instrument_class == 'OPTAA' and method == 'Telemetered': uframe_dataset_name = 'CE07SHSM/MFD37/01-OPTAAD000/telemetered/optaa_dj_dcl_instrument' var_list[0].name = 'time' var_list[0].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' elif platform_name == 'CE09OSSM' and node == 'MFN' and instrument_class == 'OPTAA' and method == 'Telemetered': uframe_dataset_name = 'CE09OSSM/MFD37/01-OPTAAC000/telemetered/optaa_dj_dcl_instrument' var_list[0].name = 'time' var_list[0].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' #NUTNR elif platform_name == 'CE01ISSM' and node == 'NSIF' and instrument_class == 'NUTNR' and method == 'Telemetered': uframe_dataset_name = 'CE01ISSM/RID16/07-NUTNRB000/telemetered/suna_dcl_recovered' var_list[0].name = 'time' var_list[1].name = 'nitrate_concentration' var_list[2].name = 'salinity_corrected_nitrate' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'umol/L' var_list[2].units = 'umol/L' elif platform_name == 'CE02SHSM' and node == 'NSIF' and instrument_class == 'NUTNR' and method == 'Telemetered': uframe_dataset_name = 'CE02SHSM/RID26/07-NUTNRB000/telemetered/suna_dcl_recovered' var_list[0].name = 'time' var_list[1].name = 'nitrate_concentration' var_list[2].name = 'salinity_corrected_nitrate' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'umol/L' var_list[2].units = 'umol/L' elif platform_name == 'CE04OSSM' and node == 'NSIF' and instrument_class == 'NUTNR' and method == 'Telemetered': uframe_dataset_name = 'CE04OSSM/RID26/07-NUTNRB000/telemetered/suna_dcl_recovered' var_list[0].name = 'time' var_list[1].name = 'nitrate_concentration' var_list[2].name = 'salinity_corrected_nitrate' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'umol/L' var_list[2].units = 'umol/L' elif platform_name == 'CE06ISSM' and node == 'NSIF' and instrument_class == 'NUTNR' and method == 'Telemetered': uframe_dataset_name = 'CE06ISSM/RID16/07-NUTNRB000/telemetered/suna_dcl_recovered' var_list[0].name = 'time' var_list[1].name = 'nitrate_concentration' var_list[2].name = 'salinity_corrected_nitrate' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'umol/L' var_list[2].units = 'umol/L' elif platform_name == 'CE07SHSM' and node == 'NSIF' and instrument_class == 'NUTNR' and method == 'Telemetered': uframe_dataset_name = 'CE07SHSM/RID26/07-NUTNRB000/telemetered/suna_dcl_recovered' var_list[0].name = 'time' var_list[1].name = 'nitrate_concentration' var_list[2].name = 'salinity_corrected_nitrate' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'umol/L' var_list[2].units = 'umol/L' elif platform_name == 'CE09OSSM' and node == 'NSIF' and instrument_class == 'NUTNR' and method == 'Telemetered': uframe_dataset_name = 'CE09OSSM/RID26/07-NUTNRB000/telemetered/suna_dcl_recovered' var_list[0].name = 'time' var_list[1].name = 'nitrate_concentration' var_list[2].name = 'salinity_corrected_nitrate' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'umol/L' var_list[2].units = 'umol/L' ## #MOPAK elif platform_name == 'CE01ISSM' and node == 'BUOY' and instrument_class == 'MOPAK' and method == 'RecoveredHost': uframe_dataset_name = 'CE01ISSM/SBD17/01-MOPAK0000/recovered_host/mopak_o_dcl_accel_recovered' var_list[0].name = 'time' var_list[0].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' elif platform_name == 'CE02SHSM' and node == 'BUOY' and instrument_class == 'MOPAK' and method == 'RecoveredHost': uframe_dataset_name = 'CE02SHSM/SBD11/01-MOPAK0000/recovered_host/mopak_o_dcl_accel_recovered' var_list[0].name = 'time' var_list[0].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' elif platform_name == 'CE04OSSM' and node == 'BUOY' and instrument_class == 'MOPAK' and method == 'RecoveredHost': uframe_dataset_name = 'CE04OSSM/SBD11/01-MOPAK0000/recovered_host/mopak_o_dcl_accel_recovered' var_list[0].name = 'time' var_list[0].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' elif platform_name == 'CE06ISSM' and node == 'BUOY' and instrument_class == 'MOPAK' and method == 'RecoveredHost': uframe_dataset_name = 'CE06ISSM/SBD17/01-MOPAK0000/recovered_host/mopak_o_dcl_accel_recovered' var_list[0].name = 'time' var_list[0].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' elif platform_name == 'CE07SHSM' and node == 'BUOY' and instrument_class == 'MOPAK' and method == 'RecoveredHost': uframe_dataset_name = 'CE07SHSM/SBD11/01-MOPAK0000/recovered_host/mopak_o_dcl_accel_recovered' var_list[0].name = 'time' var_list[0].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' elif platform_name == 'CE09OSSM' and node == 'BUOY' and instrument_class == 'MOPAK' and method == 'RecoveredHost': uframe_dataset_name = 'CE09OSSM/SBD11/01-MOPAK0000/recovered_host/mopak_o_dcl_accel_recovered' var_list[0].name = 'time' var_list[0].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' elif platform_name == 'CE09OSPM' and node == 'BUOY' and instrument_class == 'MOPAK' and method == 'RecoveredHost': uframe_dataset_name = 'CE09OSPM/SBS01/01-MOPAK0000/recovered_host/mopak_o_dcl_accel_recovered' var_list[0].name = 'time' var_list[0].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' #METBK elif platform_name == 'CE02SHSM' and node == 'BUOY' and instrument_class == 'METBK1' and method == 'RecoveredHost': uframe_dataset_name = 'CE02SHSM/SBD11/06-METBKA000/recovered_host/metbk_a_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'sea_surface_temperature' var_list[2].name = 'sea_surface_conductivity' var_list[3].name = 'met_salsurf' var_list[4].name = 'met_windavg_mag_corr_east' var_list[5].name = 'met_windavg_mag_corr_north' var_list[6].name = 'barometric_pressure' var_list[7].name = 'air_temperature' var_list[8].name = 'relative_humidity' var_list[9].name = 'longwave_irradiance' var_list[10].name = 'shortwave_irradiance' var_list[11].name = 'precipitation' var_list[12].name = 'met_heatflx_minute' var_list[13].name = 'met_latnflx_minute' var_list[14].name = 'met_netlirr_minute' var_list[15].name = 'met_sensflx_minute' var_list[16].name = 'eastward_velocity' var_list[17].name = 'northward_velocity' var_list[18].name = 'met_spechum' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[8].data = np.array([]) var_list[9].data = np.array([]) var_list[10].data = np.array([]) var_list[11].data = np.array([]) var_list[12].data = np.array([]) var_list[13].data = np.array([]) var_list[14].data = np.array([]) var_list[15].data = np.array([]) var_list[16].data = np.array([]) var_list[17].data = np.array([]) var_list[18].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'S/m' var_list[3].units = 'unitless' var_list[4].units = 'm/s' var_list[5].units = 'm/s' var_list[6].units = 'mbar' var_list[7].units = 'degC' var_list[8].units = '#' var_list[9].units = 'W/m' var_list[10].units = 'W/m' var_list[11].units = 'mm' var_list[12].units = 'W/m' var_list[13].units = 'W/m' var_list[14].units = 'W/m' var_list[15].units = 'W/m' var_list[16].units = 'm/s' var_list[17].units = 'm/s' var_list[18].units = 'g/kg' elif platform_name == 'CE04OSSM' and node == 'BUOY' and instrument_class == 'METBK1' and method == 'RecoveredHost': uframe_dataset_name = 'CE04OSSM/SBD11/06-METBKA000/recovered_host/metbk_a_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'sea_surface_temperature' var_list[2].name = 'sea_surface_conductivity' var_list[3].name = 'met_salsurf' var_list[4].name = 'met_windavg_mag_corr_east' var_list[5].name = 'met_windavg_mag_corr_north' var_list[6].name = 'barometric_pressure' var_list[7].name = 'air_temperature' var_list[8].name = 'relative_humidity' var_list[9].name = 'longwave_irradiance' var_list[10].name = 'shortwave_irradiance' var_list[11].name = 'precipitation' var_list[12].name = 'met_heatflx_minute' var_list[13].name = 'met_latnflx_minute' var_list[14].name = 'met_netlirr_minute' var_list[15].name = 'met_sensflx_minute' var_list[16].name = 'eastward_velocity' var_list[17].name = 'northward_velocity' var_list[18].name = 'met_spechum' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[8].data = np.array([]) var_list[9].data = np.array([]) var_list[10].data = np.array([]) var_list[11].data = np.array([]) var_list[12].data = np.array([]) var_list[13].data = np.array([]) var_list[14].data = np.array([]) var_list[15].data = np.array([]) var_list[16].data = np.array([]) var_list[17].data = np.array([]) var_list[18].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'S/m' var_list[3].units = 'unitless' var_list[4].units = 'm/s' var_list[5].units = 'm/s' var_list[6].units = 'mbar' var_list[7].units = 'degC' var_list[8].units = '#' var_list[9].units = 'W/m' var_list[10].units = 'W/m' var_list[11].units = 'mm' var_list[12].units = 'W/m' var_list[13].units = 'W/m' var_list[14].units = 'W/m' var_list[15].units = 'W/m' var_list[16].units = 'm/s' var_list[17].units = 'm/s' var_list[18].units = 'g/kg' elif platform_name == 'CE07SHSM' and node == 'BUOY' and instrument_class == 'METBK1' and method == 'RecoveredHost': uframe_dataset_name = 'CE07SHSM/SBD11/06-METBKA000/recovered_host/metbk_a_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'sea_surface_temperature' var_list[2].name = 'sea_surface_conductivity' var_list[3].name = 'met_salsurf' var_list[4].name = 'met_windavg_mag_corr_east' var_list[5].name = 'met_windavg_mag_corr_north' var_list[6].name = 'barometric_pressure' var_list[7].name = 'air_temperature' var_list[8].name = 'relative_humidity' var_list[9].name = 'longwave_irradiance' var_list[10].name = 'shortwave_irradiance' var_list[11].name = 'precipitation' var_list[12].name = 'met_heatflx_minute' var_list[13].name = 'met_latnflx_minute' var_list[14].name = 'met_netlirr_minute' var_list[15].name = 'met_sensflx_minute' var_list[16].name = 'eastward_velocity' var_list[17].name = 'northward_velocity' var_list[18].name = 'met_spechum' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[8].data = np.array([]) var_list[9].data = np.array([]) var_list[10].data = np.array([]) var_list[11].data = np.array([]) var_list[12].data = np.array([]) var_list[13].data = np.array([]) var_list[14].data = np.array([]) var_list[15].data = np.array([]) var_list[16].data = np.array([]) var_list[17].data = np.array([]) var_list[18].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'S/m' var_list[3].units = 'unitless' var_list[4].units = 'm/s' var_list[5].units = 'm/s' var_list[6].units = 'mbar' var_list[7].units = 'degC' var_list[8].units = '#' var_list[9].units = 'W/m' var_list[10].units = 'W/m' var_list[11].units = 'mm' var_list[12].units = 'W/m' var_list[13].units = 'W/m' var_list[14].units = 'W/m' var_list[15].units = 'W/m' var_list[16].units = 'm/s' var_list[17].units = 'm/s' var_list[18].units = 'g/kg' elif platform_name == 'CE09OSSM' and node == 'BUOY' and instrument_class == 'METBK1' and method == 'RecoveredHost': uframe_dataset_name = 'CE09OSSM/SBD11/06-METBKA000/recovered_host/metbk_a_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'sea_surface_temperature' var_list[2].name = 'sea_surface_conductivity' var_list[3].name = 'met_salsurf' var_list[4].name = 'met_windavg_mag_corr_east' var_list[5].name = 'met_windavg_mag_corr_north' var_list[6].name = 'barometric_pressure' var_list[7].name = 'air_temperature' var_list[8].name = 'relative_humidity' var_list[9].name = 'longwave_irradiance' var_list[10].name = 'shortwave_irradiance' var_list[11].name = 'precipitation' var_list[12].name = 'met_heatflx_minute' var_list[13].name = 'met_latnflx_minute' var_list[14].name = 'met_netlirr_minute' var_list[15].name = 'met_sensflx_minute' var_list[16].name = 'eastward_velocity' var_list[17].name = 'northward_velocity' var_list[18].name = 'met_spechum' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[8].data = np.array([]) var_list[9].data = np.array([]) var_list[10].data = np.array([]) var_list[11].data = np.array([]) var_list[12].data = np.array([]) var_list[13].data = np.array([]) var_list[14].data = np.array([]) var_list[15].data = np.array([]) var_list[16].data = np.array([]) var_list[17].data = np.array([]) var_list[18].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'S/m' var_list[3].units = 'unitless' var_list[4].units = 'm/s' var_list[5].units = 'm/s' var_list[6].units = 'mbar' var_list[7].units = 'degC' var_list[8].units = '#' var_list[9].units = 'W/m' var_list[10].units = 'W/m' var_list[11].units = 'mm' var_list[12].units = 'W/m' var_list[13].units = 'W/m' var_list[14].units = 'W/m' var_list[15].units = 'W/m' var_list[16].units = 'm/s' var_list[17].units = 'm/s' var_list[18].units = 'g/kg' #FLORT elif platform_name == 'CE01ISSM' and node == 'NSIF' and instrument_class == 'FLORT' and method == 'RecoveredHost': uframe_dataset_name = 'CE01ISSM/RID16/02-FLORTD000/recovered_host/flort_sample' var_list[0].name = 'time' var_list[1].name = 'seawater_scattering_coefficient' var_list[2].name = 'fluorometric_chlorophyll_a' var_list[3].name = 'fluorometric_cdom' var_list[4].name = 'total_volume_scattering_coefficient' var_list[5].name = 'optical_backscatter' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm-1' var_list[2].units = 'ug/L' var_list[3].units = 'ppb' var_list[4].units = 'm-1 sr-1' var_list[5].units = 'm-1' elif platform_name == 'CE01ISSM' and node == 'BUOY' and instrument_class == 'FLORT' and method == 'RecoveredHost': uframe_dataset_name = 'CE01ISSM/SBD17/06-FLORTD000/recovered_host/flort_sample' var_list[0].name = 'time' var_list[1].name = 'seawater_scattering_coefficient' var_list[2].name = 'fluorometric_chlorophyll_a' var_list[3].name = 'fluorometric_cdom' var_list[4].name = 'total_volume_scattering_coefficient' var_list[5].name = 'optical_backscatter' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm-1' var_list[2].units = 'ug/L' var_list[3].units = 'ppb' var_list[4].units = 'm-1 sr-1' var_list[5].units = 'm-1' elif platform_name == 'CE06ISSM' and node == 'NSIF' and instrument_class == 'FLORT' and method == 'RecoveredHost': uframe_dataset_name = 'CE06ISSM/RID16/02-FLORTD000/recovered_host/flort_sample' var_list[0].name = 'time' var_list[1].name = 'seawater_scattering_coefficient' var_list[2].name = 'fluorometric_chlorophyll_a' var_list[3].name = 'fluorometric_cdom' var_list[4].name = 'total_volume_scattering_coefficient' var_list[5].name = 'optical_backscatter' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm-1' var_list[2].units = 'ug/L' var_list[3].units = 'ppb' var_list[4].units = 'm-1 sr-1' var_list[5].units = 'm-1' elif platform_name == 'CE06ISSM' and node == 'BUOY' and instrument_class == 'FLORT' and method == 'RecoveredHost': uframe_dataset_name = 'CE06ISSM/SBD17/06-FLORTD000/recovered_host/flort_sample' var_list[0].name = 'time' var_list[1].name = 'seawater_scattering_coefficient' var_list[2].name = 'fluorometric_chlorophyll_a' var_list[3].name = 'fluorometric_cdom' var_list[4].name = 'total_volume_scattering_coefficient' var_list[5].name = 'optical_backscatter' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm-1' var_list[2].units = 'ug/L' var_list[3].units = 'ppb' var_list[4].units = 'm-1 sr-1' var_list[5].units = 'm-1' elif platform_name == 'CE02SHSM' and node == 'NSIF' and instrument_class == 'FLORT' and method == 'RecoveredHost': uframe_dataset_name = 'CE02SHSM/RID27/02-FLORTD000/recovered_host/flort_sample' var_list[0].name = 'time' var_list[1].name = 'seawater_scattering_coefficient' var_list[2].name = 'fluorometric_chlorophyll_a' var_list[3].name = 'fluorometric_cdom' var_list[4].name = 'total_volume_scattering_coefficient' var_list[5].name = 'optical_backscatter' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm-1' var_list[2].units = 'ug/L' var_list[3].units = 'ppb' var_list[4].units = 'm-1 sr-1' var_list[5].units = 'm-1' elif platform_name == 'CE07SHSM' and node == 'NSIF' and instrument_class == 'FLORT' and method == 'RecoveredHost': uframe_dataset_name = 'CE07SHSM/RID27/02-FLORTD000/recovered_host/flort_sample' var_list[0].name = 'time' var_list[1].name = 'seawater_scattering_coefficient' var_list[2].name = 'fluorometric_chlorophyll_a' var_list[3].name = 'fluorometric_cdom' var_list[4].name = 'total_volume_scattering_coefficient' var_list[5].name = 'optical_backscatter' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm-1' var_list[2].units = 'ug/L' var_list[3].units = 'ppb' var_list[4].units = 'm-1 sr-1' var_list[5].units = 'm-1' elif platform_name == 'CE04OSSM' and node == 'NSIF' and instrument_class == 'FLORT' and method == 'RecoveredHost': uframe_dataset_name = 'CE04OSSM/RID27/02-FLORTD000/recovered_host/flort_sample' var_list[0].name = 'time' var_list[1].name = 'seawater_scattering_coefficient' var_list[2].name = 'fluorometric_chlorophyll_a' var_list[3].name = 'fluorometric_cdom' var_list[4].name = 'total_volume_scattering_coefficient' var_list[5].name = 'optical_backscatter' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm-1' var_list[2].units = 'ug/L' var_list[3].units = 'ppb' var_list[4].units = 'm-1 sr-1' var_list[5].units = 'm-1' elif platform_name == 'CE09OSSM' and node == 'NSIF' and instrument_class == 'FLORT' and method == 'RecoveredHost': uframe_dataset_name = 'CE09OSSM/RID27/02-FLORTD000/recovered_host/flort_sample' var_list[0].name = 'time' var_list[1].name = 'seawater_scattering_coefficient' var_list[2].name = 'fluorometric_chlorophyll_a' var_list[3].name = 'fluorometric_cdom' var_list[4].name = 'total_volume_scattering_coefficient' var_list[5].name = 'optical_backscatter' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm-1' var_list[2].units = 'ug/L' var_list[3].units = 'ppb' var_list[4].units = 'm-1 sr-1' var_list[5].units = 'm-1' #FDCHP elif platform_name == 'CE02SHSM' and node == 'BUOY' and instrument_class == 'FDCHP' and method == 'RecoveredHost': uframe_dataset_name = 'CE02SHSM/SBD12/08-FDCHPA000/recovered_host/fdchp_a_dcl_instrument_recovered' var_list[0].name = 'time' var_list[0].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' #DOSTA elif platform_name == 'CE01ISSM' and node == 'NSIF' and instrument_class == 'DOSTA' and method == 'RecoveredHost': uframe_dataset_name = 'CE01ISSM/RID16/03-DOSTAD000/recovered_host/dosta_abcdjm_ctdbp_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'dissolved_oxygen' var_list[2].name = 'estimated_oxygen_concentration' var_list[3].name = 'optode_temperature' var_list[4].name = 'dosta_abcdjm_cspp_tc_oxygen' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'umol/kg' var_list[2].units = 'umol/L' var_list[3].units = 'degC' var_list[4].units = 'umol/L' elif platform_name == 'CE02SHSM' and node == 'NSIF' and instrument_class == 'DOSTA' and method == 'RecoveredHost': uframe_dataset_name = 'CE02SHSM/RID27/04-DOSTAD000/recovered_host/dosta_abcdjm_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'dissolved_oxygen' var_list[2].name = 'estimated_oxygen_concentration' var_list[3].name = 'optode_temperature' var_list[4].name = 'dosta_abcdjm_cspp_tc_oxygen' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'umol/kg' var_list[2].units = 'umol/L' var_list[3].units = 'degC' var_list[4].units = 'umol/L' elif platform_name == 'CE04OSSM' and node == 'NSIF' and instrument_class == 'DOSTA' and method == 'RecoveredHost': uframe_dataset_name = 'CE04OSSM/RID27/04-DOSTAD000/recovered_host/dosta_abcdjm_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'dissolved_oxygen' var_list[2].name = 'estimated_oxygen_concentration' var_list[3].name = 'optode_temperature' var_list[4].name = 'dosta_abcdjm_cspp_tc_oxygen' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'umol/kg' var_list[2].units = 'umol/L' var_list[3].units = 'degC' var_list[4].units = 'umol/L' elif platform_name == 'CE06ISSM' and node == 'NSIF' and instrument_class == 'DOSTA' and method == 'RecoveredHost': uframe_dataset_name = 'CE06ISSM/RID16/03-DOSTAD000/recovered_host/dosta_abcdjm_ctdbp_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'dissolved_oxygen' var_list[2].name = 'estimated_oxygen_concentration' var_list[3].name = 'optode_temperature' var_list[4].name = 'dosta_abcdjm_cspp_tc_oxygen' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'umol/kg' var_list[2].units = 'umol/L' var_list[3].units = 'degC' var_list[4].units = 'umol/L' elif platform_name == 'CE07SHSM' and node == 'NSIF' and instrument_class == 'DOSTA' and method == 'RecoveredHost': uframe_dataset_name = 'CE07SHSM/RID27/04-DOSTAD000/recovered_host/dosta_abcdjm_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'dissolved_oxygen' var_list[2].name = 'estimated_oxygen_concentration' var_list[3].name = 'optode_temperature' var_list[4].name = 'dosta_abcdjm_cspp_tc_oxygen' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'umol/kg' var_list[2].units = 'umol/L' var_list[3].units = 'degC' var_list[4].units = 'umol/L' elif platform_name == 'CE09OSSM' and node == 'NSIF' and instrument_class == 'DOSTA' and method == 'RecoveredHost': uframe_dataset_name = 'CE09OSSM/RID27/04-DOSTAD000/recovered_host/dosta_abcdjm_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'dissolved_oxygen' var_list[2].name = 'estimated_oxygen_concentration' var_list[3].name = 'optode_temperature' var_list[4].name = 'dosta_abcdjm_cspp_tc_oxygen' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'umol/kg' var_list[2].units = 'umol/L' var_list[3].units = 'degC' var_list[4].units = 'umol/L' elif platform_name == 'CE01ISSM' and node == 'MFN' and instrument_class == 'DOSTA' and method == 'RecoveredHost': uframe_dataset_name = 'CE01ISSM/MFD37/03-DOSTAD000/recovered_host/dosta_abcdjm_ctdbp_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'dissolved_oxygen' var_list[2].name = 'dosta_ln_optode_oxygen' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'umol/kg' var_list[2].units = 'umol/L' elif platform_name == 'CE06ISSM' and node == 'MFN' and instrument_class == 'DOSTA' and method == 'RecoveredHost': uframe_dataset_name = 'CE06ISSM/MFD37/03-DOSTAD000/recovered_host/dosta_abcdjm_ctdbp_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'dissolved_oxygen' var_list[2].name = 'dosta_ln_optode_oxygen' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'umol/kg' var_list[2].units = 'umol/L' elif platform_name == 'CE07SHSM' and node == 'MFN' and instrument_class == 'DOSTA' and method == 'RecoveredHost': uframe_dataset_name = 'CE07SHSM/MFD37/03-DOSTAD000/recovered_host/dosta_abcdjm_ctdbp_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'dissolved_oxygen' var_list[2].name = 'dosta_ln_optode_oxygen' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'umol/kg' var_list[2].units = 'umol/L' elif platform_name == 'CE09OSSM' and node == 'MFN' and instrument_class == 'DOSTA' and method == 'RecoveredHost': uframe_dataset_name = 'CE09OSSM/MFD37/03-DOSTAD000/recovered_host/dosta_abcdjm_ctdbp_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'dissolved_oxygen' var_list[2].name = 'dosta_ln_optode_oxygen' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'umol/kg' var_list[2].units = 'umol/L' #ADCP elif platform_name == 'CE02SHSM' and node == 'NSIF' and instrument_class == 'ADCP' and method == 'RecoveredHost': uframe_dataset_name = 'CE02SHSM/RID26/01-ADCPTA000/recovered_host/adcp_velocity_earth' var_list[0].name = 'time' var_list[1].name = 'bin_depths' var_list[2].name = 'heading' var_list[3].name = 'pitch' var_list[4].name = 'roll' var_list[5].name = 'eastward_seawater_velocity' var_list[6].name = 'northward_seawater_velocity' var_list[7].name = 'upward_seawater_velocity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'meters' var_list[2].units = 'deci-degrees' var_list[3].units = 'deci-degrees' var_list[4].units = 'deci-degrees' var_list[5].units = 'm/s' var_list[6].units = 'm/s' var_list[7].units = 'm/s' elif platform_name == 'CE04OSSM' and node == 'NSIF' and instrument_class == 'ADCP' and method == 'RecoveredHost': uframe_dataset_name = 'CE04OSSM/RID26/01-ADCPTC000/recovered_host/adcp_velocity_earth' var_list[0].name = 'time' var_list[1].name = 'bin_depths' var_list[2].name = 'heading' var_list[3].name = 'pitch' var_list[4].name = 'roll' var_list[5].name = 'eastward_seawater_velocity' var_list[6].name = 'northward_seawater_velocity' var_list[7].name = 'upward_seawater_velocity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'meters' var_list[2].units = 'deci-degrees' var_list[3].units = 'deci-degrees' var_list[4].units = 'deci-degrees' var_list[5].units = 'm/s' var_list[6].units = 'm/s' var_list[7].units = 'm/s' elif platform_name == 'CE07SHSM' and node == 'NSIF' and instrument_class == 'ADCP' and method == 'RecoveredHost': uframe_dataset_name = 'CE07SHSM/RID26/01-ADCPTA000/recovered_host/adcp_velocity_earth' var_list[0].name = 'time' var_list[1].name = 'bin_depths' var_list[2].name = 'heading' var_list[3].name = 'pitch' var_list[4].name = 'roll' var_list[5].name = 'eastward_seawater_velocity' var_list[6].name = 'northward_seawater_velocity' var_list[7].name = 'upward_seawater_velocity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'meters' var_list[2].units = 'deci-degrees' var_list[3].units = 'deci-degrees' var_list[4].units = 'deci-degrees' var_list[5].units = 'm/s' var_list[6].units = 'm/s' var_list[7].units = 'm/s' elif platform_name == 'CE09OSSM' and node == 'NSIF' and instrument_class == 'ADCP' and method == 'RecoveredHost': uframe_dataset_name = 'CE09OSSM/RID26/01-ADCPTC000/recovered_host/adcp_velocity_earth' var_list[0].name = 'time' var_list[1].name = 'bin_depths' var_list[2].name = 'heading' var_list[3].name = 'pitch' var_list[4].name = 'roll' var_list[5].name = 'eastward_seawater_velocity' var_list[6].name = 'northward_seawater_velocity' var_list[7].name = 'upward_seawater_velocity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'meters' var_list[2].units = 'deci-degrees' var_list[3].units = 'deci-degrees' var_list[4].units = 'deci-degrees' var_list[5].units = 'm/s' var_list[6].units = 'm/s' var_list[7].units = 'm/s' elif platform_name == 'CE01ISSM' and node == 'MFN' and instrument_class == 'ADCP' and method == 'RecoveredHost': uframe_dataset_name = 'CE01ISSM/MFD35/04-ADCPTM000/recovered_host/adcp_velocity_earth' var_list[0].name = 'time' var_list[1].name = 'bin_depths' var_list[2].name = 'heading' var_list[3].name = 'pitch' var_list[4].name = 'roll' var_list[5].name = 'eastward_seawater_velocity' var_list[6].name = 'northward_seawater_velocity' var_list[7].name = 'upward_seawater_velocity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'meters' var_list[2].units = 'deci-degrees' var_list[3].units = 'deci-degrees' var_list[4].units = 'deci-degrees' var_list[5].units = 'm/s' var_list[6].units = 'm/s' var_list[7].units = 'm/s' elif platform_name == 'CE06ISSM' and node == 'MFN' and instrument_class == 'ADCP' and method == 'RecoveredHost': uframe_dataset_name = 'CE06ISSM/MFD35/04-ADCPTM000/recovered_host/adcp_velocity_earth' var_list[0].name = 'time' var_list[1].name = 'bin_depths' var_list[2].name = 'heading' var_list[3].name = 'pitch' var_list[4].name = 'roll' var_list[5].name = 'eastward_seawater_velocity' var_list[6].name = 'northward_seawater_velocity' var_list[7].name = 'upward_seawater_velocity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'meters' var_list[2].units = 'deci-degrees' var_list[3].units = 'deci-degrees' var_list[4].units = 'deci-degrees' var_list[5].units = 'm/s' var_list[6].units = 'm/s' var_list[7].units = 'm/s' elif platform_name == 'CE07SHSM' and node == 'MFN' and instrument_class == 'ADCP' and method == 'RecoveredHost': uframe_dataset_name = 'CE07SHSM/MFD35/04-ADCPTC000/recovered_host/adcp_velocity_earth' var_list[0].name = 'time' var_list[1].name = 'bin_depths' var_list[2].name = 'heading' var_list[3].name = 'pitch' var_list[4].name = 'roll' var_list[5].name = 'eastward_seawater_velocity' var_list[6].name = 'northward_seawater_velocity' var_list[7].name = 'upward_seawater_velocity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'meters' var_list[2].units = 'deci-degrees' var_list[3].units = 'deci-degrees' var_list[4].units = 'deci-degrees' var_list[5].units = 'm/s' var_list[6].units = 'm/s' var_list[7].units = 'm/s' elif platform_name == 'CE09OSSM' and node == 'MFN' and instrument_class == 'ADCP' and method == 'RecoveredHost': uframe_dataset_name = 'CE09OSSM/MFD35/04-ADCPSJ000/recovered_host/adcp_velocity_earth' var_list[0].name = 'time' var_list[1].name = 'bin_depths' var_list[2].name = 'heading' var_list[3].name = 'pitch' var_list[4].name = 'roll' var_list[5].name = 'eastward_seawater_velocity' var_list[6].name = 'northward_seawater_velocity' var_list[7].name = 'upward_seawater_velocity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'meters' var_list[2].units = 'deci-degrees' var_list[3].units = 'deci-degrees' var_list[4].units = 'deci-degrees' var_list[5].units = 'm/s' var_list[6].units = 'm/s' var_list[7].units = 'm/s' #WAVSS elif platform_name == 'CE02SHSM' and node == 'BUOY' and instrument_class == 'WAVSS_Stats' and method == 'RecoveredHost': uframe_dataset_name = 'CE02SHSM/SBD12/05-WAVSSA000/recovered_host/wavss_a_dcl_statistics_recovered' var_list[0].name = 'time' var_list[1].name = 'number_zero_crossings' var_list[2].name = 'average_wave_height' var_list[3].name = 'mean_spectral_period' var_list[4].name = 'max_wave_height' var_list[5].name = 'significant_wave_height' var_list[6].name = 'significant_period' var_list[7].name = 'wave_height_10' var_list[8].name = 'wave_period_10' var_list[9].name = 'mean_wave_period' var_list[10].name = 'peak_wave_period' var_list[11].name = 'wave_period_tp5' var_list[12].name = 'wave_height_hmo' var_list[13].name = 'mean_direction' var_list[14].name = 'mean_spread' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[8].data = np.array([]) var_list[9].data = np.array([]) var_list[10].data = np.array([]) var_list[11].data = np.array([]) var_list[12].data = np.array([]) var_list[13].data = np.array([]) var_list[14].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'counts' var_list[2].units = 'm' var_list[3].units = 'sec' var_list[4].units = 'm' var_list[5].units = 'm' var_list[6].units = 'sec' var_list[7].units = 'm' var_list[8].units = 'sec' var_list[9].units = 'sec' var_list[10].units = 'sec' var_list[11].units = 'sec' var_list[12].units = 'm' var_list[13].units = 'degrees' var_list[14].units = 'degrees' elif platform_name == 'CE04OSSM' and node == 'BUOY' and instrument_class == 'WAVSS_Stats' and method == 'RecoveredHost': uframe_dataset_name = 'CE04OSSM/SBD12/05-WAVSSA000/recovered_host/wavss_a_dcl_statistics_recovered' var_list[0].name = 'time' var_list[1].name = 'number_zero_crossings' var_list[2].name = 'average_wave_height' var_list[3].name = 'mean_spectral_period' var_list[4].name = 'max_wave_height' var_list[5].name = 'significant_wave_height' var_list[6].name = 'significant_period' var_list[7].name = 'wave_height_10' var_list[8].name = 'wave_period_10' var_list[9].name = 'mean_wave_period' var_list[10].name = 'peak_wave_period' var_list[11].name = 'wave_period_tp5' var_list[12].name = 'wave_height_hmo' var_list[13].name = 'mean_direction' var_list[14].name = 'mean_spread' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[8].data = np.array([]) var_list[9].data = np.array([]) var_list[10].data = np.array([]) var_list[11].data = np.array([]) var_list[12].data = np.array([]) var_list[13].data = np.array([]) var_list[14].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'counts' var_list[2].units = 'm' var_list[3].units = 'sec' var_list[4].units = 'm' var_list[5].units = 'm' var_list[6].units = 'sec' var_list[7].units = 'm' var_list[8].units = 'sec' var_list[9].units = 'sec' var_list[10].units = 'sec' var_list[11].units = 'sec' var_list[12].units = 'm' var_list[13].units = 'degrees' var_list[14].units = 'degrees' elif platform_name == 'CE07SHSM' and node == 'BUOY' and instrument_class == 'WAVSS_Stats' and method == 'RecoveredHost': uframe_dataset_name = 'CE07SHSM/SBD12/05-WAVSSA000/recovered_host/wavss_a_dcl_statistics_recovered' var_list[0].name = 'time' var_list[1].name = 'number_zero_crossings' var_list[2].name = 'average_wave_height' var_list[3].name = 'mean_spectral_period' var_list[4].name = 'max_wave_height' var_list[5].name = 'significant_wave_height' var_list[6].name = 'significant_period' var_list[7].name = 'wave_height_10' var_list[8].name = 'wave_period_10' var_list[9].name = 'mean_wave_period' var_list[10].name = 'peak_wave_period' var_list[11].name = 'wave_period_tp5' var_list[12].name = 'wave_height_hmo' var_list[13].name = 'mean_direction' var_list[14].name = 'mean_spread' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[8].data = np.array([]) var_list[9].data = np.array([]) var_list[10].data = np.array([]) var_list[11].data = np.array([]) var_list[12].data = np.array([]) var_list[13].data = np.array([]) var_list[14].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'counts' var_list[2].units = 'm' var_list[3].units = 'sec' var_list[4].units = 'm' var_list[5].units = 'm' var_list[6].units = 'sec' var_list[7].units = 'm' var_list[8].units = 'sec' var_list[9].units = 'sec' var_list[10].units = 'sec' var_list[11].units = 'sec' var_list[12].units = 'm' var_list[13].units = 'degrees' var_list[14].units = 'degrees' elif platform_name == 'CE09OSSM' and node == 'BUOY' and instrument_class == 'WAVSS_Stats' and method == 'RecoveredHost': uframe_dataset_name = 'CE09OSSM/SBD12/05-WAVSSA000/recovered_host/wavss_a_dcl_statistics_recovered' var_list[0].name = 'time' var_list[1].name = 'number_zero_crossings' var_list[2].name = 'average_wave_height' var_list[3].name = 'mean_spectral_period' var_list[4].name = 'max_wave_height' var_list[5].name = 'significant_wave_height' var_list[6].name = 'significant_period' var_list[7].name = 'wave_height_10' var_list[8].name = 'wave_period_10' var_list[9].name = 'mean_wave_period' var_list[10].name = 'peak_wave_period' var_list[11].name = 'wave_period_tp5' var_list[12].name = 'wave_height_hmo' var_list[13].name = 'mean_direction' var_list[14].name = 'mean_spread' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[8].data = np.array([]) var_list[9].data = np.array([]) var_list[10].data = np.array([]) var_list[11].data = np.array([]) var_list[12].data = np.array([]) var_list[13].data = np.array([]) var_list[14].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'counts' var_list[2].units = 'm' var_list[3].units = 'sec' var_list[4].units = 'm' var_list[5].units = 'm' var_list[6].units = 'sec' var_list[7].units = 'm' var_list[8].units = 'sec' var_list[9].units = 'sec' var_list[10].units = 'sec' var_list[11].units = 'sec' var_list[12].units = 'm' var_list[13].units = 'degrees' var_list[14].units = 'degrees' #VELPT elif platform_name == 'CE01ISSM' and node == 'BUOY' and instrument_class == 'VELPT' and method == 'RecoveredHost': uframe_dataset_name = 'CE01ISSM/SBD17/04-VELPTA000/recovered_host/velpt_ab_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'eastward_velocity' var_list[2].name = 'northward_velocity' var_list[3].name = 'upward_velocity' var_list[4].name = 'heading_decidegree' var_list[5].name = 'roll_decidegree' var_list[6].name = 'pitch_decidegree' var_list[7].name = 'temperature_centidegree' var_list[8].name = 'pressure_mbar' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[8].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm/s' var_list[2].units = 'm/s' var_list[3].units = 'm/s' var_list[4].units = 'deci-degrees' var_list[5].units = 'deci-degrees' var_list[6].units = 'deci-degrees' var_list[7].units = '0.01degC' var_list[8].units = '0.001dbar' elif platform_name == 'CE02SHSM' and node == 'BUOY' and instrument_class == 'VELPT' and method == 'RecoveredHost': uframe_dataset_name = 'CE02SHSM/SBD11/04-VELPTA000/recovered_host/velpt_ab_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'eastward_velocity' var_list[2].name = 'northward_velocity' var_list[3].name = 'upward_velocity' var_list[4].name = 'heading_decidegree' var_list[5].name = 'roll_decidegree' var_list[6].name = 'pitch_decidegree' var_list[7].name = 'temperature_centidegree' var_list[8].name = 'pressure_mbar' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[8].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm/s' var_list[2].units = 'm/s' var_list[3].units = 'm/s' var_list[4].units = 'deci-degrees' var_list[5].units = 'deci-degrees' var_list[6].units = 'deci-degrees' var_list[7].units = '0.01degC' var_list[8].units = '0.001dbar' elif platform_name == 'CE04OSSM' and node == 'BUOY' and instrument_class == 'VELPT' and method == 'RecoveredHost': uframe_dataset_name = 'CE04OSSM/SBD11/04-VELPTA000/recovered_host/velpt_ab_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'eastward_velocity' var_list[2].name = 'northward_velocity' var_list[3].name = 'upward_velocity' var_list[4].name = 'heading_decidegree' var_list[5].name = 'roll_decidegree' var_list[6].name = 'pitch_decidegree' var_list[7].name = 'temperature_centidegree' var_list[8].name = 'pressure_mbar' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[8].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm/s' var_list[2].units = 'm/s' var_list[3].units = 'm/s' var_list[4].units = 'deci-degrees' var_list[5].units = 'deci-degrees' var_list[6].units = 'deci-degrees' var_list[7].units = '0.01degC' var_list[8].units = '0.001dbar' elif platform_name == 'CE06ISSM' and node == 'BUOY' and instrument_class == 'VELPT' and method == 'RecoveredHost': #uframe_dataset_name = 'CE06ISSM/RID16/04-VELPTA000/recovered_host/velpt_ab_dcl_instrument_recovered' uframe_dataset_name = 'CE06ISSM/RID16/04-VELPTA000/recovered_host/velpt_ab_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'eastward_velocity' var_list[2].name = 'northward_velocity' var_list[3].name = 'upward_velocity' var_list[4].name = 'heading_decidegree' var_list[5].name = 'roll_decidegree' var_list[6].name = 'pitch_decidegree' var_list[7].name = 'temperature_centidegree' var_list[8].name = 'pressure_mbar' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[8].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm/s' var_list[2].units = 'm/s' var_list[3].units = 'm/s' var_list[4].units = 'deci-degrees' var_list[5].units = 'deci-degrees' var_list[6].units = 'deci-degrees' var_list[7].units = '0.01degC' var_list[8].units = '0.001dbar' elif platform_name == 'CE07SHSM' and node == 'BUOY' and instrument_class == 'VELPT' and method == 'RecoveredHost': uframe_dataset_name = 'CE07SHSM/SBD11/04-VELPTA000/recovered_host/velpt_ab_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'eastward_velocity' var_list[2].name = 'northward_velocity' var_list[3].name = 'upward_velocity' var_list[4].name = 'heading_decidegree' var_list[5].name = 'roll_decidegree' var_list[6].name = 'pitch_decidegree' var_list[7].name = 'temperature_centidegree' var_list[8].name = 'pressure_mbar' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[8].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm/s' var_list[2].units = 'm/s' var_list[3].units = 'm/s' var_list[4].units = 'deci-degrees' var_list[5].units = 'deci-degrees' var_list[6].units = 'deci-degrees' var_list[7].units = '0.01degC' var_list[8].units = '0.001dbar' elif platform_name == 'CE09OSSM' and node == 'BUOY' and instrument_class == 'VELPT' and method == 'RecoveredHost': uframe_dataset_name = 'CE09OSSM/SBD11/04-VELPTA000/recovered_host/velpt_ab_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'eastward_velocity' var_list[2].name = 'northward_velocity' var_list[3].name = 'upward_velocity' var_list[4].name = 'heading_decidegree' var_list[5].name = 'roll_decidegree' var_list[6].name = 'pitch_decidegree' var_list[7].name = 'temperature_centidegree' var_list[8].name = 'pressure_mbar' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[8].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm/s' var_list[2].units = 'm/s' var_list[3].units = 'm/s' var_list[4].units = 'deci-degrees' var_list[5].units = 'deci-degrees' var_list[6].units = 'deci-degrees' var_list[7].units = '0.01degC' var_list[8].units = '0.001dbar' elif platform_name == 'CE01ISSM' and node == 'NSIF' and instrument_class == 'VELPT' and method == 'RecoveredHost': uframe_dataset_name = 'CE01ISSM/RID16/04-VELPTA000/recovered_host/velpt_ab_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'eastward_velocity' var_list[2].name = 'northward_velocity' var_list[3].name = 'upward_velocity' var_list[4].name = 'heading_decidegree' var_list[5].name = 'roll_decidegree' var_list[6].name = 'pitch_decidegree' var_list[7].name = 'temperature_centidegree' var_list[8].name = 'pressure_mbar' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[8].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm/s' var_list[2].units = 'm/s' var_list[3].units = 'm/s' var_list[4].units = 'deci-degrees' var_list[5].units = 'deci-degrees' var_list[6].units = 'deci-degrees' var_list[7].units = '0.01degC' var_list[8].units = '0.001dbar' elif platform_name == 'CE02SHSM' and node == 'NSIF' and instrument_class == 'VELPT' and method == 'RecoveredHost': uframe_dataset_name = 'CE02SHSM/RID26/04-VELPTA000/recovered_host/velpt_ab_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'eastward_velocity' var_list[2].name = 'northward_velocity' var_list[3].name = 'upward_velocity' var_list[4].name = 'heading_decidegree' var_list[5].name = 'roll_decidegree' var_list[6].name = 'pitch_decidegree' var_list[7].name = 'temperature_centidegree' var_list[8].name = 'pressure_mbar' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[8].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm/s' var_list[2].units = 'm/s' var_list[3].units = 'm/s' var_list[4].units = 'deci-degrees' var_list[5].units = 'deci-degrees' var_list[6].units = 'deci-degrees' var_list[7].units = '0.01degC' var_list[8].units = '0.001dbar' elif platform_name == 'CE04OSSM' and node == 'NSIF' and instrument_class == 'VELPT' and method == 'RecoveredHost': uframe_dataset_name = 'CE04OSSM/RID26/04-VELPTA000/recovered_host/velpt_ab_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'eastward_velocity' var_list[2].name = 'northward_velocity' var_list[3].name = 'upward_velocity' var_list[4].name = 'heading_decidegree' var_list[5].name = 'roll_decidegree' var_list[6].name = 'pitch_decidegree' var_list[7].name = 'temperature_centidegree' var_list[8].name = 'pressure_mbar' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[8].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm/s' var_list[2].units = 'm/s' var_list[3].units = 'm/s' var_list[4].units = 'deci-degrees' var_list[5].units = 'deci-degrees' var_list[6].units = 'deci-degrees' var_list[7].units = '0.01degC' var_list[8].units = '0.001dbar' elif platform_name == 'CE06ISSM' and node == 'NSIF' and instrument_class == 'VELPT' and method == 'RecoveredHost': uframe_dataset_name = 'CE06ISSM/RID16/04-VELPTA000/recovered_host/velpt_ab_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'eastward_velocity' var_list[2].name = 'northward_velocity' var_list[3].name = 'upward_velocity' var_list[4].name = 'heading_decidegree' var_list[5].name = 'roll_decidegree' var_list[6].name = 'pitch_decidegree' var_list[7].name = 'temperature_centidegree' var_list[8].name = 'pressure_mbar' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[8].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm/s' var_list[2].units = 'm/s' var_list[3].units = 'm/s' var_list[4].units = 'deci-degrees' var_list[5].units = 'deci-degrees' var_list[6].units = 'deci-degrees' var_list[7].units = '0.01degC' var_list[8].units = '0.001dbar' elif platform_name == 'CE07SHSM' and node == 'NSIF' and instrument_class == 'VELPT' and method == 'RecoveredHost': uframe_dataset_name = 'CE07SHSM/RID26/04-VELPTA000/recovered_host/velpt_ab_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'eastward_velocity' var_list[2].name = 'northward_velocity' var_list[3].name = 'upward_velocity' var_list[4].name = 'heading_decidegree' var_list[5].name = 'roll_decidegree' var_list[6].name = 'pitch_decidegree' var_list[7].name = 'temperature_centidegree' var_list[8].name = 'pressure_mbar' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[8].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm/s' var_list[2].units = 'm/s' var_list[3].units = 'm/s' var_list[4].units = 'deci-degrees' var_list[5].units = 'deci-degrees' var_list[6].units = 'deci-degrees' var_list[7].units = '0.01degC' var_list[8].units = '0.001dbar' elif platform_name == 'CE09OSSM' and node == 'NSIF' and instrument_class == 'VELPT' and method == 'RecoveredHost': uframe_dataset_name = 'CE09OSSM/RID26/04-VELPTA000/recovered_host/velpt_ab_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'eastward_velocity' var_list[2].name = 'northward_velocity' var_list[3].name = 'upward_velocity' var_list[4].name = 'heading_decidegree' var_list[5].name = 'roll_decidegree' var_list[6].name = 'pitch_decidegree' var_list[7].name = 'temperature_centidegree' var_list[8].name = 'pressure_mbar' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[6].data = np.array([]) var_list[7].data = np.array([]) var_list[8].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm/s' var_list[2].units = 'm/s' var_list[3].units = 'm/s' var_list[4].units = 'deci-degrees' var_list[5].units = 'deci-degrees' var_list[6].units = 'deci-degrees' var_list[7].units = '0.01degC' var_list[8].units = '0.001dbar' #PCO2W elif platform_name == 'CE01ISSM' and node == 'NSIF' and instrument_class == 'PCO2W' and method == 'RecoveredHost': uframe_dataset_name = 'CE01ISSM/RID16/05-PCO2WB000/recovered_host/pco2w_abc_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'pco2w_thermistor_temperature' var_list[2].name = 'pco2_seawater' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'uatm' elif platform_name == 'CE01ISSM' and node == 'MFN' and instrument_class == 'PCO2W' and method == 'RecoveredHost': uframe_dataset_name = 'CE01ISSM/MFD35/05-PCO2WB000/recovered_host/pco2w_abc_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'pco2w_thermistor_temperature' var_list[2].name = 'pco2_seawater' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'uatm' elif platform_name == 'CE06ISSM' and node == 'NSIF' and instrument_class == 'PCO2W' and method == 'RecoveredHost': uframe_dataset_name = 'CE06ISSM/RID16/05-PCO2WB000/recovered_host/pco2w_abc_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'pco2w_thermistor_temperature' var_list[2].name = 'pco2_seawater' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'uatm' elif platform_name == 'CE06ISSM' and node == 'MFN' and instrument_class == 'PCO2W' and method == 'RecoveredHost': uframe_dataset_name = 'CE06ISSM/MFD35/05-PCO2WB000/recovered_host/pco2w_abc_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'pco2w_thermistor_temperature' var_list[2].name = 'pco2_seawater' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'uatm' elif platform_name == 'CE07SHSM' and node == 'MFN' and instrument_class == 'PCO2W' and method == 'RecoveredHost': uframe_dataset_name = 'CE07SHSM/MFD35/05-PCO2WB000/recovered_host/pco2w_abc_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'pco2w_thermistor_temperature' var_list[2].name = 'pco2_seawater' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'uatm' elif platform_name == 'CE09OSSM' and node == 'MFN' and instrument_class == 'PCO2W' and method == 'RecoveredHost': uframe_dataset_name = 'CE09OSSM/MFD35/05-PCO2WB000/recovered_host/pco2w_abc_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'pco2w_thermistor_temperature' var_list[2].name = 'pco2_seawater' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'uatm' #PHSEN elif platform_name == 'CE01ISSM' and node == 'NSIF' and instrument_class == 'PHSEN' and method == 'RecoveredHost': uframe_dataset_name = 'CE01ISSM/RID16/06-PHSEND000/recovered_host/phsen_abcdef_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'phsen_thermistor_temperature' var_list[2].name = 'phsen_abcdef_ph_seawater' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' elif platform_name == 'CE02SHSM' and node == 'NSIF' and instrument_class == 'PHSEN' and method == 'RecoveredHost': uframe_dataset_name = 'CE02SHSM/RID26/06-PHSEND000/recovered_host/phsen_abcdef_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'phsen_thermistor_temperature' var_list[2].name = 'phsen_abcdef_ph_seawater' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' elif platform_name == 'CE04OSSM' and node == 'NSIF' and instrument_class == 'PHSEN' and method == 'RecoveredHost': uframe_dataset_name = 'CE04OSSM/RID26/06-PHSEND000/recovered_host/phsen_abcdef_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'phsen_thermistor_temperature' var_list[2].name = 'phsen_abcdef_ph_seawater' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' elif platform_name == 'CE06ISSM' and node == 'NSIF' and instrument_class == 'PHSEN' and method == 'RecoveredHost': uframe_dataset_name = 'CE06ISSM/RID16/06-PHSEND000/recovered_host/phsen_abcdef_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'phsen_thermistor_temperature' var_list[2].name = 'phsen_abcdef_ph_seawater' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' elif platform_name == 'CE07SHSM' and node == 'NSIF' and instrument_class == 'PHSEN' and method == 'RecoveredHost': uframe_dataset_name = 'CE07SHSM/RID26/06-PHSEND000/recovered_host/phsen_abcdef_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'phsen_thermistor_temperature' var_list[2].name = 'phsen_abcdef_ph_seawater' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' elif platform_name == 'CE09OSSM' and node == 'NSIF' and instrument_class == 'PHSEN' and method == 'RecoveredHost': uframe_dataset_name = 'CE09OSSM/RID26/06-PHSEND000/recovered_host/phsen_abcdef_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'phsen_thermistor_temperature' var_list[2].name = 'phsen_abcdef_ph_seawater' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' elif platform_name == 'CE01ISSM' and node == 'MFN' and instrument_class == 'PHSEN' and method == 'RecoveredHost': uframe_dataset_name = 'CE01ISSM/MFD35/06-PHSEND000/recovered_host/phsen_abcdef_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'phsen_thermistor_temperature' var_list[2].name = 'phsen_abcdef_ph_seawater' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' elif platform_name == 'CE06ISSM' and node == 'MFN' and instrument_class == 'PHSEN' and method == 'RecoveredHost': uframe_dataset_name = 'CE06ISSM/MFD35/06-PHSEND000/recovered_host/phsen_abcdef_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'phsen_thermistor_temperature' var_list[2].name = 'phsen_abcdef_ph_seawater' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' elif platform_name == 'CE07SHSM' and node == 'MFN' and instrument_class == 'PHSEN' and method == 'RecoveredHost': uframe_dataset_name = 'CE07SHSM/MFD35/06-PHSEND000/recovered_host/phsen_abcdef_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'phsen_thermistor_temperature' var_list[2].name = 'phsen_abcdef_ph_seawater' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' elif platform_name == 'CE09OSSM' and node == 'MFN' and instrument_class == 'PHSEN' and method == 'RecoveredHost': uframe_dataset_name = 'CE09OSSM/MFD35/06-PHSEND000/recovered_host/phsen_abcdef_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'phsen_thermistor_temperature' var_list[2].name = 'phsen_abcdef_ph_seawater' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' #SPKIR elif platform_name == 'CE01ISSM' and node == 'NSIF' and instrument_class == 'SPKIR' and method == 'RecoveredHost': uframe_dataset_name = 'CE01ISSM/RID16/08-SPKIRB000/recovered_host/spkir_abj_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'spkir_abj_cspp_downwelling_vector' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'uW cm-2 nm-1' elif platform_name == 'CE02SHSM' and node == 'NSIF' and instrument_class == 'SPKIR' and method == 'RecoveredHost': uframe_dataset_name = 'CE02SHSM/RID26/08-SPKIRB000/recovered_host/spkir_abj_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'spkir_abj_cspp_downwelling_vector' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'uW cm-2 nm-1' elif platform_name == 'CE04OSSM' and node == 'NSIF' and instrument_class == 'SPKIR' and method == 'RecoveredHost': uframe_dataset_name = 'CE04OSSM/RID26/08-SPKIRB000/recovered_host/spkir_abj_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'spkir_abj_cspp_downwelling_vector' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'uW cm-2 nm-1' elif platform_name == 'CE06ISSM' and node == 'NSIF' and instrument_class == 'SPKIR' and method == 'RecoveredHost': uframe_dataset_name = 'CE06ISSM/RID16/08-SPKIRB000/recovered_host/spkir_abj_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'spkir_abj_cspp_downwelling_vector' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'uW cm-2 nm-1' elif platform_name == 'CE07SHSM' and node == 'NSIF' and instrument_class == 'SPKIR' and method == 'RecoveredHost': uframe_dataset_name = 'CE07SHSM/RID26/08-SPKIRB000/recovered_host/spkir_abj_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'spkir_abj_cspp_downwelling_vector' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'uW cm-2 nm-1' elif platform_name == 'CE09OSSM' and node == 'NSIF' and instrument_class == 'SPKIR' and method == 'RecoveredHost': uframe_dataset_name = 'CE09OSSM/RID26/08-SPKIRB000/recovered_host/spkir_abj_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'spkir_abj_cspp_downwelling_vector' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'uW cm-2 nm-1' #PRESF elif platform_name == 'CE01ISSM' and node == 'MFN' and instrument_class == 'PRESF' and method == 'RecoveredHost': uframe_dataset_name = 'CE01ISSM/MFD35/02-PRESFA000/recovered_host/presf_abc_dcl_tide_measurement_recovered' var_list[0].name = 'time' var_list[1].name = 'abs_seafloor_pressure' var_list[2].name = 'seawater_temperature' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'dbar' var_list[2].units = 'degC' elif platform_name == 'CE06ISSM' and node == 'MFN' and instrument_class == 'PRESF' and method == 'RecoveredHost': uframe_dataset_name = 'CE06ISSM/MFD35/02-PRESFA000/recovered_host/presf_abc_dcl_tide_measurement_recovered' var_list[0].name = 'time' var_list[1].name = 'abs_seafloor_pressure' var_list[2].name = 'seawater_temperature' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'dbar' var_list[2].units = 'degC' elif platform_name == 'CE07SHSM' and node == 'MFN' and instrument_class == 'PRESF' and method == 'RecoveredHost': uframe_dataset_name = 'CE07SHSM/MFD35/02-PRESFB000/recovered_host/presf_abc_dcl_tide_measurement_recovered' var_list[0].name = 'time' var_list[1].name = 'abs_seafloor_pressure' var_list[2].name = 'seawater_temperature' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'dbar' var_list[2].units = 'degC' elif platform_name == 'CE09OSSM' and node == 'MFN' and instrument_class == 'PRESF' and method == 'RecoveredHost': uframe_dataset_name = 'CE09OSSM/MFD35/02-PRESFC000/recovered_host/presf_abc_dcl_tide_measurement_recovered' var_list[0].name = 'time' var_list[1].name = 'abs_seafloor_pressure' var_list[2].name = 'seawater_temperature' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'dbar' var_list[2].units = 'degC' #CTDBP elif platform_name == 'CE01ISSM' and node == 'NSIF' and instrument_class == 'CTD' and method == 'RecoveredHost': uframe_dataset_name = 'CE01ISSM/RID16/03-CTDBPC000/recovered_host/ctdbp_cdef_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'temp' var_list[2].name = 'practical_salinity' var_list[3].name = 'density' var_list[4].name = 'pressure' var_list[5].name = 'conductivity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' var_list[3].units = 'kg/m3' var_list[4].units = 'dbar' var_list[5].units = 'S/m' elif platform_name == 'CE01ISSM' and node == 'MFN' and instrument_class == 'CTD' and method == 'RecoveredHost': uframe_dataset_name = 'CE01ISSM/MFD37/03-CTDBPC000/recovered_host/ctdbp_cdef_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'temp' var_list[2].name = 'practical_salinity' var_list[3].name = 'density' var_list[4].name = 'pressure' var_list[5].name = 'conductivity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' var_list[3].units = 'kg/m3' var_list[4].units = 'dbar' var_list[5].units = 'S/m' elif platform_name == 'CE01ISSM' and node == 'BUOY' and instrument_class == 'CTD' and method == 'RecoveredHost': uframe_dataset_name = 'CE01ISSM/SBD17/06-CTDBPC000/recovered_host/ctdbp_cdef_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'temp' var_list[2].name = 'practical_salinity' var_list[3].name = 'density' var_list[4].name = 'pressure' var_list[5].name = 'conductivity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' var_list[3].units = 'kg/m3' var_list[4].units = 'dbar' var_list[5].units = 'S/m' elif platform_name == 'CE06ISSM' and node == 'NSIF' and instrument_class == 'CTD' and method == 'RecoveredHost': uframe_dataset_name = 'CE06ISSM/RID16/03-CTDBPC000/recovered_host/ctdbp_cdef_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'temp' var_list[2].name = 'practical_salinity' var_list[3].name = 'density' var_list[4].name = 'pressure' var_list[5].name = 'conductivity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' var_list[3].units = 'kg/m3' var_list[4].units = 'dbar' var_list[5].units = 'S/m' elif platform_name == 'CE06ISSM' and node == 'MFN' and instrument_class == 'CTD' and method == 'RecoveredHost': uframe_dataset_name = 'CE06ISSM/MFD37/03-CTDBPC000/recovered_host/ctdbp_cdef_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'temp' var_list[2].name = 'practical_salinity' var_list[3].name = 'density' var_list[4].name = 'pressure' var_list[5].name = 'conductivity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' var_list[3].units = 'kg/m3' var_list[4].units = 'dbar' var_list[5].units = 'S/m' elif platform_name == 'CE06ISSM' and node == 'BUOY' and instrument_class == 'CTD' and method == 'RecoveredHost': uframe_dataset_name = 'CE06ISSM/SBD17/06-CTDBPC000/recovered_host/ctdbp_cdef_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'temp' var_list[2].name = 'practical_salinity' var_list[3].name = 'density' var_list[4].name = 'pressure' var_list[5].name = 'conductivity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' var_list[3].units = 'kg/m3' var_list[4].units = 'dbar' var_list[5].units = 'S/m' elif platform_name == 'CE02SHSM' and node == 'NSIF' and instrument_class == 'CTD' and method == 'RecoveredHost': uframe_dataset_name = 'CE02SHSM/RID27/03-CTDBPC000/recovered_host/ctdbp_cdef_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'temp' var_list[2].name = 'practical_salinity' var_list[3].name = 'density' var_list[4].name = 'pressure' var_list[5].name = 'conductivity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' var_list[3].units = 'kg/m3' var_list[4].units = 'dbar' var_list[5].units = 'S/m' elif platform_name == 'CE07SHSM' and node == 'NSIF' and instrument_class == 'CTD' and method == 'RecoveredHost': uframe_dataset_name = 'CE07SHSM/RID27/03-CTDBPC000/recovered_host/ctdbp_cdef_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'temp' var_list[2].name = 'practical_salinity' var_list[3].name = 'density' var_list[4].name = 'pressure' var_list[5].name = 'conductivity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' var_list[3].units = 'kg/m3' var_list[4].units = 'dbar' var_list[5].units = 'S/m' elif platform_name == 'CE04OSSM' and node == 'NSIF' and instrument_class == 'CTD' and method == 'RecoveredHost': uframe_dataset_name = 'CE04OSSM/RID27/03-CTDBPC000/recovered_host/ctdbp_cdef_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'temp' var_list[2].name = 'practical_salinity' var_list[3].name = 'density' var_list[4].name = 'pressure' var_list[5].name = 'conductivity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' var_list[3].units = 'kg/m3' var_list[4].units = 'dbar' var_list[5].units = 'S/m' elif platform_name == 'CE09OSSM' and node == 'NSIF' and instrument_class == 'CTD' and method == 'RecoveredHost': uframe_dataset_name = 'CE09OSSM/RID27/03-CTDBPC000/recovered_host/ctdbp_cdef_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'temp' var_list[2].name = 'practical_salinity' var_list[3].name = 'density' var_list[4].name = 'pressure' var_list[5].name = 'conductivity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' var_list[3].units = 'kg/m3' var_list[4].units = 'dbar' var_list[5].units = 'S/m' elif platform_name == 'CE07SHSM' and node == 'MFN' and instrument_class == 'CTD' and method == 'RecoveredHost': uframe_dataset_name = 'CE07SHSM/MFD37/03-CTDBPC000/recovered_host/ctdbp_cdef_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'temp' var_list[2].name = 'practical_salinity' var_list[3].name = 'density' var_list[4].name = 'pressure' var_list[5].name = 'conductivity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' var_list[3].units = 'kg/m3' var_list[4].units = 'dbar' var_list[5].units = 'S/m' elif platform_name == 'CE09OSSM' and node == 'MFN' and instrument_class == 'CTD' and method == 'RecoveredHost': uframe_dataset_name = 'CE09OSSM/MFD37/03-CTDBPE000/recovered_host/ctdbp_cdef_dcl_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'temp' var_list[2].name = 'practical_salinity' var_list[3].name = 'density' var_list[4].name = 'pressure' var_list[5].name = 'conductivity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' var_list[3].units = 'kg/m3' var_list[4].units = 'dbar' var_list[5].units = 'S/m' #VEL3D elif platform_name == 'CE01ISSM' and node == 'MFN' and instrument_class == 'VEL3D' and method == 'RecoveredHost': uframe_dataset_name = 'CE01ISSM/MFD35/01-VEL3DD000/recovered_host/vel3d_cd_dcl_velocity_data_recovered' var_list[0].name = 'time' var_list[1].name = 'vel3d_c_eastward_turbulent_velocity' var_list[2].name = 'vel3d_c_northward_turbulent_velocity' var_list[3].name = 'vel3d_c_upward_turbulent_velocity' var_list[4].name = 'seawater_pressure_mbar' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm/s' var_list[2].units = 'm/s' var_list[3].units = 'm/s' var_list[4].units = '0.001dbar' elif platform_name == 'CE06ISSM' and node == 'MFN' and instrument_class == 'VEL3D' and method == 'RecoveredHost': uframe_dataset_name = 'CE06ISSM/MFD35/01-VEL3DD000/recovered_host/vel3d_cd_dcl_velocity_data_recovered' var_list[0].name = 'time' var_list[1].name = 'vel3d_c_eastward_turbulent_velocity' var_list[2].name = 'vel3d_c_northward_turbulent_velocity' var_list[3].name = 'vel3d_c_upward_turbulent_velocity' var_list[4].name = 'seawater_pressure_mbar' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm/s' var_list[2].units = 'm/s' var_list[3].units = 'm/s' var_list[4].units = '0.001dbar' elif platform_name == 'CE07SHSM' and node == 'MFN' and instrument_class == 'VEL3D' and method == 'RecoveredHost': uframe_dataset_name = 'CE07SHSM/MFD35/01-VEL3DD000/recovered_host/vel3d_cd_dcl_velocity_data_recovered' var_list[0].name = 'time' var_list[1].name = 'vel3d_c_eastward_turbulent_velocity' var_list[2].name = 'vel3d_c_northward_turbulent_velocity' var_list[3].name = 'vel3d_c_upward_turbulent_velocity' var_list[4].name = 'seawater_pressure_mbar' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm/s' var_list[2].units = 'm/s' var_list[3].units = 'm/s' var_list[4].units = '0.001dbar' elif platform_name == 'CE09OSSM' and node == 'MFN' and instrument_class == 'VEL3D' and method == 'RecoveredHost': uframe_dataset_name = 'CE09OSSM/MFD35/01-VEL3DD000/recovered_host/vel3d_cd_dcl_velocity_data_recovered' var_list[0].name = 'time' var_list[1].name = 'vel3d_c_eastward_turbulent_velocity' var_list[2].name = 'vel3d_c_northward_turbulent_velocity' var_list[3].name = 'vel3d_c_upward_turbulent_velocity' var_list[4].name = 'seawater_pressure_mbar' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'm/s' var_list[2].units = 'm/s' var_list[3].units = 'm/s' var_list[4].units = '0.001dbar' #PCO2A elif platform_name == 'CE02SHSM' and node == 'BUOY' and instrument_class == 'PCO2A' and method == 'RecoveredHost': uframe_dataset_name = 'CE02SHSM/SBD12/04-PCO2AA000/recovered_host/pco2a_a_dcl_instrument_water_recovered' var_list[0].name = 'time' var_list[1].name = 'partial_pressure_co2_ssw' var_list[2].name = 'partial_pressure_co2_atm' var_list[3].name = 'pco2_co2flux' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'uatm' var_list[2].units = 'uatm' var_list[3].units = 'mol m-2 s-1' elif platform_name == 'CE04OSSM' and node == 'BUOY' and instrument_class == 'PCO2A' and method == 'RecoveredHost': uframe_dataset_name = 'CE04OSSM/SBD12/04-PCO2AA000/recovered_host/pco2a_a_dcl_instrument_water_recovered' var_list[0].name = 'time' var_list[1].name = 'partial_pressure_co2_ssw' var_list[2].name = 'partial_pressure_co2_atm' var_list[3].name = 'pco2_co2flux' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'uatm' var_list[2].units = 'uatm' var_list[3].units = 'mol m-2 s-1' elif platform_name == 'CE07SHSM' and node == 'BUOY' and instrument_class == 'PCO2A' and method == 'RecoveredHost': uframe_dataset_name = 'CE07SHSM/SBD12/04-PCO2AA000/recovered_host/pco2a_a_dcl_instrument_water_recovered' var_list[0].name = 'time' var_list[1].name = 'partial_pressure_co2_ssw' var_list[2].name = 'partial_pressure_co2_atm' var_list[3].name = 'pco2_co2flux' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'uatm' var_list[2].units = 'uatm' var_list[3].units = 'mol m-2 s-1' elif platform_name == 'CE09OSSM' and node == 'BUOY' and instrument_class == 'PCO2A' and method == 'RecoveredHost': uframe_dataset_name = 'CE09OSSM/SBD12/04-PCO2AA000/recovered_host/pco2a_a_dcl_instrument_water_recovered' var_list[0].name = 'time' var_list[1].name = 'partial_pressure_co2_ssw' var_list[2].name = 'partial_pressure_co2_atm' var_list[3].name = 'pco2_co2flux' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'uatm' var_list[2].units = 'uatm' var_list[3].units = 'mol m-2 s-1' #OPTAA elif platform_name == 'CE01ISSM' and node == 'NSIF' and instrument_class == 'OPTAA' and method == 'RecoveredHost': uframe_dataset_name = 'CE01ISSM/RID16/01-OPTAAD000/recovered_host/optaa_dj_dcl_instrument_recovered' var_list[0].name = 'time' var_list[0].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' elif platform_name == 'CE02SHSM' and node == 'NSIF' and instrument_class == 'OPTAA' and method == 'RecoveredHost': uframe_dataset_name = 'CE02SHSM/RID27/01-OPTAAD000/recovered_host/optaa_dj_dcl_instrument_recovered' var_list[0].name = 'time' var_list[0].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' elif platform_name == 'CE04OSSM' and node == 'NSIF' and instrument_class == 'OPTAA' and method == 'RecoveredHost': uframe_dataset_name = 'CE04OSSM/RID27/01-OPTAAD000/recovered_host/optaa_dj_dcl_instrument_recovered' var_list[0].name = 'time' var_list[0].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' elif platform_name == 'CE06ISSM' and node == 'NSIF' and instrument_class == 'OPTAA' and method == 'RecoveredHost': uframe_dataset_name = 'CE06ISSM/RID16/01-OPTAAD000/recovered_host/optaa_dj_dcl_instrument_recovered' var_list[0].name = 'time' var_list[0].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' elif platform_name == 'CE07SHSM' and node == 'NSIF' and instrument_class == 'OPTAA' and method == 'RecoveredHost': uframe_dataset_name = 'CE07SHSM/RID27/01-OPTAAD000/recovered_host/optaa_dj_dcl_instrument_recovered' var_list[0].name = 'time' var_list[0].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' elif platform_name == 'CE09OSSM' and node == 'NSIF' and instrument_class == 'OPTAA' and method == 'RecoveredHost': uframe_dataset_name = 'CE09OSSM/RID27/01-OPTAAD000/recovered_host/optaa_dj_dcl_instrument_recovered' var_list[0].name = 'time' var_list[0].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' elif platform_name == 'CE01ISSM' and node == 'MFN' and instrument_class == 'OPTAA' and method == 'RecoveredHost': uframe_dataset_name = 'CE01ISSM/MFD37/01-OPTAAD000/recovered_host/optaa_dj_dcl_instrument_recovered' var_list[0].name = 'time' var_list[0].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' elif platform_name == 'CE06ISSM' and node == 'MFN' and instrument_class == 'OPTAA' and method == 'RecoveredHost': uframe_dataset_name = 'CE06ISSM/MFD37/01-OPTAAD000/recovered_host/optaa_dj_dcl_instrument_recovered' var_list[0].name = 'time' var_list[0].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' elif platform_name == 'CE07SHSM' and node == 'MFN' and instrument_class == 'OPTAA' and method == 'RecoveredHost': uframe_dataset_name = 'CE07SHSM/MFD37/01-OPTAAD000/recovered_host/optaa_dj_dcl_instrument_recovered' var_list[0].name = 'time' var_list[0].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' elif platform_name == 'CE09OSSM' and node == 'MFN' and instrument_class == 'OPTAA' and method == 'RecoveredHost': uframe_dataset_name = 'CE09OSSM/MFD37/01-OPTAAC000/recovered_host/optaa_dj_dcl_instrument_recovered' var_list[0].name = 'time' var_list[0].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' #NUTNR elif platform_name == 'CE01ISSM' and node == 'NSIF' and instrument_class == 'NUTNR' and method == 'RecoveredHost': uframe_dataset_name = 'CE01ISSM/RID16/07-NUTNRB000/recovered_host/suna_dcl_recovered' var_list[0].name = 'time' var_list[1].name = 'nitrate_concentration' var_list[2].name = 'salinity_corrected_nitrate' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'umol/L' var_list[2].units = 'umol/L' elif platform_name == 'CE02SHSM' and node == 'NSIF' and instrument_class == 'NUTNR' and method == 'RecoveredHost': uframe_dataset_name = 'CE02SHSM/RID26/07-NUTNRB000/recovered_host/suna_dcl_recovered' var_list[0].name = 'time' var_list[1].name = 'nitrate_concentration' var_list[2].name = 'salinity_corrected_nitrate' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'umol/L' var_list[2].units = 'umol/L' elif platform_name == 'CE04OSSM' and node == 'NSIF' and instrument_class == 'NUTNR' and method == 'RecoveredHost': uframe_dataset_name = 'CE04OSSM/RID26/07-NUTNRB000/recovered_host/suna_dcl_recovered' var_list[0].name = 'time' var_list[1].name = 'nitrate_concentration' var_list[2].name = 'salinity_corrected_nitrate' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'umol/L' var_list[2].units = 'umol/L' elif platform_name == 'CE06ISSM' and node == 'NSIF' and instrument_class == 'NUTNR' and method == 'RecoveredHost': uframe_dataset_name = 'CE06ISSM/RID16/07-NUTNRB000/recovered_host/suna_dcl_recovered' var_list[0].name = 'time' var_list[1].name = 'nitrate_concentration' var_list[2].name = 'salinity_corrected_nitrate' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'umol/L' var_list[2].units = 'umol/L' elif platform_name == 'CE07SHSM' and node == 'NSIF' and instrument_class == 'NUTNR' and method == 'RecoveredHost': uframe_dataset_name = 'CE07SHSM/RID26/07-NUTNRB000/recovered_host/suna_dcl_recovered' var_list[0].name = 'time' var_list[1].name = 'nitrate_concentration' var_list[2].name = 'salinity_corrected_nitrate' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'umol/L' var_list[2].units = 'umol/L' elif platform_name == 'CE09OSSM' and node == 'NSIF' and instrument_class == 'NUTNR' and method == 'RecoveredHost': uframe_dataset_name = 'CE09OSSM/RID26/07-NUTNRB000/recovered_host/suna_dcl_recovered' var_list[0].name = 'time' var_list[1].name = 'nitrate_concentration' var_list[2].name = 'salinity_corrected_nitrate' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'umol/L' var_list[2].units = 'umol/L' elif platform_name == 'CE01ISSM' and node == 'NSIF' and instrument_class == 'CTD' and method == 'RecoveredInst': uframe_dataset_name = 'CE01ISSM/RID16/03-CTDBPC000/recovered_inst/ctdbp_cdef_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'ctdbp_seawater_temperature' var_list[2].name = 'practical_salinity' var_list[3].name = 'density' var_list[4].name = 'ctdbp_seawater_pressure' var_list[5].name = 'ctdbp_seawater_conductivity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' var_list[3].units = 'kg/m3' var_list[4].units = 'dbar' var_list[5].units = 'S/m' elif platform_name == 'CE01ISSM' and node == 'MFN' and instrument_class == 'CTD' and method == 'RecoveredInst': uframe_dataset_name = 'CE01ISSM/MFD37/03-CTDBPC000/recovered_inst/ctdbp_cdef_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'ctdbp_seawater_temperature' var_list[2].name = 'practical_salinity' var_list[3].name = 'density' var_list[4].name = 'ctdbp_seawater_pressure' var_list[5].name = 'ctdbp_seawater_conductivity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' var_list[3].units = 'kg/m3' var_list[4].units = 'dbar' var_list[5].units = 'S/m' elif platform_name == 'CE01ISSM' and node == 'BUOY' and instrument_class == 'CTD' and method == 'RecoveredInst': uframe_dataset_name = 'CE01ISSM/SBD17/06-CTDBPC000/recovered_inst/ctdbp_cdef_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'ctdbp_seawater_temperature' var_list[2].name = 'practical_salinity' var_list[3].name = 'density' var_list[4].name = 'ctdbp_seawater_pressure' var_list[5].name = 'ctdbp_seawater_conductivity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' var_list[3].units = 'kg/m3' var_list[4].units = 'dbar' var_list[5].units = 'S/m' elif platform_name == 'CE06ISSM' and node == 'NSIF' and instrument_class == 'CTD' and method == 'RecoveredInst': uframe_dataset_name = 'CE06ISSM/RID16/03-CTDBPC000/recovered_inst/ctdbp_cdef_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'ctdbp_seawater_temperature' var_list[2].name = 'practical_salinity' var_list[3].name = 'density' var_list[4].name = 'ctdbp_seawater_pressure' var_list[5].name = 'ctdbp_seawater_conductivity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' var_list[3].units = 'kg/m3' var_list[4].units = 'dbar' var_list[5].units = 'S/m' elif platform_name == 'CE06ISSM' and node == 'MFN' and instrument_class == 'CTD' and method == 'RecoveredInst': uframe_dataset_name = 'CE06ISSM/MFD37/03-CTDBPC000/recovered_inst/ctdbp_cdef_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'ctdbp_seawater_temperature' var_list[2].name = 'practical_salinity' var_list[3].name = 'density' var_list[4].name = 'ctdbp_seawater_pressure' var_list[5].name = 'ctdbp_seawater_conductivity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' var_list[3].units = 'kg/m3' var_list[4].units = 'dbar' var_list[5].units = 'S/m' elif platform_name == 'CE06ISSM' and node == 'BUOY' and instrument_class == 'CTD' and method == 'RecoveredInst': uframe_dataset_name = 'CE06ISSM/SBD17/06-CTDBPC000/recovered_inst/ctdbp_cdef_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'ctdbp_seawater_temperature' var_list[2].name = 'practical_salinity' var_list[3].name = 'density' var_list[4].name = 'ctdbp_seawater_pressure' var_list[5].name = 'ctdbp_seawater_conductivity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' var_list[3].units = 'kg/m3' var_list[4].units = 'dbar' var_list[5].units = 'S/m' elif platform_name == 'CE02SHSM' and node == 'NSIF' and instrument_class == 'CTD' and method == 'RecoveredInst': uframe_dataset_name = 'CE02SHSM/RID27/03-CTDBPC000/recovered_inst/ctdbp_cdef_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'ctdbp_seawater_temperature' var_list[2].name = 'practical_salinity' var_list[3].name = 'density' var_list[4].name = 'ctdbp_seawater_pressure' var_list[5].name = 'ctdbp_seawater_conductivity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' var_list[3].units = 'kg/m3' var_list[4].units = 'dbar' var_list[5].units = 'S/m' elif platform_name == 'CE07SHSM' and node == 'NSIF' and instrument_class == 'CTD' and method == 'RecoveredInst': uframe_dataset_name = 'CE07SHSM/RID27/03-CTDBPC000/recovered_inst/ctdbp_cdef_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'ctdbp_seawater_temperature' var_list[2].name = 'practical_salinity' var_list[3].name = 'density' var_list[4].name = 'ctdbp_seawater_pressure' var_list[5].name = 'ctdbp_seawater_conductivity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' var_list[3].units = 'kg/m3' var_list[4].units = 'dbar' var_list[5].units = 'S/m' elif platform_name == 'CE04OSSM' and node == 'NSIF' and instrument_class == 'CTD' and method == 'RecoveredInst': uframe_dataset_name = 'CE04OSSM/RID27/03-CTDBPC000/recovered_inst/ctdbp_cdef_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'ctdbp_seawater_temperature' var_list[2].name = 'practical_salinity' var_list[3].name = 'density' var_list[4].name = 'ctdbp_seawater_pressure' var_list[5].name = 'ctdbp_seawater_conductivity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' var_list[3].units = 'kg/m3' var_list[4].units = 'dbar' var_list[5].units = 'S/m' elif platform_name == 'CE09OSSM' and node == 'NSIF' and instrument_class == 'CTD' and method == 'RecoveredInst': uframe_dataset_name = 'CE09OSSM/RID27/03-CTDBPC000/recovered_inst/ctdbp_cdef_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'ctdbp_seawater_temperature' var_list[2].name = 'practical_salinity' var_list[3].name = 'density' var_list[4].name = 'ctdbp_seawater_pressure' var_list[5].name = 'ctdbp_seawater_conductivity' var_list[0].data = np.array([]) var_list[1].data = np.array([]) var_list[2].data = np.array([]) var_list[3].data = np.array([]) var_list[4].data = np.array([]) var_list[5].data = np.array([]) var_list[0].units = 'seconds since 1900-01-01' var_list[1].units = 'degC' var_list[2].units = 'unitless' var_list[3].units = 'kg/m3' var_list[4].units = 'dbar' var_list[5].units = 'S/m' elif platform_name == 'CE07SHSM' and node == 'MFN' and instrument_class == 'CTD' and method == 'RecoveredInst': uframe_dataset_name = 'CE07SHSM/MFD37/03-CTDBPC000/recovered_inst/ctdbp_cdef_instrument_recovered' var_list[0].name = 'time' var_list[1].name = 'ctdbp_seawater_temperature' var_list[2].name = 'practical_salinity' var_list[3].name = 'density' var_list[4].name = 'ctdbp_seawater_pressure' var_list[5].name = 'ctdbp_seawater_conductivity' var_list[0].data = np.array([]) var_list[1].data =
np.array([])
numpy.array
# Copyright 2014-2019 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. # # Author: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # ''' Restricted algebraic diagrammatic construction ''' import time import numpy as np import pyscf.ao2mo as ao2mo from pyscf import lib from pyscf.lib import logger from pyscf.adc import radc_ao2mo from pyscf.adc import dfadc from pyscf import __config__ from pyscf import df from pyscf import symm def kernel(adc, nroots=1, guess=None, eris=None, verbose=None): adc.method = adc.method.lower() if adc.method not in ("adc(2)", "adc(2)-x", "adc(3)"): raise NotImplementedError(adc.method) cput0 = (time.clock(), time.time()) log = logger.Logger(adc.stdout, adc.verbose) if adc.verbose >= logger.WARN: adc.check_sanity() adc.dump_flags() if eris is None: eris = adc.transform_integrals() imds = adc.get_imds(eris) matvec, diag = adc.gen_matvec(imds, eris) guess = adc.get_init_guess(nroots, diag, ascending = True) conv, adc.E, U = lib.linalg_helper.davidson_nosym1(lambda xs : [matvec(x) for x in xs], guess, diag, nroots=nroots, verbose=log, tol=adc.conv_tol, max_cycle=adc.max_cycle, max_space=adc.max_space,tol_residual=adc.tol_residual) adc.U =
np.array(U)
numpy.array
# -*- coding: utf-8 -*- ''' Copyright (c) 2021, MIT Interactive Robotics Group, PI <NAME>. Authors: <NAME>, <NAME>, <NAME>, <NAME> All rights reserved. https://github.com/befelix/safe-exploration/blob/master/safe_exploration/visualization/utils_visualization.py ''' import numpy as np import numpy.linalg as nLa from IPython import embed from matplotlib.patches import Ellipse import matplotlib.pyplot as plt # https://stackoverflow.com/questions/287871/how-to-print-colored-text-to-the-terminal class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKCYAN = '\033[96m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' def print_FAIL(m): print(bcolors.FAIL + m + bcolors.ENDC) def print_OK(m): print(bcolors.WARNING + m + bcolors.ENDC) def plot_ellipsoid_2D(centroid, Q, ax, color="r", alpha=1.0): A = nLa.inv(Q) # ------------- # https://gist.github.com/Gabriel-p/4ddd31422a88e7cdf953 # A : (d x d) matrix of the ellipse equation in the 'center form': # (x-c)' * A * (x-c) = 1 # 'centroid' is the center coordinates of the ellipse. # V is the rotation matrix that gives the orientation of the ellipsoid. # https://en.wikipedia.org/wiki/Rotation_matrix # http://mathworld.wolfram.com/RotationMatrix.html U, D, V = nLa.svd(A) # x, y radii. rx, ry = 1./np.sqrt(D) # Major and minor semi-axis of the ellipse. dx, dy = 2 * rx, 2 * ry a, b = max(dx, dy), min(dx, dy) # Eccentricity # e = np.sqrt(a ** 2 - b ** 2) / a arcsin = -1. * np.rad2deg(np.arcsin(V[0][0])) arccos = np.rad2deg(
np.arccos(V[0][1])
numpy.arccos
import numpy as np import pandas as pd import json import os from tqdm import tqdm import cv2 from math import sin, cos from mmcv.image import imread, imwrite import mmcv from pycocotools import mask as maskUtils import multiprocessing import copy from .custom import CustomDataset from .registry import DATASETS from .car_models import car_id2name from .kaggle_pku_utils import euler_to_Rot, euler_angles_to_quaternions, \ quaternion_upper_hemispher, quaternion_to_euler_angle, draw_line, draw_points, non_max_suppression_fast from .visualisation_utils import draw_result_kaggle_pku, draw_box_mesh_kaggle_pku, refine_yaw_and_roll, \ restore_x_y_from_z_withIOU, get_IOU, nms_with_IOU, nms_with_IOU_and_vote, nms_with_IOU_and_vote_return_index from albumentations.augmentations import transforms from math import acos, pi from scipy.spatial.transform import Rotation as R class NumpyEncoder(json.JSONEncoder): """ Special json encoder for numpy types """ def default(self, obj): if isinstance(obj, (np.int_, np.intc, np.intp, np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.uint32, np.uint64)): return int(obj) elif isinstance(obj, (np.float_, np.float16, np.float32, np.float64)): return float(obj) elif isinstance(obj, (np.ndarray,)): #### This is the fix return obj.tolist() elif isinstance(obj, (bytes)): return obj.decode("ascii") return json.JSONEncoder.default(self, obj) @DATASETS.register_module class KagglePKUDataset(CustomDataset): CLASSES = ('car',) def load_annotations(self, ann_file, outdir='/data/Kaggle/pku-autonomous-driving'): # some hard coded parameters self.outdir = outdir self.image_shape = (2710, 3384) # this is generally the case self.bottom_half = 1480 # this self.unique_car_mode = [2, 6, 7, 8, 9, 12, 14, 16, 18, 19, 20, 23, 25, 27, 28, 31, 32, 35, 37, 40, 43, 46, 47, 48, 50, 51, 54, 56, 60, 61, 66, 70, 71, 76] self.cat2label = {car_model: i for i, car_model in enumerate(self.unique_car_mode)} # From camera.zip self.camera_matrix = np.array([[2304.5479, 0, 1686.2379], [0, 2305.8757, 1354.9849], [0, 0, 1]], dtype=np.float32) print("Loading Car model files...") self.car_model_dict = self.load_car_models() self.car_id2name = car_id2name annotations = [] if not self.test_mode: outfile = ann_file if os.path.isfile(outfile): annotations = json.load(open(outfile, 'r')) else: PATH = '/data/Kaggle/ApolloScape_3D_car/train/split/' ImageId = [i.strip() for i in open(PATH + 'train-list.txt').readlines()] train = pd.read_csv(ann_file) for idx in tqdm(range(len(train))): filename = train['ImageId'].iloc[idx] + '.jpg' if filename not in ImageId: continue annotation = self.load_anno_idx(idx, train) annotations.append(annotation) with open(outfile, 'w') as f: json.dump(annotations, f, indent=4, cls=NumpyEncoder) annotations = self.clean_corrupted_images(annotations) annotations = self.clean_outliers(annotations) self.print_statistics_annotations(annotations) else: if os.path.isfile(ann_file): # This for evulating ApolloScape # Using readlines() file = open(ann_file, 'r') lines = file.readlines() for fn in lines: filename = os.path.join(self.img_prefix, fn.replace('\n', '')) info = {'filename': filename} annotations.append(info) else: for fn in os.listdir(self.img_prefix): filename = os.path.join(self.img_prefix, fn) info = {'filename': filename} annotations.append(info) # We also generate the albumentation enhances valid images # below is a hard coded list.... if False: self.generate_albu_valid(annotations) # We also will generate a pickle file if the translation, SSD like offset regression # this will need to be done only once if False: self.group_rectangles(annotations) self.annotations = annotations return annotations def load(self, t): return self.load_anno_idx(*t) def generate_albu_valid(self, annotations): num_albu = len(self.pipeline_dict[-1].transforms[-3].transforms) for i_albu in range(num_albu): params = self.pipeline_dict[-1].transforms[-3].transforms[i_albu] # always set p=1 so that we will always tranform the image params['p'] = 1 operation = getattr(transforms, params['type']) # delete the 'type' params_input = params.copy() del params_input['type'] im_out_dir = self.img_prefix + '_' + params['type'] if not os.path.exists(im_out_dir): os.mkdir(im_out_dir) print('Generating: %s' % params['type']) for im_idx in tqdm(range(len(annotations))): image = imread(annotations[im_idx]['filename']) img_aug = operation(**params_input)(image=image)['image'] im_out_file = annotations[im_idx]['filename'].split('/')[-1] imwrite(img_aug, os.path.join(im_out_dir, im_out_file)) def load_car_models(self): car_model_dir = os.path.join(self.outdir, 'car_models_json') car_model_dict = {} for car_name in tqdm(os.listdir(car_model_dir)): with open(os.path.join(self.outdir, 'car_models_json', car_name)) as json_file: car_model_dict[car_name[:-5]] = json.load(json_file) return car_model_dict def RotationDistance(self, p, g): true = [g[1], g[0], g[2]] pred = [p[1], p[0], p[2]] q1 = R.from_euler('xyz', true) q2 = R.from_euler('xyz', pred) diff = R.inv(q2) * q1 W = np.clip(diff.as_quat()[-1], -1., 1.) # in the official metrics code: # Peking University/Baidu - Autonomous Driving # return Object3D.RadianToDegree( Math.Acos(diff.W) ) # this code treat θ and θ+2π differntly. # So this should be fixed as follows. W = (acos(W) * 360) / pi if W > 180: W = 360 - W return W def load_anno_idx(self, idx, train, draw=False, draw_dir='/data/cyh/kaggle/train_image_gt_vis'): labels = [] bboxes = [] rles = [] eular_angles = [] quaternion_semispheres = [] translations = [] img_name = self.img_prefix + train['ImageId'].iloc[idx] + '.jpg' if not os.path.isfile(img_name): assert "Image file does not exist!" else: if draw: image = imread(img_name) mask_all = np.zeros(image.shape) merged_image = image.copy() alpha = 0.8 # transparency gt = self._str2coords(train['PredictionString'].iloc[idx]) for gt_pred in gt: eular_angle = np.array([gt_pred['yaw'], gt_pred['pitch'], gt_pred['roll']]) translation = np.array([gt_pred['x'], gt_pred['y'], gt_pred['z']]) quaternion = euler_angles_to_quaternions(eular_angle) quaternion_semisphere = quaternion_upper_hemispher(quaternion) new_eular_angle = quaternion_to_euler_angle(quaternion_semisphere) distance = self.RotationDistance(new_eular_angle, eular_angle) # distance = np.sum(np.abs(new_eular_angle - eular_angle)) if distance > 0.001: print("Wrong !!!", img_name) labels.append(gt_pred['id']) eular_angles.append(eular_angle) quaternion_semispheres.append(quaternion_semisphere) translations.append(translation) # rendering the car according to: # Augmented Reality | Kaggle # car_id2name is from: # https://github.com/ApolloScapeAuto/dataset-api/blob/master/car_instance/car_models.py car_name = car_id2name[gt_pred['id']].name vertices = np.array(self.car_model_dict[car_name]['vertices']) vertices[:, 1] = -vertices[:, 1] triangles = np.array(self.car_model_dict[car_name]['faces']) - 1 # project 3D points to 2d image plane yaw, pitch, roll = gt_pred['yaw'], gt_pred['pitch'], gt_pred['roll'] # I think the pitch and yaw should be exchanged yaw, pitch, roll = -pitch, -yaw, -roll Rt = np.eye(4) t = np.array([gt_pred['x'], gt_pred['y'], gt_pred['z']]) Rt[:3, 3] = t Rt[:3, :3] = euler_to_Rot(yaw, pitch, roll).T Rt = Rt[:3, :] P = np.ones((vertices.shape[0], vertices.shape[1] + 1)) P[:, :-1] = vertices P = P.T img_cor_points = np.dot(self.camera_matrix, np.dot(Rt, P)) img_cor_points = img_cor_points.T img_cor_points[:, 0] /= img_cor_points[:, 2] img_cor_points[:, 1] /= img_cor_points[:, 2] # project 3D points to 2d image plane x1, y1, x2, y2 = img_cor_points[:, 0].min(), img_cor_points[:, 1].min(), img_cor_points[:, 0].max(), img_cor_points[:, 1].max() bboxes.append([x1, y1, x2, y2]) # project 3D points to 2d image plane if draw: # project 3D points to 2d image plane mask_seg = np.zeros(image.shape, dtype=np.uint8) mask_seg_mesh = np.zeros(image.shape, dtype=np.uint8) for t in triangles: coord = np.array([img_cor_points[t[0]][:2], img_cor_points[t[1]][:2], img_cor_points[t[2]][:2]], dtype=np.int32) # This will draw the mask for segmenation cv2.drawContours(mask_seg, np.int32([coord]), 0, (255, 255, 255), -1) cv2.polylines(mask_seg_mesh, np.int32([coord]), 1, (0, 255, 0)) mask_all += mask_seg_mesh ground_truth_binary_mask = np.zeros(mask_seg.shape, dtype=np.uint8) ground_truth_binary_mask[mask_seg == 255] = 1 if self.bottom_half > 0: # this indicate w ground_truth_binary_mask = ground_truth_binary_mask[int(self.bottom_half):, :] # x1, x2, y1, y2 = mesh_point_to_bbox(ground_truth_binary_mask) # TODO: problem of masking # Taking a kernel for dilation and erosion, # the kernel size is set at 1/10th of the average width and heigh of the car kernel_size = int(((y2 - y1) / 2 + (x2 - x1) / 2) / 10) kernel = np.ones((kernel_size, kernel_size), np.uint8) # Following is the code to find mask ground_truth_binary_mask_img = ground_truth_binary_mask.sum(axis=2).astype(np.uint8) ground_truth_binary_mask_img[ground_truth_binary_mask_img > 1] = 1 ground_truth_binary_mask_img = cv2.dilate(ground_truth_binary_mask_img, kernel, iterations=1) ground_truth_binary_mask_img = cv2.erode(ground_truth_binary_mask_img, kernel, iterations=1) fortran_ground_truth_binary_mask = np.asfortranarray(ground_truth_binary_mask_img) encoded_ground_truth = maskUtils.encode(fortran_ground_truth_binary_mask) rles.append(encoded_ground_truth) # bm = maskUtils.decode(encoded_ground_truth) if draw: # if False: mask_all = mask_all * 255 / mask_all.max() cv2.addWeighted(image.astype(np.uint8), 1.0, mask_all.astype(np.uint8), alpha, 0, merged_image) for box in bboxes: cv2.rectangle(merged_image, (int(box[0]), int(box[1])), (int(box[2]), int(box[3])), (0, 0, 255), thickness=5) imwrite(merged_image, os.path.join(draw_dir, train['ImageId'].iloc[idx] + '.jpg')) if len(bboxes): bboxes = np.array(bboxes, dtype=np.float32) labels = np.array(labels, dtype=np.int64) eular_angles = np.array(eular_angles, dtype=np.float32) quaternion_semispheres = np.array(quaternion_semispheres, dtype=np.float32) translations = np.array(translations, dtype=np.float32) assert len(gt) == len(bboxes) == len(labels) == len(eular_angles) == len(quaternion_semispheres) == len( translations) annotation = { 'filename': img_name, 'width': self.image_shape[1], 'height': self.image_shape[0], 'bboxes': bboxes, 'labels': labels, 'eular_angles': eular_angles, 'quaternion_semispheres': quaternion_semispheres, 'translations': translations, 'rles': rles } return annotation def eular_angle_classification(self, annotations, draw_dir=""): # for ann in tqdm(annotations): for ann in tqdm(annotations[5000: 5010]): # for ann in tqdm(annotations[0: 50]): img_name = ann['filename'] image = imread(img_name) mask_all = np.zeros(image.shape) merged_image = image.copy() alpha = 0.9 # transparency bboxes = ann['bboxes'] labels = ann['labels'] eular_angles = ann['eular_angles'] quaternion_semispheres = ann['quaternion_semispheres'] translations = ann['translations'] assert len(bboxes) == len(labels) == len(eular_angles) == len(quaternion_semispheres) == len(translations) for gt_car_idx in range(len(ann['quaternion_semispheres'])): eular_angle = np.array(eular_angles[gt_car_idx]) # if 'Camera' in img_name: # this is an apolloscape dataset # eular_angle_kaggle = np.array([eular_angle[1], eular_angle[0], eular_angle[2]]) # elif 'ID' in img_name: # eular_angle_kaggle = eular_angle # else: # print("Unidentified class") quaternion = euler_angles_to_quaternions(eular_angle) quaternion_semisphere = quaternion_upper_hemispher(quaternion) ea_make = quaternion_to_euler_angle(quaternion_semisphere) json_q = quaternion_semispheres[gt_car_idx] ea_json = quaternion_to_euler_angle(json_q) ea_json = np.array(ea_json) # q1 = R.from_euler('xyz', eular_angle) # q2 = R.from_euler('xyz', q) # print('GT eular angle: ', eular_angle) # print('Generate eular angle:', ea_make) # print('Json generated eular angle', ea_json) # print('Generate q:', quaternion_semisphere) # print('Json q:', json_q) # print("diff is: %f" % np.sum(np.abs(ea_json-ea_make))) if self.RotationDistance(ea_make, ea_json) > 0.01: print('Wrong!!!!!!!!!!!!!') # rendering the car according to: # Augmented Reality | Kaggle # car_id2name is from: # https://github.com/ApolloScapeAuto/dataset-api/blob/master/car_instance/car_models.py car_name = car_id2name[labels[gt_car_idx]].name vertices = np.array(self.car_model_dict[car_name]['vertices']) vertices[:, 1] = -vertices[:, 1] triangles = np.array(self.car_model_dict[car_name]['faces']) - 1 translation = np.array(translations[gt_car_idx]) Rt = np.eye(4) Rt[:3, 3] = translation # project 3D points to 2d image plane # Apollo below is correct # https://en.wikipedia.org/wiki/Euler_angles # Y, P, R = euler_to_Rot_YPR(eular_angle[1], eular_angle[0], eular_angle[2]) rot_mat = euler_to_Rot(eular_angle[0], eular_angle[1], eular_angle[2]).T # check eular from rot mat Rt[:3, :3] = rot_mat Rt = Rt[:3, :] P = np.ones((vertices.shape[0], vertices.shape[1] + 1)) P[:, :-1] = vertices P = P.T img_cor_points = np.dot(self.camera_matrix, np.dot(Rt, P)) img_cor_points = img_cor_points.T img_cor_points[:, 0] /= img_cor_points[:, 2] img_cor_points[:, 1] /= img_cor_points[:, 2] x1, y1, x2, y2 = img_cor_points[:, 0].min(), img_cor_points[:, 1].min(), img_cor_points[:, 0].max(), img_cor_points[:, 1].max() bboxes.append([x1, y1, x2, y2]) # project 3D points to 2d image plane mask_seg = np.zeros(image.shape, dtype=np.uint8) for t in triangles: coord = np.array([img_cor_points[t[0]][:2], img_cor_points[t[1]][:2], img_cor_points[t[2]][:2]], dtype=np.int32) # This will draw the mask for segmenation # cv2.drawContours(mask_seg, np.int32([coord]), 0, (255, 255, 255), -1) cv2.polylines(mask_seg, np.int32([coord]), 1, (0, 255, 0)) mask_all += mask_seg mask_all = mask_all * 255 / mask_all.max() cv2.addWeighted(image.astype(np.uint8), 1.0, mask_all.astype(np.uint8), alpha, 0, merged_image) im_write_file = os.path.join(draw_dir, img_name.split('/')[-1]) print("Writing image to: %s" % os.path.join(draw_dir, img_name.split('/')[-1])) imwrite(merged_image, im_write_file) return True def plot_and_examine(self, annotations, draw_dir='/data/Kaggle/wudi_data/train_image_gt_vis'): # for ann in tqdm(annotations): # for ann in tqdm(annotations[5000: 5010]): for ann in tqdm(annotations): img_name = ann['filename'] image = imread(img_name) mask_all = np.zeros(image.shape) merged_image = image.copy() alpha = 0.9 # transparency bboxes = ann['bboxes'] labels = ann['labels'] eular_angles = ann['eular_angles'] quaternion_semispheres = ann['quaternion_semispheres'] translations = ann['translations'] assert len(bboxes) == len(labels) == len(eular_angles) == len(quaternion_semispheres) == len(translations) for gt_car_idx in range(len(ann['quaternion_semispheres'])): eular_angle = np.array(eular_angles[gt_car_idx]) # if 'Camera' in img_name: # this is an apolloscape dataset # eular_angle_kaggle = np.array([eular_angle[1], eular_angle[0], eular_angle[2]]) # elif 'ID' in img_name: # eular_angle_kaggle = eular_angle # else: # print("Unidentified class") quaternion = euler_angles_to_quaternions(eular_angle) quaternion_semisphere = quaternion_upper_hemispher(quaternion) ea_make = quaternion_to_euler_angle(quaternion_semisphere) json_q = quaternion_semispheres[gt_car_idx] ea_json = quaternion_to_euler_angle(json_q) ea_json = np.array(ea_json) # q1 = R.from_euler('xyz', eular_angle) # q2 = R.from_euler('xyz', q) # print('GT eular angle: ', eular_angle) # print('Generate eular angle:', ea_make) # print('Json generated eular angle', ea_json) # print('Generate q:', quaternion_semisphere) # print('Json q:', json_q) # print("diff is: %f" % np.sum(np.abs(ea_json-ea_make))) if self.RotationDistance(ea_make, ea_json) > 0.01: print('Wrong!!!!!!!!!!!!!') # rendering the car according to: # Augmented Reality | Kaggle # car_id2name is from: # https://github.com/ApolloScapeAuto/dataset-api/blob/master/car_instance/car_models.py car_name = car_id2name[labels[gt_car_idx]].name vertices = np.array(self.car_model_dict[car_name]['vertices']) vertices[:, 1] = -vertices[:, 1] triangles = np.array(self.car_model_dict[car_name]['faces']) - 1 translation = np.array(translations[gt_car_idx]) Rt = np.eye(4) Rt[:3, 3] = translation # project 3D points to 2d image plane # Apollo below is correct # https://en.wikipedia.org/wiki/Euler_angles # Y, P, R = euler_to_Rot_YPR(eular_angle[1], eular_angle[0], eular_angle[2]) rot_mat = euler_to_Rot(-eular_angle[1], -eular_angle[0], -eular_angle[2]).T # check eular from rot mat Rt[:3, :3] = rot_mat Rt = Rt[:3, :] P = np.ones((vertices.shape[0], vertices.shape[1] + 1)) P[:, :-1] = vertices P = P.T img_cor_points = np.dot(self.camera_matrix, np.dot(Rt, P)) img_cor_points = img_cor_points.T img_cor_points[:, 0] /= img_cor_points[:, 2] img_cor_points[:, 1] /= img_cor_points[:, 2] x1, y1, x2, y2 = img_cor_points[:, 0].min(), img_cor_points[:, 1].min(), img_cor_points[:, 0].max(), img_cor_points[:, 1].max() bboxes.append([x1, y1, x2, y2]) # project 3D points to 2d image plane mask_seg = np.zeros(image.shape, dtype=np.uint8) for t in triangles: coord = np.array([img_cor_points[t[0]][:2], img_cor_points[t[1]][:2], img_cor_points[t[2]][:2]], dtype=np.int32) # This will draw the mask for segmenation # cv2.drawContours(mask_seg, np.int32([coord]), 0, (255, 255, 255), -1) cv2.polylines(mask_seg, np.int32([coord]), 1, (0, 255, 0)) mask_all += mask_seg mask_all = mask_all * 255 / mask_all.max() cv2.addWeighted(image.astype(np.uint8), 1.0, mask_all.astype(np.uint8), alpha, 0, merged_image) im_write_file = os.path.join(draw_dir, img_name.split('/')[-1]) print("Writing image to: %s" % os.path.join(draw_dir, img_name.split('/')[-1])) imwrite(merged_image, im_write_file) return True def visualise_pred_postprocessing(self, outputs, args): car_cls_coco = 2 for idx in tqdm(range(len(outputs))): # ann = self.annotations[idx] test_folder = '/data/home/yyj/code/kaggle/new_code/Kaggle_PKU_Baidu/data/pku_data/test_images/' img_name = os.path.join(test_folder, os.path.basename(outputs[idx][2]['file_name'])) if not os.path.isfile(img_name): assert "Image file does not exist!" else: image = imread(img_name) output = outputs[idx] # output is a tuple of three elements bboxes, segms, six_dof = output[0], output[1], output[2] car_cls_score_pred = six_dof['car_cls_score_pred'] quaternion_pred = six_dof['quaternion_pred'] trans_pred_world = six_dof['trans_pred_world'].copy() euler_angle = np.array([quaternion_to_euler_angle(x) for x in quaternion_pred]) car_labels = np.argmax(car_cls_score_pred, axis=1) kaggle_car_labels = [self.unique_car_mode[x] for x in car_labels] car_names = np.array([car_id2name[x].name for x in kaggle_car_labels]) assert len(bboxes[car_cls_coco]) == len(segms[car_cls_coco]) == len(kaggle_car_labels) \ == len(trans_pred_world) == len(euler_angle) == len(car_names) # print('change ',trans_pred_world,trans_pred_world_refined) quaternion_semisphere_refined, flag = refine_yaw_and_roll(image, bboxes[car_cls_coco], segms[car_cls_coco], car_names, euler_angle, quaternion_pred, trans_pred_world, self.car_model_dict, self.camera_matrix) if flag: output[2]['quaternion_pred'] = quaternion_semisphere_refined euler_angle = np.array([quaternion_to_euler_angle(x) for x in output[2]['quaternion_pred']]) trans_pred_world_refined = restore_x_y_from_z_withIOU(image, bboxes[car_cls_coco], segms[car_cls_coco], car_names, euler_angle, trans_pred_world, self.car_model_dict, self.camera_matrix) output[2]['trans_pred_world'] = trans_pred_world_refined # img_box_mesh_refined = self.visualise_box_mesh(image,bboxes[car_cls_coco], segms[car_cls_coco],car_names, euler_angle,trans_pred_world_refined) # img_box_mesh_refined, iou_flag = self.visualise_box_mesh(image,bboxes[car_cls_coco], segms[car_cls_coco],car_names, euler_angle,trans_pred_world) # if iou_flag: # print('iou problem',os.path.basename(img_name)) # img_kaggle = self.visualise_kaggle(image, coords) # img_mesh = self.visualise_mesh(image, bboxes[car_cls_coco], segms[car_cls_coco], car_names, euler_angle, # trans_pred_world) # imwrite(img_kaggle, os.path.join(args.out[:-4] + '_kaggle_vis/' + img_name.split('/')[-1])) # imwrite(img_mesh, os.path.join(args.out[:-4] + '_mes_vis/' + img_name.split('/')[-1])) # img_box_mesh_half = cv2.resize(img_box_mesh,None,fx=0.5,fy=0.5) # img_kaggle_half = cv2.resize(img_kaggle,None,fx=0.5,fy=0.5) # img_concat = np.concatenate([img_kaggle_half,img_box_mesh_half],axis=1) # imwrite(img_concat, os.path.join(args.out[:-4] + '_mes_box_vis/' + img_name.split('/')[-1])) # imwrite(img_box_mesh, os.path.join(args.out[:-4] + '_mes_box_vis_10_0.7/' + img_name.split('/')[-1])) # imwrite(img_box_mesh_refined, os.path.join(args.out[:-4] + '_mes_box_vis_10_0.7_IOU=0/' + img_name.split('/')[-1])[:-4]+'_refined.jpg') return outputs def distributed_visualise_pred_merge_postprocessing(self, img_id, outputs, args, vote=2, tmp_dir="./results/", draw_flag=False): car_cls_coco = 2 bboxes_list = [] segms_list = [] six_dof_list = [] bboxes_with_IOU_list = [] bboxes_merge = outputs[0][img_id][0].copy() segms_merge = outputs[0][img_id][1].copy() six_dof_merge = outputs[0][img_id][2].copy() last_name = "" for i, output in enumerate(outputs): a = output[img_id] file_name = os.path.basename(a[2]['file_name']) if last_name != "" and file_name != last_name: assert "Image error!" last_name = file_name img_name = os.path.join(self.img_prefix, file_name) if not os.path.isfile(img_name): assert "Image file does not exist!" image = imread(img_name) bboxes, segms, six_dof = a[0], a[1], a[2] bboxes_list.append(bboxes) segms_list.append(segms) six_dof_list.append(six_dof) bboxes_with_IOU = get_IOU(image, bboxes[car_cls_coco], segms[car_cls_coco], six_dof, car_id2name, self.car_model_dict, self.unique_car_mode, self.camera_matrix) new_bboxes_with_IOU = np.zeros((bboxes_with_IOU.shape[0], bboxes_with_IOU.shape[1] + 1)) for bbox_idx in range(bboxes_with_IOU.shape[0]): new_bboxes_with_IOU[bbox_idx] = np.append(bboxes_with_IOU[bbox_idx], float(i)) bboxes_with_IOU_list.append(new_bboxes_with_IOU) bboxes_with_IOU = np.concatenate(bboxes_with_IOU_list, axis=0) inds = nms_with_IOU_and_vote(bboxes_with_IOU, vote=vote) ## IOU nms filter out processing return output indices inds = np.array(inds) inds_list = [] start = 0 for bboxes_iou in bboxes_with_IOU_list: end = bboxes_iou.shape[0] + start i = np.where((inds >= start) & (inds < end)) if i: inds_current = inds[i] - start else: inds_current = [] inds_list.append(inds_current) start = end bboxes_merge_concat = [] segms_merge_concat = [] car_cls_score_pred_concat = [] quaternion_pred_concat = [] trans_pred_world_concat = [] for ids, bboxes, segms, six_dof in zip(inds_list, bboxes_list, segms_list, six_dof_list): bboxes_merge_concat.append(bboxes[car_cls_coco][ids]) segms_merge_concat.append(np.array(segms[car_cls_coco])[ids]) car_cls_score_pred_concat.append(six_dof['car_cls_score_pred'][ids]) quaternion_pred_concat.append(six_dof['quaternion_pred'][ids]) trans_pred_world_concat.append(six_dof['trans_pred_world'][ids]) bboxes_merge[car_cls_coco] = np.concatenate(bboxes_merge_concat, axis=0) segms_merge[car_cls_coco] = np.concatenate(segms_merge_concat, axis=0) six_dof_merge['car_cls_score_pred'] = np.concatenate(car_cls_score_pred_concat, axis=0) six_dof_merge['quaternion_pred'] = np.concatenate(quaternion_pred_concat, axis=0) six_dof_merge['trans_pred_world'] = np.concatenate(trans_pred_world_concat, axis=0) output_model_merge = (bboxes_merge, segms_merge, six_dof_merge) if draw_flag: car_cls_score_pred = six_dof_merge['car_cls_score_pred'] quaternion_pred = six_dof_merge['quaternion_pred'] trans_pred_world = six_dof_merge['trans_pred_world'].copy() euler_angle = np.array([quaternion_to_euler_angle(x) for x in quaternion_pred]) car_labels = np.argmax(car_cls_score_pred, axis=1) kaggle_car_labels = [self.unique_car_mode[x] for x in car_labels] car_names = np.array([car_id2name[x].name for x in kaggle_car_labels]) # img_box_mesh_refined = self.visualise_box_mesh(image,bboxes[car_cls_coco], segms[car_cls_coco],car_names, euler_angle,trans_pred_world_refined) img_box_mesh_refined, iou_flag = self.visualise_box_mesh(image, bboxes_merge[car_cls_coco], segms_merge[car_cls_coco], car_names, euler_angle, trans_pred_world) imwrite(img_box_mesh_refined, os.path.join(args.out[:-4] + '_mes_box_vis_merged/' + img_name.split('/')[-1])[ :-4] + '_merged.jpg') tmp_file = os.path.join(tmp_dir, "{}.pkl".format(last_name[:-4])) mmcv.dump(output_model_merge, tmp_file) return output_model_merge def distributed_visualise_pred_merge_postprocessing_weight_merge(self, img_id, outputs, args, vote=0, tmp_dir="./results/", draw_flag=False): car_cls_coco = 2 bboxes_list = [] segms_list = [] six_dof_list = [] bboxes_with_IOU_list = [] bboxes_merge = outputs[0][img_id][0].copy() segms_merge = outputs[0][img_id][1].copy() six_dof_merge = outputs[0][img_id][2].copy() last_name = "" if vote == 0: vote = len(outputs) for i, output in enumerate(outputs): a = output[img_id] file_name = os.path.basename(a[2]['file_name']) if last_name != "" and file_name != last_name: assert "Image error!" last_name = file_name img_name = os.path.join(self.img_prefix, file_name) if not os.path.isfile(img_name): assert "Image file does not exist!" image = imread(img_name) bboxes, segms, six_dof = a[0], a[1], a[2] bboxes_list.append(bboxes) segms_list.append(segms) six_dof_list.append(six_dof) bboxes_with_IOU = get_IOU(image, bboxes[car_cls_coco], segms[car_cls_coco], six_dof, car_id2name, self.car_model_dict, self.unique_car_mode, self.camera_matrix) new_bboxes_with_IOU = np.zeros((bboxes_with_IOU.shape[0], bboxes_with_IOU.shape[1] + 1)) for bbox_idx in range(bboxes_with_IOU.shape[0]): new_bboxes_with_IOU[bbox_idx] = np.append(bboxes_with_IOU[bbox_idx], float(i)) bboxes_with_IOU_list.append(new_bboxes_with_IOU) bboxes_with_IOU = np.concatenate(bboxes_with_IOU_list, axis=0) inds_index = nms_with_IOU_and_vote_return_index(bboxes_with_IOU, vote=vote) ## IOU nms filter out processing return output indices inds = np.array(list(inds_index.keys())) trans_pred_world = np.concatenate([sd['trans_pred_world'] for sd in six_dof_list], axis=0) # Now we weighted average of the translation for ii in inds_index: weight = bboxes_with_IOU[:, 5][inds_index[ii]] / np.sum(bboxes_with_IOU[:, 5][inds_index[ii]]) trans_pred_world[ii] = np.sum(trans_pred_world[inds_index[ii]] * np.expand_dims(weight, axis=1), axis=0) inds_list = [] start = 0 for bi in range(len(bboxes_with_IOU_list)): bboxes_iou = bboxes_with_IOU_list[bi] end = bboxes_iou.shape[0] + start i = np.where((inds >= start) & (inds < end)) if i: inds_i = inds[i] - start else: inds_i = [] six_dof_list[bi]['trans_pred_world'] = trans_pred_world[start:end] inds_list.append(inds_i) start = end bboxes_merge_concat = [] segms_merge_concat = [] car_cls_score_pred_concat = [] quaternion_pred_concat = [] trans_pred_world_concat = [] for ids, bboxes, segms, six_dof in zip(inds_list, bboxes_list, segms_list, six_dof_list): bboxes_merge_concat.append(bboxes[car_cls_coco][ids]) segms_merge_concat.append(np.array(segms[car_cls_coco])[ids]) car_cls_score_pred_concat.append(six_dof['car_cls_score_pred'][ids]) quaternion_pred_concat.append(six_dof['quaternion_pred'][ids]) trans_pred_world_concat.append(six_dof['trans_pred_world'][ids]) bboxes_merge[car_cls_coco] = np.concatenate(bboxes_merge_concat, axis=0) segms_merge[car_cls_coco] = np.concatenate(segms_merge_concat, axis=0) six_dof_merge['car_cls_score_pred'] = np.concatenate(car_cls_score_pred_concat, axis=0) six_dof_merge['quaternion_pred'] = np.concatenate(quaternion_pred_concat, axis=0) six_dof_merge['trans_pred_world'] = np.concatenate(trans_pred_world_concat, axis=0) output_model_merge = (bboxes_merge, segms_merge, six_dof_merge) if draw_flag: car_cls_score_pred = six_dof_merge['car_cls_score_pred'] quaternion_pred = six_dof_merge['quaternion_pred'] trans_pred_world = six_dof_merge['trans_pred_world'].copy() euler_angle = np.array([quaternion_to_euler_angle(x) for x in quaternion_pred]) car_labels = np.argmax(car_cls_score_pred, axis=1) kaggle_car_labels = [self.unique_car_mode[x] for x in car_labels] car_names = np.array([car_id2name[x].name for x in kaggle_car_labels]) # img_box_mesh_refined = self.visualise_box_mesh(image,bboxes[car_cls_coco], segms[car_cls_coco],car_names, euler_angle,trans_pred_world_refined) img_box_mesh_refined, iou_flag = self.visualise_box_mesh(image, bboxes_merge[car_cls_coco], segms_merge[car_cls_coco], car_names, euler_angle, trans_pred_world) imwrite(img_box_mesh_refined, os.path.join(args.out[:-4] + '_mes_box_vis_merged/' + img_name.split('/')[-1])[ :-4] + '_merged.jpg') tmp_file = os.path.join(tmp_dir, "{}.pkl".format(last_name[:-4])) mmcv.dump(output_model_merge, tmp_file) return output_model_merge def visualise_pred_merge_postprocessing(self, outputs, args, conf_thred=0.8): car_cls_coco = 2 test_folder = '/data/home/yyj/code/kaggle/new_code/Kaggle_PKU_Baidu/data/pku_data/test_images/' ## first we have to guarantee the outputs image names keep sequence consistence output_model_merge = [] for idx, (a, b) in enumerate(zip(outputs[0], outputs[1])): print(idx) img_name_a = os.path.basename(a[2]['file_name']) img_name_b = os.path.basename(b[2]['file_name']) assert img_name_a == img_name_b img_name = os.path.join(test_folder, img_name_a) if not os.path.isfile(img_name): assert "Image file does not exist!" else: image = imread(img_name) bboxes_a, segms_a, six_dof_a = a[0], a[1], a[2] bboxes_b, segms_b, six_dof_b = b[0], b[1], b[2] bboxes_merge = bboxes_a.copy() segms_merge = segms_a.copy() six_dof_merge = six_dof_a.copy() bboxes_a_with_IOU = get_IOU(image, bboxes_a[car_cls_coco], segms_a[car_cls_coco], six_dof_a, car_id2name, self.car_model_dict, self.unique_car_mode, self.camera_matrix) bboxes_b_with_IOU = get_IOU(image, bboxes_b[car_cls_coco], segms_b[car_cls_coco], six_dof_b, car_id2name, self.car_model_dict, self.unique_car_mode, self.camera_matrix) bboxes_with_IOU = np.concatenate([bboxes_a_with_IOU, bboxes_b_with_IOU], axis=0) inds = nms_with_IOU(bboxes_with_IOU) ## IOU nms filter out processing return output indices inds = np.array(inds) inds_a = inds[np.where(inds < bboxes_a_with_IOU.shape[0])] inds_b = inds[np.where(inds >= bboxes_a_with_IOU.shape[0])] - bboxes_a_with_IOU.shape[0] bboxes_merge[car_cls_coco] = np.concatenate( [bboxes_a[car_cls_coco][inds_a], bboxes_b[car_cls_coco][inds_b]], axis=0) segms_merge[car_cls_coco] = np.concatenate( [np.array(segms_a[car_cls_coco])[inds_a], np.array(segms_b[car_cls_coco])[inds_b]], axis=0) six_dof_merge['car_cls_score_pred'] = np.concatenate( [six_dof_a['car_cls_score_pred'][inds_a], six_dof_b['car_cls_score_pred'][inds_b]], axis=0) six_dof_merge['quaternion_pred'] = np.concatenate( [six_dof_a['quaternion_pred'][inds_a], six_dof_b['quaternion_pred'][inds_b]], axis=0) six_dof_merge['trans_pred_world'] = np.concatenate( [six_dof_a['trans_pred_world'][inds_a], six_dof_b['trans_pred_world'][inds_b]], axis=0) output_model_merge.append((bboxes_merge, segms_merge, six_dof_merge)) car_cls_score_pred = six_dof_merge['car_cls_score_pred'] quaternion_pred = six_dof_merge['quaternion_pred'] trans_pred_world = six_dof_merge['trans_pred_world'].copy() euler_angle = np.array([quaternion_to_euler_angle(x) for x in quaternion_pred]) car_labels = np.argmax(car_cls_score_pred, axis=1) kaggle_car_labels = [self.unique_car_mode[x] for x in car_labels] car_names = np.array([car_id2name[x].name for x in kaggle_car_labels]) # img_box_mesh_refined = self.visualise_box_mesh(image,bboxes[car_cls_coco], segms[car_cls_coco],car_names, euler_angle,trans_pred_world_refined) img_box_mesh_refined, iou_flag = self.visualise_box_mesh(image, bboxes_merge[car_cls_coco], segms_merge[car_cls_coco], car_names, euler_angle, trans_pred_world) imwrite(img_box_mesh_refined, os.path.join(args.out[:-4] + '_mes_box_vis_merged/' + img_name.split('/')[-1])[ :-4] + '_merged.jpg') return output_model_merge def visualise_box_mesh(self, image, bboxes, segms, car_names, euler_angle, trans_pred_world): im_combime, iou_flag = draw_box_mesh_kaggle_pku(image, bboxes, segms, car_names, self.car_model_dict, self.camera_matrix, trans_pred_world, euler_angle) return im_combime, iou_flag def visualise_mesh(self, image, bboxes, segms, car_names, euler_angle, trans_pred_world): im_combime = draw_result_kaggle_pku(image, bboxes, segms, car_names, self.car_model_dict, self.camera_matrix, trans_pred_world, euler_angle) return im_combime def visualise_kaggle(self, img, coords): # You will also need functions from the previous cells x_l = 1.02 y_l = 0.80 z_l = 2.31 img = img.copy() for point in coords: # Get values x, y, z = point[3], point[4], point[5] # yaw, pitch, roll = -pitch, -yaw, -roll yaw, pitch, roll = point[0], point[1], point[2] yaw, pitch, roll = -pitch, -yaw, -roll # Math Rt = np.eye(4) t = np.array([x, y, z]) Rt[:3, 3] = t Rt[:3, :3] = euler_to_Rot(yaw, pitch, roll).T Rt = Rt[:3, :] P = np.array([[x_l, -y_l, -z_l, 1], [x_l, -y_l, z_l, 1], [-x_l, -y_l, z_l, 1], [-x_l, -y_l, -z_l, 1], [0, 0, 0, 1]]).T img_cor_points = np.dot(self.camera_matrix, np.dot(Rt, P)) img_cor_points = img_cor_points.T img_cor_points[:, 0] /= img_cor_points[:, 2] img_cor_points[:, 1] /= img_cor_points[:, 2] img_cor_points = img_cor_points.astype(int) # Drawing img = draw_line(img, img_cor_points) img = draw_points(img, img_cor_points[-1:]) return img def clean_corrupted_images(self, annotations): # For training images, there are 5 corrupted images: corrupted_images = ['ID_1a5a10365', 'ID_4d238ae90', 'ID_408f58e9f', 'ID_bb1d991f6', 'ID_c44983aeb'] annotations_clean = [ann for ann in annotations if ann['filename'].split('/')[-1][:-4] not in corrupted_images] return annotations_clean def clean_outliers(self, annotations): """ We get rid of the outliers in this dataset : if translation[0] < -80 or translation[0] > 80 or translation[1] < 1 or translation[1] > 50 or translation[2] < 3 or translation[2] > 150 :param train: :return: """ corrupted_count = 0 clean_count = 0 annotations_clean = [] for idx in range(len(annotations)): ann = annotations[idx] bboxes = [] labels = [] eular_angles = [] quaternion_semispheres = [] translations = [] rles = [] for box_idx in range(len(ann['bboxes'])): translation = ann['translations'][box_idx] if translation[0] < -80 or translation[0] > 80 or \ translation[1] < 1 or translation[1] > 50 \ or translation[2] < 3 or translation[2] > 150: corrupted_count += 1 continue else: bboxes.append(ann['bboxes'][box_idx]) labels.append(ann['labels'][box_idx]) eular_angles.append(ann['eular_angles'][box_idx]) quaternion_semispheres.append(ann['quaternion_semispheres'][box_idx]) translations.append(ann['translations'][box_idx]) rles.append(ann['rles'][box_idx]) bboxes = np.array(bboxes, dtype=np.float32) labels = np.array(labels, dtype=np.int64) eular_angles = np.array(eular_angles, dtype=np.float32) quaternion_semispheres = np.array(quaternion_semispheres, dtype=np.float32) translations = np.array(translations, dtype=np.float32) assert len(bboxes) == len(labels) == len(eular_angles) == len(quaternion_semispheres) == len(translations) clean_count += len(bboxes) annotation = { 'filename': ann['filename'], 'width': ann['width'], 'height': ann['height'], 'bboxes': bboxes, 'labels': labels, 'eular_angles': eular_angles, 'quaternion_semispheres': quaternion_semispheres, 'translations': translations, 'rles': rles } annotations_clean.append(annotation) print("Totaly corrupted count is: %d, clean count: %d" % (corrupted_count, clean_count)) return annotations_clean def group_rectangles(self, annotations, outfile='/data/Kaggle/bboxes_with_translation_pick.pkl', draw_flag=True): """ This will generate the referenced bboxes for translation regression. Only done onces :param annotations: :param outfile: :param draw_flag: :return: """ bboxes_with_translation = [] for idx in range(len(annotations)): ann = annotations[idx] bboxes_with_translation.append(np.concatenate((ann['bboxes'], ann['translations']), axis=1)) bboxes_with_translation = np.vstack(bboxes_with_translation) print('Total number of cars: %d.' % bboxes_with_translation.shape[0]) # We read an image first bboxes_with_translation_pick = non_max_suppression_fast(bboxes_with_translation, overlapThresh=0.99) # Some boxes are outside the boundary, we need to get rid of them: idx_valid = np.array(bboxes_with_translation_pick[:, 0] <= self.image_shape[1]) & \ np.array(bboxes_with_translation_pick[:, 1] <= self.image_shape[0]) & \ np.array(bboxes_with_translation_pick[:, 0] >= 0) & np.array( bboxes_with_translation_pick[:, 1] >= 1480) bboxes_with_translation_pick = bboxes_with_translation_pick[idx_valid] print('Final number of selected boxed: %d.' % bboxes_with_translation_pick.shape[0]) mmcv.dump(bboxes_with_translation_pick, outfile) if draw_flag: img = imread(annotations[0]['filename']) img_2 = img.copy() for bb in bboxes_with_translation: img = cv2.rectangle(img, (bb[0], bb[1]), (bb[2], bb[3]), color=(0, 255, 0), thickness=1) imwrite(img, '/data/Kaggle/wudi_data/rect_all.jpg') for bb in bboxes_with_translation_pick: img_2 = cv2.rectangle(img_2, (bb[0], bb[1]), (bb[2], bb[3]), color=(0, 255, 0), thickness=1) imwrite(img_2, '/data/Kaggle/wudi_data/rect_selected.jpg') def print_statistics_annotations(self, annotations): """ Print some statistics from annotations :param annotations: :return: """ car_per_image = [] xp, yp = [], [] xw, yw, zw = [], [], [] car_models = [] for idx in range(len(annotations)): ann = annotations[idx] car_per_image.append(len(ann['bboxes'])) for box_idx in range(len(ann['bboxes'])): car_models.append(ann['labels'][box_idx]) translation = ann['translations'][box_idx] xpt, ypt, xwt, ywt, zwt = self._get_img_coords(translation=translation) xp.append(xpt) yp.append(ypt) xw.append(xwt) yw.append(ywt) zw.append(zwt) car_per_image = np.array(car_per_image) print('Total images: %d, car num sum: %d, minmin: %d, max: %d, mean: %d' % (len(annotations), car_per_image.sum(), car_per_image.min(), car_per_image.max(), car_per_image.mean())) """ Total images: 6691, car num sum: 74029, minmin: 1, max: 43, mean: 11 """ xp, yp = np.array(xp), np.array(yp) print("x min: %d, max: %d, mean: %d" % (int(min(xp)), int(max(xp)), int(xp.mean()))) print("y min: %d, max: %d, mean: %d" % (int(min(yp)), int(max(yp)), int(yp.mean()))) """ x min: -851, max: 4116, mean: 1551 y min: 1482, max: 3427, mean: 1820 """ xw, yw, zw = np.array(xw), np.array(yw), np.array(zw) print("x min: %d, max: %d, mean: %d, std: %.3f" % (int(min(xw)), int(max(xw)), int(xw.mean()), xw.std())) print("y min: %d, max: %d, mean: %d, std: %.3f" % (int(min(yw)), int(max(yw)), int(yw.mean()), yw.std())) print("z min: %d, max: %d, mean: %d, std: %.3f" % (int(min(zw)), int(max(zw)), int(zw.mean()), zw.std())) """ x min: -90, max: 519, mean: -3, std: 14.560 y min: 1, max: 689, mean: 9, std: 6.826 z min: 3, max: 3502, mean: 52, std: 40.046 """ car_models = np.array(car_models) print("Car model: max: %d, min: %d, total: %d" % (car_models.max(), car_models.min(), len(car_models))) # Car model: max: 76, min: 2, total: 49684 print('Unique car models:') print(np.unique(car_models)) # array([2, 6, 7, 8, 9, 12, 14, 16, 18, 19, 20, 23, 25, 27, 28, 31, 32, # 35, 37, 40, 43, 46, 47, 48, 50, 51, 54, 56, 60, 61, 66, 70, 71, 76]) print("Number of unique car models: %d" % len(np.unique(car_models))) # 34 def print_statistics(self, train): car_per_image = np.array([len(self._str2coords(s)) for s in train['PredictionString']]) print('Total images: %d, car num sum: %d, minmin: %d, max: %d, mean: %d' % (len(car_per_image), car_per_image.sum(), car_per_image.min(), car_per_image.max(), car_per_image.mean())) """ Total images: 4262, car num sum: 49684, minmin: 1, max: 44, mean: 11 """ xs, ys = [], [] for ps in train['PredictionString']: x, y = self._get_img_coords(ps) xs += list(x) ys += list(y) xs, ys = np.array(xs), np.array(ys) print("x min: %d, max: %d, mean: %d" % (int(min(xs)), int(max(xs)), int(xs.mean()))) print("y min: %d, max: %d, mean: %d" % (int(min(ys)), int(max(ys)), int(ys.mean()))) """ x min: -851, max: 4116, mean: 1551 y min: 1482, max: 3427, mean: 1820 """ # car points looking from the sky xs, ys, zs = [], [], [] for ps in train['PredictionString']: coords = self._str2coords(ps) xs += [c['x'] for c in coords] ys += [c['y'] for c in coords] zs += [c['z'] for c in coords] xs, ys, zs = np.array(xs), np.array(ys), np.array(zs) print("x min: %d, max: %d, mean: %d, std: %.3f" % (int(min(xs)), int(max(xs)), int(xs.mean()), xs.std())) print("y min: %d, max: %d, mean: %d, std: %.3f" % (int(min(ys)), int(max(ys)), int(ys.mean()), ys.std())) print("z min: %d, max: %d, mean: %d, std: %.3f" % (int(min(zs)), int(max(zs)), int(zs.mean()), zs.std())) """ x min: -90, max: 519, mean: -3, std: 14.560 y min: 1, max: 689, mean: 9, std: 6.826 z min: 3, max: 3502, mean: 52, std: 40.046 # Clean x min: -79, max: 79, mean: -3, std: 14.015 y min: 1, max: 42, mean: 9, std: 4.695 z min: 3, max: 150, mean: 50, std: 29.596 """ # Next we filter our 99.9% data distribution xmin, xmax = -80, 80 ymin, ymax = 1, 50 xs_cdf = sum((xs > xmin) * (xs < xmax)) ys_cdf = sum((ys > ymin) * (ys < ymax)) xs_ys_cdf = sum((xs > xmin) * (xs < xmax) * (ys > ymin) * (ys < ymax)) print('X within range (%d, %d) will have cdf of: %.6f, outlier number: %d' % ( xmin, xmax, xs_cdf / len(xs), len(xs) - xs_cdf)) print('Y within range (%d, %d) will have cdf of: %.6f, outlier number: %d' % ( ymin, ymax, ys_cdf / len(ys), len(ys) - ys_cdf)) print('Both will have cdf of: %.6f, outlier number: %d' % (xs_ys_cdf / len(ys), len(ys) - xs_ys_cdf)) car_models = [] for ps in train['PredictionString']: coords = self._str2coords(ps) for car in coords: car_models.append(car['id']) car_models = np.array(np.hstack(car_models)) print("Car model: max: %d, min: %d, total: %d" % (car_models.max(), car_models.min(), len(car_models))) # Car model: max: 76, min: 2, total: 49684 print('Unique car models:') print(np.unique(car_models)) # array([2, 6, 7, 8, 9, 12, 14, 16, 18, 19, 20, 23, 25, 27, 28, 31, 32, # 35, 37, 40, 43, 46, 47, 48, 50, 51, 54, 56, 60, 61, 66, 70, 71, 76]) print("Number of unique car models: %d" % len(np.unique(car_models))) # 34 def _str2coords(self, s, names=('id', 'yaw', 'pitch', 'roll', 'x', 'y', 'z')): """ Input: s: PredictionString (e.g. from train dataframe) names: array of what to extract from the string Output: list of dicts with keys from `names` """ coords = [] for l in np.array(s.split()).reshape([-1, 7]): coords.append(dict(zip(names, l.astype('float')))) if 'id' in coords[-1]: coords[-1]['id'] = int(coords[-1]['id']) return coords def _get_img_coords(self, s=None, translation=None): ''' Input is a PredictionString (e.g. from train dataframe) Output is two arrays: xs: x coordinates in the image ys: y coordinates in the image ''' if translation is not None: xs, ys, zs = translation P = np.array([xs, ys, zs]).T img_p = np.dot(self.camera_matrix, P).T img_p[0] /= img_p[2] img_p[1] /= img_p[2] return img_p[0], img_p[1], xs, ys, zs else: coords = self._str2coords(s) xs = [c['x'] for c in coords] ys = [c['y'] for c in coords] zs = [c['z'] for c in coords] P = np.array(list(zip(xs, ys, zs))).T img_p = np.dot(self.camera_matrix, P).T img_p[:, 0] /= img_p[:, 2] img_p[:, 1] /= img_p[:, 2] img_xs = img_p[:, 0] img_ys = img_p[:, 1] img_zs = img_p[:, 2] # z = Distance from the camera return img_xs, img_ys def get_ann_info(self, idx): ann_info = self.img_infos[idx] return self._parse_ann_info(ann_info) def _filter_imgs(self, min_size=32): """Filter images too small or without ground truths.""" valid_inds = [] for i, img_info in enumerate(self.img_infos): if min(img_info['width'], img_info['height']) >= min_size: valid_inds.append(i) return valid_inds def _parse_ann_info(self, ann_info): """Parse bbox and mask annotation. Args: ann_info (list[dict]): Annotation info of an image. with_mask (bool): Whether to parse mask annotations. Returns: dict: A dict containing the following keys: bboxes, bboxes_ignore, labels, masks, seg_map. "masks" are raw annotations and not decoded into binary masks. """ gt_bboxes = [] gt_class_labels = [] # this will always be fixed as car class gt_labels = [] gt_bboxes_ignore = [] gt_masks_ann = [] eular_angles = [] quaternion_semispheres = [] translations = [] if self.rotation_augmenation: # We follow the camera rotation augmentation as in # https://www.kaggle.com/outrunner/rotation-augmentation # It's put in here (instead of dataset.pipeline.transform is because # we need car model json alpha = ((np.random.random() ** 0.5) * 8 - 5.65) * np.pi / 180. beta = (np.random.random() * 50 - 25) * np.pi / 180. gamma = (np.random.random() * 6 - 3) * np.pi / 180. + beta / 3 Mat, Rot = self.rotateImage(alpha, beta, gamma) else: Mat, Rot = self.rotateImage(0, 0, 0) for i in range(len(ann_info['bboxes'])): x1, y1, x2, y2 = ann_info['bboxes'][i] w, h = x2 - x1, y2 - y1 if w < 1 or h < 1: continue translation = ann_info['translations'][i] # X within range (-80, 80) will have cdf of: 0.999738, outlier number: 13 # Y within range (1, 50) will have cdf of: 0.999819, outlier number: 9 if translation[0] < -80 or translation[0] > 80 or translation[1] < 1 or translation[1] > 50: continue if self.bottom_half: # we only take bottom half image bbox = [x1, y1 - self.bottom_half, x2, y2 - self.bottom_half] else: bbox = [x1, y1, x2, y2] if ann_info.get('iscrowd', False): # TODO: train mask need to include gt_bboxes_ignore.append(bbox) else: if not self.rotation_augmenation: gt_bboxes.append(bbox) gt_label = self.cat2label[ann_info['labels'][i]] gt_labels.append(gt_label) gt_class_labels.append(3) # coco 3 is "car" class mask = maskUtils.decode(ann_info['rles'][i]) gt_masks_ann.append(mask) eular_angles.append(ann_info['eular_angles'][i]) quaternion_semispheres.append(ann_info['quaternion_semispheres'][i]) translations.append(translation) else: yaw, pitch, roll = ann_info['eular_angles'][i] r1 = R.from_euler('xyz', [-pitch, -yaw, -roll], degrees=False) r2 = R.from_euler('xyz', [beta, -alpha, -gamma], degrees=False) pitch_rot, yaw_rot, roll_rot = (r2 * r1).as_euler('xyz') * (-1) eular_angle_rot = np.array([yaw_rot, pitch_rot, roll_rot]) quaternion_rot = euler_angles_to_quaternions(eular_angle_rot) quaternion_semisphere_rot = quaternion_upper_hemispher(quaternion_rot) quaternion_semisphere_rot = np.array(quaternion_semisphere_rot, dtype=np.float32) x, y, z = translation x_rot, y_rot, z_rot, _ = np.dot(Rot, [x, y, z, 1]) translation_rot = np.array([x_rot, y_rot, z_rot]) car_name = car_id2name[ann_info['labels'][i]].name vertices = np.array(self.car_model_dict[car_name]['vertices']) vertices[:, 1] = -vertices[:, 1] triangles = np.array(self.car_model_dict[car_name]['faces']) - 1 bbox_rot, mask_rot = self.get_box_and_mask(eular_angle_rot, translation_rot, vertices, triangles) # Some rotated bbox might be out of the image if bbox_rot[2] < 0 or bbox_rot[3] < 0 or \ bbox_rot[0] > self.image_shape[0] or bbox_rot[1] > self.image_shape[1] - self.bottom_half: continue gt_label = self.cat2label[ann_info['labels'][i]] gt_bboxes.append(bbox_rot) gt_labels.append(gt_label) gt_class_labels.append(3) # coco 3 is "car" class gt_masks_ann.append(mask_rot) eular_angles.append(eular_angle_rot) quaternion_semispheres.append(quaternion_semisphere_rot) translations.append(translation_rot) if gt_bboxes: gt_bboxes = np.array(gt_bboxes, dtype=np.float32) quaternion_semispheres = np.array(quaternion_semispheres, dtype=np.float32) translations = np.array(translations, dtype=np.float32) gt_labels = np.array(gt_labels, dtype=np.int64) else: gt_bboxes = np.zeros((0, 4), dtype=np.float32) gt_labels = np.array([], dtype=np.int64) if gt_bboxes_ignore: gt_bboxes_ignore = np.array(gt_bboxes_ignore, dtype=np.float32) else: gt_bboxes_ignore = np.zeros((0, 4), dtype=np.float32) ann = dict( bboxes=gt_bboxes, labels=gt_class_labels, carlabels=gt_labels, bboxes_ignore=gt_bboxes_ignore, masks=gt_masks_ann, eular_angles=eular_angles, quaternion_semispheres=quaternion_semispheres, translations=translations, Mat=Mat) return ann def rotateImage(self, alpha=0, beta=0, gamma=0): fx, dx = self.camera_matrix[0, 0], self.camera_matrix[0, 2] fy, dy = self.camera_matrix[1, 1], self.camera_matrix[1, 2] # Projection 2D -> 3D matrix A1 = np.array([[1 / fx, 0, -dx / fx], [0, 1 / fx, -dy / fx], [0, 0, 1], [0, 0, 1]]) # Rotation matrices around the X, Y, and Z axis RX = np.array([[1, 0, 0, 0], [0, cos(alpha), -sin(alpha), 0], [0, sin(alpha), cos(alpha), 0], [0, 0, 0, 1]]) RY = np.array([[cos(beta), 0, -sin(beta), 0], [0, 1, 0, 0], [sin(beta), 0, cos(beta), 0], [0, 0, 0, 1]]) RZ = np.array([[cos(gamma), -sin(gamma), 0, 0], [sin(gamma), cos(gamma), 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]) # Composed rotation matrix with (RX, RY, RZ) R = np.dot(RZ, np.dot(RX, RY)) # 3D -> 2D matrix A2 = np.array([[fx, 0, dx, 0], [0, fy, dy, 0], [0, 0, 1, 0]]) # Final transformation matrix trans = np.dot(A2, np.dot(R, A1)) # Apply matrix transformation return trans, R def get_box_and_mask(self, eular_angle, translation, vertices, triangles): # project 3D points to 2d image plane yaw, pitch, roll = eular_angle # I think the pitch and yaw should be exchanged yaw, pitch, roll = -pitch, -yaw, -roll Rt = np.eye(4) t = translation Rt[:3, 3] = t Rt[:3, :3] = euler_to_Rot(yaw, pitch, roll).T Rt = Rt[:3, :] P = np.ones((vertices.shape[0], vertices.shape[1] + 1)) P[:, :-1] = vertices P = P.T img_cor_points = np.dot(self.camera_matrix, np.dot(Rt, P)) img_cor_points = img_cor_points.T img_cor_points[:, 0] /= img_cor_points[:, 2] img_cor_points[:, 1] /= img_cor_points[:, 2] # project 3D points to 2d image plane x1, y1, x2, y2 = img_cor_points[:, 0].min(), img_cor_points[:, 1].min(), \ img_cor_points[:, 0].max(), img_cor_points[:, 1].max() bbox = np.array([x1, y1, x2, y2]) if self.bottom_half: # we only take bottom half image bbox = [x1, y1 - self.bottom_half, x2, y2 - self.bottom_half] #### Now draw the mask # project 3D points to 2d image plane mask_seg = np.zeros(self.image_shape, dtype=np.uint8) mask_seg_mesh = np.zeros(self.image_shape, dtype=np.uint8) for t in triangles: coord = np.array([img_cor_points[t[0]][:2], img_cor_points[t[1]][:2], img_cor_points[t[2]][:2]], dtype=np.int32) # This will draw the mask for segmenation cv2.drawContours(mask_seg, np.int32([coord]), 0, (255, 255, 255), -1) cv2.polylines(mask_seg_mesh, np.int32([coord]), 1, (0, 255, 0)) ground_truth_binary_mask =
np.zeros(mask_seg.shape, dtype=np.uint8)
numpy.zeros
import datacube import xarray as xr import datetime import warnings; warnings.simplefilter('ignore') import numpy as np from datetime import datetime from time import time from sklearn import svm import warnings warnings.filterwarnings("ignore") import matplotlib.pyplot as plt import matplotlib.image as mpimg import scipy.ndimage from sklearn.externals import joblib from .dc_water_classifier import wofs_classify import random import itertools from sklearn.metrics import f1_score, recall_score, precision_score dc = datacube.Datacube(app = 'wasard_test', config = '/home/localuser/.datacube.conf') class wasard_classifier: """Classifier object used for classifying water bodies in a SAR dataset :attribute classifier: LinearSVC object used in classifying datapoints as water or not water :attribute coefficient: coefficient of the LinearSVC classifier, used to determine what data will classified as water and not water :attribute precision: classifier's precision score, using the Landsat scene it was trained on as truth labels :attribute recall: classifier's recall score, using the Landsat scene it was trained on as truth labels :attribute f1: classifier's precision score, created by taking the harmonic mean of the recall and precision scores :return: wasard_classifier object """ def __init__(self, classifier = None, sar_dataset = None, landsat_dataset = None, pct = .1, bands = 2, sar_time_index = -1, landsat_time_index = -1): """Defines the classifier as the loaded filestring passed in by the user, if a filestring passed in, otherwise trains a new classifier :param filestring: .pkl filestring of a previously trained classifier :param sar_dataset: xarray dataset containing sar data, loaded form datacube :param landsat_dataset: xarray dataset containing sar data, loaded form datacube :param pct: ratio of total training data to be used to train the classifier, lower numbers yield faster runtimes :param bands: indicates whether the classifier will be trained using 1 or 2 features :param sar_time_index: specific time index of sar scene to be used to train classifier, if the user wishes to specify :param sar_time_index: specific time index of landsat scene to be used to train classifier, if the user wishes to specify """ if classifier: self.classifier = joblib.load(classifier) if type(classifier) == str else classifier self.coefficient = self.classifier.coef_ else: assert sar_dataset and landsat_dataset, "User must pass in either a .pkl filestring or both a SAR and Landsat dataset" self.train_classifier( sar_dataset = sar_dataset, landsat_dataset = landsat_dataset, pct = pct, bands = bands, sar_time_index = sar_time_index, landsat_time_index = landsat_time_index) def train_classifier(self, sar_dataset = None, landsat_dataset = None, pct = .1, bands = 2, sar_time_index = -1, landsat_time_index = -1): """generates a classifier for a sar dataset using a support vector machine :param sar_dataset: xarray dataset containing sar data, loaded form datacube :param landsat_dataset: xarray dataset containing sar data, loaded form datacube :param pct: ratio of total training data to be used to train the classifier, lower numbers yield faster runtimes :param bands: indicates whether the classifier will be trained using 1 or 2 features :param sar_time_index: specific time index of sar scene to be used to train classifier, if the user wishes to specify :param sar_time_index: specific time index of landsat scene to be used to train classifier, if the user wishes to specify :return: LinearSVC object, which can be used to classify other sar scenes """ train_data, test_data = _get_train_data(sar_dataset, landsat_dataset, pct = pct, bands = bands, sar_time_index = sar_time_index, landsat_time_index = landsat_time_index) # separate data attributes from target/truth value in order to train classifier with correct labels training_attributes = train_data[:,0:-1] training_truth = train_data[:,-1] testing_attributes = test_data[:,0:-1] testing_truth = test_data[:,-1] # train SVM using training data classifier = svm.LinearSVC() classifier.fit(training_attributes, training_truth) # classify test dataset in order to verify its effectiveness total_tests = testing_truth.size testing_attributes = np.stack(testing_attributes) wasard_predictions = classifier.predict(testing_attributes) # print(wasard_predictions.shape) # wasard_predictions = _filter_isolated_cells(wasard_predictions, struct=np.ones((3,3)), max_size = 200) # 3 metrics used to measure the effectiveness of the classifier f1 = f1_score(testing_truth, wasard_predictions) recall = recall_score(testing_truth, wasard_predictions) precision = precision_score(testing_truth, wasard_predictions) sar_index, lsat_index = _find_training_indices(sar_dataset, landsat_dataset) sar_scene = sar_dataset.isel(time=sar_index).expand_dims('time') clf = wasard_classifier(classifier=classifier) temp = clf.wasard_classify(sar_scene) f1, precision, recall = _get_scores(temp, landsat_dataset, lsat_index) self.f1 = f1 self.recall = recall self.precision = precision self.classifier = classifier self.coefficient = self.classifier.coef_ def wasard_classify (self, sar_dataset): """Return new xarray Dataset identical to sar_dataset but with predicted water values added, using a provided classifier :param sar_dataset: xarray Dataset containing sar data, loaded from datacube :return: new xarray Dataset identical to sar_dataset with new array "wasard" added, containing predicted water values """ satellite_type = 'sentinel' if hasattr(sar_dataset, 'vv') else 'alos' dataset_dims = (sar_dataset.coords.dims['time'], sar_dataset.coords.dims['latitude'], sar_dataset.coords.dims['longitude']) bands = self.coefficient.size band2 = None if satellite_type == 'sentinel': band1 = sar_dataset.vh.values.ravel() if bands == 2: band2 = sar_dataset.vv.values.ravel() elif satellite_type == 'alos': band1 = sar_dataset.hv.values.ravel() # band2 = sar_dataset.incidence_angle.values.ravel() # assemble features into array and predict water using the classifier if bands == 1: dinput = np.dstack([band1]) predictions = self.classifier.predict(dinput[0]) elif bands == 2: dinput = np.dstack([band1, band2]) predictions = self.classifier.predict(dinput[0]) else: raise ValueError("Bands must be 1 or 2") predictions = predictions.reshape(dataset_dims) sar_dataset_copy = sar_dataset.copy(deep=True) sar_dataset_copy['wasard'] = (('time', 'latitude', 'longitude'),predictions) # reduce noise from speckle and other isolated fals positives sar_dataset_copy = _filter_all(sar_dataset_copy, max_size=100) return sar_dataset_copy def save(self, filestring): """saves a classfier to the disk :param filestring: name of the file which will contain the classifier """ joblib.dump(self.classifier, "{}.pkl".format(filestring)) def get_best_classifier( n_classifiers, sar_dataset = None, landsat_dataset = None, pct = .1, bands = 2, sar_time_index = -1, landsat_time_index = -1): """generates a list of classifiers for a sar dataset using a support vector machine :param n: int indicating the number of classifiers that should be included in the returned list :param sar_dataset: xarray dataset containing sar data, loaded form datacube :param landsat_dataset: xarray dataset containing sar data, loaded form datacube :param pct: ratio of total training data to be used to train the classifier, lower numbers yield faster runtimes :param bands: indicates whether the classifier will be trained using 1 or 2 features :param sar_time_index: specific time index of sar scene to be used to train classifier, if the user wishes to specify :param sar_time_index: specific time index of landsat scene to be used to train classifier, if the user wishes to specify :return: list containing n classifiers, which the user can then sort to find the most effective one """ clf_ls = [wasard_classifier( sar_dataset = sar_dataset, landsat_dataset = landsat_dataset, pct = pct, bands = bands, sar_time_index = sar_time_index, landsat_time_index = landsat_time_index) for x in range(n_classifiers)] clf_ls_precision_sorted = sorted(clf_ls, key = lambda clf: clf.precision, reverse=True) return clf_ls_precision_sorted def wasard_plot(sar_dataset, sar_time_index, landsat_dataset=None, landsat_time_index=None, size=(10,10), plot_over_image = False): """Plots water values predicted from SAR data :param sar_dataset: xarray Dataset of sar data, with wasard values added from wasard_classify :param sar_time_index: int indicating the time slice to pull the wasard values from :param landsat_dataset: xarray containing data from landsat_dataset, with latitudinal and longitudinal bounds identical to the Sentinel scene_index, used for identifying watervalues detected by WASAR that do not correspond with those detected by WOFS :param landsat_time_index: time slice from the landsat_dataset array to be compared to the SAR scene_index :param size: tuple indicating the size of the output plot :param plot_over_image: boolean indicating whether the wasard values will be plot on top of a landsat_dataset image, preventing a new figure from being drawn :return: None """ sar_dataset_at_time = sar_dataset.isel(time=sar_time_index).copy(deep=True) # prevents function from setting up a new plot, if the data are to be plotted over an image if not plot_over_image: fig = plt.figure(figsize=size) # plot wasard values over proper coordinates using xarray.dataarray.plot try: water = sar_dataset_at_time.wasard.where(sar_dataset_at_time.wasard==1) water.plot.imshow(levels = 5, colors = 'blue', add_colorbar = 0, add_labels=0) # throws ValueError if wasard detected no water except ValueError: pass if landsat_dataset: landsat_dataset_at_time = landsat_dataset.isel(time=landsat_time_index) landsat_dataset_wofs = get_wofs_values(landsat_dataset_at_time) wofs_resolution_adjusted = _fit_landsat_dataset_resolution(landsat_dataset_wofs, sar_dataset) diff_array = (wofs_resolution_adjusted - sar_dataset_at_time.wasard).values sar_dataset_at_time['diff'] = (('latitude','longitude'),diff_array) sar_dataset_at_time['FalseN'] = sar_dataset_at_time['diff'].where(sar_dataset_at_time['diff'] == 1) false_neg_bool_array = np.logical_and(sar_dataset_at_time.wasard==1,sar_dataset_at_time['diff'] != 1) sar_dataset_at_time['FalseP'] = sar_dataset_at_time['diff'].where(false_neg_bool_array) try: false_positives = sar_dataset_at_time.FalseP false_negatives = sar_dataset_at_time.FalseN false_positives.plot.imshow(levels = 5, colors = 'red', add_colorbar = 0, add_labels=0) false_negatives.plot.imshow(levels = 5, colors = 'yellow', add_colorbar = 0, add_labels=0) except ValueError: pass def wasard_time_plot(sar_dataset, size=(15,15), plot_over_image = False): """creates a plot showing the presence of water over time in a given area :param sar_dataset: xarray Dataset of sar data, with wasard values added from wasard_classify :param size: tuple indicating the size of the output plot :param plot_over_image: boolean indicating whether the wasard values will be plot on top of a landsat_dataset image, preventing a new figure from being drawn :return: None """ # create an array containing the percent of time slices in which each pixel is predicted to hold water sar_dataset_copy = sar_dataset.copy(deep=True) valid_time_indices = _find_nodatas(sar_dataset_copy) aggregate_predictions = np.zeros((sar_dataset_copy.latitude.size, sar_dataset_copy.longitude.size)) divisor = len(valid_time_indices) for x in valid_time_indices: aggregate_predictions += np.nan_to_num(sar_dataset_copy.wasard[x]) # divide total by number of valid datases in order to get the percent of the time each pixel holds water aggregate_predictions = aggregate_predictions / divisor sar_dataset_copy['aggregate_predictions'] = (('latitude', 'longitude'), aggregate_predictions) start_color_index = 1 if not plot_over_image: # set up figure to plot over start_time_string = str(sar_dataset.time.values[min(valid_time_indices)])[0:10] end_time_string = str(sar_dataset.time.values[max(valid_time_indices)])[0:10] fig = plt.figure(figsize=size) start_color_index = 0 fig.suptitle('Water Frequency, {} to {}'.format(start_time_string, end_time_string, fontsize=20)) # construct a plot using different colors to correspond to different flooding percentages color_pct = {0: 'black', 1: 'red', 2: 'orange', 3: 'yellow', 4: 'green', 5: 'blue'} for x in range(start_color_index,6): cond = np.logical_and((1.0 * x-1)/5 < sar_dataset_copy.aggregate_predictions, sar_dataset_copy.aggregate_predictions <= (1.0*x)/5) water = sar_dataset_copy.aggregate_predictions.where(cond) try: water.plot.imshow(levels = 5, colors = color_pct[x], add_colorbar = 0, add_labels=0) # throws ValueError when no values are plotted except ValueError: pass # previous loop missed some values where pixels always contained water(why?), so they're replotted here permanent_water = sar_dataset_copy.aggregate_predictions.where(sar_dataset_copy.aggregate_predictions == 1) try: permanent_water.plot.imshow(levels = 5, colors = 'blue', add_colorbar = 0, add_labels=0) except ValueError: pass print("% of time containing water:\nblack: 0%\nred: 0-20%\norange: 20-40%\nyellow: 40-60%\ngreen: 60-80%\nblue: 80-100%") #specific names for sar_dataset def get_correlation(sar_wasard_dataset, landsat_dataset, sar_time_index, landsat_time_index): """returns the percent of pixels from the sar_dataset scene_index that have the same predicted water value as the landsat_dataset scene_index :param landsat_dataset: xarray Dataset containing landsat data, loaded from datacube. If none, program predicts water values from the most recently trained classifier :param sar_dataset: xarray Dataset of sar data, with wasard values added from wasard_classify :param landsat_time_index: int indicating which time index from the landat Dataset will be used :param sar_time_index: int indicating which time index from the SAR dataset will be used :return: Ratio of pixels with the same predicted water value between the two scene_indexs to the total number of pixels """ # assert 'wasard' in sar_dataset.variable_names.keys() assert 'wasard' in sar_wasard_dataset.data_vars, "sar_dataset must include ""wasard"" datavar" landsat_dataset_at_time = landsat_dataset.isel(time=landsat_time_index) landsat_dataset_wofs = get_wofs_values(landsat_dataset_at_time) wofs_with_adjusted_resolution = _fit_landsat_dataset_resolution(landsat_dataset_wofs, sar_wasard_dataset) sar_dataset_at_time = sar_wasard_dataset.isel(time=sar_time_index) # subtract wasard arrays of one dataset from the other, resulting array has value 0 when the wasard values were the same, and 1 when they were different differences_array = wofs_with_adjusted_resolution - sar_dataset_at_time.wasard total = differences_array.size # generate dict containing the number of false positives, false negatives, and correlating values between each acquisition unique, counts = np.unique(differences_array, return_counts=True) difference_counts = dict(zip(unique, counts)) result = {'False Positives':0, 'False Negatives':0, 'Correlating':0} result['False Positives'] = difference_counts[-1] / total result['False Negatives'] = difference_counts[1] / total result['Correlating'] = difference_counts[0] / total return result def _find_training_indices(sar_dataset, landsat_dataset): """returns the optimal landsat and sentinel scene to train a new classifier on :param sar_datset: xarray Dataset containing landsat data, loaded from datacube :param landsat_dataset: xarray dataset containing landsat data, loaded from datacube """ cloud_cover_percentages = _get_cloud_avg(landsat_dataset) # Lambdas for filtering is_clear_enough = lambda time_index: cloud_cover_percentages[time_index] < 20 if hasattr(sar_dataset, 'vv'): filter_nodata_sar = lambda time_index: abs(np.sum(sar_dataset.vv[time_index])) > 10000 filter_nodata_landsat = lambda time_index: np.sum(landsat_dataset.red[time_index]) > 0 # indices for selecting from datasets sar_time_indices = range(sar_dataset.dims['time']) if hasattr(sar_dataset, 'vv'): sar_time_indices = filter(filter_nodata_sar, sar_time_indices) landsat_dataset_time_indices = range(landsat_dataset.dims['time']) # filtering datasets landsat_dataset_time_indices = filter(is_clear_enough, landsat_dataset_time_indices) landsat_dataset_time_indices = filter(filter_nodata_landsat, landsat_dataset_time_indices) distance_in_time = lambda time_pair: abs(sar_dataset.time.values[time_pair[0]] - landsat_dataset.time.values[time_pair[1]]) cloud_cover = lambda time_pair: (cloud_cover_percentages[time_pair[1]], distance_in_time(time_pair)) time_combinations = itertools.product(sar_time_indices, landsat_dataset_time_indices) time_combinations_distance_sorted = sorted(time_combinations, key = distance_in_time)[0:5] for time_pair in time_combinations_distance_sorted: if cloud_cover(time_pair)[0] < 5: sar_index, landsat_dataset_index = time_pair # one of the top 5 pairs in terms of distance is below 5% cloud, no need to sort by cloud cover, so return indices now return (sar_index, landsat_dataset_index) time_combinations_cloud_cover_sorted = sorted(time_combinations_distance_sorted, key = cloud_cover) sar_index, landsat_dataset_index = time_combinations_cloud_cover_sorted[0] return (sar_index, landsat_dataset_index) def _get_cloud_avg(dataset): """generates a dict of cloud cover percentages over a given landsat dataset along with the average cloud cover over time :param dataset: xarray Dataset containing landsat data, loaded from datacube :return: dict of cloud cover percentage at each time slice """ tot = dataset.red[0].size time_indices = range(dataset.time.size) # use cf mask or pixel qa values to determine which pixels contain clouds if hasattr(dataset, 'cf_mask'): cloudy_pixels = np.logical_or(dataset.cf_mask == 3, dataset.cf_mask == 4) else: acceptable_values = [322, 386, 834, 898, 1346 , 324, 388, 836, 900, 1348] avgs = {} global_mask = acceptable_values[0] == dataset.pixel_qa.values for bitmask in acceptable_values: global_mask = np.logical_or(global_mask, bitmask == dataset.pixel_qa.values) for time in range(global_mask.shape[0]): avg = np.count_nonzero(global_mask[time]) / global_mask[time].size avgs[time] = (1-avg) * 100 return avgs # determine cloud cover for each time slice cloud_pct = lambda time_index: np.count_nonzero(cloudy_pixels[time_index]) / tot * 100 cloud_avgs = {time_index: cloud_pct(time_index) for time_index in time_indices} return (cloud_avgs) def get_clean_mask(landsat_dataset): acceptable_values = [322, 386, 834, 898, 1346 , 324, 388, 836, 900, 1348] global_mask = acceptable_values[0] == landsat_dataset.pixel_qa.values for bitmask in acceptable_values: global_mask = np.logical_or(global_mask, bitmask == landsat_dataset.pixel_qa.values) return global_mask def get_wofs_values(landsat_dataset): """classifies a landsat scene using the wofs algorithm :param landsat_dataset: xarray with dims 'latitude','longitude' containing data from a landsat scene :return: xarray dataset containing wofs classification values """ # landsat dataset needs dim 'time' for wofs_classify to work, re-add it here since using isel took it away landsat_dataset = landsat_dataset.expand_dims('time') clean_mask = None if hasattr(landsat_dataset, 'cf_mask') else get_clean_mask(landsat_dataset) landsat_dataset_wofs = wofs_classify(landsat_dataset, clean_mask = clean_mask) landsat_dataset_wofs = landsat_dataset_wofs.isel(time=0) return landsat_dataset_wofs def _fit_landsat_dataset_resolution(landsat_dataset_wofs, sar_dataset): """adjusts the resolution of the landsat_dataset scene to fit that of the SAR scene :param landsat_dataset: xarray Dataset containing landsat data, loaded from datacube. If none, program predicts water values from the most recently trained classifier :param sar_dataset: xarray Dataset of sar data, with WASARD values added :return: xarray dataset of the input landsat_dataset scene, stretched to match the resolution of the SAR scene """ satellite_type = 'sentinel' if hasattr(sar_dataset, 'vv') else 'alos' wofs_values = landsat_dataset_wofs.wofs.values sar_dataset_rows = sar_dataset.latitude.size sar_dataset_columns = sar_dataset.longitude.size landsat_dataset_rows = landsat_dataset_wofs.latitude.size landsat_dataset_columns = landsat_dataset_wofs.longitude.size resolution_multiplier = round(max(sar_dataset_rows, landsat_dataset_rows) / min(sar_dataset_rows, landsat_dataset_rows)) wofs_values_columns_repeated = np.repeat(wofs_values, resolution_multiplier, axis = 1) wofs_values_rows_columns_repeated = np.repeat(wofs_values_columns_repeated, resolution_multiplier, axis = 0) wofs_values = wofs_values_rows_columns_repeated wofs_rows = wofs_values.shape[0] wofs_columns = wofs_values.shape[1] # truncate or lengthen landsat_dataset to fit sar_dataset values while wofs_rows > sar_dataset_rows: random_row = np.random.randint(0,wofs_rows) wofs_values = np.delete(wofs_values, random_row, 0) wofs_rows = wofs_values.shape[0] while wofs_columns > sar_dataset_columns: random_column =
np.random.randint(0,wofs_columns)
numpy.random.randint
# imports framework import sys sys.path.insert(0, 'evoman') from environment import Environment from our_controller import player_controller # imports other libs import time import numpy as np import pandas as pd from scipy.stats import hmean import matplotlib.pyplot as plt import pickle import glob, os import math mode = 'test' parameters = { 'enemies' : (1,4,6,7), 'timeexpire' : 600, 'number_of_iterations' : 150, 'population_size' : 10, 'generated_on_mutation' : 5, 'mutation_alpha' : 0.5, # using after doomsday and crossover 'doomsday_interval' : 20, 'doomsday_survivals' : 5, 'neuronet_inicialization' : (-1,1), 'gamma' : 0.7, 'layers' : [ {'units':32, 'activation':'sigmoid', 'input_dim':14}, {'units':12, 'activation':'sigmoid'}, {'units':5, 'activation':'sigmoid'} #output ], 'number_of_projectiles' : 5 } best_agents = { 'first' : [], 'second' : [], 'third' : [], 'agent' : [] } experiment_name = 'our_tests' if not os.path.exists(experiment_name): os.makedirs(experiment_name) player_controller = player_controller(parameters) if mode.lower() != 'test': os.environ['SDL_VIDEODRIVER'] = 'dummy' # initializes simulation in individual evolution mode, for single static enemy. env = Environment( experiment_name=experiment_name, enemies=[1], playermode="ai", player_controller=player_controller, enemymode="static", level=2, speed="fastest", timeexpire=parameters["timeexpire"] ) enemies = parameters['enemies'] class NeuroNet: def __init__(self, weights=None): self.weights = [] self.results = None if (weights is not None): self.weights = weights else: for shape in player_controller.get_shapes(): self.weights.append(np.random.uniform(*parameters['neuronet_inicialization'], shape)) self.fitness = -math.inf def get_weights(self): return self.weights def GA(n_iter, n_pop): f_num = n_pop start, P = start_or_load(n_iter, n_pop) alpha_muta = 1/n_iter if start == 0: evaluate(P) if mode.lower() != 'test': for it in range(start, n_iter): log_str = f'GENERATION: {it} | BEST FITNESS: {P[0].fitness}' print(log_str) log_to_file(log_str) F = [muta(nn, 1-(alpha_muta*it)) for nn in P] G = [muta(nn, parameters['mutation_alpha']) for nn in crossover(P, f_num)] P = F + G P = select(P, n_pop) best_agents['first'].append(test_agent(P[0])) best_agents['agent'].append(P[0]) best_agents['second'].append(test_agent(P[1])) best_agents['third'].append(test_agent(P[2])) if it%parameters['doomsday_interval'] == 0 and it != 0: P = P[:parameters['doomsday_survivals']] N = [NeuroNet() for _ in range(f_num-parameters['doomsday_survivals'])] evaluate(N) F = [muta(nn, parameters['mutation_alpha']) for nn in N] P += F pickle.dump([it+1, P, best_agents], open(experiment_name+'/Evoman.pkl', 'wb')) # os.remove('Evoman.pkl') env.update_parameter('speed', "normal") env.update_parameter('timeexpire', 3000) df = pd.DataFrame(best_agents['first']) plt.plot(df['result'], label='mean') plt.plot(df['fitness'], label='fitness') plt.legend() plt.savefig(experiment_name+'/results.png') plt.close('all') best = best_agents['agent'][df['result'].idxmax()] df.to_csv(experiment_name+'/results.csv') for en in enemies: env.update_parameter('enemies', [en]) simulation(env, best) others = [en for en in range(1, 9) if en not in enemies] for en in others: env.update_parameter('enemies', [en]) simulation(env, best) return P def test_agent(agent): # use after select function only if agent.results is not None: return agent.results results = {} avarage_helper = [] gains = [] env.update_parameter('timeexpire', 3000) for en in enemies: env.update_parameter('enemies', [en]) f, p, e, t = simulation(env, agent) avarage_helper.append([p, e]) results[en] = [p, e] gains.append(100.01 + p - e) results['avarage_train'] = np.mean(avarage_helper, axis=0) avarage_helper = [] others = [en for en in range(1, 9) if en not in enemies] for en in others: env.update_parameter('enemies', [en]) f, p, e, t = simulation(env, agent) avarage_helper.append([p, e]) results[en] = [p, e] gains.append(100.01 + p - e) results['avarage_test'] = np.mean(avarage_helper, axis=0) results['avarage'] = np.mean((results['avarage_train'], results['avarage_test']), axis=0) results['result'] = hmean(gains) results['fitness'] = agent.fitness agent.results = results env.update_parameter('timeexpire', parameters['timeexpire']) return results def start_or_load(n_iter, n_pop): if os.path.exists(experiment_name+'/Evoman.pkl'): a = pickle.load(open(experiment_name+'/Evoman.pkl', 'rb')) if a[0] < n_iter or mode.lower() == 'test': global best_agents best_agents = a[2] return a[0], a[1] return 0, [NeuroNet() for _ in range(n_pop)] def calc_weights(nn, alpha): weights = nn.get_weights() new_weights = [(weight * alpha) for weight in weights] return new_weights def crossover(P, n): F = [] pairs = np.random.choice(P, (n//2, 2), False) for pair in pairs: a = np.random.random() w1 = calc_weights(pair[0], a) w2 = calc_weights(pair[1], 1 - a) w = [(w1[j] + w2[j]) for j in range(len(w1))] F.append( NeuroNet(w) ) evaluate(F) return F def muta(nn, alpha): weights = nn.get_weights() F = [] for _ in range(parameters['generated_on_mutation']): f = [] for layer in weights: l=[] shape = layer.shape for gene in np.nditer(layer): l.append(gene + np.random.normal(0, alpha)) l = np.array(l).reshape(shape) f.append(l) F.append( NeuroNet(f) ) evaluate(F) F.insert(0, nn) return select(F, 1)[0] def select(P, n): P.sort(key=lambda nn: nn.fitness, reverse=True) # sort from bigger to lower return P[:n] ini = time.time() # sets time marker # runs simulation def simulation(env,y): player_controller.set_weights(y.get_weights()) _ ,p,e,t = env.play(pcont=y) #fitness, playerlife, enemylife, gametime f = parameters['gamma'] * (100-e) + (1-parameters['gamma']) * p - math.log(t) return f, p, e, t # evaluation def evaluate(x): fitness=[] for en in enemies: env.update_parameter('enemies', [en]) fitness.append((list(map(lambda y: simulation(env,y)[0], x)))) arrray =
np.array(fitness)
numpy.array
"""Rotations in three dimensions - SO(3). See :doc:`rotations` for more information. """ import warnings import math import numpy as np from numpy.testing import assert_array_almost_equal unitx = np.array([1.0, 0.0, 0.0]) unity = np.array([0.0, 1.0, 0.0]) unitz = np.array([0.0, 0.0, 1.0]) R_id = np.eye(3) a_id = np.array([1.0, 0.0, 0.0, 0.0]) q_id = np.array([1.0, 0.0, 0.0, 0.0]) q_i = np.array([0.0, 1.0, 0.0, 0.0]) q_j = np.array([0.0, 0.0, 1.0, 0.0]) q_k = np.array([0.0, 0.0, 0.0, 1.0]) e_xyz_id = np.array([0.0, 0.0, 0.0]) e_zyx_id = np.array([0.0, 0.0, 0.0]) p0 = np.array([0.0, 0.0, 0.0]) eps = 1e-7 def norm_vector(v): """Normalize vector. Parameters ---------- v : array-like, shape (n,) nd vector Returns ------- u : array, shape (n,) nd unit vector with norm 1 or the zero vector """ norm = np.linalg.norm(v) if norm == 0.0: return v else: return np.asarray(v) / norm def norm_matrix(R): """Normalize rotation matrix. Parameters ---------- R : array-like, shape (3, 3) Rotation matrix with small numerical errors Returns ------- R : array, shape (3, 3) Normalized rotation matrix """ R = np.asarray(R) c2 = R[:, 1] c3 = norm_vector(R[:, 2]) c1 = norm_vector(np.cross(c2, c3)) c2 = norm_vector(np.cross(c3, c1)) return np.column_stack((c1, c2, c3)) def norm_angle(a): """Normalize angle to (-pi, pi]. Parameters ---------- a : float or array-like, shape (n,) Angle(s) in radians Returns ------- a_norm : float or array-like, shape (n,) Normalized angle(s) in radians """ # Source of the solution: http://stackoverflow.com/a/32266181 return -((np.pi - np.asarray(a)) % (2.0 * np.pi) - np.pi) def norm_axis_angle(a): """Normalize axis-angle representation. Parameters ---------- a : array-like, shape (4,) Axis of rotation and rotation angle: (x, y, z, angle) Returns ------- a : array-like, shape (4,) Axis of rotation and rotation angle: (x, y, z, angle). The length of the axis vector is 1 and the angle is in [0, pi). No rotation is represented by [1, 0, 0, 0]. """ angle = a[3] norm = np.linalg.norm(a[:3]) if angle == 0.0 or norm == 0.0: return np.array([1.0, 0.0, 0.0, 0.0]) res = np.empty(4) res[:3] = a[:3] / norm angle = norm_angle(angle) if angle < 0.0: angle *= -1.0 res[:3] *= -1.0 res[3] = angle return res def norm_compact_axis_angle(a): """Normalize compact axis-angle representation. Parameters ---------- a : array-like, shape (3,) Axis of rotation and rotation angle: angle * (x, y, z) Returns ------- a : array-like, shape (3,) Axis of rotation and rotation angle: angle * (x, y, z). The angle is in [0, pi). No rotation is represented by [0, 0, 0]. """ angle = np.linalg.norm(a) if angle == 0.0: return np.zeros(3) axis = a / angle return axis * norm_angle(angle) def perpendicular_to_vectors(a, b): """Compute perpendicular vector to two other vectors. Parameters ---------- a : array-like, shape (3,) 3d vector b : array-like, shape (3,) 3d vector Returns ------- c : array-like, shape (3,) 3d vector that is orthogonal to a and b """ return np.cross(a, b) def perpendicular_to_vector(a): """Compute perpendicular vector to one other vector. There is an infinite number of solutions to this problem. Thus, we restrict the solutions to [1, 0, z] and return [0, 0, 1] if the z component of a is 0. Parameters ---------- a : array-like, shape (3,) 3d vector Returns ------- b : array-like, shape (3,) A 3d vector that is orthogonal to a. It does not necessarily have unit length. """ if abs(a[2]) < eps: return np.copy(unitz) # Now that we solved the problem for [x, y, 0], we can solve it for all # other vectors by restricting solutions to [1, 0, z] and find z. # The dot product of orthogonal vectors is 0, thus # a[0] * 1 + a[1] * 0 + a[2] * z == 0 or -a[0] / a[2] = z return np.array([1.0, 0.0, -a[0] / a[2]]) def angle_between_vectors(a, b, fast=False): """Compute angle between two vectors. Parameters ---------- a : array-like, shape (n,) nd vector b : array-like, shape (n,) nd vector fast : bool, optional (default: False) Use fast implementation instead of numerically stable solution Returns ------- angle : float Angle between a and b """ if len(a) != 3 or fast: return np.arccos( np.clip(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)), -1.0, 1.0)) else: return np.arctan2(np.linalg.norm(np.cross(a, b)), np.dot(a, b)) def vector_projection(a, b): """Orthogonal projection of vector a on vector b. Parameters ---------- a : array-like, shape (3,) Vector a that will be projected on vector b b : array-like, shape (3,) Vector b on which vector a will be projected Returns ------- a_on_b : array, shape (3,) Vector a """ b_norm_squared = np.dot(b, b) if b_norm_squared == 0.0: return np.zeros(3) return np.dot(a, b) * b / b_norm_squared def random_vector(random_state=np.random.RandomState(0), n=3): """Generate an nd vector with normally distributed components. Each component will be sampled from :math:`\mathcal{N}(\mu=0, \sigma=1)`. Parameters ---------- random_state : np.random.RandomState, optional (default: random seed 0) Random number generator n : int, optional (default: 3) Number of vector components Returns ------- v : array-like, shape (n,) Random vector """ return random_state.randn(n) def random_axis_angle(random_state=np.random.RandomState(0)): """Generate random axis-angle. The angle will be sampled uniformly from the interval :math:`[0, \pi)` and each component of the rotation axis will be sampled from :math:`\mathcal{N}(\mu=0, \sigma=1)` and than the axis will be normalized to length 1. Parameters ---------- random_state : np.random.RandomState, optional (default: random seed 0) Random number generator Returns ------- a : array-like, shape (4,) Axis of rotation and rotation angle: (x, y, z, angle) """ angle = np.pi * random_state.rand() a = np.array([0, 0, 0, angle]) a[:3] = norm_vector(random_state.randn(3)) return a def random_compact_axis_angle(random_state=np.random.RandomState(0)): """Generate random compact axis-angle. The angle will be sampled uniformly from the interval :math:`[0, \pi)` and each component of the rotation axis will be sampled from :math:`\mathcal{N}(\mu=0, \sigma=1)` and than the axis will be normalized to length 1. Parameters ---------- random_state : np.random.RandomState, optional (default: random seed 0) Random number generator Returns ------- a : array-like, shape (3,) Axis of rotation and rotation angle: angle * (x, y, z) """ a = random_axis_angle(random_state) return a[:3] * a[3] def random_quaternion(random_state=np.random.RandomState(0)): """Generate random quaternion. Parameters ---------- random_state : np.random.RandomState, optional (default: random seed 0) Random number generator Returns ------- q : array-like, shape (4,) Unit quaternion to represent rotation: (w, x, y, z) """ return norm_vector(random_state.randn(4)) def cross_product_matrix(v): """Generate the cross-product matrix of a vector. The cross-product matrix :math:`\\boldsymbol{V}` satisfies the equation .. math:: \\boldsymbol{V} \\boldsymbol{w} = \\boldsymbol{v} \\times \\boldsymbol{w} It is a skew-symmetric (antisymmetric) matrix, i.e. :math:`-\\boldsymbol{V} = \\boldsymbol{V}^T`. Parameters ---------- v : array-like, shape (3,) 3d vector Returns ------- V : array-like, shape (3, 3) Cross-product matrix """ return np.array([[0.0, -v[2], v[1]], [v[2], 0.0, -v[0]], [-v[1], v[0], 0.0]]) def check_skew_symmetric_matrix(V, tolerance=1e-6, strict_check=True): """Input validation of a skew-symmetric matrix. Check whether the transpose of the matrix is its negative: .. math:: V^T = -V Parameters ---------- V : array-like, shape (3, 3) Cross-product matrix tolerance : float, optional (default: 1e-6) Tolerance threshold for checks. strict_check : bool, optional (default: True) Raise a ValueError if V.T is not numerically close enough to -V. Otherwise we print a warning. Returns ------- V : array-like, shape (3, 3) Validated cross-product matrix """ V = np.asarray(V, dtype=np.float) if V.ndim != 2 or V.shape[0] != 3 or V.shape[1] != 3: raise ValueError("Expected skew-symmetric matrix with shape (3, 3), " "got array-like object with shape %s" % (V.shape,)) if not np.allclose(V.T, -V, atol=tolerance): error_msg = ("Expected skew-symmetric matrix, but it failed the test " "V.T = %r\n-V = %r" % (V.T, -V)) if strict_check: raise ValueError(error_msg) else: warnings.warn(error_msg) return V def check_matrix(R, tolerance=1e-6, strict_check=True): """Input validation of a rotation matrix. We check whether R multiplied by its inverse is approximately the identity matrix and the determinant is approximately 1. Parameters ---------- R : array-like, shape (3, 3) Rotation matrix tolerance : float, optional (default: 1e-6) Tolerance threshold for checks. Default tolerance is the same as in assert_rotation_matrix(R). strict_check : bool, optional (default: True) Raise a ValueError if the rotation matrix is not numerically close enough to a real rotation matrix. Otherwise we print a warning. Returns ------- R : array, shape (3, 3) Validated rotation matrix """ R = np.asarray(R, dtype=np.float) if R.ndim != 2 or R.shape[0] != 3 or R.shape[1] != 3: raise ValueError("Expected rotation matrix with shape (3, 3), got " "array-like object with shape %s" % (R.shape,)) RRT = np.dot(R, R.T) if not np.allclose(RRT, np.eye(3), atol=tolerance): error_msg = ("Expected rotation matrix, but it failed the test " "for inversion by transposition. np.dot(R, R.T) " "gives %r" % RRT) if strict_check: raise ValueError(error_msg) else: warnings.warn(error_msg) R_det = np.linalg.det(R) if abs(R_det - 1) > tolerance: error_msg = ("Expected rotation matrix, but it failed the test " "for the determinant, which should be 1 but is %g; " "that is, it probably represents a rotoreflection" % R_det) if strict_check: raise ValueError(error_msg) else: warnings.warn(error_msg) return R def check_axis_angle(a): """Input validation of axis-angle representation. Parameters ---------- a : array-like, shape (4,) Axis of rotation and rotation angle: (x, y, z, angle) Returns ------- a : array, shape (4,) Validated axis of rotation and rotation angle: (x, y, z, angle) """ a = np.asarray(a, dtype=np.float) if a.ndim != 1 or a.shape[0] != 4: raise ValueError("Expected axis and angle in array with shape (4,), " "got array-like object with shape %s" % (a.shape,)) return norm_axis_angle(a) def check_compact_axis_angle(a): """Input validation of compact axis-angle representation. Parameters ---------- a : array-like, shape (3,) Axis of rotation and rotation angle: angle * (x, y, z) Returns ------- a : array, shape (3,) Validated axis of rotation and rotation angle: angle * (x, y, z) """ a = np.asarray(a, dtype=np.float) if a.ndim != 1 or a.shape[0] != 3: raise ValueError("Expected axis and angle in array with shape (3,), " "got array-like object with shape %s" % (a.shape,)) return norm_compact_axis_angle(a) def check_quaternion(q, unit=True): """Input validation of quaternion representation. Parameters ---------- q : array-like, shape (4,) Quaternion to represent rotation: (w, x, y, z) unit : bool, optional (default: True) Normalize the quaternion so that it is a unit quaternion Returns ------- q : array-like, shape (4,) Validated quaternion to represent rotation: (w, x, y, z) """ q = np.asarray(q, dtype=np.float) if q.ndim != 1 or q.shape[0] != 4: raise ValueError("Expected quaternion with shape (4,), got " "array-like object with shape %s" % (q.shape,)) if unit: return norm_vector(q) else: return q def check_quaternions(Q, unit=True): """Input validation of quaternion representation. Parameters ---------- Q : array-like, shape (n_steps, 4) Quaternions to represent rotations: (w, x, y, z) unit : bool, optional (default: True) Normalize the quaternions so that they are unit quaternions Returns ------- Q : array-like, shape (n_steps, 4) Validated quaternions to represent rotations: (w, x, y, z) """ Q_checked = np.asarray(Q, dtype=np.float) if Q_checked.ndim != 2 or Q_checked.shape[1] != 4: raise ValueError( "Expected quaternion array with shape (n_steps, 4), got " "array-like object with shape %s" % (Q_checked.shape,)) if unit: for i in range(len(Q)): Q_checked[i] = norm_vector(Q_checked[i]) return Q_checked def matrix_from_two_vectors(a, b): """Compute rotation matrix from two vectors. We assume that the two given vectors form a plane so that we can compute a third, orthogonal vector with the cross product. The x-axis will point in the same direction as a, the y-axis corresponds to the normalized vector rejection of b on a, and the z-axis is the cross product of the other basis vectors. Parameters ---------- a : array-like, shape (3,) First vector, must not be 0 b : array-like, shape (3,) Second vector, must not be 0 or parallel to v1 Returns ------- R : array, shape (3, 3) Rotation matrix """ if np.linalg.norm(a) == 0: raise ValueError("a must not be the zero vector.") if np.linalg.norm(b) == 0: raise ValueError("b must not be the zero vector.") c = perpendicular_to_vectors(a, b) if np.linalg.norm(c) == 0: raise ValueError("a and b must not be parallel.") a = norm_vector(a) b_on_a_projection = vector_projection(b, a) b_on_a_rejection = b - b_on_a_projection b = norm_vector(b_on_a_rejection) c = norm_vector(c) return np.column_stack((a, b, c)) def matrix_from_axis_angle(a): """Compute rotation matrix from axis-angle. This is called exponential map or Rodrigues' formula. This typically results in an active rotation matrix. Parameters ---------- a : array-like, shape (4,) Axis of rotation and rotation angle: (x, y, z, angle) Returns ------- R : array-like, shape (3, 3) Rotation matrix """ a = check_axis_angle(a) ux, uy, uz, theta = a c = math.cos(theta) s = math.sin(theta) ci = 1.0 - c R = np.array([[ci * ux * ux + c, ci * ux * uy - uz * s, ci * ux * uz + uy * s], [ci * uy * ux + uz * s, ci * uy * uy + c, ci * uy * uz - ux * s], [ci * uz * ux - uy * s, ci * uz * uy + ux * s, ci * uz * uz + c], ]) # This is equivalent to # R = (np.eye(3) * np.cos(a[3]) + # (1.0 - np.cos(a[3])) * a[:3, np.newaxis].dot(a[np.newaxis, :3]) + # cross_product_matrix(a[:3]) * np.sin(a[3])) return R def matrix_from_compact_axis_angle(a): """Compute rotation matrix from compact axis-angle. This is called exponential map or Rodrigues' formula. This typically results in an active rotation matrix. Parameters ---------- a : array-like, shape (3,) Axis of rotation and rotation angle: angle * (x, y, z) Returns ------- R : array-like, shape (3, 3) Rotation matrix """ a = axis_angle_from_compact_axis_angle(a) return matrix_from_axis_angle(a) def matrix_from_quaternion(q): """Compute rotation matrix from quaternion. This typically results in an active rotation matrix. Parameters ---------- q : array-like, shape (4,) Unit quaternion to represent rotation: (w, x, y, z) Returns ------- R : array-like, shape (3, 3) Rotation matrix """ q = check_quaternion(q) uq = norm_vector(q) w, x, y, z = uq x2 = 2.0 * x * x y2 = 2.0 * y * y z2 = 2.0 * z * z xy = 2.0 * x * y xz = 2.0 * x * z yz = 2.0 * y * z xw = 2.0 * x * w yw = 2.0 * y * w zw = 2.0 * z * w R = np.array([[1.0 - y2 - z2, xy - zw, xz + yw], [xy + zw, 1.0 - x2 - z2, yz - xw], [xz - yw, yz + xw, 1.0 - x2 - y2]]) return R def matrix_from_angle(basis, angle): """Compute passive rotation matrix from rotation about basis vector. Parameters ---------- basis : int from [0, 1, 2] The rotation axis (0: x, 1: y, 2: z) angle : float Rotation angle Returns ------- R : array-like, shape (3, 3) Rotation matrix """ c = np.cos(angle) s = np.sin(angle) if basis == 0: R = np.array([[1.0, 0.0, 0.0], [0.0, c, s], [0.0, -s, c]]) elif basis == 1: R = np.array([[c, 0.0, -s], [0.0, 1.0, 0.0], [s, 0.0, c]]) elif basis == 2: R = np.array([[c, s, 0.0], [-s, c, 0.0], [0.0, 0.0, 1.0]]) else: raise ValueError("Basis must be in [0, 1, 2]") return R passive_matrix_from_angle = matrix_from_angle def active_matrix_from_angle(basis, angle): """Compute active rotation matrix from rotation about basis vector. Parameters ---------- basis : int from [0, 1, 2] The rotation axis (0: x, 1: y, 2: z) angle : float Rotation angle Returns ------- R : array-like, shape (3, 3) Rotation matrix """ c = np.cos(angle) s = np.sin(angle) if basis == 0: R = np.array([[1.0, 0.0, 0.0], [0.0, c, -s], [0.0, s, c]]) elif basis == 1: R = np.array([[c, 0.0, s], [0.0, 1.0, 0.0], [-s, 0.0, c]]) elif basis == 2: R = np.array([[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]]) else: raise ValueError("Basis must be in [0, 1, 2]") return R def matrix_from_euler_xyz(e): """Compute passive rotation matrix from intrinsic xyz Tait-Bryan angles. Parameters ---------- e : array-like, shape (3,) Angles for rotation around x-, y'-, and z''-axes (intrinsic rotations) Returns ------- R : array-like, shape (3, 3) Rotation matrix """ alpha, beta, gamma = e R = passive_matrix_from_angle(0, alpha).dot( passive_matrix_from_angle(1, beta)).dot( passive_matrix_from_angle(2, gamma)) return R def matrix_from_euler_zyx(e): """Compute passive rotation matrix from intrinsic zyx Tait-Bryan angles. Parameters ---------- e : array-like, shape (3,) Angles for rotation around z-, y'-, and x''-axes (intrinsic rotations) Returns ------- R : array-like, shape (3, 3) Rotation matrix """ gamma, beta, alpha = e R = passive_matrix_from_angle(2, gamma).dot( passive_matrix_from_angle(1, beta)).dot( passive_matrix_from_angle(0, alpha)) return R def active_matrix_from_intrinsic_euler_xzx(e): """Compute active rotation matrix from intrinsic xzx Euler angles. Parameters ---------- e : array-like, shape (3,) Angles for rotation around x-, z'-, and x''-axes (intrinsic rotations) Returns ------- R : array-like, shape (3, 3) Rotation matrix """ alpha, beta, gamma = e R = active_matrix_from_angle(0, alpha).dot( active_matrix_from_angle(2, beta)).dot( active_matrix_from_angle(0, gamma)) return R def active_matrix_from_extrinsic_euler_xzx(e): """Compute active rotation matrix from extrinsic xzx Euler angles. Parameters ---------- e : array-like, shape (3,) Angles for rotation around x-, z-, and x-axes (extrinsic rotations) Returns ------- R : array-like, shape (3, 3) Rotation matrix """ alpha, beta, gamma = e R = active_matrix_from_angle(0, gamma).dot( active_matrix_from_angle(2, beta)).dot( active_matrix_from_angle(0, alpha)) return R def active_matrix_from_intrinsic_euler_xyx(e): """Compute active rotation matrix from intrinsic xyx Euler angles. Parameters ---------- e : array-like, shape (3,) Angles for rotation around x-, y'-, and x''-axes (intrinsic rotations) Returns ------- R : array-like, shape (3, 3) Rotation matrix """ alpha, beta, gamma = e R = active_matrix_from_angle(0, alpha).dot( active_matrix_from_angle(1, beta)).dot( active_matrix_from_angle(0, gamma)) return R def active_matrix_from_extrinsic_euler_xyx(e): """Compute active rotation matrix from extrinsic xyx Euler angles. Parameters ---------- e : array-like, shape (3,) Angles for rotation around x-, y-, and x-axes (extrinsic rotations) Returns ------- R : array-like, shape (3, 3) Rotation matrix """ alpha, beta, gamma = e R = active_matrix_from_angle(0, gamma).dot( active_matrix_from_angle(1, beta)).dot( active_matrix_from_angle(0, alpha)) return R def active_matrix_from_intrinsic_euler_yxy(e): """Compute active rotation matrix from intrinsic yxy Euler angles. Parameters ---------- e : array-like, shape (3,) Angles for rotation around y-, x'-, and y''-axes (intrinsic rotations) Returns ------- R : array-like, shape (3, 3) Rotation matrix """ alpha, beta, gamma = e R = active_matrix_from_angle(1, alpha).dot( active_matrix_from_angle(0, beta)).dot( active_matrix_from_angle(1, gamma)) return R def active_matrix_from_extrinsic_euler_yxy(e): """Compute active rotation matrix from extrinsic yxy Euler angles. Parameters ---------- e : array-like, shape (3,) Angles for rotation around y-, x-, and y-axes (extrinsic rotations) Returns ------- R : array-like, shape (3, 3) Rotation matrix """ alpha, beta, gamma = e R = active_matrix_from_angle(1, gamma).dot( active_matrix_from_angle(0, beta)).dot( active_matrix_from_angle(1, alpha)) return R def active_matrix_from_intrinsic_euler_yzy(e): """Compute active rotation matrix from intrinsic yzy Euler angles. Parameters ---------- e : array-like, shape (3,) Angles for rotation around y-, z'-, and y''-axes (intrinsic rotations) Returns ------- R : array-like, shape (3, 3) Rotation matrix """ alpha, beta, gamma = e R = active_matrix_from_angle(1, alpha).dot( active_matrix_from_angle(2, beta)).dot( active_matrix_from_angle(1, gamma)) return R def active_matrix_from_extrinsic_euler_yzy(e): """Compute active rotation matrix from extrinsic yzy Euler angles. Parameters ---------- e : array-like, shape (3,) Angles for rotation around y-, z-, and y-axes (extrinsic rotations) Returns ------- R : array-like, shape (3, 3) Rotation matrix """ alpha, beta, gamma = e R = active_matrix_from_angle(1, gamma).dot( active_matrix_from_angle(2, beta)).dot( active_matrix_from_angle(1, alpha)) return R def active_matrix_from_intrinsic_euler_zyz(e): """Compute active rotation matrix from intrinsic zyz Euler angles. Parameters ---------- e : array-like, shape (3,) Angles for rotation around z-, y'-, and z''-axes (intrinsic rotations) Returns ------- R : array-like, shape (3, 3) Rotation matrix """ alpha, beta, gamma = e R = active_matrix_from_angle(2, alpha).dot( active_matrix_from_angle(1, beta)).dot( active_matrix_from_angle(2, gamma)) return R def active_matrix_from_extrinsic_euler_zyz(e): """Compute active rotation matrix from extrinsic zyz Euler angles. .. warning:: This function was not implemented correctly in versions 1.3 and 1.4 as the order of the angles was reversed, which actually corresponds to intrinsic rotations. This has been fixed in version 1.5. Parameters ---------- e : array-like, shape (3,) Angles for rotation around z-, y-, and z-axes (extrinsic rotations) Returns ------- R : array-like, shape (3, 3) Rotation matrix """ alpha, beta, gamma = e R = active_matrix_from_angle(2, gamma).dot( active_matrix_from_angle(1, beta)).dot( active_matrix_from_angle(2, alpha)) return R def active_matrix_from_intrinsic_euler_zxz(e): """Compute active rotation matrix from intrinsic zxz Euler angles. Parameters ---------- e : array-like, shape (3,) Angles for rotation around z-, x'-, and z''-axes (intrinsic rotations) Returns ------- R : array-like, shape (3, 3) Rotation matrix """ alpha, beta, gamma = e R = active_matrix_from_angle(2, alpha).dot( active_matrix_from_angle(0, beta)).dot( active_matrix_from_angle(2, gamma)) return R def active_matrix_from_extrinsic_euler_zxz(e): """Compute active rotation matrix from extrinsic zxz Euler angles. .. warning:: This function was not implemented correctly in versions 1.3 and 1.4 as the order of the angles was reversed, which actually corresponds to intrinsic rotations. This has been fixed in version 1.5. Parameters ---------- e : array-like, shape (3,) Angles for rotation around z-, x-, and z-axes (extrinsic rotations) Returns ------- R : array-like, shape (3, 3) Rotation matrix """ alpha, beta, gamma = e R = active_matrix_from_angle(2, gamma).dot( active_matrix_from_angle(0, beta)).dot( active_matrix_from_angle(2, alpha)) return R def active_matrix_from_intrinsic_euler_xzy(e): """Compute active rotation matrix from intrinsic xzy Cardan angles. Parameters ---------- e : array-like, shape (3,) Angles for rotation around x-, z'-, and y''-axes (intrinsic rotations) Returns ------- R : array-like, shape (3, 3) Rotation matrix """ alpha, beta, gamma = e R = active_matrix_from_angle(0, alpha).dot( active_matrix_from_angle(2, beta)).dot( active_matrix_from_angle(1, gamma)) return R def active_matrix_from_extrinsic_euler_xzy(e): """Compute active rotation matrix from extrinsic xzy Cardan angles. Parameters ---------- e : array-like, shape (3,) Angles for rotation around x-, z-, and y-axes (extrinsic rotations) Returns ------- R : array-like, shape (3, 3) Rotation matrix """ alpha, beta, gamma = e R = active_matrix_from_angle(1, gamma).dot( active_matrix_from_angle(2, beta)).dot( active_matrix_from_angle(0, alpha)) return R def active_matrix_from_intrinsic_euler_xyz(e): """Compute active rotation matrix from intrinsic xyz Cardan angles. Parameters ---------- e : array-like, shape (3,) Angles for rotation around x-, y'-, and z''-axes (intrinsic rotations) Returns ------- R : array-like, shape (3, 3) Rotation matrix """ alpha, beta, gamma = e R = active_matrix_from_angle(0, alpha).dot( active_matrix_from_angle(1, beta)).dot( active_matrix_from_angle(2, gamma)) return R def active_matrix_from_extrinsic_euler_xyz(e): """Compute active rotation matrix from extrinsic xyz Cardan angles. Parameters ---------- e : array-like, shape (3,) Angles for rotation around x-, y-, and z-axes (extrinsic rotations) Returns ------- R : array-like, shape (3, 3) Rotation matrix """ alpha, beta, gamma = e R = active_matrix_from_angle(2, gamma).dot( active_matrix_from_angle(1, beta)).dot( active_matrix_from_angle(0, alpha)) return R def active_matrix_from_intrinsic_euler_yxz(e): """Compute active rotation matrix from intrinsic yxz Cardan angles. Parameters ---------- e : array-like, shape (3,) Angles for rotation around y-, x'-, and z''-axes (intrinsic rotations) Returns ------- R : array-like, shape (3, 3) Rotation matrix """ alpha, beta, gamma = e R = active_matrix_from_angle(1, alpha).dot( active_matrix_from_angle(0, beta)).dot( active_matrix_from_angle(2, gamma)) return R def active_matrix_from_extrinsic_euler_yxz(e): """Compute active rotation matrix from extrinsic yxz Cardan angles. Parameters ---------- e : array-like, shape (3,) Angles for rotation around y-, x-, and z-axes (extrinsic rotations) Returns ------- R : array-like, shape (3, 3) Rotation matrix """ alpha, beta, gamma = e R = active_matrix_from_angle(2, gamma).dot( active_matrix_from_angle(0, beta)).dot( active_matrix_from_angle(1, alpha)) return R def active_matrix_from_intrinsic_euler_yzx(e): """Compute active rotation matrix from intrinsic yzx Cardan angles. Parameters ---------- e : array-like, shape (3,) Angles for rotation around y-, z'-, and x''-axes (intrinsic rotations) Returns ------- R : array-like, shape (3, 3) Rotation matrix """ alpha, beta, gamma = e R = active_matrix_from_angle(1, alpha).dot( active_matrix_from_angle(2, beta)).dot( active_matrix_from_angle(0, gamma)) return R def active_matrix_from_extrinsic_euler_yzx(e): """Compute active rotation matrix from extrinsic yzx Cardan angles. Parameters ---------- e : array-like, shape (3,) Angles for rotation around y-, z-, and x-axes (extrinsic rotations) Returns ------- R : array-like, shape (3, 3) Rotation matrix """ alpha, beta, gamma = e R = active_matrix_from_angle(0, gamma).dot( active_matrix_from_angle(2, beta)).dot( active_matrix_from_angle(1, alpha)) return R def active_matrix_from_intrinsic_euler_zyx(e): """Compute active rotation matrix from intrinsic zyx Cardan angles. Parameters ---------- e : array-like, shape (3,) Angles for rotation around z-, y'-, and x''-axes (intrinsic rotations) Returns ------- R : array-like, shape (3, 3) Rotation matrix """ alpha, beta, gamma = e R = active_matrix_from_angle(2, alpha).dot( active_matrix_from_angle(1, beta)).dot( active_matrix_from_angle(0, gamma)) return R def active_matrix_from_extrinsic_euler_zyx(e): """Compute active rotation matrix from extrinsic zyx Cardan angles. Parameters ---------- e : array-like, shape (3,) Angles for rotation around z-, y-, and x-axes (extrinsic rotations) Returns ------- R : array-like, shape (3, 3) Rotation matrix """ alpha, beta, gamma = e R = active_matrix_from_angle(0, gamma).dot( active_matrix_from_angle(1, beta)).dot( active_matrix_from_angle(2, alpha)) return R def active_matrix_from_intrinsic_euler_zxy(e): """Compute active rotation matrix from intrinsic zxy Cardan angles. Parameters ---------- e : array-like, shape (3,) Angles for rotation around z-, x'-, and y''-axes (intrinsic rotations) Returns ------- R : array-like, shape (3, 3) Rotation matrix """ alpha, beta, gamma = e R = active_matrix_from_angle(2, alpha).dot( active_matrix_from_angle(0, beta)).dot( active_matrix_from_angle(1, gamma)) return R def active_matrix_from_extrinsic_euler_zxy(e): """Compute active rotation matrix from extrinsic zxy Cardan angles. Parameters ---------- e : array-like, shape (3,) Angles for rotation around z-, x-, and y-axes (extrinsic rotations) Returns ------- R : array-like, shape (3, 3) Rotation matrix """ alpha, beta, gamma = e R = active_matrix_from_angle(1, gamma).dot( active_matrix_from_angle(0, beta)).dot( active_matrix_from_angle(2, alpha)) return R def active_matrix_from_extrinsic_roll_pitch_yaw(rpy): """Compute active rotation matrix from extrinsic roll, pitch, and yaw. Parameters ---------- rpy : array-like, shape (3,) Angles for rotation around x- (roll), y- (pitch), and z-axes (yaw), extrinsic rotations Returns ------- R : array-like, shape (3, 3) Rotation matrix """ return active_matrix_from_extrinsic_euler_xyz(rpy) def matrix_from(R=None, a=None, q=None, e_xyz=None, e_zyx=None): """Compute rotation matrix from another representation. Parameters ---------- R : array-like, shape (3, 3) Rotation matrix a : array-like, shape (4,) Axis of rotation and rotation angle: (x, y, z, angle) q : array-like, shape (4,) Unit quaternion to represent rotation: (w, x, y, z) e_xyz : array-like, shape (3,) Angles for rotation around x-, y'-, and z''-axes (intrinsic rotations) e_zyx : array-like, shape (3,) Angles for rotation around z-, y'-, and x''-axes (intrinsic rotations) Returns ------- R : array-like, shape (3, 3) Rotation matrix """ if R is not None: return R if a is not None: return matrix_from_axis_angle(a) if q is not None: return matrix_from_quaternion(q) if e_xyz is not None: return matrix_from_euler_xyz(e_xyz) if e_zyx is not None: return matrix_from_euler_zyx(e_zyx) raise ValueError("Cannot compute rotation matrix from no rotation.") def _general_intrinsic_euler_from_active_matrix( R, n1, n2, n3, proper_euler, strict_check=True): """General algorithm to extract intrinsic euler angles from a matrix. The implementation is based on SciPy's implementation: https://github.com/scipy/scipy/blob/master/scipy/spatial/transform/rotation.pyx Parameters ---------- R : array-like, shape (3, 3) Active rotation matrix n1 : array, shape (3,) First rotation axis (basis vector) n2 : array, shape (3,) Second rotation axis (basis vector) n3 : array, shape (3,) Third rotation axis (basis vector) proper_euler : bool Is this an Euler angle convention or a Cardan / Tait-Bryan convention? Proper Euler angles rotate about the same axis twice, for example, z, y', and z''. strict_check : bool, optional (default: True) Raise a ValueError if the rotation matrix is not numerically close enough to a real rotation matrix. Otherwise we print a warning. Returns ------- euler_angles : array, shape (3,) Extracted intrinsic rotation angles in radians about the axes n1, n2, and n3 in this order. The first and last angle are normalized to [-pi, pi]. The middle angle is normalized to either [0, pi] (proper Euler angles) or [-pi/2, pi/2] (Cardan / Tait-Bryan angles). References ---------- Shuster, Markley: General Formula for Extracting the Euler Angles, https://arc.aiaa.org/doi/abs/10.2514/1.16622 """ D = check_matrix(R, strict_check=strict_check) # Differences to the paper: # - we call the angles alpha, beta, and gamma # - we obtain angles from intrinsic rotations, thus some matrices are # transposed like in SciPy's implementation # Step 2 # - Equation 5 n1_cross_n2 = np.cross(n1, n2) lmbda = np.arctan2( np.dot(n1_cross_n2, n3), np.dot(n1, n3) ) # - Equation 6 C = np.vstack((n2, n1_cross_n2, n1)) # Step 3 # - Equation 8 CDCT = np.dot(np.dot(C, D), C.T) O = np.dot(CDCT, active_matrix_from_angle(0, lmbda).T) # Step 4 # - Equation 10a beta = lmbda + np.arccos(O[2, 2]) safe1 = abs(beta - lmbda) >= np.finfo(float).eps safe2 = abs(beta - lmbda - np.pi) >= np.finfo(float).eps if safe1 and safe2: # Default case, no gimbal lock # Step 5 # - Equation 10b alpha = np.arctan2(O[0, 2], -O[1, 2]) # - Equation 10c gamma = np.arctan2(O[2, 0], O[2, 1]) # Step 7 if proper_euler: valid_beta = 0.0 <= beta <= np.pi else: # Cardan / Tait-Bryan angles valid_beta = -0.5 * np.pi <= beta <= 0.5 * np.pi # - Equation 12 if not valid_beta: alpha += np.pi beta = 2.0 * lmbda - beta gamma -= np.pi else: # Step 6 - Handle gimbal locks # a) gamma = 0.0 if not safe1: # b) alpha = np.arctan2(O[1, 0] - O[0, 1], O[0, 0] + O[1, 1]) else: # c) alpha = np.arctan2(O[1, 0] + O[0, 1], O[0, 0] - O[1, 1]) euler_angles = norm_angle([alpha, beta, gamma]) return euler_angles def euler_xyz_from_matrix(R, strict_check=True): """Compute xyz Euler angles from passive rotation matrix. Parameters ---------- R : array-like, shape (3, 3) Passive rotation matrix strict_check : bool, optional (default: True) Raise a ValueError if the rotation matrix is not numerically close enough to a real rotation matrix. Otherwise we print a warning. Returns ------- e_xyz : array-like, shape (3,) Angles for rotation around x-, y'-, and z''-axes (intrinsic rotations) """ R = check_matrix(R, strict_check=strict_check) if np.abs(R[0, 2]) != 1.0: # NOTE: There are two solutions: angle2 and pi - angle2! angle2 = np.arcsin(-R[0, 2]) angle1 = np.arctan2(R[1, 2] / np.cos(angle2), R[2, 2] / np.cos(angle2)) angle3 = np.arctan2(R[0, 1] / np.cos(angle2), R[0, 0] / np.cos(angle2)) else: if R[0, 2] == 1.0: angle3 = 0.0 angle2 = -np.pi / 2.0 angle1 = np.arctan2(-R[1, 0], -R[2, 0]) else: angle3 = 0.0 angle2 = np.pi / 2.0 angle1 = np.arctan2(R[1, 0], R[2, 0]) return np.array([angle1, angle2, angle3]) def euler_zyx_from_matrix(R, strict_check=True): """Compute zyx Euler angles from passive rotation matrix. Parameters ---------- R : array-like, shape (3, 3) Passive rotation matrix strict_check : bool, optional (default: True) Raise a ValueError if the rotation matrix is not numerically close enough to a real rotation matrix. Otherwise we print a warning. Returns ------- e_zyx : array-like, shape (3,) Angles for rotation around z-, y'-, and x''-axes (intrinsic rotations) """ R = check_matrix(R, strict_check=strict_check) if np.abs(R[2, 0]) != 1.0: # NOTE: There are two solutions: angle2 and pi - angle2! angle2 = np.arcsin(R[2, 0]) angle3 = np.arctan2(-R[2, 1] / np.cos(angle2), R[2, 2] / np.cos(angle2)) angle1 = np.arctan2(-R[1, 0] / np.cos(angle2), R[0, 0] / np.cos(angle2)) else: if R[2, 0] == 1.0: angle3 = 0.0 angle2 = np.pi / 2.0 angle1 = np.arctan2(R[0, 1], -R[0, 2]) else: angle3 = 0.0 angle2 = -np.pi / 2.0 angle1 = np.arctan2(R[0, 1], R[0, 2]) return np.array([angle1, angle2, angle3]) def intrinsic_euler_xzx_from_active_matrix(R, strict_check=True): """Compute intrinsic xzx Euler angles from active rotation matrix. Parameters ---------- R : array-like, shape (3, 3) Rotation matrix strict_check : bool, optional (default: True) Raise a ValueError if the rotation matrix is not numerically close enough to a real rotation matrix. Otherwise we print a warning. Returns ------- e : array, shape (3,) Angles for rotation around x-, z'-, and x''-axes (intrinsic rotations) """ return _general_intrinsic_euler_from_active_matrix( R, unitx, unitz, unitx, True, strict_check) def extrinsic_euler_xzx_from_active_matrix(R, strict_check=True): """Compute active rotation matrix from extrinsic xzx Euler angles. Parameters ---------- R : array-like, shape (3, 3) Rotation matrix strict_check : bool, optional (default: True) Raise a ValueError if the rotation matrix is not numerically close enough to a real rotation matrix. Otherwise we print a warning. Returns ------- e : array-like, shape (3,) Angles for rotation around x-, z-, and x-axes (extrinsic rotations) """ return _general_intrinsic_euler_from_active_matrix( R, unitx, unitz, unitx, True, strict_check)[::-1] def intrinsic_euler_xyx_from_active_matrix(R, strict_check=True): """Compute intrinsic xyx Euler angles from active rotation matrix. Parameters ---------- R : array-like, shape (3, 3) Rotation matrix strict_check : bool, optional (default: True) Raise a ValueError if the rotation matrix is not numerically close enough to a real rotation matrix. Otherwise we print a warning. Returns ------- e : array, shape (3,) Angles for rotation around x-, y'-, and x''-axes (intrinsic rotations) """ return _general_intrinsic_euler_from_active_matrix( R, unitx, unity, unitx, True, strict_check) def extrinsic_euler_xyx_from_active_matrix(R, strict_check=True): """Compute extrinsic xyx Euler angles from active rotation matrix. Parameters ---------- R : array-like, shape (3, 3) Rotation matrix strict_check : bool, optional (default: True) Raise a ValueError if the rotation matrix is not numerically close enough to a real rotation matrix. Otherwise we print a warning. Returns ------- e : array, shape (3,) Angles for rotation around x-, y-, and x-axes (extrinsic rotations) """ return _general_intrinsic_euler_from_active_matrix( R, unitx, unity, unitx, True, strict_check)[::-1] def intrinsic_euler_yxy_from_active_matrix(R, strict_check=True): """Compute intrinsic yxy Euler angles from active rotation matrix. Parameters ---------- R : array-like, shape (3, 3) Rotation matrix strict_check : bool, optional (default: True) Raise a ValueError if the rotation matrix is not numerically close enough to a real rotation matrix. Otherwise we print a warning. Returns ------- e : array-like, shape (3,) Angles for rotation around y-, x'-, and y''-axes (intrinsic rotations) """ return _general_intrinsic_euler_from_active_matrix( R, unity, unitx, unity, True, strict_check) def extrinsic_euler_yxy_from_active_matrix(R, strict_check=True): """Compute extrinsic yxy Euler angles from active rotation matrix. Parameters ---------- R : array-like, shape (3, 3) Rotation matrix strict_check : bool, optional (default: True) Raise a ValueError if the rotation matrix is not numerically close enough to a real rotation matrix. Otherwise we print a warning. Returns ------- e : array-like, shape (3,) Angles for rotation around y-, x-, and y-axes (extrinsic rotations) """ return _general_intrinsic_euler_from_active_matrix( R, unity, unitx, unity, True, strict_check)[::-1] def intrinsic_euler_yzy_from_active_matrix(R, strict_check=True): """Compute intrinsic yzy Euler angles from active rotation matrix. Parameters ---------- R : array-like, shape (3, 3) Rotation matrix strict_check : bool, optional (default: True) Raise a ValueError if the rotation matrix is not numerically close enough to a real rotation matrix. Otherwise we print a warning. Returns ------- e : array-like, shape (3,) Angles for rotation around y-, z'-, and y''-axes (intrinsic rotations) """ return _general_intrinsic_euler_from_active_matrix( R, unity, unitz, unity, True, strict_check) def extrinsic_euler_yzy_from_active_matrix(R, strict_check=True): """Compute extrinsic yzy Euler angles from active rotation matrix. Parameters ---------- R : array-like, shape (3, 3) Rotation matrix strict_check : bool, optional (default: True) Raise a ValueError if the rotation matrix is not numerically close enough to a real rotation matrix. Otherwise we print a warning. Returns ------- e : array-like, shape (3,) Angles for rotation around y-, z-, and y-axes (extrinsic rotations) """ return _general_intrinsic_euler_from_active_matrix( R, unity, unitz, unity, True, strict_check)[::-1] def intrinsic_euler_zyz_from_active_matrix(R, strict_check=True): """Compute intrinsic zyz Euler angles from active rotation matrix. Parameters ---------- R : array-like, shape (3, 3) Rotation matrix strict_check : bool, optional (default: True) Raise a ValueError if the rotation matrix is not numerically close enough to a real rotation matrix. Otherwise we print a warning. Returns ------- e : array-like, shape (3,) Angles for rotation around z-, y'-, and z''-axes (intrinsic rotations) """ return _general_intrinsic_euler_from_active_matrix( R, unitz, unity, unitz, True, strict_check) def extrinsic_euler_zyz_from_active_matrix(R, strict_check=True): """Compute extrinsic zyz Euler angles from active rotation matrix. Parameters ---------- R : array-like, shape (3, 3) Rotation matrix strict_check : bool, optional (default: True) Raise a ValueError if the rotation matrix is not numerically close enough to a real rotation matrix. Otherwise we print a warning. Returns ------- e : array-like, shape (3,) Angles for rotation around z-, y-, and z-axes (extrinsic rotations) """ return _general_intrinsic_euler_from_active_matrix( R, unitz, unity, unitz, True, strict_check)[::-1] def intrinsic_euler_zxz_from_active_matrix(R, strict_check=True): """Compute intrinsic zxz Euler angles from active rotation matrix. Parameters ---------- R : array-like, shape (3, 3) Rotation matrix strict_check : bool, optional (default: True) Raise a ValueError if the rotation matrix is not numerically close enough to a real rotation matrix. Otherwise we print a warning. Returns ------- e : array-like, shape (3,) Angles for rotation around z-, x'-, and z''-axes (intrinsic rotations) """ return _general_intrinsic_euler_from_active_matrix( R, unitz, unitx, unitz, True, strict_check) def extrinsic_euler_zxz_from_active_matrix(R, strict_check=True): """Compute extrinsic zxz Euler angles from active rotation matrix. Parameters ---------- R : array-like, shape (3, 3) Rotation matrix strict_check : bool, optional (default: True) Raise a ValueError if the rotation matrix is not numerically close enough to a real rotation matrix. Otherwise we print a warning. Returns ------- e : array-like, shape (3,) Angles for rotation around z-, x-, and z-axes (extrinsic rotations) """ return _general_intrinsic_euler_from_active_matrix( R, unitz, unitx, unitz, True, strict_check)[::-1] def intrinsic_euler_xzy_from_active_matrix(R, strict_check=True): """Compute intrinsic xzy Cardan angles from active rotation matrix. Parameters ---------- R : array-like, shape (3, 3) Rotation matrix strict_check : bool, optional (default: True) Raise a ValueError if the rotation matrix is not numerically close enough to a real rotation matrix. Otherwise we print a warning. Returns ------- e : array-like, shape (3,) Angles for rotation around x-, z'-, and y''-axes (intrinsic rotations) """ return _general_intrinsic_euler_from_active_matrix( R, unitx, unitz, unity, False, strict_check) def extrinsic_euler_xzy_from_active_matrix(R, strict_check=True): """Compute extrinsic xzy Cardan angles from active rotation matrix. Parameters ---------- R : array-like, shape (3, 3) Rotation matrix strict_check : bool, optional (default: True) Raise a ValueError if the rotation matrix is not numerically close enough to a real rotation matrix. Otherwise we print a warning. Returns ------- e : array-like, shape (3,) Angles for rotation around x-, z-, and y-axes (extrinsic rotations) """ return _general_intrinsic_euler_from_active_matrix( R, unity, unitz, unitx, False, strict_check)[::-1] def intrinsic_euler_xyz_from_active_matrix(R, strict_check=True): """Compute intrinsic xyz Cardan angles from active rotation matrix. Parameters ---------- R : array-like, shape (3, 3) Rotation matrix strict_check : bool, optional (default: True) Raise a ValueError if the rotation matrix is not numerically close enough to a real rotation matrix. Otherwise we print a warning. Returns ------- e : array-like, shape (3,) Angles for rotation around x-, y'-, and z''-axes (intrinsic rotations) """ return _general_intrinsic_euler_from_active_matrix( R, unitx, unity, unitz, False, strict_check) def extrinsic_euler_xyz_from_active_matrix(R, strict_check=True): """Compute extrinsic xyz Cardan angles from active rotation matrix. Parameters ---------- R : array-like, shape (3, 3) Rotation matrix strict_check : bool, optional (default: True) Raise a ValueError if the rotation matrix is not numerically close enough to a real rotation matrix. Otherwise we print a warning. Returns ------- e : array-like, shape (3,) Angles for rotation around x-, y-, and z-axes (extrinsic rotations) """ return _general_intrinsic_euler_from_active_matrix( R, unitz, unity, unitx, False, strict_check)[::-1] def intrinsic_euler_yxz_from_active_matrix(R, strict_check=True): """Compute intrinsic yxz Cardan angles from active rotation matrix. Parameters ---------- R : array-like, shape (3, 3) Rotation matrix strict_check : bool, optional (default: True) Raise a ValueError if the rotation matrix is not numerically close enough to a real rotation matrix. Otherwise we print a warning. Returns ------- e : array-like, shape (3,) Angles for rotation around y-, x'-, and z''-axes (intrinsic rotations) """ return _general_intrinsic_euler_from_active_matrix( R, unity, unitx, unitz, False, strict_check) def extrinsic_euler_yxz_from_active_matrix(R, strict_check=True): """Compute extrinsic yxz Cardan angles from active rotation matrix. Parameters ---------- R : array-like, shape (3, 3) Rotation matrix strict_check : bool, optional (default: True) Raise a ValueError if the rotation matrix is not numerically close enough to a real rotation matrix. Otherwise we print a warning. Returns ------- e : array-like, shape (3,) Angles for rotation around y-, x-, and z-axes (extrinsic rotations) """ return _general_intrinsic_euler_from_active_matrix( R, unitz, unitx, unity, False, strict_check)[::-1] def intrinsic_euler_yzx_from_active_matrix(R, strict_check=True): """Compute intrinsic yzx Cardan angles from active rotation matrix. Parameters ---------- R : array-like, shape (3, 3) Rotation matrix strict_check : bool, optional (default: True) Raise a ValueError if the rotation matrix is not numerically close enough to a real rotation matrix. Otherwise we print a warning. Returns ------- e : array-like, shape (3,) Angles for rotation around y-, z'-, and x''-axes (intrinsic rotations) """ return _general_intrinsic_euler_from_active_matrix( R, unity, unitz, unitx, False, strict_check) def extrinsic_euler_yzx_from_active_matrix(R, strict_check=True): """Compute extrinsic yzx Cardan angles from active rotation matrix. Parameters ---------- R : array-like, shape (3, 3) Rotation matrix strict_check : bool, optional (default: True) Raise a ValueError if the rotation matrix is not numerically close enough to a real rotation matrix. Otherwise we print a warning. Returns ------- e : array-like, shape (3,) Angles for rotation around y-, z-, and x-axes (extrinsic rotations) """ return _general_intrinsic_euler_from_active_matrix( R, unitx, unitz, unity, False, strict_check)[::-1] def intrinsic_euler_zyx_from_active_matrix(R, strict_check=True): """Compute intrinsic zyx Cardan angles from active rotation matrix. Parameters ---------- R : array-like, shape (3, 3) Rotation matrix strict_check : bool, optional (default: True) Raise a ValueError if the rotation matrix is not numerically close enough to a real rotation matrix. Otherwise we print a warning. Returns ------- e : array, shape (3,) Angles for rotation around z-, y'-, and x''-axes (intrinsic rotations) """ return _general_intrinsic_euler_from_active_matrix( R, unitz, unity, unitx, False, strict_check) def extrinsic_euler_zyx_from_active_matrix(R, strict_check=True): """Compute extrinsic zyx Cardan angles from active rotation matrix. Parameters ---------- R : array-like, shape (3, 3) Rotation matrix strict_check : bool, optional (default: True) Raise a ValueError if the rotation matrix is not numerically close enough to a real rotation matrix. Otherwise we print a warning. Returns ------- e : array, shape (3,) Angles for rotation around z-, y-, and x-axes (extrinsic rotations) """ return _general_intrinsic_euler_from_active_matrix( R, unitx, unity, unitz, False, strict_check)[::-1] def intrinsic_euler_zxy_from_active_matrix(R, strict_check=True): """Compute intrinsic zxy Cardan angles from active rotation matrix. Parameters ---------- R : array-like, shape (3, 3) Rotation matrix strict_check : bool, optional (default: True) Raise a ValueError if the rotation matrix is not numerically close enough to a real rotation matrix. Otherwise we print a warning. Returns ------- e : array, shape (3,) Angles for rotation around z-, x'-, and y''-axes (intrinsic rotations) """ return _general_intrinsic_euler_from_active_matrix( R, unitz, unitx, unity, False, strict_check) def extrinsic_euler_zxy_from_active_matrix(R, strict_check=True): """Compute extrinsic zxy Cardan angles from active rotation matrix. Parameters ---------- R : array-like, shape (3, 3) Rotation matrix strict_check : bool, optional (default: True) Raise a ValueError if the rotation matrix is not numerically close enough to a real rotation matrix. Otherwise we print a warning. Returns ------- e : array-like, shape (3,) Angles for rotation around z-, x-, and y-axes (extrinsic rotations) """ return _general_intrinsic_euler_from_active_matrix( R, unity, unitx, unitz, False, strict_check)[::-1] def axis_angle_from_matrix(R, strict_check=True): """Compute axis-angle from rotation matrix. This operation is called logarithmic map. Note that there are two possible solutions for the rotation axis when the angle is 180 degrees (pi). We usually assume active rotations. Parameters ---------- R : array-like, shape (3, 3) Rotation matrix strict_check : bool, optional (default: True) Raise a ValueError if the rotation matrix is not numerically close enough to a real rotation matrix. Otherwise we print a warning. Returns ------- a : array-like, shape (4,) Axis of rotation and rotation angle: (x, y, z, angle). The angle is constrained to [0, pi]. """ R = check_matrix(R, strict_check=strict_check) angle = np.arccos((np.trace(R) - 1.0) / 2.0) if angle == 0.0: # R == np.eye(3) return np.array([1.0, 0.0, 0.0, 0.0]) a = np.empty(4) # We can usually determine the rotation axis by inverting Rodrigues' # formula. Subtracting opposing off-diagonal elements gives us # 2 * sin(angle) * e, # where e is the normalized rotation axis. axis_unnormalized = np.array( [R[2, 1] - R[1, 2], R[0, 2] - R[2, 0], R[1, 0] - R[0, 1]]) if abs(angle - np.pi) < 1e-4: # np.trace(R) close to -1 # The threshold is a result from this discussion: # https://github.com/rock-learning/pytransform3d/issues/43 # The standard formula becomes numerically unstable, however, # Rodrigues' formula reduces to R = I + 2 (ee^T - I), with the # rotation axis e, that is, ee^T = 0.5 * (R + I) and we can find the # squared values of the rotation axis on the diagonal of this matrix. # We can still use the original formula to reconstruct the signs of # the rotation axis correctly. a[:3] = np.sqrt(0.5 * (np.diag(R) + 1.0)) * np.sign(axis_unnormalized) else: a[:3] = axis_unnormalized # The norm of axis_unnormalized is 2.0 * np.sin(angle), that is, we # could normalize with a[:3] = a[:3] / (2.0 * np.sin(angle)), # but the following is much more precise for angles close to 0 or pi: a[:3] /= np.linalg.norm(a[:3]) a[3] = angle return a def axis_angle_from_quaternion(q): """Compute axis-angle from quaternion. This operation is called logarithmic map. We usually assume active rotations. Parameters ---------- q : array-like, shape (4,) Unit quaternion to represent rotation: (w, x, y, z) Returns ------- a : array-like, shape (4,) Axis of rotation and rotation angle: (x, y, z, angle). The angle is constrained to [0, pi) so that the mapping is unique. """ q = check_quaternion(q) p = q[1:] p_norm = np.linalg.norm(p) if p_norm < np.finfo(float).eps: return np.array([1.0, 0.0, 0.0, 0.0]) else: axis = p / p_norm angle = (2.0 * np.arccos(q[0]),) return np.hstack((axis, angle)) def axis_angle_from_compact_axis_angle(a): """Compute axis-angle from compact axis-angle representation. We usually assume active rotations. Parameters ---------- a : array-like, shape (3,) Axis of rotation and rotation angle: angle * (x, y, z). Returns ------- a : array-like, shape (4,) Axis of rotation and rotation angle: (x, y, z, angle). The angle is constrained to [0, pi]. """ a = check_compact_axis_angle(a) angle = np.linalg.norm(a) if angle == 0.0: return np.array([1.0, 0.0, 0.0, 0.0]) else: axis = a / angle return np.hstack((axis, (angle,))) def axis_angle_from_two_directions(a, b): """Compute axis-angle representation from two direction vectors. The rotation will transform direction vector a to direction vector b. The direction vectors don't have to be normalized as this will be done internally. Note that there is more than one possible solution. Parameters ---------- a : array-like, shape (3,) First direction vector b : array-like, shape (3,) Second direction vector Returns ------- a : array-like, shape (4,) Axis of rotation and rotation angle: (x, y, z, angle). The angle is constrained to [0, pi]. """ a = norm_vector(a) b = norm_vector(b) cos_angle = a.dot(b) if abs(-1.0 - cos_angle) < eps: # For 180 degree rotations we have an infinite number of solutions, # but we have to pick one axis. axis = perpendicular_to_vector(a) else: axis = np.cross(a, b) aa = np.empty(4) aa[:3] = norm_vector(axis) aa[3] = np.arccos(cos_angle) return norm_axis_angle(aa) def compact_axis_angle(a): """Compute 3-dimensional axis-angle from a 4-dimensional one. In a 3-dimensional axis-angle, the 4th dimension (the rotation) is represented by the norm of the rotation axis vector, which means we transform :math:`\\left( \\boldsymbol{\hat{e}}, \\theta \\right)` to :math:`\\theta \\boldsymbol{\hat{e}}`. We usually assume active rotations. Parameters ---------- a : array-like, shape (4,) Axis of rotation and rotation angle: (x, y, z, angle). Returns ------- a : array-like, shape (3,) Axis of rotation and rotation angle: angle * (x, y, z) (compact representation). """ a = check_axis_angle(a) return a[:3] * a[3] def compact_axis_angle_from_matrix(R): """Compute compact axis-angle from rotation matrix. This operation is called logarithmic map. Note that there are two possible solutions for the rotation axis when the angle is 180 degrees (pi). We usually assume active rotations. Parameters ---------- R : array-like, shape (3, 3) Rotation matrix strict_check : bool, optional (default: True) Raise a ValueError if the rotation matrix is not numerically close enough to a real rotation matrix. Otherwise we print a warning. Returns ------- a : array-like, shape (3,) Axis of rotation and rotation angle: angle * (x, y, z). The angle is constrained to [0, pi]. """ a = axis_angle_from_matrix(R) return compact_axis_angle(a) def compact_axis_angle_from_quaternion(q): """Compute compact axis-angle from quaternion (logarithmic map). We usually assume active rotations. Parameters ---------- q : array-like, shape (4,) Unit quaternion to represent rotation: (w, x, y, z) Returns ------- a : array-like, shape (3,) Axis of rotation and rotation angle: angle * (x, y, z). The angle is constrained to [0, pi]. """ a = axis_angle_from_quaternion(q) return compact_axis_angle(a) def quaternion_from_matrix(R, strict_check=True): """Compute quaternion from rotation matrix. We usually assume active rotations. .. warning:: When computing a quaternion from the rotation matrix there is a sign ambiguity: q and -q represent the same rotation. Parameters ---------- R : array-like, shape (3, 3) Rotation matrix strict_check : bool, optional (default: True) Raise a ValueError if the rotation matrix is not numerically close enough to a real rotation matrix. Otherwise we print a warning. Returns ------- q : array-like, shape (4,) Unit quaternion to represent rotation: (w, x, y, z) """ R = check_matrix(R, strict_check=strict_check) q = np.empty(4) # Source: http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/ trace = np.trace(R) if trace > 0.0: sqrt_trace = np.sqrt(1.0 + trace) q[0] = 0.5 * sqrt_trace q[1] = 0.5 / sqrt_trace * (R[2, 1] - R[1, 2]) q[2] = 0.5 / sqrt_trace * (R[0, 2] - R[2, 0]) q[3] = 0.5 / sqrt_trace * (R[1, 0] - R[0, 1]) else: if R[0, 0] > R[1, 1] and R[0, 0] > R[2, 2]: sqrt_trace = np.sqrt(1.0 + R[0, 0] - R[1, 1] - R[2, 2]) q[0] = 0.5 / sqrt_trace * (R[2, 1] - R[1, 2]) q[1] = 0.5 * sqrt_trace q[2] = 0.5 / sqrt_trace * (R[1, 0] + R[0, 1]) q[3] = 0.5 / sqrt_trace * (R[0, 2] + R[2, 0]) elif R[1, 1] > R[2, 2]: sqrt_trace = np.sqrt(1.0 + R[1, 1] - R[0, 0] - R[2, 2]) q[0] = 0.5 / sqrt_trace * (R[0, 2] - R[2, 0]) q[1] = 0.5 / sqrt_trace * (R[1, 0] + R[0, 1]) q[2] = 0.5 * sqrt_trace q[3] = 0.5 / sqrt_trace * (R[2, 1] + R[1, 2]) else: sqrt_trace = np.sqrt(1.0 + R[2, 2] - R[0, 0] - R[1, 1]) q[0] = 0.5 / sqrt_trace * (R[1, 0] - R[0, 1]) q[1] = 0.5 / sqrt_trace * (R[0, 2] + R[2, 0]) q[2] = 0.5 / sqrt_trace * (R[2, 1] + R[1, 2]) q[3] = 0.5 * sqrt_trace return q def quaternion_from_axis_angle(a): """Compute quaternion from axis-angle. This operation is called exponential map. We usually assume active rotations. Parameters ---------- a : array-like, shape (4,) Axis of rotation and rotation angle: (x, y, z, angle) Returns ------- q : array-like, shape (4,) Unit quaternion to represent rotation: (w, x, y, z) """ a = check_axis_angle(a) theta = a[3] q = np.empty(4) q[0] = np.cos(theta / 2) q[1:] = np.sin(theta / 2) * a[:3] return q def quaternion_from_compact_axis_angle(a): """Compute quaternion from compact axis-angle (exponential map). We usually assume active rotations. Parameters ---------- a : array-like, shape (4,) Axis of rotation and rotation angle: angle * (x, y, z) Returns ------- q : array-like, shape (4,) Unit quaternion to represent rotation: (w, x, y, z) """ a = axis_angle_from_compact_axis_angle(a) return quaternion_from_axis_angle(a) def quaternion_xyzw_from_wxyz(q_wxyz): """Converts from w, x, y, z to x, y, z, w convention. Parameters ---------- q_wxyz : array-like, shape (4,) Quaternion with scalar part before vector part Returns ------- q_xyzw : array-like, shape (4,) Quaternion with scalar part after vector part """ q_wxyz = check_quaternion(q_wxyz) return np.array([q_wxyz[1], q_wxyz[2], q_wxyz[3], q_wxyz[0]]) def quaternion_wxyz_from_xyzw(q_xyzw): """Converts from x, y, z, w to w, x, y, z convention. Parameters ---------- q_xyzw : array-like, shape (4,) Quaternion with scalar part after vector part Returns ------- q_wxyz : array-like, shape (4,) Quaternion with scalar part before vector part """ q_xyzw = check_quaternion(q_xyzw) return np.array([q_xyzw[3], q_xyzw[0], q_xyzw[1], q_xyzw[2]]) def quaternion_integrate(Qd, q0=np.array([1.0, 0.0, 0.0, 0.0]), dt=1.0): """Integrate angular velocities to quaternions. Parameters ---------- A : array-like, shape (n_steps, 3) Angular velocities in a compact axis-angle representation. Each angular velocity represents the rotational offset after one unit of time. q0 : array-like, shape (4,), optional (default: [1, 0, 0, 0]) Unit quaternion to represent initial rotation: (w, x, y, z) dt : float, optional (default: 1) Time interval between steps. Returns ------- Q : array-like, shape (n_steps, 4) Quaternions to represent rotations: (w, x, y, z) """ Q = np.empty((len(Qd), 4)) Q[0] = q0 for t in range(1, len(Qd)): qd = (Qd[t] + Qd[t - 1]) / 2.0 Q[t] = concatenate_quaternions( quaternion_from_compact_axis_angle(dt * qd), Q[t - 1]) return Q def quaternion_gradient(Q, dt=1.0): """Time-derivatives of a sequence of quaternions. Note that this function does not provide the exact same functionality for quaternions as [NumPy's gradient function](https://numpy.org/doc/stable/reference/generated/numpy.gradient.html) for positions. Gradients are always computed as central differences except the first and last gradient. We additionally accept a parameter dt that defines the time interval between each quaternion. Note that this means that we expect this to be constant for the whole sequence. Parameters ---------- Q : array-like, shape (n_steps, 4) Quaternions to represent rotations: (w, x, y, z) dt : float, optional (default: 1) Time interval between steps. If you have non-constant dt, you can pass 1 and manually divide angular velocities by their corresponding time interval afterwards. Returns ------- A : array-like, shape (n_steps, 3) Angular velocities in a compact axis-angle representation. Each angular velocity represents the rotational offset after one unit of time. """ Q = check_quaternions(Q) Qd = np.empty((len(Q), 3)) Qd[0] = compact_axis_angle_from_quaternion( concatenate_quaternions(Q[1], q_conj(Q[0]))) / dt for t in range(1, len(Q) - 1): # divided by two because of central differences Qd[t] = compact_axis_angle_from_quaternion( concatenate_quaternions(Q[t + 1], q_conj(Q[t - 1]))) / (2.0 * dt) Qd[-1] = compact_axis_angle_from_quaternion( concatenate_quaternions(Q[-1], q_conj(Q[-2]))) / dt return Qd def concatenate_quaternions(q1, q2): """Concatenate two quaternions. We use Hamilton's quaternion multiplication. Suppose we want to apply two extrinsic rotations given by quaternions q1 and q2 to a vector v. We can either apply q2 to v and then q1 to the result or we can concatenate q1 and q2 and apply the result to v. Parameters ---------- q1 : array-like, shape (4,) First quaternion q2 : array-like, shape (4,) Second quaternion Returns ------- q12 : array-like, shape (4,) Quaternion that represents the concatenated rotation q1 * q2 """ q1 = check_quaternion(q1, unit=False) q2 = check_quaternion(q2, unit=False) q12 = np.empty(4) q12[0] = q1[0] * q2[0] -
np.dot(q1[1:], q2[1:])
numpy.dot
from __future__ import annotations import os import numpy as np import pytest import xarray as xr from xclim.testing import open_dataset try: import clisops.core.subset as subset import geopandas as gpd except ImportError: subset = False gpd = False pytestmark = pytest.mark.slow TESTS_HOME = os.path.abspath(os.path.dirname(__file__)) TESTS_DATA = os.path.join(TESTS_HOME, "data") class TestSubsetRaises: @pytest.mark.skipif( subset is False, reason="`clisops` subset utilities are not installed." ) def test_raises_deprecation_warning(self): with pytest.deprecated_call(): from xclim import subset assert subset.__doc__ @pytest.mark.skipif( hasattr(subset, "__all__"), reason="Necessary dependencies are installed." ) def test_raise_import_error(self): with pytest.raises(ImportError): from xclim import subset assert subset.__doc__ @pytest.mark.skipif( subset is False, reason="`clisops` subset utilities are not installed." ) class TestSubsetTime: nc_poslons = os.path.join("cmip3", "tas.sresb1.giss_model_e_r.run1.atm.da.nc") def test_simple(self): da = open_dataset(self.nc_poslons).tas yr_st = "2050" yr_ed = "2059" out = subset.subset_time(da, start_date=yr_st, end_date=yr_ed) out1 = subset.subset_time(da, start_date=f"{yr_st}-01", end_date=f"{yr_ed}-12") out2 = subset.subset_time( da, start_date=f"{yr_st}-01-01", end_date=f"{yr_ed}-12-31" ) np.testing.assert_array_equal(out, out1) np.testing.assert_array_equal(out, out2) np.testing.assert_array_equal(len(
np.unique(out.time.dt.year)
numpy.unique