prompt
stringlengths
19
879k
completion
stringlengths
3
53.8k
api
stringlengths
8
59
import unittest import numpy as np from op_test import OpTest class TestLodResetOpByAttr(OpTest): def setUp(self): self.op_type = "lod_reset" x = np.random.random((10, 20)).astype("float32") lod = [[0, 3, 5, 10]] target_lod_0 = [0, 7, 10] self.inputs = {'X': (x, lod)} self.attrs = {'target_lod': target_lod_0} self.outputs = {'Out': (x, [target_lod_0])} def test_check_output(self): self.check_output() def test_check_grad(self): self.check_grad(["X"], "Out") class TestLodResetOpByInput(OpTest): def setUp(self): self.op_type = "lod_reset" x = np.random.random((10, 20)).astype("float32") lod = [[0, 3, 5, 10]] target_lod_0 = [0, 4, 7, 10] self.inputs = { 'X': (x, lod), 'TargetLoD':
np.array([target_lod_0])
numpy.array
# -*- coding: utf-8 -*- # ---------------------------------------------------------------------- # Copyright (c) 2021 # # See the LICENSE file for details # see the AUTHORS file for authors # ---------------------------------------------------------------------- #-------------------- # System wide imports # ------------------- import os import os.path import logging import statistics # --------------------- # Third party libraries # --------------------- import PIL import numpy as np import matplotlib.pyplot as plt import sklearn.cluster as cluster from matplotlib.widgets import Button #-------------- # local imports # ------------- from streetool.utils import get_image, paging # ----------------------- # Module global variables # ----------------------- log = logging.getLogger("streetoool") # ---------------- # Module constants # ---------------- class Cycler: def __init__(self, connection, subject_list, **kwargs): self.subject = [] if subject_list is None else subject_list self.i = 0 self.N = len(self.subject) self.conn = connection self.epsilon = kwargs.get('epsilon',1) self.compute = kwargs.get('compute',False) self.fix = kwargs.get('fix',False) self.reset() if self.compute: self.one_compute_step(0) else: self.one_database_step(0) def reset(self): self.fig, self.axe = plt.subplots() # The dimensions are [left, bottom, width, height] # All quantities are in fractions of figure width and height. axnext = self.fig.add_axes([0.90, 0.01, 0.095, 0.050]) self.bnext = Button(axnext, 'Next') self.bnext.on_clicked(self.next) axprev = self.fig.add_axes([0.79, 0.01, 0.095, 0.050]) self.bprev = Button(axprev, 'Previous') self.bprev.on_clicked(self.prev) self.axe.set_xlabel("X, pixels") self.axe.set_ylabel("Y, pixels") self.axim = None self.sca = list() self.txt = list() self.prev_extent = dict() def load(self, i): subject_id = self.subject[i][0] log.info(f"Searching for image whose subject id is {subject_id}") filename, image_id = get_image(self.conn, subject_id) if not filename: raise Exception(f"No image for subject-id {subject_id}") img = PIL.Image.open(filename) width, height = img.size if self.axim is None: self.axim = self.axe.imshow(img, alpha=0.5, zorder=-1, aspect='equal', origin='upper') self.prev_extent[(width,height)] = self.axim.get_extent() else: self.axim.set_data(img) ext = self.prev_extent.get((width,height), None) # Swap exteent components when current image is rotated respect to the previous if ext is None: ext = list(self.prev_extent[(height,width)]) tmp = ext[1] ext[1] = ext[2] ext[2] = tmp self.prev_extent[(width,height)] = tuple(ext) self.axim.set_extent(ext) self.axe.relim() self.axe.autoscale_view() return subject_id, image_id def update(self, i): # remove whats drawn in the scatter plots for sca in self.sca: sca.remove() self.sca = list() for txt in self.txt: txt.remove() self.txt = list() if self.compute: self.one_compute_step(i) else: self.one_database_step(i) self.fig.canvas.draw_idle() self.fig.canvas.flush_events() def next(self, event): self.i = (self.i +1) % self.N self.update(self.i) def prev(self, event): self.i = (self.i -1 + self.N) % self.N self.update(self.i) def one_database_step(self, i): subject_id, image_id = self.load(i) self.axe.set_title(f'Subject {subject_id}\nEC5 Id {image_id}\nLight Sources from the database') cursor = self.conn.cursor() cursor.execute(''' SELECT DISTINCT cluster_id FROM spectra_classification_v WHERE subject_id = :subject_id ORDER BY cluster_id ASC ''', {'subject_id': subject_id} ) cluster_ids = cursor.fetchall() for (cluster_id,) in cluster_ids: cursor2 = self.conn.cursor() cursor2.execute(''' SELECT source_x, source_y, epsilon FROM spectra_classification_v WHERE subject_id = :subject_id AND cluster_id = :cluster_id ''', {'subject_id': subject_id, 'cluster_id': cluster_id} ) coordinates = cursor2.fetchall() N_Classifications = len(coordinates) log.info(f"Subject {subject_id}: cluster_id {cluster_id} has {N_Classifications} data points") X, Y, EPS = tuple(zip(*coordinates)) Xc = statistics.mean(X); Yc = statistics.mean(Y); sca = self.axe.scatter(X, Y, marker='o', zorder=1) self.sca.append(sca) txt = self.axe.text(Xc+EPS[0], Yc+EPS[0], cluster_id, fontsize=9, zorder=2) self.txt.append(txt) def one_compute_step(self, i): fix = self.fix epsilon = self.epsilon subject_id, image_id = self.load(i) self.axe.set_title(f'Subject {subject_id}\nEC5 Id {image_id}\nDetected light sources by DBSCAN (\u03B5 = {epsilon} px)') cursor = self.conn.cursor() cursor.execute(''' SELECT source_x, source_y FROM spectra_classification_v WHERE subject_id = :subject_id ''', {'subject_id': subject_id} ) coordinates = cursor.fetchall() N_Classifications = len(coordinates) coordinates = np.array(coordinates) model = cluster.DBSCAN(eps=epsilon, min_samples=2) # Fit the model and predict clusters yhat = model.fit_predict(coordinates) # retrieve unique clusters clusters = np.unique(yhat) log.info(f"Subject {subject_id}: {len(clusters)} clusters from {N_Classifications} classifications, ids: {clusters}") for cl in clusters: # get row indexes for samples with this cluster row_ix =
np.where(yhat == cl)
numpy.where
""" .. module:: constraints :platform: Unix :synopsis: This module implements the usual statistical tools you need to calculate cosmological parameters confidence intervals .. moduleauthor:: <NAME> <<EMAIL>> """ from __future__ import division,print_function,with_statement from operator import mul from functools import reduce import sys if sys.version_info.major>=3: import _pickle as pickle else: import cPickle as pickle ######################################################### import numpy as np from numpy.linalg import solve,inv from scipy.interpolate import interp1d,Rbf from emcee.ensemble import _function_wrapper ########################################################################### ###########Hack to make scipy interpolate objects pickleable############### ########################################################################### class _interpolate_wrapper(object): def __init__(self,f,args,kwargs): self.f = f self.args = args self.kwargs = kwargs def __call__(self): try: return self.f(*self.args,**self.kwargs) except: import traceback print("lenstools: Exception while building the interpolators") print(" exception:") traceback.print_exc() raise ################################################################################################# #############################Principal Component Analysis handler################################ ################################################################################################# def pca_transform(data,pca,n_components): assert n_components<=pca.components_.shape[0] return pca.transform(data).T[:n_components].T class PCA(object): """ Handles principal component analysis """ def fit(self,data): #Scale the data to zero mean and unit variance self._pca_mean = data.mean(0) self._pca_std = data.std(0) self._data_scaled = data.copy() self._data_scaled -= self._pca_mean[None] self._data_scaled /= self._pca_std[None] self._data_scaled /= np.sqrt(self._data_scaled.shape[0] - 1) #Perform singular value decomposition left,eigenvalues,right = np.linalg.svd(self._data_scaled,full_matrices=False) #Assign eigenvalues and eigenvectors as attributes self.components_ = right self.explained_variance_ = eigenvalues**2 @property def eigenvalues(self): return self.explained_variance_ @property def eigenvectors(self): return self.components_*np.sqrt(self._data_scaled.shape[0] - 1)*self._pca_std[None] + self._pca_mean[None] def transform(self,X): #Cast X to the right dimensions if len(X.shape)==1: X_copy = X.copy()[None] else: X_copy = X.copy() #Subtract mean and scale by variance X_copy -= self._pca_mean[None] X_copy /= (self._pca_std[None]*np.sqrt(self._data_scaled.shape[0] - 1)) #Compute the projection via dot product components = X_copy.dot(self.components_.transpose()) if len(X.shape)==1: return components[0] else: return components def inverse_transform(self,X,n_components=None): #Cast X to the right dimensions if len(X.shape)==1: X_copy = X.copy()[None] else: X_copy = X.copy() #Use the PCA basis vectors to project back to the original space if n_components is not None: basis_vectors = self.components_[:n_components] X_copy = X_copy[:,:n_components] else: basis_vectors = self.components_ #Original space original_components = X_copy.dot(basis_vectors) #De-whitening original_components *= (self._pca_std[None]*np.sqrt(self._data_scaled.shape[0] - 1)) original_components += self._pca_mean[None] if original_components.shape[0]==1: return original_components[0] else: return original_components def select_components(self,X,n_components): all_components = self.transform(X) return self.inverse_transform(all_components,n_components=n_components) ######################################################### #############Default Gaussian data likelihood############ ######################################################### def gaussian_likelihood(chi2,norm=1.0): return norm*np.exp(-0.5*chi2) ###################################################################### ##########Default chi2 calculation with the sandwich product########## ###################################################################### def chi2(parameters,*args,**kwargs): model_feature = _predict(parameters,kwargs["num_bins"],kwargs["interpolator"]) inverse_covariance = kwargs["inverse_covariance"] if model_feature.ndim == 1: observed_feature = kwargs["observed_feature"] else: observed_feature = kwargs["observed_feature"][np.newaxis,:] inverse_covariance_dot = np.dot(observed_feature - model_feature,inverse_covariance) return ((observed_feature - model_feature) * inverse_covariance_dot).sum(-1) ####################################################################### #############Feature prediction wrapper################################ ####################################################################### def _predict(parameters,num_bins,interpolator): #For each feature bin, compute its interpolated value if parameters.ndim == 1: interpolated_feature = np.zeros(num_bins) for n in range(num_bins): interpolated_feature[n] = interpolator[n]()(*parameters) else: interpolated_feature = np.zeros((parameters.shape[0],num_bins)) for n in range(num_bins): interpolated_feature[:,n] = interpolator[n]()(*parameters.transpose()) return interpolated_feature ############################################## ###########Analysis base class################ ############################################## class Analysis(object): """ The base class of this module; the idea in weak lensing analysis is that one has a set of simulated data, that serves as training model, and then uses that set to fit the observations for the best model parameters. :param parameter_set: the points in parameter space that the simulated data cover; the first axis refers to the model, the second to the number of parameters :type parameter_set: array :param training_set: the measured feature in each model; the first axis refers to the model, the others to the feature indices (or bins) :type training_set: array :param observed_set: the measured feature in the data, should be a one dimensional array :type observed_set: array """ _analysis_type = None def __init__(self,parameter_set=None,training_set=None): assert self._analysis_type is not None,"Don't instantiate this class directly, use one of its subclasses!" if parameter_set is not None and training_set is not None: assert parameter_set.shape[0] == training_set.shape[0],"There should be one feature for each of the simulated models!" self.parameter_set = parameter_set self.training_set = training_set def __repr__(self): try: return "{0} type analysis, based on {1} models spanning a {2}-dimensional parameter space ({3} bins)".format(self._analysis_type,self.parameter_set.shape[0],self.parameter_set.shape[1],self.training_set.shape[1]) except AttributeError: return "{0} type analysis, no models in it yet!".format(self._analysis_type) def __mul__(self,other): assert isinstance(other,self.__class__) assert (self.parameter_set==other.parameter_set).all() new_analysis = self.__class__(parameter_set=self.parameter_set.copy(),training_set=np.hstack((self.training_set,other.training_set))) return new_analysis def add_feature_label(self,feature_label): """ Add a feature label to the current analysis, i.e. a set of multipole moments if the feature is the power spectrum, or a set of thresholds if the feature is a PDF, etc... :param feature_label: the feature label to add, must have the same shape as the training set :type feature_label: array. """ assert feature_label.shape == self.training_set.shape[1:],"Feature label must have the same shape as the simulated feature!" self.feature_label = feature_label def add_model(self,parameters,feature): """ Add a model to the training set of the current analysis :param parameters: parameter set of the new model :type parameters: array :param feature: measured feature of the new model :type feature: array """ #If the analysis doesn't have any models, add the first, otherwise simply vstack them if self.parameter_set is None: assert self.training_set is None self.parameter_set = parameters.copy()[np.newaxis,:] self.training_set = feature.copy()[np.newaxis,:] else: #Check for input valudity assert parameters.shape[0] == self.parameter_set.shape[1] assert feature.shape == self.training_set.shape[1:] self.parameter_set = np.vstack((self.parameter_set,parameters)) self.training_set = np.vstack((self.training_set,feature)) def remove_model(self,model_list): """ Remove one or more models from the Analysis instance :param model_list: list of the indices of the models to remove (0 indicates the first model) :type model_list: int. or list of int. """ try: self.parameter_set = np.delete(self.parameter_set,model_list,axis=0) self.training_set = np.delete(self.training_set,model_list,axis=0) except: print("No models to delete or indices are out of bounds!") def reparametrize(self,formatter,*args,**kwargs): """ Reparametrize the parameter set of the analysis by calling the formatter handle on the current parameter set (can be used to enlarge/shrink/relabel the parameter set) :param formatter: formatter function called on the current parameter_set (args and kwargs are passed to it) :type formatter: callable """ self.parameter_set = formatter(self.parameter_set,*args,**kwargs) assert self.parameter_set.shape[0]==self.training_set.shape[0],"The reparametrization messed up the number of points in parameter space!!" def transform(self,transformation,inplace=False,**kwargs): """ Allows a general transformation on the training_set of the analysis by calling an arbitrary transformation function :param transformation: callback function called on the training_set :type transformation: callable :param inplace: if True the transformation is performed in place, otherwise a new Analysis instance is created :type inplace: bool. :param kwargs: the keyword arguments are passed to the transformation callable :type kwargs: dict. """ transformed_training_set = transformation(self.training_set,**kwargs) assert self.parameter_set.shape[0]==transformed_training_set.shape[0],"The reparametrization messed up the number of training features!!" if inplace: self.training_set = transformed_training_set else: return self.__class__(parameter_set=self.parameter_set.copy(),training_set=transformed_training_set) def principalComponents(self): """ Computes the principal components of the training_set :returns: pcaHandler instance """ pca = PCA() pca.fit(self.training_set) return pca def find(self,parameters,rtol=1.0e-05): """ Finds the index of the training model that has the specified combination of parameters :param parameters: the parameters of the model to find :type parameters: array. :param rtol: tolerance of the search (must be less than 1) :type rtol: float. :returns: array of int. with the indices of the corresponding models """ assert len(parameters)==self.parameter_set.shape[1] search_result = np.all(np.isclose(self.parameter_set,parameters,rtol=rtol),axis=1) return np.where(search_result==True)[0] def save(self,filename): """ Save the current Analysis instance as a pickled binary file for future reuse as an emulator; useful after you trained the emulator with a simulated feature set and you want to reuse it in the future :param filename: Name of the file to which you want to save the emulator, or file object :type filename: str. or file object """ assert type(filename) in [str,file],"filename must be a string or a file object!" if type(filename)==str: with open(filename,"wb") as dumpfile: pickle.dump(self,dumpfile) else: pickle.dump(self,filename) @classmethod def load(cls,filename): """ Unpickle a previously pickled instance: be sure the file you are unpickling comes from a trusted source, this operation is potentially dangerous for your computer! :param filename: Name of the file from which you want to load the instance, or file object :type filename: str. or file object """ assert type(filename) in [str,file],"filename must be a string or a file object!" if type(filename)==str: with open(filename,"rb") as dumpfile: emulator = pickle.load(dumpfile) else: emulator = pickle.load(filename) assert isinstance(emulator,cls) return emulator ################################################### #############Fisher matrix analysis################ ################################################### class FisherAnalysis(Analysis): _analysis_type = "Fisher" _fiducial = 0 """ The class handler of a Fisher matrix analysis, inherits from the base class Analysis """ def add_model(self,parameters,feature): super(FisherAnalysis,self).add_model(parameters,feature) try: self.check() except Exception as e: self.remove_model(-1) raise RuntimeError(e) def set_fiducial(self,n): """ Sets the fiducial model (with respect to which to compute the derivatives), default is 0 (i.e. self.parameter_set[0]) :param n: the parameter set you want to use as fiducial :type n: int. """ assert n < self.parameter_set.shape[0],"There are less than {0} models in your analysis".format(n+1) self._fiducial = n @property def fiducial(self): return self.training_set[self._fiducial] @property def _variations(self): """ Checks the parameter variations with respect to the fiducial cosmology :returns: bool array (True if the parameter is varied, False otherwise) """ return self.parameter_set!=self.parameter_set[self._fiducial] @property def variations(self): """ Checks the parameter variations with respect to the fiducial cosmology :returns: iterable with the positions of the variations """ for n,b in enumerate(self._variations.sum(1)): if b: yield n def check(self): """ Asserts that the parameters are varied one at a time, and that a parameter is not varied more than once :raises: AssertionError """ assert (self._variations.sum(1)<2).all(),"You can vary only a parameter at a time!" #Check how many variations are there for each parameter num_par_variations = self._variations.sum(0) if (num_par_variations<2).all(): return 0 else: return 1 def where(self,par=None): """ Finds the locations of the varied parameters in the parameter set :returns: dict. with the locations of the variations, for each parameter """ loc = dict() v = np.where(self._variations==1) #Decide if keys are lists or simple numbers if self.check(): for n in range(self.parameter_set.shape[1]): loc[n] = list() for n in range(len(v[0])): loc[v[1][n]].append(v[0][n]) else: for n in range(len(v[0])): loc[v[1][n]] = v[0][n] if par is None: return loc else: return loc[par] @property def varied(self): """ Returns the indices of the parameters that are varied :returns: list with the indices of the varied parameters """ loc = self.where().keys() loc.sort() return loc def compute_derivatives(self): """ Computes the feature derivatives with respect to the parameter sets using one step finite differences; the derivatives are computed with respect to the fiducial parameter set :returns: array of shape (p,N), where N is the feature dimension and p is the number of varied parameters """ assert self.parameter_set.shape[0] > 1,"You need at least 2 models to proceed in a Fisher Analysis!" assert self.check()==0,"Finite differences implemented only at first order! Cannot compute derivatives" #Find the varied parameters and their locations loc_varied = self.where() par_varied = loc_varied.keys() par_varied.sort() #Allocate space for the derivatives derivatives = np.zeros((len(par_varied),)+self.training_set.shape[1:]) #cycle to parameters to calculate derivatives for n,p in enumerate(par_varied): #Calculate the finite difference derivative with respect to this parameter derivatives[n] = (self.training_set[loc_varied[p]] - self.training_set[self._fiducial]) / (self.parameter_set[loc_varied[p],p] - self.parameter_set[self._fiducial,p]) #set the derivatives attribute and return the result self.derivatives = derivatives return derivatives ############################################################################################################################# def observables2parameters(self,features_covariance=None): """ Computes the conversion matrix M that allows to match a feature vector V to its best fit parameters P, in the sense P = P[fiducial] + MV :param features_covariance: covariance matrix of the simulated features, must be provided! :type features_covariance: 2 dimensional array (or 1 dimensional if diagonal) :returns: the (p,N) conversion matrix :rtype: array """ #Safety checks assert features_covariance is not None,"No science without the covariance matrix, you must provide one!" assert features_covariance.shape in [self.training_set.shape[-1:],self.training_set.shape[-1:]*2] #Check if derivatives are already computed if not hasattr(self,"derivatives"): self.compute_derivatives() #Linear algebra manipulations (parameters = M x features) if features_covariance.shape == self.training_set.shape[1:] * 2: Y = solve(features_covariance,self.derivatives.transpose()) else: Y = (1/features_covariance[:,np.newaxis]) * self.derivatives.transpose() XY = np.dot(self.derivatives,Y) return solve(XY,Y.transpose()) ############################################################################################################################# def chi2(self,observed_feature,features_covariance): """ Computes the chi2 between an observed feature and the fiducial feature, using the provided covariance :param observed_feature: observed feature to fit, its last dimension must have the same shape as self.training_set[0] :type observed_feature: array :param features_covariance: covariance matrix of the simulated features, must be provided for a correct fit! :type features_covariance: 2 dimensional array (or 1 dimensional if diagonal) :returns: chi2 of the comparison :rtype: float. """ assert features_covariance is not None,"No science without the covariance matrix, you must provide one!" #Cast the observed feature in suitable shape if len(observed_feature.shape)==1: observed_feature = observed_feature[None] single = True else: single = False #Check for correct shape of input assert observed_feature.shape[-1:]==self.training_set.shape[-1:] assert features_covariance.shape in [self.training_set.shape[-1:],self.training_set.shape[-1:]*2] #Compute the difference difference = observed_feature - self.fiducial[None] #Compute the chi2 if features_covariance.shape==self.training_set.shape[-1:]: result = ((difference**2)/features_covariance[None]).sum(-1) else: result = (difference * solve(features_covariance,difference.transpose()).transpose()).sum(-1) #Return the result if single: return result[0] else: return result ############################################################################################################################# def fit(self,observed_feature,features_covariance): """ Maximizes the gaussian likelihood on which the Fisher matrix formalism is based, and returns the best fit for the parameters given the observed feature :param observed_feature: observed feature to fit, must have the same shape as self.training_set[0] :type observed_feature: array :param features_covariance: covariance matrix of the simulated features, must be provided for a correct fit! :type features_covariance: 2 dimensional array (or 1 dimensional if assumed diagonal) :returns: array with the best fitted parameter values """ assert features_covariance is not None,"No science without the covariance matrix, you must provide one!" #Check for correct shape of input assert observed_feature.shape==self.training_set.shape[1:] assert features_covariance.shape==observed_feature.shape * 2 or features_covariance.shape==observed_feature.shape #If derivatives are not computed, compute them if not hasattr(self,"derivatives"): self.compute_derivatives() M = self.observables2parameters(features_covariance) #Compute difference in parameters (with respect to the fiducial model) dP = np.dot(M,observed_feature - self.training_set[self._fiducial]) #Return the actual best fit return self.parameter_set[self._fiducial,self.varied] + dP def classify(self,observed_feature,features_covariance,labels=range(2),confusion=False): """ Performs a Fisher classification of the observed feature, choosing the most probable label based on the value of the chi2 :param observed_feature: observed feature to fit, the last dimenstion must have the same shape as self.training_set[0] :type observed_feature: array :param features_covariance: covariance matrix of the simulated features, must be provided for a correct classification! :type features_covariance: 2 dimensional array (or 1 dimensional if assumed diagonal) :param labels: labels of the classification, must be the indices of the available classes (from 0 to training_set.shape[0]) :type labels: iterable :param confusion: if True, an array with the label percentage occurrences is returned; if False an array of labels is returned :type confusion: bool. :returns: array with the labels resulting from the classification :rtype: int. """ fiducial_original = self._fiducial #Compute all the chi squared values, for each observed feature and each label all_chi2 = list() for l in labels: self.set_fiducial(l) all_chi2.append(self.chi2(observed_feature,features_covariance)) self.set_fiducial(fiducial_original) #Cast the list into an array all_chi2 =
np.array(all_chi2)
numpy.array
__authors__ = ["<NAME> - ESRF ISDD Advanced Analysis and Modelling"] __license__ = "MIT" __date__ = "30-08-2018" """ Wiggler code: computes wiggler radiation distributions and samples rays according to them. Fully replaces and upgrades the shadow3 wiggler model. The radiation is calculating using sr-xraylib """ import numpy from srxraylib.util.inverse_method_sampler import Sampler1D from srxraylib.sources.srfunc import wiggler_trajectory, wiggler_spectrum, wiggler_cdf, sync_f import scipy from scipy.interpolate import interp1d import scipy.constants as codata from shadow4.sources.s4_electron_beam import S4ElectronBeam from shadow4.sources.s4_light_source import S4LightSource from shadow4.sources.wiggler.s4_wiggler import S4Wiggler from shadow4.beam.beam import Beam # This is similar to sync_f in srxraylib but faster def sync_f_sigma_and_pi(rAngle, rEnergy): r""" angular dependency of synchrotron radiation emission NAME: sync_f_sigma_and_pi PURPOSE: Calculates the function used for calculating the angular dependence of synchrotron radiation. CATEGORY: Mathematics. CALLING SEQUENCE: Result = sync_f_sigma_and_pi(rAngle,rEnergy) INPUTS: rAngle: (array) the reduced angle, i.e., angle[rads]*Gamma. It can be a scalar or a vector. rEnergy: (scalar) a value for the reduced photon energy, i.e., energy/critical_energy. KEYWORD PARAMETERS: OUTPUTS: returns the value of the sync_f for sigma and pi polarizations The result is an array of the same dimension as rAngle. PROCEDURE: The number of emitted photons versus vertical angle Psi is proportional to sync_f, which value is given by the formulas in the references. References: <NAME>, "Spectra and optics of synchrotron radiation" BNL 50522 report (1976) <NAME> and <NAME>, Synchrotron Radiation, Akademik-Verlag, Berlin, 1968 OUTPUTS: returns the value of the sync_f function PROCEDURE: Uses BeselK() function MODIFICATION HISTORY: Written by: <NAME>, <EMAIL>, 2002-05-23 2002-07-12 <EMAIL> adds circular polarization term for wavelength integrated spectrum (S&T formula 5.25) 2012-02-08 <EMAIL>: python version 2019-10-31 <EMAIL> speed-up changes for shadow4 """ # # ; For 11 in Pag 6 in Green 1975 # ji = numpy.sqrt((1.0 + rAngle**2)**3) * rEnergy / 2.0 efe_sigma = scipy.special.kv(2.0 / 3.0, ji) * (1.0 + rAngle**2) efe_pi = rAngle * scipy.special.kv(1.0 / 3.0, ji) / numpy.sqrt(1.0 + rAngle ** 2) * (1.0 + rAngle ** 2) return efe_sigma**2,efe_pi**2 class S4WigglerLightSource(S4LightSource): def __init__(self, name="Undefined", electron_beam=None, magnetic_structure=None): super().__init__(name, electron_beam=electron_beam if not electron_beam is None else S4ElectronBeam(), magnetic_structure=magnetic_structure if not magnetic_structure is None else S4Wiggler()) # results of calculations self.__result_trajectory = None self.__result_parameters = None self.__result_cdf = None def get_trajectory(self): return self.__result_trajectory, self.__result_parameters def __calculate_radiation(self): wiggler = self.get_magnetic_structure() electron_beam = self.get_electron_beam() if wiggler._magnetic_field_periodic == 1: (traj, pars) = wiggler_trajectory(b_from=0, inData="", nPer=wiggler.number_of_periods(), nTrajPoints=wiggler._NG_J, ener_gev=electron_beam._energy_in_GeV, per=wiggler.period_length(), kValue=wiggler.K_vertical(), trajFile="",) elif wiggler._magnetic_field_periodic == 0: print(">>>>>>>>>>>>>>>>>>>>>>", "shift_x_flag = ",wiggler._shift_x_flag, "shift_x_value = ",wiggler._shift_x_value, "shift_betax_flag = ",wiggler._shift_betax_flag, "shift_betax_value = ",wiggler._shift_betax_value ) (traj, pars) = wiggler_trajectory(b_from=1, inData=wiggler._file_with_magnetic_field, nPer=1, nTrajPoints=wiggler._NG_J, ener_gev=electron_beam._energy_in_GeV, # per=self.syned_wiggler.period_length(), # kValue=self.syned_wiggler.K_vertical(), trajFile="", shift_x_flag = wiggler._shift_x_flag , shift_x_value = wiggler._shift_x_value , shift_betax_flag = wiggler._shift_betax_flag , shift_betax_value = wiggler._shift_betax_value,) self.__result_trajectory = traj self.__result_parameters = pars # print(">>>>>>>>>> traj pars: ",traj.shape,pars) # # plot(traj[1, :], traj[0, :], xtitle="Y", ytitle="X") # plot(traj[1, :], traj[3, :], xtitle="Y", ytitle="BetaX") # plot(traj[1, :], traj[6, :], xtitle="Y", ytitle="Curvature") # plot(traj[1, :], traj[7, :], xtitle="Y", ytitle="B") # traj[0,ii] = yx[i] # traj[1,ii] = yy[i]+j * per - start_len # traj[2,ii] = 0.0 # traj[3,ii] = betax[i] # traj[4,ii] = betay[i] # traj[5,ii] = 0.0 # traj[6,ii] = curv[i] # traj[7,ii] = bz[i] # # calculate cdf and write file for Shadow/Source # print(">>>>>>>>>>>>>>>>>>>> wiggler._EMIN,wiggler._EMAX,wiggler._NG_E",wiggler._EMIN,wiggler._EMAX,wiggler._NG_E) self.__result_cdf = wiggler_cdf(self.__result_trajectory, enerMin=wiggler._EMIN, enerMax=wiggler._EMAX, enerPoints=wiggler._NG_E, outFile="tmp.cdf", elliptical=False) def __calculate_rays(self,user_unit_to_m=1.0,F_COHER=0,NRAYS=5000,SEED=123456,EPSI_DX=0.0,EPSI_DZ=0.0, psi_interval_in_units_one_over_gamma=None, psi_interval_number_of_points=1001, verbose=True): """ compute the rays in SHADOW matrix (shape (npoints,18) ) :param F_COHER: set this flag for coherent beam :param user_unit_to_m: default 1.0 (m) :return: rays, a numpy.array((npoits,18)) """ if self.__result_cdf is None: self.__calculate_radiation() if verbose: print(">>> Results of calculate_radiation") print(">>> trajectory.shape: ", self.__result_trajectory.shape) print(">>> cdf: ", self.__result_cdf.keys()) wiggler = self.get_magnetic_structure() syned_electron_beam = self.get_electron_beam() sampled_photon_energy,sampled_theta,sampled_phi = self._sample_photon_energy_theta_and_phi(NRAYS) if verbose: print(">>> sampled sampled_photon_energy,sampled_theta,sampled_phi: ",sampled_photon_energy,sampled_theta,sampled_phi) if SEED != 0: numpy.random.seed(SEED) sigmas = syned_electron_beam.get_sigmas_all() rays = numpy.zeros((NRAYS,18)) # # sample sizes (cols 1-3) # # if wiggler._FLAG_EMITTANCE: if numpy.array(numpy.abs(sigmas)).sum() == 0: wiggler._FLAG_EMITTANCE = False if wiggler._FLAG_EMITTANCE: x_electron = numpy.random.normal(loc=0.0,scale=sigmas[0],size=NRAYS) y_electron = 0.0 z_electron = numpy.random.normal(loc=0.0,scale=sigmas[2],size=NRAYS) else: x_electron = 0.0 y_electron = 0.0 z_electron = 0.0 # traj[0,ii] = yx[i] # traj[1,ii] = yy[i]+j * per - start_len # traj[2,ii] = 0.0 # traj[3,ii] = betax[i] # traj[4,ii] = betay[i] # traj[5,ii] = 0.0 # traj[6,ii] = curv[i] # traj[7,ii] = bz[i] PATH_STEP = self.__result_cdf["step"] X_TRAJ = self.__result_cdf["x"] Y_TRAJ = self.__result_cdf["y"] SEEDIN = self.__result_cdf["cdf"] ANGLE = self.__result_cdf["angle"] CURV = self.__result_cdf["curv"] EPSI_PATH = numpy.arange(CURV.size) * PATH_STEP # self._result_trajectory[7,:] # ! C We define the 5 arrays: # ! C Y_X(5,N) ---> X(Y) # ! C Y_XPRI(5,N) ---> X'(Y) # ! C Y_CURV(5,N) ---> CURV(Y) # ! C Y_PATH(5,N) ---> PATH(Y) # ! C F(1,N) contains the array of Y values where the nodes are located. # CALL PIECESPL(SEED_Y, Y_TEMP, NP_SY, IER) # CALL CUBSPL (Y_X, X_TEMP, NP_TRAJ, IER) # CALL CUBSPL (Y_Z, Z_TEMP, NP_TRAJ, IER) # CALL CUBSPL (Y_XPRI, ANG_TEMP, NP_TRAJ, IER) # CALL CUBSPL (Y_ZPRI, ANG2_TEMP, NP_TRAJ, IER) # CALL CUBSPL (Y_CURV, C_TEMP, NP_TRAJ, IER) # CALL CUBSPL (Y_PATH, P_TEMP, NP_TRAJ, IER) SEED_Y = interp1d(SEEDIN,Y_TRAJ,kind='linear') Y_X = interp1d(Y_TRAJ,X_TRAJ,kind='cubic') Y_XPRI = interp1d(Y_TRAJ,ANGLE,kind='cubic') Y_CURV = interp1d(Y_TRAJ,CURV,kind='cubic') Y_PATH = interp1d(Y_TRAJ,EPSI_PATH,kind='cubic') # ! C+++ # ! C Compute the path length to the middle (origin) of the wiggler. # ! C We need to know the "center" of the wiggler coordinate. # ! C input: Y_PATH ---> spline array # ! C NP_TRAJ ---> # of points # ! C Y_TRAJ ---> calculation point (ind. variable) # ! C output: PATH0 ---> value of Y_PATH at X = Y_TRAJ. If # ! C Y_TRAJ = 0, then PATH0 = 1/2 length # ! C of trajectory. # ! C+++ Y_TRAJ = 0.0 # CALL SPL_INT (Y_PATH, NP_TRAJ, Y_TRAJ, PATH0, IER) PATH0 = Y_PATH(Y_TRAJ) # ! C # ! C These flags are set because of the original program structure. # ! C # F_PHOT = 0 # F_COLOR = 3 # FSOUR = 3 # FDISTR = 4 ws_ev,ws_f,tmp = wiggler_spectrum(self.__result_trajectory, enerMin=wiggler._EMIN, enerMax=wiggler._EMAX, nPoints=500, # per=self.syned_wiggler.period_length(), electronCurrent=syned_electron_beam._current, outFile="", elliptical=False) ws_flux_per_ev = ws_f / (ws_ev*1e-3) samplerE = Sampler1D(ws_flux_per_ev,ws_ev) sampled_energies,h,h_center = samplerE.get_n_sampled_points_and_histogram(NRAYS) ############################################### gamma = syned_electron_beam.gamma() m2ev = codata.c * codata.h / codata.e TOANGS = m2ev * 1e10 ##################################################### RAD_MIN = 1.0 / numpy.abs(self.__result_cdf["curv"]).max() critical_energy = TOANGS * 3.0 * numpy.power(gamma, 3) / 4.0 / numpy.pi / 1.0e10 * (1.0 / RAD_MIN) if psi_interval_in_units_one_over_gamma is None: c = numpy.array([-0.3600382, 0.11188709]) # see file fit_psi_interval.py # x = numpy.log10(self._EMIN / critical_energy) x = numpy.log10(wiggler._EMIN / (4 * critical_energy)) # the wiggler that does not have an unique # Ec. To be safe, I use 4 times the # Ec vale to make the interval wider than for the BM y_fit = c[1] + c[0] * x psi_interval_in_units_one_over_gamma = 10 ** y_fit # this is the semi interval psi_interval_in_units_one_over_gamma *= 4 # doubled interval if psi_interval_in_units_one_over_gamma < 2: psi_interval_in_units_one_over_gamma = 2 if verbose: print(">>> psi_interval_in_units_one_over_gamma: ",psi_interval_in_units_one_over_gamma) angle_array_mrad = numpy.linspace(-0.5*psi_interval_in_units_one_over_gamma * 1e3 / gamma, 0.5*psi_interval_in_units_one_over_gamma * 1e3 / gamma, psi_interval_number_of_points) # a = numpy.linspace(-0.6,0.6,150) a = angle_array_mrad ##################################################################### a8 = 1.0 hdiv_mrad = 1.0 # i_a = self.syned_electron_beam._current # # fm = sync_f(a*self.syned_electron_beam.gamma()/1e3,eene,polarization=0) * \ # numpy.power(eene,2)*a8*i_a*hdiv_mrad*numpy.power(self.syned_electron_beam._energy_in_GeV,2) # # plot(a,fm,title="sync_f") # # samplerAng = Sampler1D(fm,a) # # sampled_theta,hx,h = samplerAng.get_n_sampled_points_and_histogram(10*NRAYS) # plot(h,hx) for itik in range(NRAYS): # ARG_Y = GRID(2,ITIK) # CALL SPL_INT (SEED_Y, NP_SY, ARG_Y, Y_TRAJ, IER) arg_y = numpy.random.random() # ARG_Y[itik] Y_TRAJ = SEED_Y(arg_y) # ! <EMAIL> 2014-05-19 # ! in wiggler some problems arise because spl_int # ! does not return a Y value in the correct range. # ! In those cases, we make a linear interpolation instead. # if ((y_traj.le.y_temp(1)).or.(y_traj.gt.y_temp(NP_SY))) then # y_traj_old = y_traj # CALL LIN_INT (SEED_Y, NP_SY, ARG_Y, Y_TRAJ, IER) # print*,'SOURCESYNC: bad y_traj from SPL_INT, corrected with LIN_SPL: ',y_traj_old,'=>',y_traj # endif # # CALL SPL_INT (Y_X, NP_TRAJ, Y_TRAJ, X_TRAJ, IER) # CALL SPL_INT (Y_XPRI, NP_TRAJ, Y_TRAJ, ANGLE, IER) # CALL SPL_INT (Y_CURV, NP_TRAJ, Y_TRAJ, CURV, IER) # CALL SPL_INT (Y_PATH, NP_TRAJ, Y_TRAJ, EPSI_PATH, IER) # END IF X_TRAJ = Y_X(Y_TRAJ) ANGLE = Y_XPRI(Y_TRAJ) CURV = Y_CURV(Y_TRAJ) EPSI_PATH = Y_PATH(Y_TRAJ) # print("\n>>><<<",arg_y,Y_TRAJ,X_TRAJ,ANGLE,CURV,EPSI_PATH) # EPSI_PATH = EPSI_PATH - PATH0 ! now refer to wiggler's origin # IF (CURV.LT.0) THEN # POL_ANGLE = 90.0D0 ! instant orbit is CW # ELSE # POL_ANGLE = -90.0D0 ! CCW # END IF # IF (CURV.EQ.0) THEN # R_MAGNET = 1.0D+20 # ELSE # R_MAGNET = ABS(1.0D0/CURV) # END IF # POL_ANGLE = TORAD*POL_ANGLE EPSI_PATH = EPSI_PATH - PATH0 # now refer to wiggler's origin if CURV < 0: POL_ANGLE = 90.0 # instant orbit is CW else: POL_ANGLE = -90.0 # CCW if CURV == 0.0: R_MAGNET = 1.0e20 else: R_MAGNET = numpy.abs(1.0/CURV) POL_ANGLE = POL_ANGLE * numpy.pi / 180.0 # ! C # ! C Compute the actual distance (EPSI_W*) from the orbital focus # ! C EPSI_WX = EPSI_DX + EPSI_PATH EPSI_WZ = EPSI_DZ + EPSI_PATH # ! BUG <EMAIL> found that these routine does not make the # ! calculation correctly. Changed to new one BINORMAL # !CALL GAUSS (SIGMAX, EPSI_X, EPSI_WX, XXX, E_BEAM(1), istar1) # !CALL GAUSS (SIGMAZ, EPSI_Z, EPSI_WZ, ZZZ, E_BEAM(3), istar1) # ! # ! calculation of the electrom beam moments at the current position # ! (sX,sZ) = (epsi_wx,epsi_ez): # ! <x2> = sX^2 + sigmaX^2 # ! <x x'> = sX sigmaXp^2 # ! <x'2> = sigmaXp^2 (same for Z) # # ! then calculate the new recalculated sigmas (rSigmas) and correlation rho of the # ! normal bivariate distribution at the point in the electron trajectory # ! rsigmaX = sqrt(<x2>) # ! rsigmaXp = sqrt(<x'2>) # ! rhoX = <x x'>/ (rsigmaX rsigmaXp) (same for Z) # # if (abs(sigmaX) .lt. 1e-15) then !no emittance # sigmaXp = 0.0d0 # XXX = 0.0 # E_BEAM(1) = 0.0 # else # sigmaXp = epsi_Xold/sigmaX ! true only at waist, use epsi_xOld as it has been redefined :( # rSigmaX = sqrt( (epsi_wX**2) * (sigmaXp**2) + sigmaX**2 ) # rSigmaXp = sigmaXp # if (abs(rSigmaX*rSigmaXp) .lt. 1e-15) then !no emittance # rhoX = 0.0 # else # rhoX = epsi_wx * sigmaXp**2 / (rSigmaX * rSigmaXp) # endif # # CALL BINORMAL (rSigmaX, rSigmaXp, rhoX, XXX, E_BEAM(1), istar1) # endif # if wiggler._FLAG_EMITTANCE: # CALL BINORMAL (rSigmaX, rSigmaXp, rhoX, XXX, E_BEAM(1), istar1) # [ c11 c12 ] [ sigma1^2 rho*sigma1*sigma2 ] # [ c21 c22 ] = [ rho*sigma1*sigma2 sigma2^2 ] sigmaX,sigmaXp,sigmaZ,sigmaZp = syned_electron_beam.get_sigmas_all() epsi_wX = sigmaX * sigmaXp rSigmaX = numpy.sqrt( (epsi_wX**2) * (sigmaXp**2) + sigmaX**2 ) rSigmaXp = sigmaXp rhoX = epsi_wX * sigmaXp**2 / (rSigmaX * rSigmaXp) mean = [0, 0] cov = [[sigmaX**2, rhoX*sigmaX*sigmaXp], [rhoX*sigmaX*sigmaXp, sigmaXp**2]] # diagonal covariance sampled_x, sampled_xp =
numpy.random.multivariate_normal(mean, cov, 1)
numpy.random.multivariate_normal
import numpy as np def nichols_grid(gmin,pmin,pmax,cm=None,cp=None): # Round Gmin from below to nearest multiple of -20dB, # and Pmin,Pmax to nearest multiple of 360 gmin = min(-20,20*np.floor(gmin/20)) pmax = 360*np.ceil(pmax/360); pmin = min(pmax-360,360*np.floor(pmin/360)); if cp is None: p1 = np.array([1,5,10,20,30,50,90,120,150,180]) else: p1 = cp g1_part1 = np.array([6,3,2,1,.75,.5,.4,.3,.25,.2,.15,.1,.05,0,-.05,-.1,-.15,-.2,-.25,-.3,-.4,-.5,-.75,-1,-2,-3,-4,-5,-6,-9,-12,-16]) g1_part2 =np.arange(-20,max(-40,gmin)-1,-10) if gmin >-40: g1 = np.hstack([g1_part1,g1_part2]) else: g1 = np.hstack([g1_part1,g1_part2,gmin]) # Compute gains GH and phases PH in H plane [p,g] = np.meshgrid((np.pi/180)*p1,10**(g1/20)) z = g* np.exp(1j*p) H = z/(1-z) gH = 20*np.log10(np.abs(H)) pH = np.remainder((180/np.pi)*np.angle(H)+360,360) # Add phase lines for angle between 180 and 360 (using symmetry) p_name = ["%.2f deg" % p1_temp for p1_temp in np.hstack([-360+p1,-p1])] gH = np.hstack([gH,gH]) pH = np.hstack([pH,360-pH]) phase_lines = [] for indice in range(gH.shape[1]): phase_lines.append({"y": gH[:,indice],"x": pH[:,indice]-360,"name":p_name[indice]}) # (2) Generate isogain lines for following gain values: if cm is None: g2_part1 = np.array([6,3,1,.5,.25,0,-1,-3,-6,-12,-20]) g2_part2 = np.arange(-40,-20,gmin-1) g2 = np.hstack([g2_part1,g2_part2]) else: g2 = cm #% Phase points p2 = np.array([1,2,3,4,5,7.5,10,15,20,25,30,45,60,75,90,105,120,135,150,175,180]); p2 = np.hstack([p2,np.flip(360-p2[:-1])]) [g,p] = np.meshgrid(10**(g2/20),(np.pi/180)*p2) # mesh in H/(1+H) plane z = g* np.exp(1j*p) H = z/(1-z) gH = 20*np.log10(np.abs(H)) pH = np.remainder((180/np.pi)*np.angle(H)+360,360) # add gain line using symmetry g_name = ["%.2f dB" % g2_temp for g2_temp in g2] pH = pH-360 mag_lines = [] for indice in range(pH.shape[1]): mag_lines.append({"y": gH[:,indice],"x": pH[:,indice],"name":g_name[indice]}) return mag_lines,phase_lines def rlocus_grid(rad_max): data = [] # add frequency line wn_vect = np.linspace(0,rad_max,10) theta_vect = np.linspace(np.pi/2,3*np.pi/2,30) for index in range(len(wn_vect)): wn = wn_vect[index] name = "{:.3f} rad/s".format(wn) x = np.ravel(wn*np.cos(theta_vect)) y = np.ravel(wn*np.sin(theta_vect)) data_temp = {"x": x,"y":y,"name":name} data.append(data_temp) #add damping line wn_vect = np.linspace(0,rad_max,30) theta_vect = (np.pi/2)+np.pi*np.arange(20)/20 for index in range(len(theta_vect)): theta = theta_vect[index] m = np.abs(np.cos(-theta)) name = "m={:.3f}".format(m) x = np.ravel(wn_vect*
np.cos(theta)
numpy.cos
import matplotlib matplotlib.use("agg") import numpy as np import os import time import plotly.graph_objs as go import ot import torch from torch import nn, optim, distributions import torch.backends.cudnn as cudnn cudnn.benchmark = True cudnn.deterministic = False if "CUDNN_DETERMINISTIC" in os.environ: if os.environ["CUDNN_DETERMINISTIC"] not in (0, False, "false", "FALSE", "False"): cudnn.benchmark = False cudnn.deterministic = True from batchgenerators.dataloading import MultiThreadedAugmenter from trixi.util import Config, ResultLogDict from trixi.experiment import PytorchExperiment from neuralprocess.util import set_seeds, tensor_to_loc_scale from neuralprocess.experiment.util import ( get_default_experiment_parser, run_experiment, ) from neuralprocess.data import ( GaussianProcessGenerator, WeaklyPeriodicKernel, StepFunctionGenerator, LotkaVolterraGenerator, FourierSeriesGenerator, TemperatureGenerator, ) from neuralprocess.data.gp import GaussianKernel, WeaklyPeriodicKernel, Matern52Kernel from neuralprocess.model import ( NeuralProcess, AttentiveNeuralProcess, ConvCNP, ConvDeepSet, GPConvDeepSet, generic, ) def make_defaults(representation_channels=128): DEFAULTS = Config( # Base name="NeuralProcessExperiment", description="Learn a distribution over functions with a Neural Process", n_epochs=600000, batch_size=256, seed=1, device="cuda", representation_channels=representation_channels, # Data generator=GaussianProcessGenerator, generator_kwargs=dict( kernel_type=GaussianKernel, kernel_kwargs=dict(lengthscale=0.5), x_range=[-3, 3], num_context=[3, 100], num_target=[3, 100], target_larger_than_context=True, target_includes_context=False, target_fixed_size=False, output_noise=0.0, # additive noise on context values linspace=False, # x values from linspace instead of uniform number_of_threads_in_multithreaded=1, # will use MP if > 1 ), # Model: # modules are instantiated first and then passed to the constructor # of the model model=NeuralProcess, model_kwargs=dict(distribution=distributions.Normal), modules=dict(prior_encoder=generic.MLP, decoder=generic.MLP), modules_kwargs=dict( prior_encoder=dict( in_channels=2, # context in + out out_channels=2 * representation_channels, # mean + sigma hidden_channels=128, hidden_layers=6, ), decoder=dict( in_channels=representation_channels + 1, # sample + target in out_channels=2, # mean + sigma hidden_channels=128, hidden_layers=6, ), ), output_transform_logvar=True, # logvar to sigma transform on sigma outputs # Optimization optimizer=optim.Adam, optimizer_kwargs=dict(lr=1e-3), lr_min=1e-6, # training stops when LR falls below this scheduler=optim.lr_scheduler.StepLR, scheduler_kwargs=dict(step_size=1000, gamma=0.995), scheduler_step_train=True, clip_grad=1e3, # argument for nn.clip_grad_norm lr_warmup=0, # linearly increase LR from 0 during first lr_warmup epochs # Logging backup_every=1000, validate_every=1000, show_every=100, num_samples=50, plot_y_range=[-3, 3], # Testing test_batches_single=100, test_batches_distribution=30, test_batches_diversity=100, test_batch_size=1024, test_num_context=[ "random", ], # can also have integers in this list test_num_context_random=[3, 100], test_num_target_single=100, test_num_target_distribution=100, test_num_target_diversity=100, test_latent_samples=100, # use this many latent samples for NP and ANP test_single=True, test_distribution=True, test_diversity=True, ) MODS = {} MODS["ATTENTION"] = Config( # you also need to set DETERMINISTICENCODER for this model=AttentiveNeuralProcess, model_kwargs=dict( project_to=128, # embed_dim in attention mechanism project_bias=True, in_channels=1, # context and target in representation_channels=representation_channels, ), modules=dict(attention=nn.MultiheadAttention), modules_kwargs=dict(attention=dict(embed_dim=128, num_heads=8)), ) MODS["CONVCNP"] = Config( model=ConvCNP, model_kwargs=dict( in_channels=1, out_channels=1, use_gp=False, learn_length_scale=True, init_length_scale=0.1, use_density=True, use_density_norm=True, points_per_unit=20, # grid resolution range_padding=0.1, # grid range extension grid_divisible_by=64, ), modules=dict(conv_net=generic.SimpleUNet), modules_kwargs=dict( conv_net=dict( in_channels=8, out_channels=8, num_blocks=6, input_bypass=True, # input concatenated to output ) ), ) MODS["GPCONVCNP"] = Config( # Requires CONVCNP model_kwargs=dict(use_gp=True, use_density_norm=False) ) MODS["NOSAMPLE"] = Config(model_kwargs=dict(gp_sample_from_posterior=False)) MODS["LEARNNOISE"] = Config( # Requires GPCONVCNP model_kwargs=dict( gp_noise_learnable=True, gp_noise_init=-2.0, ) ) MODS["LEARNLAMBDA"] = Config( # Requires GPCONVCNP model_kwargs=dict(gp_lambda_learnable=True) ) MODS["MATERNKERNEL"] = Config(generator_kwargs=dict(kernel_type=Matern52Kernel)) MODS["WEAKLYPERIODICKERNEL"] = Config( generator_kwargs=dict(kernel_type=WeaklyPeriodicKernel) ) MODS["STEP"] = Config( generator=StepFunctionGenerator, generator_kwargs=dict( y_range=[-3, 3], number_of_steps=[3, 10], min_step_width=0.1, min_step_height=0.1, ), ) MODS["FOURIER"] = Config( generator=FourierSeriesGenerator, generator_kwargs=dict( series_length=[10, 20], amplitude=[-1, 1], phase=[-1, 1], bias=[-1, 1], frequency_scale=1.0, ), ) MODS["FOURIERSINGLE"] = Config( generator=FourierSeriesGenerator, generator_kwargs=dict( series_length=[1, 2], amplitude=[-2, 2], phase=[-1, 1], bias=[-1, 1], frequency_scale=[0.1, 2.0], ), ) MODS["LOTKAVOLTERRA"] = Config( generator=LotkaVolterraGenerator, generator_kwargs=dict( num_context=[20, 80], num_target=[70, 150], number_of_threads_in_multithreaded=8, predator_init=[50, 100], prey_init=[100, 150], rate0=[0.005, 0.01], rate1=[0.5, 0.8], rate2=[0.5, 0.8], rate3=[0.005, 0.01], sequence_length=10000, y_rescale=0.01, x_rescale=0.1, max_time=100.0, max_population=500, super_sample=1.5, x_range=[0, 5], ), model_kwargs=dict(out_channels=2), modules_kwargs=dict( prior_encoder=dict(in_channels=3), decoder=dict(out_channels=4), deterministic_encoder=dict(in_channels=3), ), plot_y_range=[0, 3], test_num_context_random=[20, 80], ) MODS["TEMPERATURE"] = Config( generator=TemperatureGenerator, generator_kwargs=dict( num_context=[20, 100], num_target=[20, 100], sequence_length=30 * 24, # ca. 1 month x_range=(0, 3), ), test_num_context_random=[20, 100], ) MODS["DETERMINISTICENCODER"] = Config( modules=dict(deterministic_encoder=generic.MLP), modules_kwargs=dict( deterministic_encoder=dict( in_channels=2, out_channels=representation_channels, hidden_channels=128, hidden_layers=6, ), decoder=dict(in_channels=2 * representation_channels + 1), ), ) MODS["LONG"] = Config(n_epochs=1200000, scheduler_kwargs=dict(step_size=2000)) return {"DEFAULTS": DEFAULTS}, MODS class NeuralProcessExperiment(PytorchExperiment): def setup(self): set_seeds(self.config.seed, "cuda" in self.config.device) self.setup_model() self.setup_optimization() self.setup_data() def setup_model(self): modules = dict() for mod_name, mod_type in self.config.modules.items(): modules[mod_name] = mod_type(**self.config.modules_kwargs[mod_name]) modules.update(self.config.model_kwargs) self.model = self.config.model(**modules) self.clog.show_text(repr(self.model), "Model") def setup_optimization(self): self.optimizer = self.config.optimizer( self.model.parameters(), **self.config.optimizer_kwargs ) self.scheduler = self.config.scheduler( self.optimizer, **self.config.scheduler_kwargs ) if self.config.lr_warmup > 0: for group in self.optimizer.param_groups: group["lr"] = 0.0 def setup_data(self): self.generator = self.config.generator( self.config.batch_size, **self.config.generator_kwargs ) if self.generator.number_of_threads_in_multithreaded > 1: self.generator = MultiThreadedAugmenter( self.generator, None, self.generator.number_of_threads_in_multithreaded, seeds=np.arange(self.generator.number_of_threads_in_multithreaded) + self.generator.number_of_threads_in_multithreaded * self.config.seed, ) def _setup_internal(self): super()._setup_internal() # manually set up a ResultLogDict with running mean ability self.results.close() self.results = ResultLogDict( "results-log.json", base_dir=self.elog.result_dir, mode="w", running_mean_length=self.config.show_every, ) # save modifications we made to config self.elog.save_config(self.config, "config") def prepare(self): # move everything to specified device for name, model in self.get_pytorch_modules().items(): model.to(self.config.device) def train(self, epoch): self.model.train() self.optimizer.zero_grad() batch = next(self.generator) batch["epoch"] = epoch # logging context_in = batch["context_in"].to(self.config.device) context_out = batch["context_out"].to(self.config.device) target_in = batch["target_in"].to(self.config.device) target_out = batch["target_out"].to(self.config.device) # forward # ------------------------------------ # on rare occasions, the cholesky decomposition in the GP # fails, if it does, we just go to the next batch skip = False try: prediction = self.model( context_in, context_out, target_in, target_out, store_rep=False, ) prediction = tensor_to_loc_scale( prediction, distributions.Normal, logvar_transform=self.config.output_transform_logvar, axis=2, ) batch["prediction_mu"] = prediction.loc.detach().cpu().repeat(1, 1, 2) batch["prediction_sigma"] = prediction.scale.detach().cpu().repeat(1, 1, 2) # loss loss_recon = -prediction.log_prob(target_out) loss_recon = loss_recon.mean(0).sum() # batch mean loss_total = loss_recon if hasattr(self.model, "prior"): loss_latent = distributions.kl_divergence( self.model.posterior, self.model.prior ) loss_latent = loss_latent.mean(0).sum() # batch mean loss_total += loss_latent # backward, check for NaN gradients loss_total.backward() if ( type(self.model) == ConvCNP and type(self.model.input_interpolation) == GPConvDeepSet ): for p in self.model.parameters(): if p.grad is not None and torch.any(torch.isnan(p.grad)): skip = True break except RuntimeError as re: skip = True # if Cholesky fails or we get NaN gradients, we skip this batch if not skip: if self.config.clip_grad > 0: nn.utils.clip_grad_norm_(self.model.parameters(), self.config.clip_grad) self.optimizer.step() else: self.print("Skipping batch at epoch {}".format(epoch)) return # logging and LR updates batch["loss_recon"] = loss_recon.item() if hasattr(self.model, "prior"): batch["loss_latent"] = loss_latent.item() batch["loss_total"] = loss_total.item() self.log(batch, validate=False) self.step_params(loss_total.item(), epoch, val=False) def log(self, summary, validate=False): if validate: backup = True show = True else: backup = (summary["epoch"] + 1) % self.config.backup_every == 0 show = (summary["epoch"] + 1) % self.config.show_every == 0 # add_result logs to self.results and also plots for l in ("loss_recon", "loss_latent", "loss_total"): if l in summary: name = l if validate: name += "_val" self.add_result( summary[l], name, summary["epoch"], "Loss", plot_result=show, plot_running_mean=not validate, ) self.make_plots(summary, save=backup, show=show, validate=validate) def make_plots(self, summary, save=False, show=True, validate=False): if not save and not show: return if hasattr(self.generator, "x_range"): x_range = self.generator.x_range elif hasattr(self.generator.generator, "x_range"): x_range = self.generator.generator.x_range else: x_range = [-3, 3] # we select the first batch item for plotting context_in = summary["context_in"][0, :, 0].numpy() context_out = summary["context_out"][0].numpy() target_in = summary["target_in"][0, :, 0].numpy() target_out = summary["target_out"][0].numpy() prediction_mu = summary["prediction_mu"][0].numpy() prediction_sigma = summary["prediction_sigma"][0].numpy() if "samples" in summary: samples = summary["samples"][:, 0, :, 0].numpy().T if validate: name = "val" + os.sep else: name = "" # plotly plot for Visdom if show and self.vlog is not None: fig = go.Figure() fig.update_xaxes(range=x_range) fig.update_yaxes(range=self.config.plot_y_range) for c in range(context_out.shape[-1]): fig.add_trace( go.Scatter( x=target_in, y=target_out[..., c], mode="lines", line=dict(color="blue", width=1, dash="dash"), name="target[{}]".format(c), ) ) fig.add_trace( go.Scatter( x=context_in, y=context_out[..., c], mode="markers", marker=dict(color="blue", size=6), name="context[{}]".format(c), ) ) fig.add_trace( go.Scatter( x=target_in, y=prediction_mu[..., c], mode="lines", line=dict(color="black", width=1), name="prediction[{}]".format(c), ) ) fig.add_trace( go.Scatter( x=target_in, y=prediction_mu[..., c] - prediction_sigma[..., c], mode="lines", line=dict(width=0, color="black"), name="- 1 sigma[{}]".format(c), ) ) fig.add_trace( go.Scatter( x=target_in, y=prediction_mu[..., c] + prediction_sigma[..., c], mode="lines", fill="tonexty", fillcolor="rgba(0,0,0,0.1)", line=dict(width=0, color="black"), name="+ 1 sigma[{}]".format(c), ) ) # samples will only be shown for first channel! if "samples" in summary: for s in range(samples.shape[1]): fig.add_trace( go.Scatter( x=target_in, y=samples[:, s], mode="lines", line=dict(width=1, color="rgba(0,255,0,0.2)"), showlegend=False, ) ) self.vlog.show_plotly_plt(fig, name=name + "samples") else: id_ = "prior" if validate else "posterior" self.vlog.show_plotly_plt(fig, name=name + id_) del fig # matplotlib plot for saving if save and self.elog is not None: epoch_str = "{:05d}".format(summary["epoch"]) fig, ax = matplotlib.pyplot.subplots(1, 1) ax.plot(target_in, target_out, "b--", lw=1) ax.plot(context_in, context_out, "bo", ms=6) ax.plot(target_in, prediction_mu, color="black") ax.axis([*x_range, *self.config.plot_y_range]) for c in range(context_out.shape[-1]): ax.fill_between( target_in, prediction_mu[..., c] - prediction_sigma[..., c], prediction_mu[..., c] + prediction_sigma[..., c], color="black", alpha=0.2, ) if "samples" in summary: ax.plot(target_in, samples, color="green", alpha=0.2) self.elog.show_matplot_plt( fig, name=os.path.join(name, "samples", epoch_str) ) else: id_ = "prior" if validate else "posterior" self.elog.show_matplot_plt(fig, name=os.path.join(name, id_, epoch_str)) matplotlib.pyplot.close(fig) def validate(self, epoch): if (epoch + 1) % self.config.validate_every != 0: return self.model.eval() with torch.no_grad(): batch = next(self.generator) batch["epoch"] = epoch # logging context_in = batch["context_in"].to(self.config.device) context_out = batch["context_out"].to(self.config.device) target_in = batch["target_in"].to(self.config.device) target_out = batch["target_out"].to(self.config.device) prediction = self.model( context_in, context_out, target_in, target_out, store_rep=False ) prediction = tensor_to_loc_scale( prediction, distributions.Normal, logvar_transform=self.config.output_transform_logvar, axis=2, ) batch["prediction_mu"] = prediction.loc.detach().cpu() batch["prediction_sigma"] = prediction.scale.detach().cpu() loss_recon = -prediction.log_prob(target_out) loss_recon = loss_recon.mean(0).sum() # batch mean loss_total = loss_recon batch["loss_recon"] = loss_recon.item() # logging if hasattr(self.model, "prior"): loss_latent = distributions.kl_divergence( self.model.posterior, self.model.prior ) loss_latent = loss_latent.mean(0).sum() # batch mean loss_total += loss_latent batch["loss_latent"] = loss_latent.item() batch["loss_total"] = loss_total.item() self.log(batch, "val") # create plot with different samples try: summary = self.make_samples() summary["epoch"] = epoch self.make_plots(summary, save=True, show=True, validate=True) except ( ValueError, NotImplementedError, AttributeError, ) as e: # if models can't sample pass except RuntimeError as e: # numerical instability in GP cholesky self.print("Skipped sampling because of numerical instability.") pass except Exception as e: raise e # default configuration doesn't do anything here, but when # we use something like ReduceLROnPlateau, we need this call self.step_params(loss_total.item(), epoch, val=True) def make_samples(self): with torch.no_grad(): if isinstance(self.generator, MultiThreadedAugmenter): generator = self.generator.generator else: generator = self.generator generator.batch_size = 1 generator.num_target = 100 generator.num_context = 10 batch = next(generator) generator.batch_size = self.config.batch_size generator.num_target = self.config.generator_kwargs.num_target generator.num_context = self.config.generator_kwargs.num_context context_in = batch["context_in"].to(self.config.device) context_out = batch["context_out"].to(self.config.device) target_in = batch["target_in"].to(self.config.device) target_out = batch["target_out"].to(self.config.device) prediction = self.model( context_in, context_out, target_in, target_out, store_rep=True ) prediction = tensor_to_loc_scale( prediction, distributions.Normal, logvar_transform=self.config.output_transform_logvar, axis=2, ) samples = self.model.sample(target_in, self.config.num_samples) samples = tensor_to_loc_scale( samples, distributions.Normal, logvar_transform=True, axis=3 ).loc batch["prediction_mu"] = prediction.loc.cpu() batch["prediction_sigma"] = prediction.scale.cpu() batch["samples"] = samples.cpu() return batch def step_params(self, loss, epoch, val): if epoch < self.config.lr_warmup: for group in self.optimizer.param_groups: lr = ( self.config.optimizer_kwargs.lr * (epoch + 1) / self.config.lr_warmup ) group["lr"] = lr return if self.config.scheduler_step_train and val: pass elif self.config.scheduler_step_train: self.scheduler.step(epoch) elif val: self.scheduler.step(loss) else: pass for group in self.optimizer.param_groups: if group["lr"] < self.config.lr_min: self.print("Learning rate too small, stopping...") self.stop() def test(self): if self.config.test_single: self.test_single() if self.config.test_distribution: self.test_distribution() if self.config.test_diversity: self.test_diversity() def test_single(self): if isinstance(self.generator, MultiThreadedAugmenter): generator = self.generator.generator else: generator = self.generator # for this evaluation we want to separate target and context entirely generator.target_include_context = False generator.batch_size = self.config.test_batch_size generator.num_target = self.config.test_num_target_single generator.test = True self.model.eval() info = {} info["dims"] = ["instance", "test_num_context", "metric"] info["coords"] = { "test_num_context": self.config.test_num_context, "metric": [ "predictive_likelihood", "predictive_error_squared", "reconstruction_likelihood", "reconstruction_error_squared", ], } scores = [] # Catch possible RuntimeError from GP fail_counter = 0 while len(scores) < self.config.test_batches_single and fail_counter < 100: try: scores_batch = [] for num_context in self.config.test_num_context: with torch.no_grad(): if num_context == "random": generator.num_context = self.config.test_num_context_random else: generator.num_context = int(num_context) batch = next(generator) context_in = batch["context_in"].to(self.config.device) context_out = batch["context_out"].to(self.config.device) target_in = batch["target_in"].to(self.config.device) target_out = batch["target_out"].to(self.config.device) # PREDICTIVE PERFORMANCE prediction = self.model( context_in, context_out, target_in, target_out, store_rep=True, ) prediction = tensor_to_loc_scale( prediction, distributions.Normal, logvar_transform=self.config.output_transform_logvar, axis=2, ) predictive_error = torch.pow(prediction.loc - target_out, 2) predictive_error = predictive_error.cpu().numpy() predictive_error = np.nanmean(predictive_error, axis=(1, 2)) if isinstance( self.model, (NeuralProcess, AttentiveNeuralProcess) ): predictive_ll = [] while len(predictive_ll) < self.config.test_latent_samples: prediction = self.model.sample(target_in, 1)[0].cpu() prediction = tensor_to_loc_scale( prediction, distributions.Normal, logvar_transform=self.config.output_transform_logvar, axis=2, ) ll = prediction.log_prob(target_out.cpu()).numpy() ll = np.nanmean(ll, axis=(1, 2)) predictive_ll.append(ll) predictive_ll = np.nanmean(predictive_ll, axis=0) elif self.model.use_gp: predictive_ll = [] for i in range(20): prediction = self.model.sample( target_in, self.config.test_latent_samples // 20 ).cpu() prediction = tensor_to_loc_scale( prediction, distributions.Normal, logvar_transform=self.config.output_transform_logvar, axis=3, ) ll = prediction.log_prob( target_out.cpu() .unsqueeze(0) .expand_as(prediction.loc) ).numpy() predictive_ll.append(np.nanmean(ll, axis=(2, 3))) predictive_ll = np.concatenate(predictive_ll, 0) predictive_ll = np.nanmean(predictive_ll, 0) else: predictive_ll = prediction.log_prob(target_out) predictive_ll = predictive_ll.cpu().numpy() predictive_ll = np.nanmean(predictive_ll, axis=(1, 2)) # RECONSTRUCTION PERFORMANCE reconstruction = self.model( context_in, context_out, context_in, context_out, store_rep=True, ) reconstruction = tensor_to_loc_scale( reconstruction, distributions.Normal, logvar_transform=self.config.output_transform_logvar, axis=2, ) reconstruction_error = torch.pow( reconstruction.loc - context_out, 2 ) reconstruction_error = reconstruction_error.cpu().numpy() reconstruction_error = np.nanmean( reconstruction_error, axis=(1, 2) ) if isinstance( self.model, (NeuralProcess, AttentiveNeuralProcess) ): reconstruction_ll = [] while ( len(reconstruction_ll) < self.config.test_latent_samples ): reconstruction = self.model.sample(context_in, 1)[ 0 ].cpu() reconstruction = tensor_to_loc_scale( reconstruction, distributions.Normal, logvar_transform=self.config.output_transform_logvar, axis=2, ) ll = reconstruction.log_prob(context_out.cpu()).numpy() ll = np.nanmean(ll, axis=(1, 2)) reconstruction_ll.append(ll) reconstruction_ll = np.nanmean(reconstruction_ll, axis=0) elif self.model.use_gp: reconstruction_ll = [] for i in range(20): reconstruction = self.model.sample( context_in, self.config.test_latent_samples // 20 ).cpu() reconstruction = tensor_to_loc_scale( reconstruction, distributions.Normal, logvar_transform=self.config.output_transform_logvar, axis=3, ) ll = reconstruction.log_prob( context_out.cpu() .unsqueeze(0) .expand_as(reconstruction.loc) ).numpy() reconstruction_ll.append(
np.nanmean(ll, axis=(2, 3))
numpy.nanmean
""" anni_RL test file for testing keras reinforcement learning. Uses pygame_visualizer to visualize the results. """ import numpy as np import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from utils import pygame_visualizer, ingest import gym # Things to note: # distance in each direction to a wall # distance to the goal (do we include direction?) # 4 actions that can be taken, N,E,S,W # Configuration parameters for the whole setup seed = 42 gamma = 0.99 # Discount factor for past rewards max_steps_per_episode = 10000 env = gym.make("CartPole-v0") # Create the environment env.seed(seed) eps = np.finfo(np.float32).eps.item() # Smallest number such that 1.0 + eps != 1.0 def step(visualizer, grid): # runs every iteration, makes an RL prediction on where to go pass if __name__ == "__main__": # grid = ingest.txt_to_np("grid.txt") DIRECTIONS = ["N", "E", "S", "W"] BLOCKSIZE = 50 VISUALIZE = True # create the visualizer # visualizer = pygame_visualizer.Visualizer(grid, BLOCKSIZE, VISUALIZE) # create the model num_inputs = 4 num_actions = 2 num_hidden = 128 # not sure what this does inputs = layers.Input(shape=(num_inputs,)) common = layers.Dense(num_hidden, activation="relu")(inputs) action = layers.Dense(num_actions, activation="softmax")(common) critic = layers.Dense(1, activation="linear")(common) model = keras.Model(inputs=inputs, outputs=[action, critic]) optimizer = keras.optimizers.Adam(learning_rate=0.01) huber_loss = keras.losses.Huber() action_probs_history = [] critic_value_history = [] rewards_history = [] running_reward = 0 episode_count = 0 while True: state = env.reset() episode_reward = 0 with tf.GradientTape() as tape: for timestep in range(1, max_steps_per_episode): env.render() # Adding this line would show the attempts # of the agent in a pop up window. state = tf.convert_to_tensor(state) state = tf.expand_dims(state, 0) # Predict action probabilities and estimated future rewards # from environment state action_probs, critic_value = model(state) critic_value_history.append(critic_value[0, 0]) # Sample action from action probability distribution action = np.random.choice(num_actions, p=np.squeeze(action_probs)) action_probs_history.append(tf.math.log(action_probs[0, action])) # Apply the sampled action in our environment state, reward, done, _ = env.step(action) rewards_history.append(reward) episode_reward += reward if done: break # Update running reward to check condition for solving running_reward = 0.05 * episode_reward + (1 - 0.05) * running_reward # Calculate expected value from rewards # - At each timestep what was the total reward received after that timestep # - Rewards in the past are discounted by multiplying them with gamma # - These are the labels for our critic returns = [] discounted_sum = 0 for r in rewards_history[::-1]: discounted_sum = r + gamma * discounted_sum returns.insert(0, discounted_sum) # Normalize returns =
np.array(returns)
numpy.array
''' Generate bounding box as the minimum exterior rectangle of a cluster by searching. ''' import os from ctypes import alignment from frame import get_frames, get_timestamps import matplotlib.pyplot as plt import matplotlib.patches as pc from numpy import ndarray, max, min, abs, zeros, where,array, cov, dot, transpose, arccos, cos, pi from numpy.linalg import inv, eig from typing import List, Tuple from radar_scenes.sequence import Sequence # bounding box type AABB = Tuple[float, float, float, float] OBB = Tuple[float, float, float, float, float] def get_AABB(cluster: ndarray)-> AABB: ''' get axis algned bounding boxes from a frame by finding the max, min x and y param cluster: numpy array with the first row as x coordinate, second row as y coordinate return aligned_box: <x, y, w, h> as YOLO convention ''' max_x = max(cluster[0, :]) max_y = max(cluster[1, :]) min_x = min(cluster[0, :]) min_y = min(cluster[1, :]) w = abs(max_x-min_x) h = abs(max_y-min_y) # becuase of vehicle coordinate system x = (max_x + min_x) / 2 y = (max_y + min_y) / 2 aligned_box = (x, y, w, h) return aligned_box def get_OBB(cluster: ndarray): #-> Tuple(ndarray, OBB): cluster =
transpose(cluster)
numpy.transpose
import h5py import os.path import numpy as np from argparse import ArgumentParser from typing import Tuple from adaptiveleak.utils.file_utils import make_dir def load_dataset(path: str) -> Tuple[np.ndarray, np.ndarray]: with h5py.File(path, 'r') as fin: inputs = fin['inputs'][:] labels = fin['output'][:] return inputs, labels if __name__ == '__main__': parser = ArgumentParser() parser.add_argument('--dataset', type=str, required=True) args = parser.parse_args() dataset_folder = os.path.join('..', 'datasets', args.dataset) # Load the data folds train_inputs, train_labels = load_dataset(path=os.path.join(dataset_folder, 'train', 'data.h5')) test_inputs, test_labels = load_dataset(path=os.path.join(dataset_folder, 'test', 'data.h5')) # Merge the folds merged_inputs =
np.concatenate([train_inputs, test_inputs], axis=0)
numpy.concatenate
import sys import os import unittest import numpy as np import numpy.testing as npt from oct2py import octave sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'build', 'debug')) sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'build', 'debug', 'swig')) import yafft class Test2PointFFT(unittest.TestCase): def setUp(self): octave.restart() octave.addpath('./octave') octave.addpath('./test/octave') octave.eval('pkg load signal') # load signal package # Test data self.in1 = np.array([1, 0], dtype=np.complex64) self.out1 = np.array([1, 1], dtype=np.complex64) self.in2 = np.array([0, 1], dtype=np.complex64) self.out2 = np.array([1, -1], dtype=np.complex64) def tearDown(self): octave.exit() def test_octave_2point_fft(self): res = octave.my_fft(self.in1) res = np.squeeze(res) npt.assert_almost_equal(res, self.out1) res = octave.my_fft(self.in2) res = np.squeeze(res) npt.assert_almost_equal(res, self.out2) def test_dit_2point_fft(self): data = self.in1 yafft.fft_radix2(data, yafft.DECIMATION_IN_TIME) npt.assert_almost_equal(data, self.out1) data = self.in2 yafft.fft_radix2(data, yafft.DECIMATION_IN_TIME) npt.assert_almost_equal(data, self.out2) def test_dif_2point_fft(self): data = self.in1 yafft.fft_radix2(data, yafft.DECIMATION_IN_FREQUENCY) npt.assert_almost_equal(data, self.out1) data = self.in2 yafft.fft_radix2(data, yafft.DECIMATION_IN_FREQUENCY) npt.assert_almost_equal(data, self.out2) class Test4PointFFT(unittest.TestCase): def setUp(self): octave.restart() octave.addpath('./octave') octave.addpath('./test/octave') octave.eval('pkg load signal') # load signal package # Test data self.in1 = np.array([1, 0, 0, 0], dtype=np.complex64) self.out1 = np.array([1, 1, 1, 1], dtype=np.complex64) self.in2 = np.array([0, 1, 0, 0], dtype=np.complex64) self.out2 = np.array([1, -1j, -1, 1j], dtype=np.complex64) self.in3 = np.array([0, 0, 1, 0], dtype=np.complex64) self.out3 = np.array([1, -1, 1, -1], dtype=np.complex64) self.in4 = np.array([0, 0, 0, 1], dtype=np.complex64) self.out4 = np.array([1, 1j, -1, -1j], dtype=np.complex64) def tearDown(self): octave.exit() def test_octave_4point_fft(self): res = octave.my_fft(self.in1) res = np.squeeze(res) npt.assert_almost_equal(res, self.out1) res = octave.my_fft(self.in2) res = np.squeeze(res) npt.assert_almost_equal(res, self.out2) res = octave.my_fft(self.in3) res = np.squeeze(res) npt.assert_almost_equal(res, self.out3) res = octave.my_fft(self.in4) res = np.squeeze(res) npt.assert_almost_equal(res, self.out4) def test_dit_4point_fft(self): data = self.in1 yafft.fft_radix2(data, yafft.DECIMATION_IN_TIME) npt.assert_almost_equal(data, self.out1) data = self.in2 yafft.fft_radix2(data, yafft.DECIMATION_IN_TIME) npt.assert_almost_equal(data, self.out2) data = self.in3 yafft.fft_radix2(data, yafft.DECIMATION_IN_TIME) npt.assert_almost_equal(data, self.out3) data = self.in4 yafft.fft_radix2(data, yafft.DECIMATION_IN_TIME) npt.assert_almost_equal(data, self.out4) def test_dif_4point_fft(self): data = self.in1 yafft.fft_radix2(data, yafft.DECIMATION_IN_FREQUENCY) npt.assert_almost_equal(data, self.out1) data = self.in2 yafft.fft_radix2(data, yafft.DECIMATION_IN_FREQUENCY) npt.assert_almost_equal(data, self.out2) data = self.in3 yafft.fft_radix2(data, yafft.DECIMATION_IN_FREQUENCY) npt.assert_almost_equal(data, self.out3) data = self.in4 yafft.fft_radix2(data, yafft.DECIMATION_IN_FREQUENCY) npt.assert_almost_equal(data, self.out4) class Test8PointFFT(unittest.TestCase): def setUp(self): octave.restart() octave.addpath('./octave') octave.addpath('./test/octave') octave.eval('pkg load signal') # load signal package # Test data v = 1/np.sqrt(2) self.in1 = np.array([1, 0, 0, 0, 0, 0, 0, 0], dtype=np.complex64) self.out1 = np.array([1, 1, 1, 1, 1, 1, 1, 1], dtype=np.complex64) self.in2 = np.array([0, 1, 0, 0, 0, 0, 0, 0], dtype=np.complex64) self.out2 = np.array([1, v-1j*v, -1j, -v-1j*v, -1, -v+1j*v, 1j, v+1j*v], dtype=np.complex64) self.in3 = np.array([0, 0, 1, 0, 0, 0, 0, 0], dtype=np.complex64) self.out3 = np.array([1, -1j, -1, 1j, 1, -1j, -1, 1j], dtype=np.complex64) self.in4 = np.array([0, 0, 0, 1, 0, 0, 0, 0], dtype=np.complex64) self.out4 = np.array([1, -v-1j*v, 1j, v-1j*v, -1, v+1j*v, -1j, -v+1j*v], dtype=np.complex64) self.in5 = np.array([0, 0, 0, 0, 1, 0, 0, 0], dtype=np.complex64) self.out5 = np.array([1, -1, 1, -1, 1, -1, 1, -1], dtype=np.complex64) self.in6 = np.array([0, 0, 0, 0, 0, 1, 0, 0], dtype=np.complex64) self.out6 = np.array([1, -v+1j*v, -1j, v+1j*v, -1, v-1j*v, 1j, -v-1j*v], dtype=np.complex64) self.in7 = np.array([0, 0, 0, 0, 0, 0, 1, 0], dtype=np.complex64) self.out7 = np.array([1, 1j, -1, -1j, 1, 1j, -1, -1j], dtype=np.complex64) self.in8 = np.array([0, 0, 0, 0, 0, 0, 0, 1], dtype=np.complex64) self.out8 = np.array([1, v+1j*v, 1j, -v+1j*v, -1, -v-1j*v, -1j, v-1j*v], dtype=np.complex64) def tearDown(self): octave.exit() def test_octave_8point_fft(self): res = octave.my_fft(self.in1) res = np.squeeze(res) npt.assert_almost_equal(res, self.out1) res = octave.my_fft(self.in2) res =
np.squeeze(res)
numpy.squeeze
import numpy as np _2PI_ = np.pi * 2 _PI_ = np.pi def _get_x_y_mtx(Lx, Ly, Mx, My): v_x, v_y = np.arange(Mx)/Mx*Lx, np.arange(My)/My*Ly mtx_x, mtx_y = np.meshgrid(v_x, v_y) return mtx_x, mtx_y def _get_kx_ky_mtx(Lx, Ly, Mx, My, real_x=True): if real_x: v_kx = np.fft.rfftfreq(Mx) * Mx / Lx * _2PI_ else: v_kx = np.fft.fftfreq(Mx) * Mx / Lx * _2PI_ v_ky = np.fft.fftfreq(My) * My / Ly * _2PI_ return np.meshgrid(v_kx, v_ky) _logistic_der = lambda x: 4.0 *
np.exp(-x)
numpy.exp
import numpy as np from typing import * from numpy.typing import ArrayLike from scipy.spatial import Delaunay from tallem.utility import ask_package_install, package_exists def flywing(): ''' Fly wings example (Klingenberg, 2015 | https://en.wikipedia.org/wiki/Procrustes_analysis) ''' arr1 = np.array([[588.0, 443.0], [178.0, 443.0], [56.0, 436.0], [50.0, 376.0], [129.0, 360.0], [15.0, 342.0], [92.0, 293.0], [79.0, 269.0], [276.0, 295.0], [281.0, 331.0], [785.0, 260.0], [754.0, 174.0], [405.0, 233.0], [386.0, 167.0], [466.0, 59.0]]) arr2 = np.array([[477.0, 557.0], [130.129, 374.307], [52.0, 334.0], [67.662, 306.953], [111.916, 323.0], [55.119, 275.854], [107.935, 277.723], [101.899, 259.73], [175.0, 329.0], [171.0, 345.0], [589.0, 527.0], [591.0, 468.0], [299.0, 363.0], [306.0, 317.0], [406.0, 288.0]]) return([arr1, arr2]) def gaussian_blob(n_pixels: int, r: float): ''' Generates a closure which, given a 2D location *mu=(x,y)*, generates a white blob with [normalized] radius 0 < r <= 1 in a (n_pixels x n_pixels) image. If *mu* is in [0,1] x [0,1], the center of the white blob should be visible If *mu* has as both of its coordinates outside of [0,1]x[0,1], the blob may be partially visible If *mu* has both of its coordinates outside of [-r, 1+r]x[-r, 1+r], then image should be essentially black The returned closure completely autograd's numpy wrapper to do the image generation. Thus, the resulting function can be differentiated (w.r.t *mu*) using the reverse-mode differentiation process that *autograd* provides. This function also returns the global normalizing constant needed normalize the pixel intensities in [0,1], for plotting or other purposes. Return: (blob, c) where - blob := differentiable closure which, given a vector (x,y), generates the blob image a flat vector. - c := maximum value of the intensity of any given pixel for any choice of *mu*. ''' import autograd.numpy as auto_np sd = r/3.090232 sigma = sd**2 sigma_inv = 1.0/sigma denom = np.sqrt(((2*auto_np.pi)**2) * (sigma**2)) def blob(mu): # mu can be anywhere; center of image is [0.5, 0.5] loc = auto_np.linspace(0, 1, n_pixels, False) + 1/(2*n_pixels) x,y = auto_np.meshgrid(loc, loc) grid = auto_np.exp(-0.5*(sigma_inv * ((x-mu[0])**2 + (y-mu[1])**2)))/denom return(auto_np.ravel(grid).flatten()) return(blob, auto_np.exp(0)/denom) def plot_image(P, figsize=(8,8), max_val = "default"): if max_val == "default": max_val = np.max(P) import matplotlib.pyplot as plt fig = plt.figure(figsize=figsize) plt.imshow(P, cmap='gray', vmin=0, vmax=max_val) fig.gca().axes.get_xaxis().set_visible(False) fig.gca().axes.get_yaxis().set_visible(False) def plot_images(P, shape, max_val = "default", figsize=(8,8), layout = None): ''' P := numpy array where each row is a grayscale image shape := the shape to reshape each row of P prior to plotting ''' import matplotlib.pyplot as plt if max_val == "default": max_val = np.max(P) if P.ndim == 1: fig = plt.figure(figsize=figsize) plt.imshow(P.reshape(shape), cmap='gray', vmin=0, vmax=max_val) fig.gca().axes.get_xaxis().set_visible(False) fig.gca().axes.get_yaxis().set_visible(False) return(fig, ax) else: assert layout is not None, "missing layout" fig, axs = plt.subplots(*layout, figsize=figsize) axs = axs.flatten() for i, (img, ax) in enumerate(zip(P, axs)): #fig.add_subplot(layout[0], layout[1], i+1) plt.axis("off") ax.imshow(P[i,:].reshape(shape), cmap='gray', vmin=0, vmax=max_val, aspect='auto') ax.axes.xaxis.set_visible(False) ax.axes.yaxis.set_visible(False) plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0.1, hspace=0.1) return(fig, axs) def scatter2D(P, layout = None, figsize=(8,8), **kwargs): import matplotlib.pyplot as plt if isinstance(P, np.ndarray): if "fig" in kwargs.keys() and "ax" in kwargs.keys(): fig, ax = kwargs["fig"], kwargs["ax"] kwargs.pop('fig', None) kwargs.pop('ax', None) else: fig = plt.figure(figsize=figsize) ax = fig.add_subplot() ax.scatter(*P.T, **kwargs) return(fig, ax) elif isinstance(P, Iterable): assert layout is not None, "missing layout" assert len(P) == np.prod(layout) if "fig" in kwargs.keys() and "ax" in kwargs.keys(): fig, ax = kwargs["fig"], kwargs["ax"] kwargs.pop('fig', None) else: fig = plt.figure(figsize=figsize) for i, p in enumerate(P): ax = fig.add_subplot(layout[0], layout[1], i+1) ax.scatter(*p.T, **kwargs) return(fig, ax) def scatter3D(P, angles = None, layout = None, figsize=(8,8), **kwargs): import matplotlib.pyplot as plt if isinstance(P, np.ndarray): import numbers if angles is not None: if isinstance(angles, numbers.Integral): angles = np.linspace(0, 360, angles, endpoint=False) assert len(angles) == np.prod(layout) if "fig" in kwargs.keys() and "ax" in kwargs.keys(): fig, ax = kwargs["fig"], kwargs["ax"] kwargs.pop('fig', None) kwargs.pop('ax', None) else: fig, ax = plt.subplots(*layout, figsize=figsize) for i, theta in enumerate(angles): ax = fig.add_subplot(layout[0], layout[1], i+1, projection='3d') ax.scatter3D(*P.T, **kwargs) ax.view_init(30, theta) else: if "fig" in kwargs.keys() and "ax" in kwargs.keys(): fig, ax = kwargs["fig"], kwargs["ax"] kwargs.pop('fig', None) kwargs.pop('ax', None) else: fig = plt.figure(figsize=figsize) ax = fig.add_subplot(projection='3d') ax.scatter3D(*P.T, **kwargs) elif isinstance(P, Iterable): import numbers assert layout is not None, "missing layout" if angles is None: angles = np.repeat(60, len(P)) elif isinstance(angles, numbers.Integral): angles = np.linspace(0, 2*np.pi, len(P), endpoint=False) assert len(angles) == np.prod(layout) if "fig" in kwargs.keys() and "ax" in kwargs.keys(): fig, ax = kwargs["fig"], kwargs["ax"] kwargs.pop('fig', None) kwargs.pop('ax', None) else: fig, ax = plt.subplots(*layout, figsize=figsize) for i, p in enumerate(P): ax = fig.add_subplot(layout[0], layout[1], i+1, projection='3d') ax.scatter3D(*p.T, **kwargs) ax.view_init(30, angles[i]) plt.setp(plt.gcf().get_axes(), xticks=[], yticks=[]); return(fig, ax) def rotating_disk(n_pixels: int, r: float, sigma: float = 1.0): from scipy.ndimage import gaussian_filter import numpy as np I = np.zeros(shape=(n_pixels, n_pixels)) p = np.linspace(0, 1, n_pixels, False) + 1/(2*n_pixels) # center locations of pixels, in normalized space z = np.array([r, 0.0]).reshape((2,1)) d = np.array([0.5, 0.5]).reshape((2,1)) x,y = np.meshgrid(p, p) def disk_image(theta: float): R = np.array([[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]]) c = (R @ z) + d # center of disk in [0,1]^2 D = np.flipud(np.sqrt((x - c[0])**2 + (y - c[1])**2)) D[D <= r] = -1.0 D[D > r] = 0.0 D[D == -1.0] = 1.0 return(np.ravel(gaussian_filter(D, sigma=1.0)).flatten()) return(disk_image, 1.0) # D = np.zeros(np.prod(x.shape)) # for i, (xi,yi) in enumerate(zip(x.flatten(),y.flatten())): # p = np.array([xi,yi]) # D[i] = np.dot(p-b, u)# np.linalg.norm(z-v) def white_bars(n_pixels: int, r: float, sigma: float = 1.0): ''' Returns a parameterization that yields a white vertical bar at various orientations in an image. Fixed parameters: n_pixels := number of pixels to make square image r := constant between [0,1] indicating how wide to make the bar sigma := kernel parameter for gaussian blur Returns: bar := closure w/ parameters y_offset in [0, 1] and theta in [0, pi] c := normalizing constant for plotting ''' from scipy.ndimage import gaussian_filter import numpy as np w = r p = np.linspace(0, 1, n_pixels, False) + 1/(2*n_pixels) # center locations of pixels, in normalized space x,y = np.meshgrid(p,p) c = np.array([0.5, 0.5]) # center of image def bar(theta: float, d: float): assert np.all(np.bitwise_and(d >= -1.0, d <= 1.0)), "d must be in the range [-1, 1]" assert np.all(np.bitwise_and(theta >= 0.0, theta <= np.pi)), "theta must be in the range [0, pi]" u = np.array([ 1.0, np.tan(theta) ]) u = u / np.linalg.norm(u) c = np.array([0.5, 0.5]) # center of image d = d * (np.sqrt(2) / 2) # scale where to place center of bar if theta > np.pi/2: d = -d b = c + d*u # center of bar D = np.zeros(np.prod(x.shape)) for i, (xi,yi) in enumerate(zip(x.flatten(),y.flatten())): p =
np.array([xi,yi])
numpy.array
#!/usr/bin/env python import os import numpy as np import matplotlib.pyplot as plt from astropy.constants import pc from astropy import units as u from astropy.table import Table,join from astropy.stats import sigma_clip from .sqbase import datadir trlines_qsfit = { 'CIVb':'BR_CIV_1549__EW', 'MgIIb':'BR_MGII_2798__EW', 'Hbeta':'BR_HB__EW', 'HAb':'BR_HA__EW', } trlines_shen07 = { 'CIVb':'EW_CIV', 'MgIIb':'EW_MGII', 'Hbeta':'EW_BROAD_HB', 'HAb':'EW_BROAD_HA', } def get_qsfit_M1450(qsfit,alpha_nu=-0.4): cwave = np.zeros(len(qsfit)) qsfitCont = np.zeros(len(qsfit)) for wv in ['1450','2245','3000','4210','5100']: contk = 'CONT%s__LUM' % wv contwk = 'CONT%s__WAVE' % wv ii = np.where((cwave==0) & ~np.isnan(qsfit[contk]))[0] if len(ii) > 0: cwave[ii] = qsfit[contwk][ii] qsfitCont[ii] = qsfit[contk][ii] cnu = (cwave*u.Angstrom).to(u.Hz,equivalencies=u.spectral()) cnu1450 = (1450.*u.Angstrom).to(u.Hz,equivalencies=u.spectral()) qsfitLnu1450 = (qsfitCont*1e42/cnu)*(cnu1450/cnu)**alpha_nu fourpidsqr = 4*np.pi*(10*pc.to('cm').value)**2 qsfitM1450 = -2.5*np.log10(qsfitLnu1450.value/fourpidsqr) - 48.6 return qsfitM1450 def compare_qsfit_shen07(line,qsfit,shen07,minEw=10,**kwargs): trendFn = kwargs.get('EmissionLineTrendFilename','emlinetrends_v6') lineCatalog = Table.read(os.path.join(datadir,trendFn+'.fits')) line_i = np.where(lineCatalog['name']==line)[0][0] # qsfitEw = qsfit[trlines_qsfit[line]] qsfitM1450 = get_qsfit_M1450(qsfit) ii1 = np.where(~np.isnan(qsfitEw) & ~np.isnan(qsfitM1450) & (qsfitM1450<-19) & (qsfitM1450>-30) & (qsfitEw>minEw))[0] x = sigma_clip(np.log10(qsfitEw[ii1]),sigma=3) qsfit_mn,qsfit_std = x.mean(),x.std() qsfitstr = 'QSFIT: {0:.2f} +/- {1:.2f}'.format(qsfit_mn,qsfit_std) ii1 = ii1[~x.mask] qsfitEw = np.array(qsfitEw[ii1]) qsfitM1450 = qsfitM1450[ii1] # shenEw = shen07[trlines_shen07[line]] ii2 = np.where(shenEw>minEw)[0] x = sigma_clip(
np.log10(shenEw[ii2])
numpy.log10
import numpy import scipy.special class SimpleNeuralNetwork: def __init__(self, inputnodes=None, hiddennodes=None, outputnodes=None, learningrate=None): self.inputnodes = inputnodes self.hiddennodes = hiddennodes self.outputnodes = outputnodes self.learningrate = learningrate self.activation_function = lambda x: scipy.special.expit(x) if inputnodes is not None and hiddennodes is not None and outputnodes is not None: self.weights_input_hidden = numpy.random.rand(self.hiddennodes, self.inputnodes) - 0.5 self.weights_hidden_output = numpy.random.rand(self.outputnodes, self.hiddennodes) - 0.5 @staticmethod def load(): snn = SimpleNeuralNetwork() snn.weights_input_hidden = numpy.load("../data/snn-ih.npy") snn.weights_hidden_output = numpy.load("../data/snn-ho.npy") return snn def train(self, inputs, targets): targets =
numpy.array(targets, ndmin=2)
numpy.array
import neuroglancer import numpy as np import networkx as nx import random class SkeletonSource(neuroglancer.skeleton.SkeletonSource): def __init__(self, cc, dimensions, voxel_size, node_attrs=None, edge_attrs=None): super(SkeletonSource, self).__init__(dimensions) self.vertex_attributes["distance"] = neuroglancer.skeleton.VertexAttributeInfo( data_type=np.float32, num_components=1 ) self.vertex_attributes["node_edge"] = neuroglancer.skeleton.VertexAttributeInfo( data_type=np.float32, num_components=1 ) self.vertex_attributes["edge_len"] = neuroglancer.skeleton.VertexAttributeInfo( data_type=np.float32, num_components=1 ) self.vertex_attributes["component"] = neuroglancer.skeleton.VertexAttributeInfo( data_type=np.float32, num_components=3 ) self.vertex_attributes[ "connected_component" ] = neuroglancer.skeleton.VertexAttributeInfo( data_type=np.float32, num_components=3 ) self.vertex_attributes[ "component_size" ] = neuroglancer.skeleton.VertexAttributeInfo( data_type=np.float32, num_components=1 ) self.cc = cc self.voxel_size = voxel_size for node, attrs in self.cc.nodes.items(): assert "location" in attrs self.component_ids = {} self.connected_component_ids = {} for i, component in enumerate(nx.connected_components(self.cc)): for node in component: self.cc.nodes[node]["connected_component_id"] = i def get_skeleton(self, i): edges = [] distances = [] vertex_positions = [] node_edge = [] edge_len = [] component = [] component_size = [] connected_component = [] print( f"rendering nodes and edges with {len(self.cc.nodes)} nodes and {len(self.cc.edges)} edges" ) for i, n in enumerate(self.cc.nodes): vertex_positions.append( self.cc.nodes[n]["location"] / self.voxel_size ) vertex_positions.append( self.cc.nodes[n]["location"] / self.voxel_size ) distances.append(0.1) distances.append(0.1) edges.append(2 * i) edges.append(2 * i + 1) node_edge.append(1) node_edge.append(1) edge_len.append(0) edge_len.append(0) component.append( self.component_ids.setdefault( self.cc.nodes[n].get("component_id", 0), ( random.randint(0, 255) / 256, random.randint(0, 255) / 256, random.randint(0, 255) / 256, ), ) ) component.append( self.component_ids.setdefault( self.cc.nodes[n].get("component_id", 0), ( random.randint(0, 255) / 256, random.randint(0, 255) / 256, random.randint(0, 255) / 256, ), ) ) connected_component.append( self.component_ids.setdefault( self.cc.nodes[n].get("component_id", 0), ( random.randint(0, 255) / 256, random.randint(0, 255) / 256, random.randint(0, 255) / 256, ), ) ) connected_component.append( self.connected_component_ids.setdefault( self.cc.nodes[n].get("connected_component_id", 0), ( random.randint(0, 255) / 256, random.randint(0, 255) / 256, random.randint(0, 255) / 256, ), ) ) component_size.append(self.cc.nodes[n].get("component_size", 0)) component_size.append(self.cc.nodes[n].get("component_size", 0)) i += 1 for j, (u, v) in enumerate(self.cc.edges): vertex_positions.append( self.cc.nodes[u]["location"] / self.voxel_size ) vertex_positions.append( self.cc.nodes[v]["location"] / self.voxel_size ) distances.append(self.cc.edges[(u, v)].get("distance", 0.5)) distances.append(self.cc.edges[(u, v)].get("distance", 0.5)) edges.append((2 * i) + 2 * j) edges.append((2 * i) + 2 * j + 1) node_edge.append(0) node_edge.append(0) edge_len.append(np.linalg.norm(vertex_positions[-1] - vertex_positions[-2])) edge_len.append(np.linalg.norm(vertex_positions[-1] - vertex_positions[-2])) component.append( self.component_ids.setdefault( self.cc.nodes[u].get("component_id", 0), ( random.randint(0, 255) / 256, random.randint(0, 255) / 256, random.randint(0, 255) / 256, ), ) ) component.append( self.component_ids.setdefault( self.cc.nodes[v].get("component_id", 0), ( random.randint(0, 255) / 256, random.randint(0, 255) / 256, random.randint(0, 255) / 256, ), ) ) connected_component.append( self.connected_component_ids.setdefault( self.cc.nodes[u].get("connected_component_id", 0), ( random.randint(0, 255) / 256, random.randint(0, 255) / 256, random.randint(0, 255) / 256, ), ) ) connected_component.append( self.connected_component_ids.setdefault( self.cc.nodes[v].get("connected_component_id", 0), ( random.randint(0, 255) / 256, random.randint(0, 255) / 256, random.randint(0, 255) / 256, ), ) ) component_size.append(self.cc.nodes[u].get("component_size", 0)) component_size.append(self.cc.nodes[v].get("component_size", 0)) return neuroglancer.skeleton.Skeleton( vertex_positions=vertex_positions, edges=edges, vertex_attributes=dict( distance=np.array(distances), node_edge=node_edge, edge_len=edge_len, component=component, component_size=component_size, connected_component=connected_component, ), # edge_attribues=dict(distances=distances), ) class MatchSource(neuroglancer.skeleton.SkeletonSource): def __init__(self, graph, dimensions, voxel_size): super(MatchSource, self).__init__(dimensions) self.vertex_attributes["source"] = neuroglancer.skeleton.VertexAttributeInfo( data_type=np.float32, num_components=3 ) self.vertex_attributes["gt_edge"] = neuroglancer.skeleton.VertexAttributeInfo( data_type=np.float32, num_components=1 ) self.vertex_attributes[ "success_edge" ] = neuroglancer.skeleton.VertexAttributeInfo( data_type=np.float32, num_components=1 ) self.vertex_attributes[ "false_match" ] = neuroglancer.skeleton.VertexAttributeInfo( data_type=np.float32, num_components=3 ) self.vertex_attributes[ "false_match_edge" ] = neuroglancer.skeleton.VertexAttributeInfo( data_type=np.float32, num_components=1 ) self.vertex_attributes["merge"] = neuroglancer.skeleton.VertexAttributeInfo( data_type=np.float32, num_components=3 ) self.vertex_attributes[ "merge_edge" ] = neuroglancer.skeleton.VertexAttributeInfo( data_type=np.float32, num_components=1 ) self.vertex_attributes["split"] = neuroglancer.skeleton.VertexAttributeInfo( data_type=np.float32, num_components=3 ) self.vertex_attributes[ "split_edge" ] = neuroglancer.skeleton.VertexAttributeInfo( data_type=np.float32, num_components=1 ) self.vertex_attributes["node_edge"] = neuroglancer.skeleton.VertexAttributeInfo( data_type=np.float32, num_components=1 ) self.vertex_attributes[ "selected_edge" ] = neuroglancer.skeleton.VertexAttributeInfo( data_type=np.float32, num_components=1 ) self.vertex_attributes[ "component_matchings" ] = neuroglancer.skeleton.VertexAttributeInfo( data_type=np.float32, num_components=3 ) self.vertex_attributes[ "all_colors" ] = neuroglancer.skeleton.VertexAttributeInfo( data_type=np.float32, num_components=3 ) self.graph = graph self.voxel_size = voxel_size self.init_colors() def init_colors(self): red = np.array((255, 128, 128)) / 256 green = np.array((128, 255, 128)) / 256 blue = np.array((128, 128, 255)) / 256 yellow = np.array((255, 255, 128)) / 256 purple = np.array((255, 128, 255)) / 256 grey = np.array((125, 125, 125)) / 256 cyan = np.array((0, 255, 255)) / 256 self.error_vis_colors = { "split": red, "merge": blue, "true_pos": green, "false_neg": red, "false_pos": blue, "filtered": grey, "other": cyan, } self.error_vis_type = { (1, 0, 0, 0, 0, 0): "filtered", (0, 1, 0, 0, 0, 0): "true_pos", (0, 0, 1, 0, 0, 0): "false_pos", (0, 0, 0, 1, 0, 0): "false_neg", (0, 0, 0, 0, 1, 0): "merge", (0, 0, 0, 0, 0, 1): "split", } self.source_colors = np.array([(255, 128, 128), (128, 128, 255)]) / 256 self.distance_color_range = np.array([(255, 128, 128), (128, 128, 255)]) / 256 self.matching_colors =
np.array([(255, 128, 128), (128, 128, 255)])
numpy.array
""" Camera Calibration, including monocular, stereo and hand-eye. Author: <NAME> Reference: https://github.com/bvnayak/stereo_calibraion Date: 2022/03/21 """ import numpy as np import cv2 import glob import argparse import yaml import matplotlib.pyplot as plt from tqdm import trange class Calibration(object): def __init__(self, filepath): self.criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001) self.criteria_cal = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 1e-5) self.criteria_stereo = (cv2.TERM_CRITERIA_MAX_ITER + cv2.TERM_CRITERIA_EPS, 100, 1e-5) self.objp = np.zeros((11*8, 3), np.float32) self.objp[:, :2] = np.mgrid[0:11, 0:8].T.reshape(-1, 2) * 9.55 # distance between corners is 9.55mm self.objpoints = [] # 3d point in real world space self.imgpoints_l = [] # 2d points in image plane. self.imgpoints_r = [] # 2d points in image plane. self.cal_path = filepath # self.test_path = rebuildpath def show(self, img): cv2.namedWindow('img', 0) cv2.resizeWindow('img', 600, 500) cv2.imshow('img', img) cv2.waitKey(1000) cv2.destroyWindow('img') def monocular_calibrate(self, cal_path, display): images_left = glob.glob(cal_path + 'l*.bmp') images_right = glob.glob(cal_path + 'r*.bmp') images_left.sort() images_right.sort() self.img_left = images_left self.img_right = images_right for i in trange(len(images_left)): img_l = cv2.imread(images_left[i]) img_r = cv2.imread(images_right[i]) gray_l = cv2.cvtColor(img_l, cv2.COLOR_BGR2GRAY) gray_r = cv2.cvtColor(img_r, cv2.COLOR_BGR2GRAY) # Find the chess board corners ret_l, corners_l = cv2.findChessboardCorners(gray_l, (11, 8), None) ret_r, corners_r = cv2.findChessboardCorners(gray_r, (11, 8), None) # If found, add object points, image points (after refining them) self.objpoints.append(self.objp) if ret_l is True: rt = cv2.cornerSubPix(gray_l, corners_l, (11, 11), (-1, -1), self.criteria) self.imgpoints_l.append(corners_l) # Draw and display the corners ret_l = cv2.drawChessboardCorners(img_l, (11, 8), corners_l, ret_l) if display: self.show(img_l) if ret_r is True: rt = cv2.cornerSubPix(gray_r, corners_r, (11, 11), (-1, -1), self.criteria) self.imgpoints_r.append(corners_r) # Draw and display the corners ret_r = cv2.drawChessboardCorners(img_r, (11, 8), corners_r, ret_r) if display: self.show(img_r) self.img_shape = gray_l.shape[::-1] rt, self.M1, self.d1, self.r1, self.t1 = cv2.calibrateCamera( self.objpoints, self.imgpoints_l, self.img_shape, None, None) rt, self.M2, self.d2, self.r2, self.t2 = cv2.calibrateCamera( self.objpoints, self.imgpoints_r, self.img_shape, None, None) def stereo_calibrate(self, dims): flags = 0 flags |= cv2.CALIB_FIX_INTRINSIC flags |= cv2.CALIB_USE_INTRINSIC_GUESS flags |= cv2.CALIB_FIX_FOCAL_LENGTH flags |= cv2.CALIB_ZERO_TANGENT_DIST ret, M1, d1, M2, d2, R, T, E, F = cv2.stereoCalibrate( self.objpoints, self.imgpoints_l, self.imgpoints_r, self.M1, self.d1, self.M2, self.d2, dims, criteria=self.criteria_stereo, flags=flags) self.R = R self.T = T self.M1 = M1 self.d1 = d1 self.M2 = M2 self.d2 = d2 camera_model = dict([('M1', np.asarray(M1).tolist()), ('M2', np.asarray(M2).tolist()), ('dist1', np.asarray(d1).tolist()), ('dist2', np.asarray(d2).tolist()), ('r1', np.asarray(self.r1).tolist()), ('r2', np.asarray(self.r2).tolist()), ('t1', np.asarray(self.t1).tolist()), ('t2', np.asarray(self.t2).tolist()), ('R', np.asarray(R).tolist()), ('T', np.asarray(T).tolist()), ('E', np.asarray(E).tolist()), ('F', np.asarray(F).tolist())]) with open("./summary/calibration_matrix.yaml", "w") as f: yaml.dump(camera_model, f) cv2.destroyAllWindows() return camera_model def _read_gripper2base(self): t = [] R = [] with open('ur.txt', 'r') as f: for i in range(20): line = f.readline().strip('\n') data = np.asarray(line.split(' ')).astype(np.float32) t.append(data[:3]) R.append(cv2.Rodrigues(data[3:])[0]) # vector to matrix t = np.asarray(t).reshape((20, 3, 1)) R = np.asarray(R).reshape((20, 3, 3)) return t, R def hand_eye_calibrate(self): self.t_gripper2base, self.R_gripper2base = self._read_gripper2base() self.R_cam2gripper_l, self.t_cam2gripper_l = cv2.calibrateHandEye(self.R_gripper2base, self.t_gripper2base, self.r1, self.t1) self.R_cam2gripper_r, self.t_cam2gripper_r = cv2.calibrateHandEye(self.R_gripper2base, self.t_gripper2base, self.r2, self.t2) def undistortion(self, seed, display): if seed < 0 or seed > len(self.img_left): print("Input seed error! Choose another one.") return; instance_img = cv2.imread(self.img_right[seed]) h = self.img_shape[0] w = self.img_shape[1] newcameramtx, roi = cv2.getOptimalNewCameraMatrix(self.M1, self.d1, (w, h), 0, (w, h)) result = cv2.undistort(instance_img, self.M1, self.d1, None, newcameramtx) if display: plt.subplot(121) plt.imshow(instance_img, cmap='gray') plt.title('Input Image') plt.subplot(122) plt.imshow(result, cmap='gray') plt.title('After Undistortion') plt.show() def getRectifyTransformation(self): h = self.img_shape[1] w = self.img_shape[0] R1, R2, P1, P2, Q, roi1, roi2 = cv2.stereoRectify( self.M1, self.d1, self.M2, self.d2, (w, h), self.R, self.T, alpha=0) map1x, map1y = cv2.initUndistortRectifyMap(self.M1, self.d1, R1, P1, (w, h), cv2.CV_32FC1) map2x, map2y = cv2.initUndistortRectifyMap(self.M2, self.d2, R2, P2, (w, h), cv2.CV_32FC1) return map1x, map1y, map2x, map2y, Q def rectify(self, test_path, display): image_test = glob.glob(test_path + '*.jpg') # images waited to be rectified image1 = cv2.imread(image_test[0]) image2 = cv2.imread(image_test[1]) map1x, map1y, map2x, map2y, Q = self.getRectifyTransformation() rectified_img1 = cv2.remap(image1, map1x, map1y, cv2.INTER_AREA) rectified_img2 = cv2.remap(image2, map2x, map2y, cv2.INTER_AREA) self.image1 = rectified_img1 self.image2 = rectified_img2 if display: plt.subplot(121) plt.imshow(image1) plt.title('Left image (after rectify)') plt.subplot(122) plt.imshow(image2) plt.title('Right image (after rectify)') plt.show() if display: plt.subplot(121) plt.imshow(rectified_img1) plt.title('Left image (after rectify)') plt.subplot(122) plt.imshow(rectified_img2) plt.title('Right image (after rectify)') plt.show() return rectified_img1, rectified_img2 def test_monocular(self): # reconstruct from 3D to 2D total_error_l = 0 total_error_r = 0 for i in range(len(self.objpoints)): imgpoints_l_re, _ = cv2.projectPoints(self.objpoints[i], self.r1[i], self.t1[i], self.M1, self.d1) imgpoints_r_re, _ = cv2.projectPoints(self.objpoints[i], self.r2[i], self.t2[i], self.M2, self.d2) error_l = cv2.norm(self.imgpoints_l[i], imgpoints_l_re, cv2.NORM_L2) / len(imgpoints_l_re) error_r = cv2.norm(self.imgpoints_r[i], imgpoints_r_re, cv2.NORM_L2) / len(imgpoints_r_re) total_error_l += error_l total_error_r += error_r print("---------- Monocular projection error ----------") print("total error left: ", total_error_l / len(self.objpoints)) print("total error right: ", total_error_r / len(self.objpoints)) def update(self, val=0): # Updating the parameters based on the trackbar positions numDisparities = cv2.getTrackbarPos('numDisparities','disp') blockSize = cv2.getTrackbarPos('blockSize','disp') preFilterCap = cv2.getTrackbarPos('preFilterCap','disp') uniquenessRatio = cv2.getTrackbarPos('uniquenessRatio','disp') speckleRange = cv2.getTrackbarPos('speckleRange','disp') speckleWindowSize = cv2.getTrackbarPos('speckleWindowSize','disp') disp12MaxDiff = cv2.getTrackbarPos('disp12MaxDiff','disp') minDisparity = cv2.getTrackbarPos('minDisparity','disp') self.stereo.setNumDisparities(numDisparities) self.stereo.setBlockSize(blockSize) self.stereo.setPreFilterCap(preFilterCap) self.stereo.setUniquenessRatio(uniquenessRatio) self.stereo.setSpeckleRange(speckleRange) self.stereo.setSpeckleWindowSize(speckleWindowSize) self.stereo.setDisp12MaxDiff(disp12MaxDiff) self.stereo.setMinDisparity(minDisparity) disparity = self.stereo.compute(self.image1, self.image2) disparity = disparity.astype(np.float32) disparity = (disparity/16.0 - minDisparity)/numDisparities cv2.imshow("disp",disparity) def sgbm(self): cv2.namedWindow('disp') cv2.createTrackbar('numDisparities','disp',100,400,self.update) cv2.createTrackbar('blockSize','disp',1,50,self.update) cv2.createTrackbar('preFilterCap','disp',5,62,self.update) cv2.createTrackbar('uniquenessRatio','disp',0,40,self.update) cv2.createTrackbar('speckleRange','disp',0,30,self.update) cv2.createTrackbar('speckleWindowSize','disp',0,30,self.update) cv2.createTrackbar('disp12MaxDiff','disp',0,100,self.update) cv2.createTrackbar('minDisparity','disp',0,25,self.update) self.stereo = cv2.StereoSGBM_create() self.update() cv2.waitKey(0) def test_stereo(self): # project from 3D to 2D total_dist_h = 0 total_dist_v = 0 for seed in range(20): r1_matrix, _ = cv2.Rodrigues(self.r1[seed]) r1 = np.asarray(r1_matrix) t1 = np.asarray(self.t1[seed]) r2_matrix, _ = cv2.Rodrigues(self.r2[seed]) r2 = np.asarray(r2_matrix) t2 = np.asarray(self.t2[seed]) projection_matrix_l = np.matmul(self.M1, np.concatenate((r1, t1), axis=1)) projection_matrix_r = np.matmul(self.M2, np.concatenate((r2, t2), axis=1)) proj_points_l = np.asarray(self.imgpoints_l[seed]).reshape(-1, 2).T proj_points_r = np.asarray(self.imgpoints_r[seed]).reshape(-1, 2).T points = cv2.triangulatePoints(projection_matrix_l, projection_matrix_r, proj_points_l, proj_points_r) points_world = cv2.convertPointsFromHomogeneous(points.T) points = points_world.reshape(8, 11, 3) for i in range(8): for j in range(10): dist_h = np.linalg.norm(points[i][j+1] - points[i][j]) total_dist_h += dist_h for i in range(7): for j in range(11): dist_v = np.linalg.norm(points[i+1][j] - points[i][j]) total_dist_v += dist_v print("---------- Stereo projection error ----------") print("Ground truth distance: 9.55mm") print("Average distance between corner points (horizontal): ", total_dist_h / (80*20), 'mm') print("Average distance between corner points (vertical): ", total_dist_v / (77*20), 'mm') print("Error: ", 0.5*((total_dist_h/(80*20)-9.55)/9.55*100 + (total_dist_v / (77*20)-9.55)/9.55*100), "%") def _homo(self, M, t): M = np.array(M).reshape((3,3)) t = np.array(t).reshape((3,1)) new_m = np.concatenate((M, t), axis=1) h = np.array([[0, 0, 0, 1]]) homo = np.concatenate((new_m, h), axis=0) return homo def test_hand_eye(self): # origin of chess board in robot base (only for left camera) points_base = [] for i in range(20): origin = np.concatenate((self.objpoints[0][0], [1]), axis=0) # in WCS M1 = self._homo(self.R_gripper2base[i], self.t_gripper2base[i]) M2 = self._homo(self.R_cam2gripper_l, self.t_cam2gripper_l) M3 = self._homo(cv2.Rodrigues(self.r1[i])[0], self.t1[i]) point = np.matmul(np.matmul(M1, np.matmul(M2, M3)), origin) points_base.append(point[:3]) print("---------- Hand-eye recovery variation ----------") print("Origin of chessboard in robot base coordinate system: ") print(np.array(points_base)) print("Variation: ",
np.var(points_base, axis=0)
numpy.var
import reader import loader import svm_model import numpy as np """ Unit test each module """ # loader returns standardized training/test dataset size = 10 imgs, labels = loader.load(data_size=size) assert len(imgs) == size and len(labels) == size, \ "loader can't load correct size of data" for i in range(size): img, label = imgs[i], labels[i] assert len(img) == 28*28, "Wrong image shape, {} != {}".format(len(img), 28*28) assert abs(
np.mean(img)
numpy.mean
#!/usr/bin/env python import numpy as np from time import time import pyfftw from numpy.fft import fft, ifft, fftshift, ifftshift, fft2, ifft2 from scipy.special import jv as besselj import finufftpy def translations_brute_force(Shathat, Mhat, cmul_trans): # Shathat: (q, te, k) # Mhat: (im, k × γ) # cmul_trans: (tr, k × γ) n_trans = cmul_trans.shape[-2] n_images = Mhat.shape[-2] Shathat = Shathat.transpose((2, 0, 1)) # Shathat: (q, te, k) n_templates = Shathat.shape[-2] ngridr = Shathat.shape[-1] n_gamma = Shathat.shape[-3] Mhat = Mhat.reshape((n_images, ngridr, n_gamma)) cmul_trans = cmul_trans.reshape((n_trans, ngridr, n_gamma)) # Mhat: (im, k, γ) # cmul_trans: (tr, k, γ) Mhat = Mhat[:, np.newaxis, :, :] cmul_trans = cmul_trans[np.newaxis, :, :, :] # Mhat: (im, 1, k, γ) # cmul_trans: (1, tr, k, γ) Mhat = Mhat.transpose((3, 2, 0, 1)).copy() cmul_trans = cmul_trans.transpose((3, 2, 0, 1)).copy() # Mhat: (γ, k, im, 1) # cmul_trans: (γ, k, 1, tr) Mhat_trans = pyfftw.empty_aligned((n_gamma, ngridr, n_images, n_trans), dtype='complex128') # Mhat_trans: (γ, k, im × tr) plan = pyfftw.FFTW(Mhat_trans, Mhat_trans, axes=(0,), direction='FFTW_FORWARD', flags=('FFTW_ESTIMATE',), threads=12) tmr_start = time() np.multiply(Mhat, cmul_trans, out=Mhat_trans) plan() Mhathat_trans = Mhat_trans.reshape((n_gamma, ngridr, n_images * n_trans)) # Mhathat_trans: (q, k, im × tr) ptm = time() - tmr_start tmr_start = time() c_n2 = np.zeros((n_gamma, n_templates, n_images*n_trans), dtype=np.complex128) # c_n2: (q, te, im × tr) for k1 in range(n_gamma): k1p = (k1 + n_gamma // 2) % n_gamma c_n2[k1, :, :] = np.matmul(np.conj(Shathat[k1p, :, :]), Mhathat_trans[k1, :, :]) c_n2 = 2 * np.pi * c_n2 c_n2 = ifft(c_n2, axis=0) # c_n2: (γ, te, im × tr) c_n2 = c_n2.reshape((n_gamma, n_templates, n_images, n_trans)) c_n2 = np.real(c_n2) # c_n2: (γ, te, im, tr) tm = time() - tmr_start return c_n2, ptm, tm def translations_brute_force_batch(Shathat, Mhat, pf_grid, tr_grid, n_psi, n_batch_im=None, n_batch_trans=500): n_templates = Shathat.shape[0] n_images = Mhat.shape[0] trans = tr_grid['trans'] n_trans = tr_grid['n_trans'] if n_batch_im is None: n_batch_im = n_images n_batch_trans = min(n_batch_trans, n_trans) zprods1 = np.zeros((n_psi, n_templates, n_images, n_trans)) # zprods1: (γ, te, im, tr) tm1 = 0 precomp1 = 0 for cn in range(0, n_images, n_batch_im): idx_im = range(cn, min(cn + n_batch_im, n_images)) for ttt in range(0, n_trans, n_batch_trans): idx_trans = range(ttt, min(ttt + n_batch_trans, n_trans)) cmul_trans = pft_phase_shift(-trans[idx_trans, :], pf_grid) # cmul_trans: (tr, k × γ) tmp, ptm, tm = translations_brute_force( Shathat, Mhat[idx_im, :], cmul_trans) zprods1[np.ix_(range(n_psi), range(n_templates), idx_im, idx_trans)] = tmp precomp1 += ptm tm1 += tm zprods1 = zprods1.transpose((2, 1, 0, 3)) return zprods1, precomp1, tm1 def svd_decomposition_alignment(SSS, Mhat, n_bessel, all_rnks, BigMul_left): ngridr = SSS.shape[-1] n_templates = SSS.shape[-2] n_gamma = SSS.shape[-3] n_images = Mhat.shape[-2] n_trans = BigMul_left.shape[-1] tmr_start = time() Mhathat = Mhat.reshape((n_images, ngridr, n_gamma)) Mhathat = fftshift(fft(Mhathat, axis=-1), axes=-1) / n_gamma MMM = np.zeros((n_images, 2 * n_bessel + 1, ngridr, n_gamma), dtype=np.complex128) for im in range(n_images): for qp in range(-n_bessel, n_bessel + 1): tmp = Mhathat[im, :, :] MMM[im, qp + n_bessel, :, :] = np.roll(tmp, -qp, axis=-1) MMM = MMM.transpose((1, 3, 2, 0)).copy() precomp2 = time() - tmr_start tmr_start = time() BigMul_right = np.zeros((sum(all_rnks), n_gamma, n_templates, n_images), dtype=np.complex128) for qp in range(-n_bessel, n_bessel + 1): rnk = all_rnks[qp + n_bessel] ofst = sum(all_rnks[:qp + n_bessel]) for ll in range(rnk): for q in range(n_gamma): tmp = np.matmul(SSS[ofst + ll, q, :, :], MMM[qp + n_bessel, q, :, :]) BigMul_right[ofst + ll, q, :, :] = tmp BigMul_right = BigMul_right.transpose((3, 2, 1, 0)).copy() c_n = np.zeros((n_images, n_templates, n_gamma, n_trans), dtype=np.complex128) for im in range(n_images): for tt in range(n_templates): c_n[im, tt, :, :] = np.matmul(BigMul_right[im, tt, :, :], BigMul_left) c_n = 2 * np.pi * c_n zprods = ifft(ifftshift(c_n, axes=-2), axis=-2) * n_gamma tm2 = time() - tmr_start return zprods, precomp2, tm2 def cartesian_to_pft(templates, T, pf_grid): xnodesr = pf_grid['xnodesr'] n_psi = pf_grid['n_psi'] ngridr = xnodesr.shape[0] n_templates = templates.shape[0] N = templates.shape[1] dx = T / N dy = T / N wx = pf_grid['wx'] wy = pf_grid['wy'] Shat = np.zeros((n_templates, ngridr * n_psi), dtype=np.complex128) upsampfac = 1.25 fcc = np.empty(len(wx), dtype=np.complex128) for k in range(n_templates): template = templates[k, :, :] # Need to force Fortran ordering because that's what the FINUFFT # interface expects. gg = np.asfortranarray(template.transpose((1, 0))) isign = -1 eps = 1e-6 # Note: Crashes if gg is a 1D vector (raveled). Why? finufftpy.nufft2d2(wx * dx, wy * dy, fcc, isign, eps, gg, upsampfac=upsampfac) Shat[k, :] = fcc return Shat def pft_to_cartesian(Shat, T, N, pf_grid): xnodesr = pf_grid['xnodesr'] n_psi = pf_grid['n_psi'] quad_wts = pf_grid['quad_wts'] ngridr = xnodesr.shape[0] n_templates = Shat.shape[0] dx = T / N dy = T / N wx = pf_grid['wx'] wy = pf_grid['wy'] templates1 = np.zeros((n_templates, N, N)) # Again, Fortran ordering is necessary for FINUFFT. gxx = np.empty((N, N), dtype=np.complex128, order='F') upsampfac = 1.25 for k in range(n_templates): fcc1 = Shat[k, :] * quad_wts isign = 1 eps = 1e-6 finufftpy.nufft2d1(wx * dx, wy * dy, fcc1, isign, eps, N, N, gxx, upsampfac=upsampfac) gxx = gxx*dx*dy/(4*np.pi**2) templates1[k, :, :] = np.real(gxx.transpose((1, 0))) return templates1 def rotate_pft(fcc, rgamma, pf_grid): xnodesr = pf_grid['xnodesr'] n_psi = pf_grid['n_psi'] ngridr = xnodesr.shape[0] ngridc = n_psi * np.ones(ngridr, dtype=np.int32) fcc_rot = np.zeros(fcc.shape, dtype=np.complex128) cnt = 0 for rr in range(ngridr): tmp = fcc[:, cnt:cnt + ngridc[rr]] ffcc = fft(tmp) n_theta = ngridc[rr] wth = ifftshift(np.arange(-n_theta/2, n_theta/2)) mul = np.exp(-1j * wth * rgamma[:, np.newaxis]) ffcc_rot = ffcc * mul tmp = ifft(ffcc_rot) fcc_rot[:, cnt:cnt + ngridc[rr]] = tmp cnt += ngridc[rr] return fcc_rot def pft_phase_shift(sh, pf_grid): all_psi = pf_grid['all_psi'] quad_xnodesr = pf_grid['all_r'] phase = (np.cos(all_psi) * sh[:, np.newaxis, 0] + np.sin(all_psi) * sh[:, np.newaxis, 1]) cmul = np.exp(-1j * quad_xnodesr * phase) return cmul def translate_pft(fcc, sh, pf_grid): cmul = pft_phase_shift(sh, pf_grid) return fcc * cmul def pft_norm(Mhat, pf_grid): quad_wts = pf_grid['quad_wts'] return np.sqrt(np.sum((np.abs(Mhat) ** 2) * quad_wts, axis=-1)) def pft_to_fb(Shat, pf_grid): ngridr = pf_grid['ngridr'] n_psi = pf_grid['n_psi'] quad_wts = pf_grid['quad_wts'] n_templates = Shat.shape[0] quad_wts_sq = quad_wts.reshape((ngridr, n_psi)) Shathat = Shat.reshape((n_templates, ngridr, n_psi)) # Shathat: (te, k, γ) Shathat = np.fft.fftshift(np.fft.fft(Shathat, axis=-1), axes=-1) Shathat = Shathat * quad_wts_sq[np.newaxis, :, :] # Shathat: (te, k, q) # There was a 2π factor missing before. Let's remove it. Shathat = Shathat / (2 * np.pi) return Shathat def make_tensor_grid(rmax, ngridr, n_psi): dr = rmax/ngridr xnodesr = dr*np.arange(1, ngridr+1) weights = dr*np.ones(ngridr) psi = 2 * np.pi / n_psi * np.arange(n_psi) all_psi = np.repeat(psi[np.newaxis, :], ngridr, axis=0) all_psi = np.ravel(all_psi) all_r = np.repeat(xnodesr[:, np.newaxis], n_psi, axis=1) all_r = np.ravel(all_r) wts_theta = 2 * np.pi / n_psi quad_wts = wts_theta * xnodesr * weights quad_wts = np.repeat(quad_wts[:, np.newaxis], n_psi, axis=-1) quad_wts = np.ravel(quad_wts) wx = np.zeros(n_psi * ngridr) wy = np.zeros(n_psi * ngridr) cnt = 0 for rr in range(ngridr): dd = xnodesr[rr] theta = 2 * np.pi / n_psi * np.arange(n_psi) wx[cnt:cnt + n_psi] = dd *
np.cos(theta)
numpy.cos
# This is a script that analyses the multimode simulation results. # This simulates a RZ multimode periodic plasma wave. # The electric field from the simulation is compared to the analytic value import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from pywarpx import picmi constants = picmi.constants ########################## # physics parameters ########################## density = 2.e24 epsilon0 = 0.001*constants.c epsilon1 = 0.001*constants.c epsilon2 = 0.001*constants.c w0 = 5.e-6 n_osc_z = 3 # Plasma frequency wp = np.sqrt((density*constants.q_e**2)/(constants.m_e*constants.ep0)) kp = wp/constants.c ########################## # numerics parameters ########################## nr = 64 nz = 200 rmin = 0.e0 zmin = 0.e0 rmax = +20.e-6 zmax = +40.e-6 # Wave vector of the wave k0 = 2.*np.pi*n_osc_z/(zmax - zmin) diagnostic_intervals = 40 ########################## # physics components ########################## uniform_plasma = picmi.UniformDistribution(density = density, upper_bound = [+18e-6, +18e-6, None], directed_velocity = [0., 0., 0.]) momentum_expressions = ["""+ epsilon0/kp*2*x/w0**2*exp(-(x**2+y**2)/w0**2)*sin(k0*z) - epsilon1/kp*2/w0*exp(-(x**2+y**2)/w0**2)*sin(k0*z) + epsilon1/kp*4*x**2/w0**3*exp(-(x**2+y**2)/w0**2)*sin(k0*z) - epsilon2/kp*8*x/w0**2*exp(-(x**2+y**2)/w0**2)*sin(k0*z) + epsilon2/kp*8*x*(x**2-y**2)/w0**4*exp(-(x**2+y**2)/w0**2)*sin(k0*z)""", """+ epsilon0/kp*2*y/w0**2*exp(-(x**2+y**2)/w0**2)*sin(k0*z) + epsilon1/kp*4*x*y/w0**3*exp(-(x**2+y**2)/w0**2)*sin(k0*z) + epsilon2/kp*8*y/w0**2*exp(-(x**2+y**2)/w0**2)*sin(k0*z) + epsilon2/kp*8*y*(x**2-y**2)/w0**4*exp(-(x**2+y**2)/w0**2)*sin(k0*z)""", """- epsilon0/kp*k0*exp(-(x**2+y**2)/w0**2)*cos(k0*z) - epsilon1/kp*k0*2*x/w0*exp(-(x**2+y**2)/w0**2)*cos(k0*z) - epsilon2/kp*k0*4*(x**2-y**2)/w0**2*exp(-(x**2+y**2)/w0**2)*cos(k0*z)"""] analytic_plasma = picmi.AnalyticDistribution(density_expression = density, upper_bound = [+18e-6, +18e-6, None], epsilon0 = epsilon0, epsilon1 = epsilon1, epsilon2 = epsilon2, kp = kp, k0 = k0, w0 = w0, momentum_expressions = momentum_expressions) electrons = picmi.Species(particle_type='electron', name='electrons', initial_distribution=analytic_plasma) protons = picmi.Species(particle_type='proton', name='protons', initial_distribution=uniform_plasma) ########################## # numerics components ########################## grid = picmi.CylindricalGrid(number_of_cells = [nr, nz], n_azimuthal_modes = 3, lower_bound = [rmin, zmin], upper_bound = [rmax, zmax], lower_boundary_conditions = ['none', 'periodic'], upper_boundary_conditions = ['none', 'periodic'], lower_boundary_conditions_particles = ['absorbing', 'periodic'], upper_boundary_conditions_particles = ['absorbing', 'periodic'], moving_window_zvelocity = 0., warpx_max_grid_size=64) solver = picmi.ElectromagneticSolver(grid=grid, cfl=1., warpx_do_pml=False) ########################## # diagnostics ########################## field_diag1 = picmi.FieldDiagnostic(name = 'diag1', grid = grid, period = diagnostic_intervals, data_list = ['Ex', 'Ez', 'By', 'Jx', 'Jz', 'part_per_cell'], write_dir = '.', warpx_file_prefix = 'Python_Langmuir_rz_multimode_plt') part_diag1 = picmi.ParticleDiagnostic(name = 'diag1', period = diagnostic_intervals, species = [electrons], data_list = ['weighting', 'momentum']) ########################## # simulation setup ########################## sim = picmi.Simulation(solver = solver, max_steps = 40, verbose = 1, warpx_current_deposition_algo = 'esirkepov', warpx_field_gathering_algo = 'energy-conserving', warpx_particle_pusher_algo = 'boris', warpx_use_filter = 0) sim.add_species(electrons, layout=picmi.GriddedLayout(n_macroparticle_per_cell=[2,16,2], grid=grid)) sim.add_species(protons, layout=picmi.GriddedLayout(n_macroparticle_per_cell=[2,16,2], grid=grid)) sim.add_diagnostic(field_diag1) sim.add_diagnostic(part_diag1) ########################## # simulation run ########################## # write_inputs will create an inputs file that can be used to run # with the compiled version. #sim.write_input_file(file_name='inputsrz_from_PICMI') # Alternatively, sim.step will run WarpX, controlling it from Python sim.step() # Below is WarpX specific code to check the results. import pywarpx from pywarpx.fields import * def calcEr( z, r, k0, w0, wp, t, epsilons) : """ Return the radial electric field as an array of the same length as z and r, in the half-plane theta=0 """ Er_array = ( epsilons[0] * constants.m_e*constants.c/constants.q_e * 2*r/w0**2 * np.exp( -r**2/w0**2 ) * np.sin( k0*z ) * np.sin( wp*t ) - epsilons[1] * constants.m_e*constants.c/constants.q_e * 2/w0 * np.exp( -r**2/w0**2 ) * np.sin( k0*z ) * np.sin( wp*t ) + epsilons[1] * constants.m_e*constants.c/constants.q_e * 4*r**2/w0**3 * np.exp( -r**2/w0**2 ) * np.sin( k0*z ) * np.sin( wp*t ) - epsilons[2] * constants.m_e*constants.c/constants.q_e * 8*r/w0**2 * np.exp( -r**2/w0**2 ) * np.sin( k0*z ) * np.sin( wp*t ) + epsilons[2] * constants.m_e*constants.c/constants.q_e * 8*r**3/w0**4 *
np.exp( -r**2/w0**2 )
numpy.exp
from os.path import basename, exists from shutil import copyfileobj from copy import deepcopy from numbers import Number import warnings import numpy as np import f90nml from f90nml.namelist import Namelist import pandas as pd import re from six import StringIO from pymagicc.utils import apply_string_substitutions from .definitions import ( DATTYPE_REGIONMODE_REGIONS, PART_OF_SCENFILE_WITH_EMISSIONS_CODE_0, PART_OF_SCENFILE_WITH_EMISSIONS_CODE_1, PART_OF_PRNFILE, convert_magicc_to_openscm_regions, convert_magicc7_to_openscm_variables, convert_magicc6_to_magicc7_variables, convert_pint_to_fortran_safe_units, DATA_HIERARCHY_SEPARATOR, ) UNSUPPORTED_OUT_FILES = [ r".*CARBONCYCLE.*OUT", r".*SUBANN.*BINOUT", r".*DAT_VOLCANIC_RF\.BINOUT", r".*PF\_.*OUT", r".*DATBASKET_.*", r".*INVERSE.*EMIS.*OUT", r".*PRECIPINPUT.*OUT", r".*TEMP_OCEANLAYERS.*\.BINOUT", r".*TIMESERIESMIX.*OUT", r".*SUMMARY_INDICATORS.OUT", ] """list: List of regular expressions which define output files we cannot read. These files are nasty to read and not that useful hence are unsupported. The solution for these files is to fix the output format rather than hacking the readers. Obviously that doesn't help for the released MAGICC6 binary but there is nothing we can do there. For MAGICC7, we should have a much nicer set. Some more details about why these files are not supported: - ``CARBONCYCLE.OUT`` has no units and we don't want to hardcode them - Sub annual binary files (including volcanic RF) are asking for trouble - Permafrost output files don't make any sense right now - Output baskets have inconsistent variable names from other outputs - Inverse emissions files have no units and we don't want to hardcode them - We have no idea what the precipitation input is - Temp ocean layers is hard to predict because it has many layers - Time series mix output files don't have units or regions - Summary indicator files are a brand new format for little gain """ def _unsupported_file(filepath): for outfile in UNSUPPORTED_OUT_FILES: if re.match(outfile, filepath): return True return False class NoReaderWriterError(ValueError): """Exception raised when a valid Reader or Writer could not be found for the file """ pass class InvalidTemporalResError(ValueError): """Exception raised when a file has a temporal resolution which cannot be processed """ pass class _InputReader(object): header_tags = [ "compiled by", "contact", "data", "date", "description", "gas", "source", "unit", "magicc-version", "run", "run_id", ] _newline_char = "\n" _variable_line_keyword = "VARIABLE" _regexp_capture_variable = None _default_todo_fill_value = "SET" def __init__(self, filepath): self.filepath = filepath def _set_lines(self): # TODO document this choice # We have to make a choice about special characters e.g. names with # umlauts. The standard seems to be utf-8 hence we set things up to # only work if the encoding is utf-8. with open( self.filepath, "r", encoding="utf-8", newline=self._newline_char ) as f: self.lines = f.readlines() def read(self): self._set_lines() nml_end, nml_start = self._find_nml() nml_values = self.process_metadata(self.lines[nml_start : nml_end + 1]) # ignore all nml_values except units metadata = {key: value for key, value in nml_values.items() if key == "units"} metadata["header"] = "".join(self.lines[:nml_start]) header_metadata = self.process_header(metadata["header"]) metadata.update(header_metadata) # Create a stream from the remaining lines, ignoring any blank lines stream = StringIO() cleaned_lines = [l.strip() for l in self.lines[nml_end + 1 :] if l.strip()] stream.write("\n".join(cleaned_lines)) stream.seek(0) df, metadata = self.process_data(stream, metadata) return metadata, df def _find_nml(self): """ Find the start and end of the embedded namelist. Returns ------- (int, int) start and end index for the namelist """ nml_start = None nml_end = None for i in range(len(self.lines)): if self.lines[i].strip().startswith("&"): nml_start = i if self.lines[i].strip().startswith("/"): nml_end = i assert ( nml_start is not None and nml_end is not None ), "Could not find namelist within {}".format(self.filepath) return nml_end, nml_start def process_metadata(self, lines): def preprocess_edge_cases(lines, inverse=False): replacements = {"W/m": "Wperm", "^": "superscript"} return apply_string_substitutions(lines, replacements, inverse=inverse) def postprocess_edge_cases(value): return preprocess_edge_cases(value, inverse=True) # TODO: replace with f90nml.reads when released (>1.0.2) parser = f90nml.Parser() lines = preprocess_edge_cases(lines) nml = parser._readstream(lines, {}) metadata = {} for k in nml["THISFILE_SPECIFICATIONS"]: metadata_key = k.split("_")[1] try: # have to do this type coercion as nml reads things like # 10superscript22 J into a threepart list, [10, # 'superscript22', 'J'] where the first part is an int metadata[metadata_key] = "".join( [str(v) for v in nml["THISFILE_SPECIFICATIONS"][k]] ) metadata[metadata_key] = postprocess_edge_cases(metadata[metadata_key]) except TypeError: metadata[metadata_key] = nml["THISFILE_SPECIFICATIONS"][k] return metadata def process_data(self, stream, metadata): """ Extract the tabulated data from the input file. Parameters ---------- stream : Streamlike object A Streamlike object (nominally StringIO) containing the table to be extracted metadata : dict Metadata read in from the header and the namelist Returns ------- (pandas.DataFrame, dict) The first element contains the data, processed to the standard MAGICCData format. The second element is th updated metadata based on the processing performed. """ ch, metadata = self._get_column_headers_and_update_metadata(stream, metadata) df = self._convert_data_block_and_headers_to_df(stream, ch) return df, metadata def _convert_data_block_and_headers_to_df(self, stream, column_headers): """ stream : Streamlike object A Streamlike object (nominally StringIO) containing the data to be extracted ch : dict Column headers to use for the output pd.DataFrame Returns ------- :obj:`pd.DataFrame` Dataframe with processed datablock """ df = pd.read_csv( stream, skip_blank_lines=True, delim_whitespace=True, header=None, index_col=0, ) if isinstance(df.index, pd.core.indexes.numeric.Float64Index): df.index = df.index.to_series().round(3) df.index.name = "time" df.columns = self._get_columns_multiindex_from_column_headers(column_headers) df = pd.DataFrame(df.T.stack(), columns=["value"]).reset_index() self._convert_to_categorical_columns(df) return df def _convert_to_categorical_columns(self, df): for categorical_column in ["variable", "todo", "unit", "region"]: df[categorical_column] = df[categorical_column].astype("category") return df def _get_columns_multiindex_from_column_headers(self, ch): return pd.MultiIndex.from_arrays( [ch["variables"], ch["todos"], ch["units"], ch["regions"]], names=("variable", "todo", "unit", "region"), ) def _get_column_headers_and_update_metadata(self, stream, metadata): if self._magicc7_style_header(): column_headers, metadata = self._read_magicc7_style_header(stream, metadata) else: column_headers, metadata = self._read_magicc6_style_header(stream, metadata) column_headers["variables"] = convert_magicc7_to_openscm_variables( column_headers["variables"] ) column_headers["regions"] = convert_magicc_to_openscm_regions( column_headers["regions"] ) return column_headers, metadata def _magicc7_style_header(self): return any(["TODO" in line for line in self.lines]) and any( ["UNITS" in line for line in self.lines] ) def _read_magicc7_style_header(self, stream, metadata): # Note that regions header line is assumed to start with 'YEARS' # instead of 'REGIONS' column_headers = { "variables": self._read_data_header_line( stream, self._variable_line_keyword ), "todos": self._read_data_header_line(stream, "TODO"), "units": self._read_data_header_line(stream, "UNITS"), "regions": self._read_data_header_line(stream, "YEARS"), } metadata.pop("units") return column_headers, metadata def _read_magicc6_style_header(self, stream, metadata): # File written in MAGICC6 style with only one header line rest of # data must be inferred. # Note that regions header line is assumed to start with 'COLCODE' # or 'YEARS' instead of 'REGIONS' try: pos_regions = stream.tell() regions = self._read_data_header_line(stream, "COLCODE") except AssertionError: stream.seek(pos_regions) regions = self._read_data_header_line(stream, "YEARS") try: unit = metadata["unit"] metadata.pop("unit") except KeyError: unit = metadata["units"] metadata.pop("units") if "(" in unit: regexp_capture_unit = re.compile(r".*\((.*)\)\s*$") unit = regexp_capture_unit.search(unit).group(1) variable = convert_magicc6_to_magicc7_variables( self._get_variable_from_filepath() ) column_headers = { "variables": [variable] * len(regions), "todos": [self._default_todo_fill_value] * len(regions), "units": [unit] * len(regions), "regions": regions, } for k in ["unit", "units", "gas"]: try: metadata.pop(k) except KeyError: pass return column_headers, metadata def _get_variable_from_filepath(self): """ Determine the file variable from the filepath. Returns ------- str Best guess of variable name from the filepath """ try: return self.regexp_capture_variable.search(self.filepath).group(1) except AttributeError: self._raise_cannot_determine_variable_from_filepath_error() @property def regexp_capture_variable(self): if self._regexp_capture_variable is None: raise NotImplementedError() return self._regexp_capture_variable def _raise_cannot_determine_variable_from_filepath_error(self): error_msg = "Cannot determine variable from filepath: {}".format(self.filepath) raise ValueError(error_msg) def process_header(self, header): """ Parse the header for additional metadata. Parameters ---------- header : str All the lines in the header. Returns ------- dict The metadata in the header. """ metadata = {} for line in header.split("\n"): line = line.strip() for tag in self.header_tags: tag_text = "{}:".format(tag) if line.lower().startswith(tag_text): metadata[tag] = line[len(tag_text) + 1 :].strip() return metadata def _read_data_header_line(self, stream, expected_header): tokens = stream.readline().split() assert ( tokens[0] == expected_header ), "Expected a header token of {}, got {}".format(expected_header, tokens[0]) return tokens[1:] def _unify_magicc_regions(self, regions): region_mapping = { "GLOBAL": "GLOBAL", "NO": "NHOCEAN", "SO": "SHOCEAN", "NL": "NHLAND", "SL": "SHLAND", "NH-OCEAN": "NHOCEAN", "SH-OCEAN": "SHOCEAN", "NH-LAND": "NHLAND", "SH-LAND": "SHLAND", } return [region_mapping[r] for r in regions] def _read_units(self, column_headers): column_headers["units"] = convert_pint_to_fortran_safe_units( column_headers["units"], inverse=True ) for i, unit in enumerate(column_headers["units"]): if unit in ("W/m2", "W/m^2"): column_headers["units"][i] = "W / m^2" return column_headers class _FourBoxReader(_InputReader): def _read_magicc6_style_header(self, stream, metadata): column_headers, metadata = super()._read_magicc6_style_header(stream, metadata) column_headers["regions"] = self._unify_magicc_regions( column_headers["regions"] ) assert ( len(set(column_headers["units"])) == 1 ), "Only one unit should be found for a MAGICC6 style file" return column_headers, metadata class _ConcInReader(_FourBoxReader): _regexp_capture_variable = re.compile(r".*\_(\w*\-?\w*\_CONC)\.IN$") def _get_variable_from_filepath(self): variable = super()._get_variable_from_filepath() return convert_magicc6_to_magicc7_variables(variable) def _read_data_header_line(self, stream, expected_header): tokens = super()._read_data_header_line(stream, expected_header) return [t.replace("_MIXINGRATIO", "") for t in tokens] class _OpticalThicknessInReader(_FourBoxReader): _regexp_capture_variable = re.compile(r".*\_(\w*\_OT)\.IN$") def _read_magicc6_style_header(self, stream, metadata): column_headers, metadata = super()._read_magicc6_style_header(stream, metadata) metadata["unit normalisation"] = column_headers["units"][0] column_headers["units"] = ["dimensionless"] * len(column_headers["units"]) return column_headers, metadata def _read_data_header_line(self, stream, expected_header): tokens = super()._read_data_header_line(stream, expected_header) return [t.replace("OT-", "") for t in tokens] class _RadiativeForcingInReader(_FourBoxReader): _regexp_capture_variable = re.compile(r".*\_(\w*\_RF)\.(IN|MON)$") def _read_data_header_line(self, stream, expected_header): tokens = super()._read_data_header_line(stream, expected_header) return [t.replace("FORC-", "") for t in tokens] # TODO: delete this in another PR def _read_magicc6_style_header(self, stream, metadata): column_headers, metadata = super()._read_magicc6_style_header(stream, metadata) return column_headers, metadata def _get_column_headers_and_update_metadata(self, stream, metadata): column_headers, metadata = super()._get_column_headers_and_update_metadata( stream, metadata ) column_headers = self._read_units(column_headers) return column_headers, metadata class _EmisInReader(_InputReader): def _read_units(self, column_headers): column_headers = super()._read_units(column_headers) units = column_headers["units"] variables = column_headers["variables"] for i, (unit, variable) in enumerate(zip(units, variables)): unit = unit.replace("-", "") if unit.startswith("Gt"): mass = "Gt" elif unit.startswith("Mt"): mass = "Mt" elif unit.startswith("kt"): mass = "kt" elif unit.startswith("t"): mass = "t" else: raise ValueError("Unexpected emissions unit") emissions_unit = unit.replace(mass, "") if not emissions_unit: emissions_unit = variable.split(DATA_HIERARCHY_SEPARATOR)[1] if "/" not in emissions_unit: # TODO: think of a way to not have to assume years... emissions_unit = "{} / yr".format(emissions_unit) else: emissions_unit = re.sub(r"(\S)\s?/\s?yr", r"\1 / yr", emissions_unit) units[i] = "{} {}".format(mass, emissions_unit) variables[i] = variable column_headers["units"] = units column_headers["variables"] = variables return column_headers class _StandardEmisInReader(_EmisInReader): _regexp_capture_variable = re.compile(r".*\_(\w*\_EMIS)\.IN$") _variable_line_keyword = "GAS" def _read_data_header_line(self, stream, expected_header): tokens = super()._read_data_header_line(stream, expected_header) return [t.replace("EMIS-", "") for t in tokens] def _get_column_headers_and_update_metadata(self, stream, metadata): column_headers, metadata = super()._get_column_headers_and_update_metadata( stream, metadata ) tmp_vars = [] for v in column_headers["variables"]: # TODO: work out a way to avoid this fragile check and calling the # conversion once in the superclass method and again below if v.endswith("_EMIS") or v.startswith("Emissions"): tmp_vars.append(v) else: tmp_vars.append(v + "_EMIS") column_headers["variables"] = convert_magicc7_to_openscm_variables(tmp_vars) column_headers = self._read_units(column_headers) return column_headers, metadata class _HistEmisInReader(_StandardEmisInReader): pass class _Scen7Reader(_StandardEmisInReader): pass class _NonStandardEmisInReader(_EmisInReader): def read(self): self._set_lines() self._stream = self._get_stream() header_notes_lines = self._read_header() df = self.read_data_block() header_notes_lines += self._read_notes() metadata = {"header": "".join(header_notes_lines)} metadata.update(self.process_header(metadata["header"])) return metadata, df def _get_stream(self): # Create a stream to work with, ignoring any blank lines stream = StringIO() cleaned_lines = [l.strip() for l in self.lines if l.strip()] stream.write("\n".join(cleaned_lines)) stream.seek(0) return stream def _read_header(self): raise NotImplementedError() def read_data_block(self): raise NotImplementedError() def _read_notes(self): raise NotImplementedError() class _ScenReader(_NonStandardEmisInReader): def _read_header(self): # I don't know how to do this without these nasty while True statements header_notes_lines = [] end_of_notes_key = "WORLD" while True: prev_pos = self._stream.tell() line = self._stream.readline() if not line: raise ValueError( "Reached end of file without finding {} which should " "always be the first region in a SCEN file".format(end_of_notes_key) ) if line.startswith(end_of_notes_key): self._stream.seek(prev_pos) break header_notes_lines.append(line) return header_notes_lines def read_data_block(self): no_years = int(self.lines[0].strip()) # go through datablocks until there are none left while True: ch = {} pos_block = self._stream.tell() region = convert_magicc_to_openscm_regions(self._stream.readline().strip()) try: variables = convert_magicc6_to_magicc7_variables( self._read_data_header_line(self._stream, "YEARS") ) except IndexError: # tried to get variables from empty string break except AssertionError: # tried to get variables from a notes line break ch["variables"] = convert_magicc7_to_openscm_variables( [v + "_EMIS" for v in variables] ) try: pos_units = self._stream.tell() ch["units"] = self._read_data_header_line(self._stream, "Yrs") except AssertionError: # for SRES SCEN files self._stream.seek(pos_units) ch["units"] = self._read_data_header_line(self._stream, "YEARS") ch = self._read_units(ch) ch["todos"] = ["SET"] * len(variables) ch["regions"] = [region] * len(variables) region_block = StringIO() for i in range(no_years): region_block.write(self._stream.readline()) region_block.seek(0) region_df = self._convert_data_block_and_headers_to_df(region_block, ch) try: df = pd.concat([region_df, df], axis="rows") except NameError: df = region_df self._stream.seek(pos_block) return self._convert_to_categorical_columns(df) def _read_notes(self): notes = [] while True: line = self._stream.readline() if not line: break notes.append(line) return notes class _PrnReader(_NonStandardEmisInReader): def read(self): metadata, df = super().read() # now fix labelling, have to copy index :( variables = df.columns.get_level_values("VARIABLE").tolist() variables = convert_magicc6_to_magicc7_variables(variables) todos = ["SET"] * len(variables) region = convert_magicc_to_openscm_regions("WORLD") concs = False emms = False if "unit" in metadata: if metadata["unit"] == "ppt": concs = True elif metadata["unit"] == "metric tons": emms = True else: error_msg = "I do not recognise the unit, {}, in file{}".format( metadata["unit"], self.filepath ) raise ValueError(error_msg) else: # just have to assume global emissions in tons emms = True if concs: unit = "ppt" variables = [v + "_CONC" for v in variables] elif emms: unit = "t" variables = [v + "_EMIS" for v in variables] column_headers = { "variables": convert_magicc7_to_openscm_variables(variables), "todos": todos, "units": [unit] * len(variables), "regions": [region] * len(variables), } if emms: column_headers = self._read_units(column_headers) df.columns = self._get_columns_multiindex_from_column_headers(column_headers) df = pd.DataFrame(df.T.stack(), columns=["value"]).reset_index() df = self._convert_to_categorical_columns(df) for k in ["gas", "unit"]: try: metadata.pop(k) except KeyError: pass return metadata, df def _read_header(self): # ignore first line, not useful for read self._stream.readline() # I don't know how to do this without these nasty while True statements header_notes_lines = [] end_of_notes_keys = ("CFC11", "CFC-11", "Years") while True: prev_pos = self._stream.tell() line = self._stream.readline() if not line: raise ValueError( "Reached end of file without finding {} which should " "always be the start of the data header line in a .prn file".format( end_of_notes_keys ) ) if line.startswith((end_of_notes_keys)): self._stream.seek(prev_pos) break header_notes_lines.append(line) return header_notes_lines def read_data_block(self): data_block_stream = StringIO() # read out the header data_block_header_line = self._stream.readline() variables = [] col_width = 10 for n in np.arange(0, len(data_block_header_line), col_width): pos = int(n) variable = data_block_header_line[pos : pos + col_width].strip() if variable != "Years": variables.append(variable) # update in read method using metadata todos = ["unknown"] * len(variables) units = ["unknown"] * len(variables) regions = ["unknown"] * len(variables) while True: prev_pos = self._stream.tell() line = self._stream.readline() if not line: # reached end of file break if not re.match(r"^\d{4}\s", line): break data_block_stream.write(line) yr_col_width = 4 col_widths = [yr_col_width] + [10] * len(variables) data_block_stream.seek(0) df = pd.read_fwf(data_block_stream, widths=col_widths, header=None, index_col=0) df.index.name = "time" df.columns = pd.MultiIndex.from_arrays( [variables, todos, units, regions], names=("VARIABLE", "TODO", "UNITS", "REGION"), ) # put stream back for notes reading self._stream.seek(prev_pos) return df def _read_notes(self): notes = [] while True: line = self._stream.readline() if not line: break notes.append(line) return notes class _OutReader(_FourBoxReader): _regexp_capture_variable = re.compile(r"DAT\_(\w*)\.OUT$") _default_todo_fill_value = "N/A" def _get_column_headers_and_update_metadata(self, stream, metadata): column_headers, metadata = super()._get_column_headers_and_update_metadata( stream, metadata ) column_headers = self._read_units(column_headers) return column_headers, metadata class _TempOceanLayersOutReader(_InputReader): _regexp_capture_variable = re.compile(r"(TEMP\_OCEANLAYERS\_?\w*)\.OUT$") _default_todo_fill_value = "N/A" def _read_magicc6_style_header(self, stream, metadata): column_headers, metadata = super()._read_magicc6_style_header(stream, metadata) if set(column_headers["variables"]) == {"TEMP_OCEANLAYERS"}: region = "GLOBAL" elif set(column_headers["variables"]) == {"TEMP_OCEANLAYERS_NH"}: region = "NHOCEAN" elif set(column_headers["variables"]) == {"TEMP_OCEANLAYERS_SH"}: region = "SHOCEAN" else: self._raise_cannot_determine_variable_from_filepath_error() column_headers["variables"] = [ "OCEAN_TEMP_" + l for l in column_headers["regions"] ] column_headers["regions"] = [region] * len(column_headers["regions"]) return column_headers, metadata class _BinData(object): def __init__(self, filepath): # read the entire file into memory self.data = open(filepath, "rb").read() self.data = memoryview(self.data) self.pos = 0 def read_chunk(self, t): """ Read out the next chunk of memory Values in fortran binary streams begin and end with the number of bytes :param t: Data type (same format as used by struct). :return: Numpy array if the variable is an array, otherwise a scalar. """ size = self.data[self.pos : self.pos + 4].cast("i")[0] d = self.data[self.pos + 4 : self.pos + 4 + size] assert ( self.data[self.pos + 4 + size : self.pos + 4 + size + 4].cast("i")[0] == size ) self.pos = self.pos + 4 + size + 4 res = np.array(d.cast(t)) # Return as a scalar or a numpy array if it is an array if res.size == 1: return res[0] return res class _BinaryOutReader(_InputReader): _regexp_capture_variable = re.compile(r"DAT\_(.*)\.BINOUT$") _default_todo_fill_value = "N/A" def read(self): # Read the entire file into memory data = _BinData(self.filepath) metadata = self.process_header(data) df, metadata = self.process_data(data, metadata) return metadata, df def process_data(self, stream, metadata): """ Extract the tabulated data from the input file # Arguments stream (Streamlike object): A Streamlike object (nominally StringIO) containing the table to be extracted metadata (dict): metadata read in from the header and the namelist # Returns df (pandas.DataFrame): contains the data, processed to the standard MAGICCData format metadata (dict): updated metadata based on the processing performed """ index = np.arange(metadata["firstyear"], metadata["lastyear"] + 1) # The first variable is the global values globe = stream.read_chunk("d") assert len(globe) == len(index) regions = stream.read_chunk("d") num_regions = int(len(regions) / len(index)) regions = regions.reshape((-1, num_regions), order="F") data =
np.concatenate((globe[:, np.newaxis], regions), axis=1)
numpy.concatenate
# coding=utf-8 # Copyright 2020 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Lint as: python3 """Helper module for dealing with datasets loaded from TFDS.""" import copy import enum from typing import List, Dict, Optional, Text, Any, Tuple, Callable import attr import cv2 import numpy as np import tensorflow.compat.v1 as tf import tensorflow_datasets as tfds def tfds_load_dataset(dataset_name, *args, **kwargs): """Helper function used to bridge internal google, and the external world.""" data_dir = kwargs.pop("data_dir", None) return tfds.load( dataset_name, *args, data_dir=data_dir, download=True, **kwargs) class Split(enum.Enum): """Enum representing different splits of data for cross validation. Two validation sets are needed for meta-learning optimizers. """ TRAIN = "TRAIN" VALID_INNER = "VALID_INNER" VALID_OUTER = "VALID_OUTER" TEST = "TEST" def split_dataset( dataset, num_per_split, num_splits = 3, ): """Helper to split a dataset for cross validaton. The first num_splits-1 datasets contain num_per_split examples. The last dataset contains the remaining number of examples. This often used to split a training set into more validation sets: e.g. train_old --> [valid_inner, valid_outer, train] Args: dataset: name of tfds dataset num_per_split: number of examples to have for each of the split off dataset. num_splits: number of splits to create. Returns: A list of the requested datasets. """ new_datasets = [] # make the first n_split-1 splits containing num_per_split examples for i in range(num_splits - 1): new_datasets.append(dataset.skip(num_per_split * i).take(num_per_split)) # The remainder of the dataset new_datasets.append(dataset.skip(num_per_split * (num_splits - 1))) return new_datasets def _add_onehot_label_to_dict(d, num_label): """Returns a new dictionary with a label_onehot key.""" d = copy.copy(d) d["label_onehot"] = tf.one_hot(d["label"], num_label) return d def _process_image_in_dict(d): """Returns a new dict with a uint8 image converted to 0-1 scaled image.""" d = copy.copy(d) image = d["image"] if image.dtype != tf.uint8: raise ValueError("Only supports uint8 images") d["image"] = tf.cast(image, tf.float32) / 255. return d @attr.s class Datasets(object): train = attr.ib(Any) valid_inner = attr.ib(Any) valid_outer = attr.ib(Any) test = attr.ib(Any) def get_image_datasets( dataset_name, batch_size, num_per_valid = 3000, num_train = None, cache_dataset = True, shuffle_buffer = None, data_dir = None, augmentation_fn = None, ): """Get an image `Datasets` instance that is ready to train with. This includes caching for speed, repeating, shuffling, preprocessing, and batching for each of the 4 splits. Args: dataset_name: Name of tfds dataset. batch_size: Batch size to use. num_per_valid: Number of validation images. num_train: Number of training examples to use. If None, use all. cache_dataset: Optionally cache the dataset for speed. shuffle_buffer: Size of shuffle buffer. If none, use the full train set size. data_dir: Location of tfds data_dir. augmentation_fn: Function to apply before batching for augmentation. Returns: `Datasets` ready to train with. """ # TODO(lmetz) pin all versions of datasets so they are consistent in time. splits, info = tfds_load_dataset( dataset_name, with_info=True, data_dir=data_dir) num_classes = info.features["label"].num_classes # Some datasets have different splits defined. For meta-learning we need 4 # splits. The following takes the splits that are defined, and tries to use # them when possible. For missing splits, examples are taken off of the train # dataset. if set(splits.keys()) == set(["train", "validation", "test"]): train = splits["train"] test = splits["test"] valid_outer = splits["validation"] # pylint: disable=unbalanced-tuple-unpacking valid_inner, train = split_dataset( train, num_per_split=num_per_valid, num_splits=2) num_test = info.splits["test"].num_examples total_num_train = info.splits["train"].num_examples num_valid = info.splits["validation"].num_examples elif (set(splits.keys()) == set(["train", "test"]) or set(splits.keys()) == set(["train", "validation"])): train = splits["train"] # pylint: disable=unbalanced-tuple-unpacking valid_inner, valid_outer, train = split_dataset( train, num_per_split=num_per_valid, num_splits=3) if "test" in info.splits: heldout_split = info.splits["test"] else: heldout_split = info.splits["validation"] num_test = heldout_split.num_examples test = splits["test"] if "test" in splits else splits["validation"] total_num_train = info.splits["train"].num_examples - num_per_valid * 2 num_valid = num_per_valid elif set(splits.keys()) == set(["train"]): train = splits["train"] # pylint: disable=unbalanced-tuple-unpacking valid_inner, valid_outer, test, train = split_dataset( train, num_per_split=num_per_valid, num_splits=4) total_num_train = info.splits["train"].num_examples - num_per_valid * 3 num_test = num_per_valid num_valid = num_per_valid else: raise ValueError("Unsure how to manage the following splits: %s" % str(list(splits.keys()))) if num_train: train = train.take(num_train) else: num_train = total_num_train datasets = Datasets( train=train, valid_inner=valid_inner, valid_outer=valid_outer, test=test) if cache_dataset: datasets = tf.nest.map_structure(lambda ds: ds.cache(), datasets) datasets = tf.nest.map_structure(lambda ds: ds.repeat(), datasets) train_shuffle = shuffle_buffer if shuffle_buffer else num_train valid_shuffle = shuffle_buffer if shuffle_buffer else num_valid test_shuffle = shuffle_buffer if shuffle_buffer else num_test datasets = Datasets( train=datasets.train.shuffle(train_shuffle), valid_inner=datasets.valid_inner.shuffle(valid_shuffle), valid_outer=datasets.valid_outer.shuffle(valid_shuffle), test=datasets.test.shuffle(test_shuffle)) def pre_process(example): example = _add_onehot_label_to_dict(example, num_classes) return _process_image_in_dict(example) datasets = tf.nest.map_structure(lambda ds: ds.map(pre_process), datasets) if augmentation_fn: datasets = tf.nest.map_structure(lambda ds: ds.map(augmentation_fn), datasets) return tf.nest.map_structure( lambda ds: ds.batch(batch_size, drop_remainder=True), datasets) def _random_slice(example, length): """Extract a random slice or pad to make all sequences a fixed length. For example -- if one passes in [1,2,3,4] with length=2, this would return one of the following: [1,2], [2,3], [3,4]. If the input is [1, 2] with length=4, this would return [1, 2, 0, 0]. Args: example: Dictionary containing a single example with the "text" key. This "text" key should be a vector with an integer type. length: Length of the slice. Returns: An example containing only a fixed slice of text. """ input_length = tf.shape(example["text"])[0] max_idx = input_length - length # pylint: disable=g-long-lambda start_idx = tf.cond( tf.greater(max_idx, 0), lambda: tf.random_uniform( [], tf.to_int32(0), tf.cast(max_idx, tf.int32), dtype=tf.int32), lambda: 0) # pylint: enable=g-long-lambda to_pad = tf.maximum(length - input_length, 0) pad_input = tf.pad(example["text"], [[0, to_pad]]) # copy to prevent a mutation of inputs. example = copy.copy(example) example["text"] = pad_input[start_idx:start_idx + length] example["text"].set_shape([length]) pad_mask = tf.pad(tf.ones([input_length]), [[0, to_pad]]) example["mask"] = pad_mask[start_idx:start_idx + length] example["mask"].set_shape([length]) return example def random_slice_text_data( dataset_name, batch_size, num_train = None, patch_length = 128, num_per_valid = 3000, cache_dataset = False, shuffle_buffer = None, ): """Gets a text dataset ready to train on. This splits the dataset into 4 cross validation splits, takes a random slice to make all entries the same length, and batches the examples. Args: dataset_name: tensorflow_dataset's dataset name. batch_size: batch size. num_train: number of training examples. If None use all examples. patch_length: length of patch to extract. num_per_valid: number of images for each validation set. cache_dataset: Cache the dataset or not. shuffle_buffer: Shuffle buffer size. If None, use dataset size. Returns: Datasets object containing tf.Dataset. """ train, info = tfds_load_dataset( dataset_name, split="train", with_info=True, shuffle_files=True) total_num_train = info.splits["train"].num_examples num_test = info.splits["test"].num_examples # pylint: disable=unbalanced-tuple-unpacking valid_inner, valid_outer, train = split_dataset( train, num_per_split=num_per_valid) # pylint: enable=unbalanced-tuple-unpacking if num_train: train = train.take(num_train) test = tfds_load_dataset(dataset_name, split="test", shuffle_files=True) datasets = Datasets( train=train, valid_inner=valid_inner, valid_outer=valid_outer, test=test) if cache_dataset: datasets = tf.nest.map_structure(lambda ds: ds.cache(), datasets) datasets = tf.nest.map_structure(lambda ds: ds.repeat(), datasets) train_shuffle = shuffle_buffer if shuffle_buffer else total_num_train - num_per_valid * 2 valid_shuffle = shuffle_buffer if shuffle_buffer else num_per_valid test_shuffle = shuffle_buffer if shuffle_buffer else num_test datasets = Datasets( train=datasets.train.shuffle(train_shuffle), valid_inner=datasets.valid_inner.shuffle(valid_shuffle), valid_outer=datasets.valid_outer.shuffle(valid_shuffle), test=datasets.test.shuffle(test_shuffle)) def pre_process(example): """Preprocess example by adding onehot label, and taking a random slice.""" if "label" in info.features: num_classes = info.features["label"].num_classes example = _add_onehot_label_to_dict(example, num_classes) return _random_slice(example, patch_length) datasets = tf.nest.map_structure(lambda ds: ds.map(pre_process), datasets) return tf.nest.map_structure( lambda ds: ds.batch(batch_size, drop_remainder=True), datasets) class ResizedDataset(tfds.core.GeneratorBasedBuilder): """Base class for a resized image tensorflow dataset.""" def __init__(self, parent_builder, size, *args, **kwargs): """Initialize the resized image dataset builder. Args: parent_builder: The builder to build the resized image dataset from. size: size to resize each example to. *args: args passed super class. **kwargs: kwargs passed super class. """ parent_builder.download_and_prepare() self._builder = parent_builder self._size = size super(ResizedDataset, self).__init__(*args, **kwargs) def _info(self): info = self._builder.info description = "\n This dataset has been resized to %dx%d!" % (self._size[0], self._size[1]) new_feature_dict = {k: v for k, v in info.features.items()} new_feature_dict["image"] = tfds.features.Image( shape=list(self._size) + [3]) return tfds.core.DatasetInfo( builder=self, description=info.description + description, homepage=info.homepage, features=tfds.features.FeaturesDict(new_feature_dict), supervised_keys=info.supervised_keys, citation=info.citation) def _split_generators(self, dl_manager): return [ tfds.core.SplitGenerator( name=split, num_shards=4, gen_kwargs=dict(split=split)) for split in self._builder.info.splits.keys() ] def _generate_examples(self, split): for exi, ex in enumerate( tfds.as_numpy(self._builder.as_dataset(split=split))): ex = self._process_example(ex) yield exi, ex def _process_example(self, example): # As of now, this simply converts the image to the passed in size. # TODO(lmetz) It might also make sense to resize then crop out the center. example["image"] = cv2.resize( example["image"], dsize=self._size, interpolation=cv2.INTER_CUBIC) return example class Food101_32x32(ResizedDataset): # pylint: disable=invalid-name """The Food101 dataset resized to be 32x32.""" VERSION = "1.0.0" def __init__(self, *args, **kwargs): parent_builder = tfds.builder("food101", version="1.0.0") super(Food101_32x32, self).__init__( *args, parent_builder=parent_builder, size=(32, 32), **kwargs) class Food101_64x64(ResizedDataset): # pylint: disable=invalid-name """The Food101 dataset resized to be 64x64.""" VERSION = "1.0.0" def __init__(self, *args, **kwargs): parent_builder = tfds.builder("food101", version="1.0.0") super(Food101_64x64, self).__init__( *args, parent_builder=parent_builder, size=(64, 64), **kwargs) class Coil100_32x32(ResizedDataset): # pylint: disable=invalid-name """The coil100 dataset resized to be 32x32.""" VERSION = "1.0.0" def __init__(self, *args, **kwargs): parent_builder = tfds.builder("coil100", version="1.0.0") super(Coil100_32x32, self).__init__( *args, parent_builder=parent_builder, size=(32, 32), **kwargs) class ColorectalHistology_32x32(ResizedDataset): # pylint: disable=invalid-name """The colorectal_histology dataset resized to be 32x32.""" VERSION = "1.0.0" def __init__(self, *args, **kwargs): parent_builder = tfds.builder("colorectal_histology", version="2.*.*") super(ColorectalHistology_32x32, self).__init__( *args, parent_builder=parent_builder, size=(32, 32), **kwargs) class DeepWeeds_32x32(ResizedDataset): # pylint: disable=invalid-name """The deep_weeds dataset resized to be 32x32.""" VERSION = "1.0.0" def __init__(self, *args, **kwargs): parent_builder = tfds.builder("deep_weeds", version="1.0.0") super(DeepWeeds_32x32, self).__init__( *args, parent_builder=parent_builder, size=(32, 32), **kwargs) class Sun397_32x32(ResizedDataset): # pylint: disable=invalid-name """The sun397/tfds dataset resized to be 32x32.""" VERSION = "1.0.0" def __init__(self, *args, **kwargs): parent_builder = tfds.builder("sun397/tfds", version="4.0.0") super(Sun397_32x32, self).__init__( *args, parent_builder=parent_builder, size=(32, 32), **kwargs) class TokenizedConfig(tfds.core.BuilderConfig): """BuilderConfig for tokenized text datasets.""" def __init__(self, version=None, text_encoder_config=None, **kwargs): """BuilderConfig for tokenized text datasets. Args: version (string): version as string. text_encoder_config: `tfds.features.text.TextEncoderConfig`, configuration for the `tfds.features.text.TextEncoder` used for the `"text"` feature. **kwargs: keyword arguments forwarded to super. """ super(TokenizedConfig, self).__init__( version=tfds.core.Version(version), **kwargs) self.text_encoder_config = ( text_encoder_config or tfds.features.text.TextEncoderConfig()) # This is an arbitrarily chosen subset of languages. WIKIPEDIA_PREFIX = [ "20190301.zh", "20190301.ru", "20190301.ja", "20190301.hsb", "20190301.en" ] def _get_builder_configs(base_configs): """Get the builder configs for tokenized datasets.""" configs = [] for prefix in base_configs: configs.append( TokenizedConfig( name="%s_bytes" % prefix, version="0.0.1", description=("Uses byte-level text encoding with " "`tfds.features.text.ByteTextEncoder`"), text_encoder_config=tfds.features.text.TextEncoderConfig( encoder=tfds.features.text.ByteTextEncoder()), )) configs.append( TokenizedConfig( name="%s_subwords8k" % prefix, version="0.0.1", description=("Uses `tfds.features.text.SubwordTextEncoder` with 8k " "vocab size"), text_encoder_config=tfds.features.text.TextEncoderConfig( encoder_cls=tfds.features.text.SubwordTextEncoder, vocab_size=8192), )) return configs class TokenizedWikipedia(tfds.core.GeneratorBasedBuilder): """Builder which tokenizes the tfds wikipedia datasets. This dataset returns 1 paragraph (split via new line) per example extracted from the articles. We additionally filter examples to have more than 5 bytes. Encoding is either bytes, or subwords. The vocab is constructed out of the first 200k examples. While this is likely not perfect this should be sufficient for meta-learning optimizers. Additionally, we make a train and test split by hashing the article seed. Finally, for computational reasons we only use 1 millon articles. For the size of the models we are training here this should be plenty. """ BUILDER_CONFIGS = _get_builder_configs(WIKIPEDIA_PREFIX) def __init__(self, config=None, **kwargs): """Initialize the resized image dataset builder. Args: config: str Config string specified to build dataset with. **kwargs: kwargs passed super class. """ # extract the base dataset. base, _ = config.split("_") self._builder = tfds.builder("wikipedia/%s" % base) super(TokenizedWikipedia, self).__init__(config=config, **kwargs) self._perc_train = 0.7 self._max_num_articles = 1000000 # Number of examples used to build the tokenizer. self._examples_for_tokenizer = 200000 def _info(self): info = self._builder.info description = "\n This dataset has been tokenized!" return tfds.core.DatasetInfo( builder=self, description=info.description + description, features=tfds.features.FeaturesDict({ "title": tfds.features.Text(), "text": tfds.features.Text( encoder_config=self.builder_config.text_encoder_config), }), supervised_keys=("text", "text"), homepage=info.homepage, citation=info.citation) def _split_generators(self, dl_manager): self.info.features["text"].maybe_build_from_corpus(self._vocab_text_gen()) return [ tfds.core.SplitGenerator( name=split, num_shards=10, gen_kwargs=dict(split=split)) for split in ["train", "test"] ] def _split_article(self, ex): for i, split in enumerate(ex["text"].split("\n")): if len(split.strip()) > 5: yield i, {"title": ex["title"], "text": split} def _generate_examples(self, split): hasher = tfds.core.hashing.Hasher("token_wikipedia_salt") for exi, example in enumerate( tfds.as_numpy(self._builder.as_dataset(split="train"))): if exi > self._max_num_articles: return # To make a train test split we first hash the key and convert it to a # floating point value between 0-1. Depending on this value we either # yield the example or not depending on the split. p = hasher.hash_key(exi) % 100000 / 100000. if split == "train" and p < self._perc_train: for i, sub_example in self._split_article(example): key = (exi, i) yield key, sub_example elif split == "test" and p >= self._perc_train: for i, sub_example in self._split_article(example): key = (exi, i) yield key, sub_example def _vocab_text_gen(self): for i, (_, ex) in enumerate(self._generate_examples("train")): # Only yield a subset of the data used for tokenization for # performance reasons. if self._examples_for_tokenizer > i: yield ex["text"] else: return # Arbitrary subset of datasets. AMAZON_PRODUCTS = ["Books_v1_02", "Camera_v1_00", "Home_v1_00", "Video_v1_00"] class TokenizedAmazonReviews(tfds.core.GeneratorBasedBuilder): """Builder which tokenizes the tfds amazon reviews datasets. For compute reasons we only tokenize with 200000 examples. We make a train and test split by hashing the example index. """ BUILDER_CONFIGS = _get_builder_configs(AMAZON_PRODUCTS) def __init__(self, config=None, **kwargs): """Initialize the resized image dataset builder. Args: config: str Config string specified to build dataset with. **kwargs: kwargs passed super class. """ # extract the base dataset. base = "_".join(config.split("_")[0:-1]) self._builder = tfds.builder("amazon_us_reviews/%s" % base) super(TokenizedAmazonReviews, self).__init__(config=config, **kwargs) self._perc_train = 0.7 self._examples_for_tokenizer = 200000 def _info(self): info = self._builder.info description = "\n This dataset has been tokenized!" return tfds.core.DatasetInfo( builder=self, description=info.description + description, features=tfds.features.FeaturesDict({ # 1-5 stars are the labels. "label": tfds.features.ClassLabel(num_classes=5), "text": tfds.features.Text( encoder_config=self.builder_config.text_encoder_config), }), supervised_keys=("text", "label"), homepage=info.homepage, citation=info.citation) def _split_generators(self, dl_manager): self.info.features["text"].maybe_build_from_corpus(self._vocab_text_gen()) return [ tfds.core.SplitGenerator( name=split, num_shards=10, gen_kwargs=dict(split=split)) for split in ["train", "test"] ] def _generate_examples(self, split): hasher = tfds.core.hashing.Hasher("token_wikipedia_salt") for exi, example in enumerate( tfds.as_numpy(self._builder.as_dataset(split="train"))): p = hasher.hash_key(exi) % 1000 / 1000. example = { "text": example["data"]["review_body"], # subtract one to zero index. "label": example["data"]["star_rating"] - 1 } if split == "train" and p < self._perc_train: yield exi, example elif split == "test" and p > self._perc_train: yield exi, example def _vocab_text_gen(self): for i, (_, ex) in enumerate(self._generate_examples("train")): if self._examples_for_tokenizer > i: yield ex["text"] else: return def _single_associative_retrieval(batch_size=128, num_pairs=5, num_tokens=10): """See associative_retrieval.""" def _onehot_pack(inp, out, loss_mask): inp_seq, outputs, loss_mask = (tf.one_hot(inp, num_tokens + 2), tf.one_hot(out, num_tokens + 2), loss_mask) return {"input": inp_seq, "output": outputs, "loss_mask": loss_mask} def _py_make_example(): """Iterator that makes single examples in python.""" while True: keys = np.random.choice(num_tokens, size=num_pairs, replace=False) values = np.random.choice(num_tokens, size=num_pairs, replace=True) empty_token_idx = num_tokens query_token_idx = num_tokens + 1 input_seq = [] output_seq = [] for k, v in zip(keys, values): input_seq.extend([k, v]) output_seq.extend([empty_token_idx, empty_token_idx]) input_seq.append(query_token_idx) output_seq.append(empty_token_idx) query_key = np.random.randint(0, num_pairs) input_seq.append(keys[query_key]) output_seq.append(values[query_key]) loss_mask =
np.zeros(2 * num_pairs + 2, dtype=np.float32)
numpy.zeros
import numpy as np import pytest import tifffile from lxml import etree # nosec from PartSegImage.image import Image from PartSegImage.image_reader import TiffImageReader from PartSegImage.image_writer import IMAGEJImageWriter, ImageWriter @pytest.fixture(scope="module") def ome_xml(bundle_test_dir): return etree.XMLSchema(file=str(bundle_test_dir / "ome.xsd.xml")) def test_scaling(tmp_path): image = Image(np.zeros((10, 50, 50), dtype=np.uint8), (30, 0.1, 0.1), axes_order="ZYX") ImageWriter.save(image, tmp_path / "image.tif") read_image = TiffImageReader.read_image(tmp_path / "image.tif") assert np.all(np.isclose(image.spacing, read_image.spacing)) def test_save_mask(tmp_path): data = np.zeros((10, 40, 40), dtype=np.uint8) data[1:-1, 1:-1, 1:-1] = 1 data[2:-3, 4:-4, 4:-4] = 2 mask = np.array(data > 0).astype(np.uint8) image = Image(data, (0.4, 0.1, 0.1), mask=mask, axes_order="ZYX") ImageWriter.save_mask(image, tmp_path / "mask.tif") read_mask = TiffImageReader.read_image(tmp_path / "mask.tif") assert np.all(np.isclose(read_mask.spacing, image.spacing)) @pytest.mark.parametrize("z_size", (1, 10)) def test_ome_save(tmp_path, bundle_test_dir, ome_xml, z_size): data = np.zeros((z_size, 20, 20, 2), dtype=np.uint8) image = Image( data, image_spacing=(27 * 10 ** -6, 6 * 10 ** -6, 6 * 10 ** -6), axes_order="ZYXC", channel_names=["a", "b"], shift=(10, 9, 8), name="Test", ) ImageWriter.save(image, tmp_path / "test.tif") with tifffile.TiffFile(tmp_path / "test.tif") as tiff: assert tiff.is_ome assert isinstance(tiff.ome_metadata, str) meta_data = tifffile.xml2dict(tiff.ome_metadata)["OME"]["Image"] assert "PhysicalSizeX" in meta_data["Pixels"] assert meta_data["Pixels"]["PhysicalSizeX"] == 6 assert "PhysicalSizeXUnit" in meta_data["Pixels"] assert meta_data["Pixels"]["PhysicalSizeXUnit"] == "µm" assert len(meta_data["Pixels"]["Channel"]) == 2 assert meta_data["Pixels"]["Channel"][0]["Name"] == "a" assert meta_data["Pixels"]["Channel"][1]["Name"] == "b" assert meta_data["Name"] == "Test" xml_file = etree.fromstring(tiff.ome_metadata.encode("utf8")) # nosec ome_xml.assert_(xml_file) read_image = TiffImageReader.read_image(tmp_path / "test.tif") assert np.allclose(read_image.spacing, image.spacing) assert np.allclose(read_image.shift, image.shift) assert read_image.channel_names == ["a", "b"] assert read_image.name == "Test" def test_scaling_imagej(tmp_path): image = Image(np.zeros((10, 50, 50), dtype=np.uint8), (30, 0.1, 0.1), axes_order="ZYX") IMAGEJImageWriter.save(image, tmp_path / "image.tif") read_image = TiffImageReader.read_image(tmp_path / "image.tif") assert np.all(np.isclose(image.spacing, read_image.spacing)) def test_save_mask_imagej(tmp_path): data =
np.zeros((10, 40, 40), dtype=np.uint8)
numpy.zeros
import json import pickle import time from copy import deepcopy from pathlib import Path import numpy as np import torch import tqdm from PIL import Image from nuscenes.eval.common.config import config_factory from nuscenes.eval.detection.data_classes import DetectionBox from nuscenes.eval.tracking.data_classes import TrackingBox from nuscenes.eval.detection.evaluate import DetectionEval from nuscenes.eval.tracking.evaluate import TrackingEval from nuscenes.nuscenes import NuScenes from nuscenes.utils import splits, geometry_utils from nuscenes.utils.data_classes import LidarPointCloud, Box from pyquaternion.quaternion import Quaternion from .nuscenes_utils import map_name_from_general_to_detection from ..dataset import DatasetTemplate class NuScenesIDTrackingDataset(DatasetTemplate): def __init__(self, dataset_cfg, class_names, training=True, root_path=None, logger=None): """ Args: root_path: dataset_cfg: class_names: training: logger: """ super().__init__( dataset_cfg=dataset_cfg, class_names=class_names, training=training, root_path=root_path, logger=logger ) self.camera_list = dataset_cfg.CAM_LIST pk_path = Path(dataset_cfg.INFO_PATH) pk_path.mkdir(parents=True, exist_ok=True) pk_file = pk_path / f'{dataset_cfg.VERSION}_{"train" if training else "val"}_{"_".join(self.class_names)}.pkl' if pk_file.is_file(): with open(pk_file, 'rb') as f: self.sample_info_dict = pickle.load(f) self.id_dict = self.sample_info_dict.pop('id_dict') self.sample_token_list = self.sample_info_dict.pop('token_list') else: start_time = time.time() self.create_sample_info_dict() print('time cost:', time.time() - start_time) self.sample_info_dict['id_dict'] = self.id_dict self.sample_info_dict['token_list'] = self.sample_token_list with open(pk_file, 'wb') as f: pickle.dump(self.sample_info_dict, f) self.sample_info_dict.pop('id_dict') self.sample_info_dict.pop('token_list') def create_sample_info_dict(self): nusc = NuScenes(version=self.dataset_cfg.VERSION, dataroot=str(self.root_path), verbose=True) self.sample_token_list = [] self.sample_info_dict = {} self.id_dict = {} split_scene_names = splits.train if self.training else splits.val instances = set() print(f'Create {"train" if self.training else "val"} info dict') for scene in tqdm.tqdm(nusc.scene): if scene['name'] in split_scene_names: cur_sample_token = scene['first_sample_token'] while True: self.sample_token_list.append((scene['name'], cur_sample_token)) cur_sample_info_dict = {} sample = nusc.get('sample', cur_sample_token) lidar_token = sample['data']['LIDAR_TOP'] lidar = nusc.get('sample_data', lidar_token) cur_sample_info_dict['lidar'] = lidar['filename'] calib_dict = {} cs_record = nusc.get('calibrated_sensor', lidar['calibrated_sensor_token']) calib_dict['LIDAR_TOP'] = (cs_record['translation'], cs_record['rotation']) ego_dict = {} ego_record = nusc.get('ego_pose', lidar['ego_pose_token']) ego_dict['LIDAR_TOP'] = (ego_record['translation'], ego_record['rotation']) camera_dict = {} intrinsic_dict = {} imsize_dict = {} for camera_name in self.camera_list: camera_token = sample['data'][camera_name] sd_record = nusc.get('sample_data', camera_token) camera_dict[camera_name] = sd_record['filename'] cs_record = nusc.get('calibrated_sensor', sd_record['calibrated_sensor_token']) calib_dict[camera_name] = (cs_record['translation'], cs_record['rotation']) ego_record = nusc.get('ego_pose', sd_record['ego_pose_token']) ego_dict[camera_name] = (ego_record['translation'], ego_record['rotation']) intrinsic_dict[camera_name] = np.array(cs_record['camera_intrinsic']) imsize_dict[camera_name] = (sd_record['width'], sd_record['height']) cur_sample_info_dict['camera'] = camera_dict cur_sample_info_dict['calib'] = calib_dict cur_sample_info_dict['ego'] = ego_dict cur_sample_info_dict['intrinsic'] = intrinsic_dict box_list = {camera_name: [] for camera_name in self.camera_list} id_list = {camera_name: [] for camera_name in self.camera_list} name_list = {camera_name: [] for camera_name in self.camera_list} anno_tokens = sample['anns'] for anno_token in anno_tokens: anno = nusc.get('sample_annotation', anno_token) if map_name_from_general_to_detection[anno['category_name']] in self.class_names \ and anno['num_lidar_pts'] > 0: box = Box(anno['translation'], anno['size'], Quaternion(anno['rotation'])) box_name = map_name_from_general_to_detection[anno['category_name']] tracking_id = anno['instance_token'] instances.add(tracking_id) lidar_box = deepcopy(box) # Move box to ego vehicle coord system. translation, rotation = ego_dict['LIDAR_TOP'] lidar_box.translate(-np.array(translation)) lidar_box.rotate(Quaternion(rotation).inverse) # Move box to lidar coord system. translation, rotation = calib_dict['LIDAR_TOP'] lidar_box.translate(-np.array(translation)) lidar_box.rotate(Quaternion(rotation).inverse) xyz = lidar_box.center dxdydz = (lidar_box.wlh[1], lidar_box.wlh[0], lidar_box.wlh[2]) # lwh v = np.dot(lidar_box.orientation.rotation_matrix,
np.array([1, 0, 0])
numpy.array
import numpy as np import SimpleITK as sitk from src.utils.image import get_ct_range, normalize_image def to_np(x): return np.squeeze(np.transpose(sitk.GetArrayFromImage(x), (2, 1, 0))) def get_bb_image(image): origin = image.GetOrigin() max_position = origin + np.array( [image.GetWidth(), image.GetHeight(), image.GetDepth()]) * image.GetSpacing() return
np.concatenate([origin, max_position], axis=0)
numpy.concatenate
import math import random import numpy as np from util import rot_matrix # Frequency at which animations are updated UPDATE_RATE = 30 # Time between each update (in seconds) UPDATE_TIME = 1 / UPDATE_RATE # Colors GREEN = np.array([0,1,0]) BLUE = np.array([0,0,1]) RED = np.array([1,0,0]) YELLOW = np.array([1,1,0]) CYAN = np.array([0,1,1]) MAGENTA = np.array([1,0,1]) class Animation: """ Base class for all animations """ def __init__(self, struct): # 3D structure on which the animation will be mapped self.struct = struct def pulse(self, t): """ Called when a beat or notable audio change occurs Note: some animations may choose not to implement this method """ pass def update(self, t): """ Called at a regular interval to update the animation """ raise NotImplementedError class TestSequence(Animation): """ Test sequence. This is used to help us connect the LED strips in the correct order on the physical cube. """ def __init__(self, struct): super().__init__(struct) self.edge_idx = 0 self.led_idx = 0 def update(self, t): # TODO: flash on first segment # We can add this later edge = self.struct.edges[self.edge_idx] self.led_idx += 1 if self.led_idx >= edge.num_leds: self.edge_idx = (self.edge_idx + 1) % len(self.struct.edges) self.led_idx = 0 self.struct.pixels[:, :] = 0 self.struct.pixels[self.edge_idx, self.led_idx, 0] = 1 class BasicStrobe(Animation): """ Basic strobe light that pulses to the beat """ def __init__(self, struct): super().__init__(struct) self.pulse_time = 0 def pulse(self, t): self.pulse_time = t def update(self, t): dt = t - self.pulse_time brightness = math.pow(0.94, 100 * dt) color = np.array([1, 1, 1]) * brightness self.struct.pixels[:, :] = color class PosiStrobe(Animation): """ Simple positional strobe effect """ def __init__(self, struct): super().__init__(struct) self.pulse_time = 0 self.pos = np.array([0, 0, 0]) def pulse(self, t): self.pulse_time = t # TODO: method to compute min/max cube extents or # sample point around structure self.pos = np.random.uniform( np.array([-0.5, -0.5, -0.5]), np.array([0.5, 0.5, 0.5]) ) def update(self, t): dist = self.struct.poss - self.pos dist = np.linalg.norm(dist, axis=-1) dist =
np.expand_dims(dist, -1)
numpy.expand_dims
# -------------- import numpy as np import warnings warnings.filterwarnings('ignore') import sys import csv #from io import StringIO #with StringIO(file_content) as f: # data = np.loadtxt(f, skiprows=1, dtype=int) #Code Starts here # Command to display all the columns of a numpy array np.set_printoptions(threshold=sys.maxsize) X=[] # Load the data. Data is already given to you in variable `path` with open(path,'r') as f: csv_data=csv.reader(f) next(csv_data) for row in csv_data: X.append(row) data=
np.asarray(X)
numpy.asarray
from ..SqueezeNet.squeezenet import SqueezeNet from ..ResNet.resnet50 import ResNet50 from ..InceptionV3.inceptionv3 import InceptionV3 from ..DenseNet.densenet import DenseNetImageNet121 from tensorflow.python.keras.optimizers import Adam from tensorflow.python.keras.preprocessing.image import ImageDataGenerator from tensorflow.python.keras.callbacks import LearningRateScheduler from tensorflow.python.keras.layers import Flatten, Dense, Input, Conv2D, GlobalAvgPool2D, Activation from tensorflow.python.keras.models import Model from tensorflow.python.keras.preprocessing import image from tensorflow.python.keras.models import load_model, save_model import tensorflow as tf from tensorflow.python.keras import backend as K from PIL import Image import os from tensorflow.python.keras.callbacks import ModelCheckpoint from io import open import json import numpy as np import warnings class ModelTraining: """ This is the Model training class, that allows you to define a deep learning network from the 4 available networks types supported by ImageAI which are SqueezeNet, ResNet50, InceptionV3 and DenseNet121. Once you instantiate this class, you must call: * """ def __init__(self): self.__modelType = "" self.__use_pretrained_model = False self.__data_dir = "" self.__train_dir = "" self.__test_dir = "" self.__num_epochs = 10 self.__trained_model_dir = "" self.__model_class_dir = "" self.__initial_learning_rate = 1e-3 self.__model_collection = [] def setModelTypeAsSqueezeNet(self): """ 'setModelTypeAsSqueezeNet()' is used to set the model type to the SqueezeNet model for the training instance object . :return: """ self.__modelType = "squeezenet" def setModelTypeAsResNet(self): """ 'setModelTypeAsResNet()' is used to set the model type to the ResNet model for the training instance object . :return: """ self.__modelType = "resnet" def setModelTypeAsDenseNet(self): """ 'setModelTypeAsDenseNet()' is used to set the model type to the DenseNet model for the training instance object . :return: """ self.__modelType = "densenet" def setModelTypeAsInceptionV3(self): """ 'setModelTypeAsInceptionV3()' is used to set the model type to the InceptionV3 model for the training instance object . :return: """ self.__modelType = "inceptionv3" def setDataDirectory(self, data_directory=""): """ 'setDataDirectory()' is required to set the path to which the data/dataset to be used for training is kept. The directory can have any name, but it must have 'train' and 'test' sub-directory. In the 'train' and 'test' sub-directories, there must be sub-directories with each having it's name corresponds to the name/label of the object whose images are to be kept. The structure of the 'test' and 'train' folder must be as follows: >> train >> class1 >> class1_train_images >> class2 >> class2_train_images >> class3 >> class3_train_images >> class4 >> class4_train_images >> class5 >> class5_train_images >> test >> class1 >> class1_test_images >> class2 >> class2_test_images >> class3 >> class3_test_images >> class4 >> class4_test_images >> class5 >> class5_test_images :param data_directory: :return: """ self.__data_dir = data_directory self.__train_dir = os.path.join(self.__data_dir, "train") self.__test_dir = os.path.join(self.__data_dir, "test") self.__trained_model_dir = os.path.join(self.__data_dir, "models") self.__model_class_dir = os.path.join(self.__data_dir, "json") def lr_schedule(self, epoch): # Learning Rate Schedule lr = self.__initial_learning_rate total_epochs = self.__num_epochs check_1 = int(total_epochs * 0.9) check_2 = int(total_epochs * 0.8) check_3 = int(total_epochs * 0.6) check_4 = int(total_epochs * 0.4) if epoch > check_1: lr *= 1e-4 elif epoch > check_2: lr *= 1e-3 elif epoch > check_3: lr *= 1e-2 elif epoch > check_4: lr *= 1e-1 return lr def trainModel(self, num_objects, num_experiments=200, enhance_data=False, batch_size = 32, initial_learning_rate=1e-3, show_network_summary=False, training_image_size = 224, continue_from_model=None, transfer_from_model=None, transfer_with_full_training=True, initial_num_objects = None, save_full_model = False): """ 'trainModel()' function starts the model actual training. It accepts the following values: - num_objects , which is the number of classes present in the dataset that is to be used for training - num_experiments , also known as epochs, it is the number of times the network will train on all the training dataset - enhance_data (optional) , this is used to modify the dataset and create more instance of the training set to enhance the training result - batch_size (optional) , due to memory constraints, the network trains on a batch at once, until all the training set is exhausted. The value is set to 32 by default, but can be increased or decreased depending on the meormory of the compute used for training. The batch_size is conventionally set to 16, 32, 64, 128. - initial_learning_rate(optional) , this value is used to adjust the weights generated in the network. You rae advised to keep this value as it is if you don't have deep understanding of this concept. - show_network_summary(optional) , this value is used to show the structure of the network should you desire to see it. It is set to False by default - training_image_size(optional) , this value is used to define the image size on which the model will be trained. The value is 224 by default and is kept at a minimum of 100. - continue_from_model (optional) , this is used to set the path to a model file trained on the same dataset. It is primarily for continuos training from a previously saved model. - transfer_from_model (optional) , this is used to set the path to a model file trained on another dataset. It is primarily used to perform tramsfer learning. - transfer_with_full_training (optional) , this is used to set the pre-trained model to be re-trained across all the layers or only at the top layers. - initial_num_objects (required if 'transfer_from_model' is set ), this is used to set the number of objects the model used for transfer learning is trained on. If 'transfer_from_model' is set, this must be set as well. - save_full_model ( optional ), this is used to save the trained models with their network types. Any model saved by this specification can be loaded without specifying the network type. * :param num_objects: :param num_experiments: :param enhance_data: :param batch_size: :param initial_learning_rate: :param show_network_summary: :param training_image_size: :param continue_from_model: :param transfer_from_model: :param initial_num_objects: :param save_full_model: :return: """ self.__num_epochs = num_experiments self.__initial_learning_rate = initial_learning_rate lr_scheduler = LearningRateScheduler(self.lr_schedule) num_classes = num_objects if(training_image_size < 100): warnings.warn("The specified training_image_size {} is less than 100. Hence the training_image_size will default to 100.".format(training_image_size)) training_image_size = 100 image_input = Input(shape=(training_image_size, training_image_size, 3)) if (self.__modelType == "squeezenet"): if (continue_from_model != None): model = SqueezeNet(weights="continued", num_classes=num_classes, model_input=image_input, model_path=continue_from_model) if (show_network_summary == True): print("Resuming training with weights loaded from a previous model") elif (transfer_from_model != None): model = SqueezeNet(weights="transfer", num_classes=num_classes, model_input=image_input, model_path=transfer_from_model, initial_num_classes=initial_num_objects,transfer_with_full_training=transfer_with_full_training) if (show_network_summary == True): print("Training using weights from a pre-trained model") else: model = SqueezeNet(weights="custom", num_classes=num_classes, model_input=image_input) elif (self.__modelType == "resnet"): if(continue_from_model != None): model = ResNet50(weights="continued", num_classes=num_classes, model_input=image_input, model_path=continue_from_model) if (show_network_summary == True): print("Resuming training with weights loaded from a previous model") elif(transfer_from_model != None): model = ResNet50(weights="transfer", num_classes=num_classes, model_input=image_input, model_path=transfer_from_model, initial_num_classes=initial_num_objects, transfer_with_full_training=transfer_with_full_training) if (show_network_summary == True): print("Training using weights from a pre-trained model") else: model = ResNet50(weights="custom", num_classes=num_classes, model_input=image_input) elif (self.__modelType == "inceptionv3"): if (continue_from_model != None): model = InceptionV3(weights="continued", classes=num_classes, model_input=image_input, model_path=continue_from_model) if (show_network_summary == True): print("Resuming training with weights loaded from a previous model") elif (transfer_from_model != None): model = InceptionV3(weights="transfer", classes=num_classes, model_input=image_input, model_path=transfer_from_model, initial_classes=initial_num_objects, transfer_with_full_training=transfer_with_full_training) if (show_network_summary == True): print("Training using weights from a pre-trained model") else: model = InceptionV3(weights="custom", classes=num_classes, model_input=image_input) elif (self.__modelType == "densenet"): if (continue_from_model != None): model = DenseNetImageNet121(weights="continued", classes=num_classes, model_input=image_input, model_path=continue_from_model) if (show_network_summary == True): print("Resuming training with weights loaded from a previous model") elif (transfer_from_model != None): model = DenseNetImageNet121(weights="transfer", classes=num_classes, model_input=image_input, model_path=transfer_from_model, initial_num_classes=initial_num_objects, transfer_with_full_training=transfer_with_full_training) if (show_network_summary == True): print("Training using weights from a pre-trained model") else: model = DenseNetImageNet121(weights="custom", classes=num_classes, model_input=image_input) optimizer = Adam(lr=self.__initial_learning_rate, decay=1e-4) model.compile(loss="categorical_crossentropy", optimizer=optimizer, metrics=["accuracy"]) if (show_network_summary == True): model.summary() model_name = 'model_ex-{epoch:03d}_acc-{val_acc:03f}.h5' if not os.path.isdir(self.__trained_model_dir): os.makedirs(self.__trained_model_dir) if not os.path.isdir(self.__model_class_dir): os.makedirs(self.__model_class_dir) model_path = os.path.join(self.__trained_model_dir, model_name) save_weights_condition = True if(save_full_model == True ): save_weights_condition = False elif(save_full_model == False): save_weights_condition = True checkpoint = ModelCheckpoint(filepath=model_path, monitor='val_acc', verbose=1, save_weights_only=save_weights_condition, save_best_only=True, period=1) if (enhance_data == True): print("Using Enhanced Data Generation") height_shift = 0 width_shift = 0 if (enhance_data == True): height_shift = 0.1 width_shift = 0.1 train_datagen = ImageDataGenerator( rescale=1. / 255, horizontal_flip=enhance_data, height_shift_range=height_shift, width_shift_range=width_shift) test_datagen = ImageDataGenerator( rescale=1. / 255) train_generator = train_datagen.flow_from_directory(self.__train_dir, target_size=(training_image_size, training_image_size), batch_size=batch_size, class_mode="categorical") test_generator = test_datagen.flow_from_directory(self.__test_dir, target_size=(training_image_size, training_image_size), batch_size=batch_size, class_mode="categorical") class_indices = train_generator.class_indices class_json = {} for eachClass in class_indices: class_json[str(class_indices[eachClass])] = eachClass with open(os.path.join(self.__model_class_dir, "model_class.json"), "w+") as json_file: json.dump(class_json, json_file, indent=4, separators=(",", " : "), ensure_ascii=True) json_file.close() print("JSON Mapping for the model classes saved to ", os.path.join(self.__model_class_dir, "model_class.json")) num_train = len(train_generator.filenames) num_test = len(test_generator.filenames) print("Number of experiments (Epochs) : ", self.__num_epochs) # model.fit_generator(train_generator, steps_per_epoch=int(num_train / batch_size), epochs=self.__num_epochs, validation_data=test_generator, validation_steps=int(num_test / batch_size), callbacks=[checkpoint, lr_scheduler]) class CustomImagePrediction: """ This is the image prediction class for custom models trained with the 'ModelTraining' class. It provides support for 4 different models which are: ResNet50, SqueezeNet, DenseNet121 and Inception V3. After instantiating this class, you can set it's properties and make image predictions using it's pre-defined functions. The following functions are required to be called before a prediction can be made * setModelPath() , path to your custom model * setJsonPath , , path to your custom model's corresponding JSON file * At least of of the following and it must correspond to the model set in the setModelPath() [setModelTypeAsSqueezeNet(), setModelTypeAsResNet(), setModelTypeAsDenseNet, setModelTypeAsInceptionV3] * loadModel() [This must be called once only before making a prediction] Once the above functions have been called, you can call the predictImage() function of the prediction instance object at anytime to predict an image. """ def __init__(self): self.__modelType = "" self.modelPath = "" self.jsonPath = "" self.numObjects = 10 self.__modelLoaded = False self.__model_collection = [] self.__input_image_size = 224 def setModelPath(self, model_path): """ 'setModelPath()' function is required and is used to set the file path to the model adopted from the list of the available 4 model types. The model path must correspond to the model type set for the prediction instance object. :param model_path: :return: """ self.modelPath = model_path def setJsonPath(self, model_json): """ 'setJsonPath()' :param model_path: :return: """ self.jsonPath = model_json def setModelTypeAsSqueezeNet(self): """ 'setModelTypeAsSqueezeNet()' is used to set the model type to the SqueezeNet model for the prediction instance object . :return: """ self.__modelType = "squeezenet" def setModelTypeAsResNet(self): """ 'setModelTypeAsResNet()' is used to set the model type to the ResNet model for the prediction instance object . :return: """ self.__modelType = "resnet" def setModelTypeAsDenseNet(self): """ 'setModelTypeAsDenseNet()' is used to set the model type to the DenseNet model for the prediction instance object . :return: """ self.__modelType = "densenet" def setModelTypeAsInceptionV3(self): """ 'setModelTypeAsInceptionV3()' is used to set the model type to the InceptionV3 model for the prediction instance object . :return: """ self.__modelType = "inceptionv3" def loadModel(self, prediction_speed="normal", num_objects=10): """ 'loadModel()' function is used to load the model structure into the program from the file path defined in the setModelPath() function. This function receives an optional value which is "prediction_speed". The value is used to reduce the time it takes to predict an image, down to about 50% of the normal time, with just slight changes or drop in prediction accuracy, depending on the nature of the image. - prediction_speed (optional), acceptable values are "normal", "fast", "faster" and "fastest" - num_objects (required), the number of objects the model is trained to recognize :param prediction_speed: :param num_objects: :return: """ self.numObjects = num_objects if (prediction_speed == "normal"): self.__input_image_size = 224 elif (prediction_speed == "fast"): self.__input_image_size = 160 elif (prediction_speed == "faster"): self.__input_image_size = 120 elif (prediction_speed == "fastest"): self.__input_image_size = 100 if (self.__modelLoaded == False): image_input = Input(shape=(self.__input_image_size, self.__input_image_size, 3)) if (self.__modelType == ""): raise ValueError("You must set a valid model type before loading the model.") elif (self.__modelType == "squeezenet"): import numpy as np from tensorflow.python.keras.preprocessing import image from ..SqueezeNet.squeezenet import SqueezeNet from .custom_utils import preprocess_input from .custom_utils import decode_predictions model = SqueezeNet(model_path=self.modelPath, weights="trained", model_input=image_input, num_classes=self.numObjects) self.__model_collection.append(model) self.__modelLoaded = True try: None except: raise ("You have specified an incorrect path to the SqueezeNet model file.") elif (self.__modelType == "resnet"): import numpy as np from tensorflow.python.keras.preprocessing import image from ..ResNet.resnet50 import ResNet50 from .custom_utils import preprocess_input from .custom_utils import decode_predictions try: model = ResNet50(model_path=self.modelPath, weights="trained", model_input=image_input, num_classes=self.numObjects) self.__model_collection.append(model) self.__modelLoaded = True except: raise ValueError("You have specified an incorrect path to the ResNet model file.") elif (self.__modelType == "densenet"): from tensorflow.python.keras.preprocessing import image from ..DenseNet.densenet import DenseNetImageNet121 from .custom_utils import decode_predictions, preprocess_input import numpy as np try: model = DenseNetImageNet121(model_path=self.modelPath, weights="trained", model_input=image_input, classes=self.numObjects) self.__model_collection.append(model) self.__modelLoaded = True except: raise ValueError("You have specified an incorrect path to the DenseNet model file.") elif (self.__modelType == "inceptionv3"): import numpy as np from tensorflow.python.keras.preprocessing import image from imageai.Prediction.InceptionV3.inceptionv3 import InceptionV3 from .custom_utils import decode_predictions, preprocess_input try: model = InceptionV3(include_top=True, weights="trained", model_path=self.modelPath, model_input=image_input, classes=self.numObjects) self.__model_collection.append(model) self.__modelLoaded = True except: raise ValueError("You have specified an incorrect path to the InceptionV3 model file.") def loadFullModel(self, prediction_speed="normal", num_objects=10): """ 'loadFullModel()' function is used to load the model structure into the program from the file path defined in the setModelPath() function. As opposed to the 'loadModel()' function, you don't need to specify the model type. This means you can load any Keras model trained with or without ImageAI and perform image prediction. - prediction_speed (optional), Acceptable values are "normal", "fast", "faster" and "fastest" - num_objects (required), the number of objects the model is trained to recognize :param prediction_speed: :param num_objects: :return: """ self.numObjects = num_objects if (prediction_speed == "normal"): self.__input_image_size = 224 elif (prediction_speed == "fast"): self.__input_image_size = 160 elif (prediction_speed == "faster"): self.__input_image_size = 120 elif (prediction_speed == "fastest"): self.__input_image_size = 100 if (self.__modelLoaded == False): image_input = Input(shape=(self.__input_image_size, self.__input_image_size, 3)) model = load_model(filepath=self.modelPath) self.__model_collection.append(model) self.__modelLoaded = True self.__modelType = "full" def save_model_to_tensorflow(self, new_model_folder, new_model_name=""): """ 'save_model_to_tensorflow' function allows you to save your loaded Keras (.h5) model and save it to the Tensorflow (.pb) model format. - new_model_folder (required), the path to the folder you want the converted Tensorflow model to be saved - new_model_name (required), the desired filename for your converted Tensorflow model e.g 'my_new_model.pb' :param new_model_folder: :param new_model_name: :return: """ if(self.__modelLoaded == True): out_prefix = "output_" output_dir = new_model_folder if os.path.exists(output_dir) == False: os.mkdir(output_dir) model_name = os.path.join(output_dir, new_model_name) keras_model = self.__model_collection[0] out_nodes = [] for i in range(len(keras_model.outputs)): out_nodes.append(out_prefix + str(i + 1)) tf.identity(keras_model.output[i], out_prefix + str(i + 1)) sess = K.get_session() from tensorflow.python.framework import graph_util, graph_io init_graph = sess.graph.as_graph_def() main_graph = graph_util.convert_variables_to_constants(sess, init_graph, out_nodes) graph_io.write_graph(main_graph, output_dir, name=model_name, as_text=False) print("Tensorflow Model Saved") def save_model_for_deepstack(self, new_model_folder, new_model_name=""): """ 'save_model_for_deepstack' function allows you to save your loaded Keras (.h5) model and save it to the deployment format of DeepStack custom API. This function will save the model and the JSON file you need for the deployment. - new_model_folder (required), the path to the folder you want the model to be saved - new_model_name (required), the desired filename for your model e.g 'my_new_model.h5' :param new_model_folder: :param new_model_name: :return: """ if(self.__modelLoaded == True): print(self.jsonPath) with open(self.jsonPath) as inputFile: model_json = json.load(inputFile) deepstack_json = {"sys-version": "1.0", "framework":"KERAS","mean":0.5,"std":255} deepstack_json["width"] = self.__input_image_size deepstack_json["height"] = self.__input_image_size deepstack_classes_map = {} for eachClass in model_json: deepstack_classes_map[eachClass] = model_json[eachClass] deepstack_json["map"] = deepstack_classes_map output_dir = new_model_folder if os.path.exists(output_dir) == False: os.mkdir(output_dir) with open(os.path.join(output_dir,"config.json"), "w+") as json_file: json.dump(deepstack_json, json_file, indent=4, separators=(",", " : "), ensure_ascii=True) json_file.close() print("JSON Config file saved for DeepStack format in ", os.path.join(output_dir, "config.json")) keras_model = self.__model_collection[0] save_model(keras_model, os.path.join(new_model_folder, new_model_name)) print("Model saved for DeepStack format in", os.path.join(os.path.join(new_model_folder, new_model_name))) def predictImage(self, image_input, result_count=1, input_type="file"): """ 'predictImage()' function is used to predict a given image by receiving the following arguments: * input_type (optional) , the type of input to be parsed. Acceptable values are "file", "array" and "stream" * image_input , file path/numpy array/image file stream of the image. * result_count (optional) , the number of predictions to be sent which must be whole numbers between 1 and the number of classes present in the model This function returns 2 arrays namely 'prediction_results' and 'prediction_probabilities'. The 'prediction_results' contains possible objects classes arranged in descending of their percentage probabilities. The 'prediction_probabilities' contains the percentage probability of each object class. The position of each object class in the 'prediction_results' array corresponds with the positions of the percentage possibilities in the 'prediction_probabilities' array. :param input_type: :param image_input: :param result_count: :return prediction_results, prediction_probabilities: """ prediction_results = [] prediction_probabilities = [] if (self.__modelLoaded == False): raise ValueError("You must call the loadModel() function before making predictions.") else: if (self.__modelType == "squeezenet"): from .custom_utils import preprocess_input from .custom_utils import decode_predictions if (input_type == "file"): try: image_to_predict = image.load_img(image_input, target_size=( self.__input_image_size, self.__input_image_size)) image_to_predict = image.img_to_array(image_to_predict, data_format="channels_last") image_to_predict = np.expand_dims(image_to_predict, axis=0) image_to_predict = preprocess_input(image_to_predict) except: raise ValueError("You have set a path to an invalid image file.") elif (input_type == "array"): try: image_input = Image.fromarray(np.uint8(image_input)) image_input = image_input.resize((self.__input_image_size, self.__input_image_size)) image_input = np.expand_dims(image_input, axis=0) image_to_predict = image_input.copy() image_to_predict =
np.asarray(image_to_predict, dtype=np.float64)
numpy.asarray
import os,sys import tensorflow as tf import numpy as np sys.path.insert(0, './scripts') sys.path.insert(0, './models') def str2bool(v): return v.lower() in ("yes", "true", "t", "1") def accuracy(predictions, labels): pred_class = np.argmax(predictions, 1) true_class =
np.argmax(labels, 1)
numpy.argmax
# -*- coding: utf-8 -*- """ Created on Sun Aug 8 21:43:54 2021 @author: oiseth """ #%% import necessary modules and packages import numpy as np from scipy import linalg from matplotlib import pyplot as plt import time_integration as ti import time_simulation as ts #%% Create signal in time domain plt.close('all') # Establish system L=3.5 I=180e-6 E=210e9 k=12*E*I/L**3 m=12e3 M=np.diag([m,m]) K=np.array([ [4,-2] , [-2, 2] ])*k C=3e-1*M+5e-4*K (lambd,phi)=linalg.eigh(K,M) phi=np.array(phi) lambd=np.array(lambd) omega_n=np.sqrt(lambd) #%% Create time vector and load dt=0.01 T=100 t=np.arange(0,T,dt) X1=500*np.random.randn(len(t)) X2=600*np.random.randn(len(t)) # Plot time series plt.figure() plt.plot(t,X1) plt.plot(t,X2) plt.show() plt.xlabel('Time [s]') plt.ylabel('Load [N]') plt.grid() #%% Solve system response by time integration plt.close('all') f=np.vstack((X1,X2)) u0=np.zeros((2,1)) udot0=np.zeros((2,1)) gamma=0.5 beta=0.25 (u,udot,uddot)=ti.linear_newmark_krenk(M,C,K,f,u0,udot0,dt,gamma,beta) (y,ydot,yddot)=ti.linear_newmark_chopra(M,C,K,f,u0,udot0,dt,gamma,beta) plt.figure() plt.plot(t,u[0,:]) plt.plot(t,y[0,:]) plt.show() plt.xlabel('Time [s]') plt.ylabel('Response [m]') plt.title('DOF 1') plt.grid() plt.figure() plt.plot(t,u[1,:]) plt.plot(t,y[1,:]) plt.show() plt.xlabel('Time [s]') plt.ylabel('Response [m]') plt.title('DOF 2') plt.grid() #%% Statistics: the difference should be almost zero delta_u=u-y delta_udot=udot-ydot delta_uddot=uddot-yddot ratio_u=np.divide( np.std(delta_u,1) , np.std(u,1) ) ratio_udot=np.divide( np.std(delta_udot,1) ,
np.std(udot,1)
numpy.std
import numpy as np from util.stats import * # ==================================================================== # util.stats # ==================================================================== def _test_mpca(display=False): if display: print() print("-"*70) print("Begin tests for 'mpca'") GENERATE_APPROXIMATIONS = True BIG_PLOTS = False SHOW_2D_POINTS = False import random # Generate some points for testing. np.random.seed(4) # 4 random.seed(0) # 0 rgen = np.random.RandomState(1) # 10 n = 100 points = (rgen.rand(n,2) - .5) * 2 # points *= np.array([.5, 1.]) # Create some testing functions (for learning different behaviors) funcs = [ lambda x: x[1] , # Linear on y lambda x: abs(x[0] + x[1]) , # "V" function on 1:1 diagonal lambda x: abs(2*x[0] + x[1]) , # "V" function on 2:1 diagonal lambda x: x[0]**2 , # Quadratic on x lambda x: (x[0] + x[1])**2 , # Quadratic on 1:1 diagonal lambda x: (2*x[0] + x[1])**3 , # Cubic on 2:1 diagonal lambda x: (x[0]**3) , # Cubic on x lambda x: rgen.rand() , # Random function ] # Calculate the response values associated with each function. responses = np.vstack(tuple(tuple(map(f, points)) for f in funcs)).T # Reduce to just the first function choice = 3 func = funcs[choice] response = responses[:,choice] # Run the princinple response analysis function. components, values = mpca(points, response) values /= np.sum(values) conditioner = np.matmul(components, np.diag(values)) if display: print() print("Components") print(components) print() print("Values") print(values) print() print("Conditioner") print(conditioner) print() components = np.array([[1.0, 0.], [0., 1.]]) values = normalize_error(np.matmul(points, components.T), response, abs_diff) values /= np.sum(values) if display: print() print() print("True Components") print(components) print() print("True Values") print(values) print() # Generate a plot of the response surfaces. from util.plot import Plot, multiplot if display: print("Generating plots of source function..") # Add function 1 p1 = Plot() p1.add("Points", *(points.T), response, opacity=.8) p1.add_func("Surface", func, [-1,1], [-1,1], plot_points=100) if GENERATE_APPROXIMATIONS: from util.approximate import NearestNeighbor, Delaunay, condition p = Plot() # Add the source points and a Delaunay fit. p.add("Points", *(points.T), response, opacity=.8) p.add_func("Truth", func, [-1,1], [-1,1]) # Add an unconditioned nearest neighbor fit. model = NearestNeighbor() model.fit(points, response) p.add_func("Unconditioned Approximation", model, [-1,1], [-1,1], mode="markers", opacity=.8) # Generate a conditioned approximation model = condition(NearestNeighbor, method="MPCA")() model.fit(points, response) p.add_func("Best Approximation", model, [-1,1], [-1,1], mode="markers", opacity=.8) if display: p.plot(show=False, height=400, width=650) if display: print("Generating metric principle components..") # Return the between vectors and the differences between those points. def between(x, y, unique=True): vecs = [] diffs = [] for i1 in range(x.shape[0]): start = i1+1 if unique else 0 for i2 in range(start, x.shape[0]): if (i1 == i2): continue vecs.append(x[i2] - x[i1]) diffs.append(y[i2] - y[i1]) return np.array(vecs), np.array(diffs) # Plot the between slopes to verify they are working. # Calculate the between slopes vecs, diffs = between(points, response) vec_lengths = np.sqrt(np.sum(vecs**2, axis=1)) between_slopes = diffs / vec_lengths bs = ((vecs.T / vec_lengths) * between_slopes).T # Extrac a random subset for display size = 100 random_subset = np.arange(len(bs)) rgen.shuffle(random_subset) bs = bs[random_subset[:size],:] # Normalize the between slopes so they fit on the plot max_bs_len = np.max(np.sqrt(np.sum(bs**2, axis=1))) bs /= max_bs_len # Get a random subset of the between slopes and plot them. p2 = Plot("","Metric PCA on Z","") p2.add("Between Slopes", *(bs.T), color=p2.color(4, alpha=.4)) if SHOW_2D_POINTS: # Add the points and transformed points for demonstration. new_pts = np.matmul(np.matmul(conditioner, points), np.linalg.inv(components)) p2.add("Original Points", *(points.T)) p2.add("Transformed Points", *(new_pts.T), color=p2.color(6, alpha=.7)) # Add the principle response components for i,(vec,m) in enumerate(zip(components, values)): vec = vec * m p2.add(f"PC {i+1}", [0,vec[0]], [0,vec[1]], mode="lines") ax, ay = (vec / sum(vec**2)**.5) * 3 p2.add_annotation(f"{m:.2f}", vec[0], vec[1]) p3 = Plot("", "PCA on X", "") p3.add("Points", *(points.T), color=p3.color(4, alpha=.4)) # Add the normal principle components components, values = pca(points) values /= np.sum(values) for i,(vec,m) in enumerate(zip(components, values)): vec = vec * m p3.add(f"PC {i+1}", [0,vec[0]], [0,vec[1]], mode="lines") ax, ay = (vec / sum(vec**2)**.5) * 3 p3.add_annotation(f"{m:.2f}", vec[0], vec[1]) if BIG_PLOTS: if display: p1.plot(file_name="source_func.html", show=False) if display: p2.plot(append=True, x_range=[-8,8], y_range=[-5,5]) else: # Make the plots (with manual ranges) p1 = p1.plot(html=False, show_legend=False) p2 = p2.plot(html=False, x_range=[-1,1], y_range=[-1,1], show_legend=False) p3 = p3.plot(html=False, x_range=[-1,1], y_range=[-1,1], show_legend=False) # Generate the multiplot of the two side-by-side figures if display: multiplot([p1,p2,p3], height=126, width=650, append=True) if display: print("-"*70) def _test_effect(display=False): if display: print() print("-"*70) print("Begin tests for 'effect'") a = {"a":.4, "b":.1, "c":.5, "d":.0} b = {"a":.1, "b":.3, "c":.5, "d":.1} c = {"a":.0, "b":.0, "c":.0, "d":1.} assert(.3 == categorical_diff(a, b)) assert(1. == categorical_diff(a, c)) assert(.9 == categorical_diff(b, c)) a = ['a','a','a','a','b','b','b','b'] b = ['a','a','b','b','b','a','a','b'] c = ['a','a','a','b','b','a','a','a'] assert(0. == effect(a,b)) assert(0. == effect(a,c)) # assert((4/6 + 3/6 + 0/6 + 0/6)/4 == effect(b, c)) a = list(range(1000)) b = list(range(1000)) assert(effect(a,b) == 1.0) b = np.random.random(size=(1000,)) assert(effect(a,b) < .1) a = ['a', 'a', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'a', 'a', 'c', 'a', 'c', 'a', 'c', 'a', 'c'] b = [890.79, 1048.97, 658.43, 659.39, 722.0, 723.34, 1040.76, 1058.02, 1177.0, 1170.94, 415.56, 462.03, 389.09, 676.82, 688.49, 735.56, 552.58, 1127.29, 1146.42, 1251.12] assert(0.0 == effect(a,b) - 0.5264043528589452) if display: print("-"*70) def _test_epdf_diff(display=False): if display: print() print("-"*70) print("Begin tests for 'epdf_diff'") # ---------------------------------------------------------------- def demo(seq): if display: print('~'*70) print(len(seq), seq) print() total = 0 for vals in edf_pair_gen(seq): total += vals[-1] if display: print("[% 4s, % 3s] (%.2f) --"%vals, round(total,3)) if display: print('~'*70) print() demo( [0] + list(range(9)) ) demo( sorted(np.random.random(size=(10,))) ) demo( list(range(9)) + [8] ) # ---------------------------------------------------------------- # a = [1, 1, 3, 3, 5, 6] # b = [0, 1, 2, 3, 4] # n = 100 if display: print(f"a = [0,100] ({n} samples)") print(f"b = [v + d for v in a]") print() for d in (.0, .01, .1, .5, .55, .9, 1., 1.5): a = [v / n for v in list(range(n+1))] b = [v+d for v in a] if display: print(f"d = {d:.2f} a~b = {epdf_diff(a,b):.2f} b~a = {epdf_diff(b,a):.2f} a~a = {epdf_diff(a,a):.2f} b~b = {epdf_diff(b,b):.2f}") if display: print() for d in (.0, .01, .1, .5, .55, .9, 1., 1.5): # Generate a random sequence. a = sorted((np.random.random(size=(10,)))) b = sorted((np.random.random(size=(1000,)) + d)) diff = epdf_diff(a, b) if display: print(f"d = {d:.2f}","", "[%.2f, %.2f]"%(min(a),max(a)), "[%.2f, %.2f]"%(min(b),max(b)),"", diff ) if display: print() # ---------------------------------------------------------------- from util.plot import Plot # Generate a random sequence. a = sorted((np.random.random(size=(2000,)))) b = sorted((np.random.random(size=(2000,)))) p = Plot("Empirical PDF Diff Test") p1 = pdf_fit(a, smooth=0.00001) p2 = pdf_fit(b, smooth=0.00001) p.add_func("a", p1, p1()) #(-.5,2)) p.add_func("b", p2, p2()) #(-.5,2)) if display: p.show(show=False, y_range=[-.5,1.5]) p = Plot("Empirical CDF Diff Test") p1 = cdf_fit(a) p2 = cdf_fit(b) p.add_func("a", p1, p1()) #(-.5,2)) p.add_func("b", p2, p2()) #(-.5,2)) if display: p.show(append=True) # ---------------------------------------------------------------- if display: print("-"*70) def _test_fit_funcs(display=False): if display: print() print("-"*70) print("Begin tests for 'fit_funcs'") from util.plot import Plot # ============================================== # Test the fit functions and smoothing # ============================================== # Make data smooth = .1 data = np.random.normal(size=(1000,)) # data[:len(data)//2] += 2 min_max = (min(data) - .1, max(data) + .1) if display: print() print("(min, max) : (%.2f, %.2f)"%(min_max)) print("Normal confidence: %.2f%%"%(100*normal_confidence(data))) print() # Make PDF fits pfit = pdf_fit(data) smooth_pfit = pdf_fit(data, smooth=smooth) # Make CDF fits cfit = cdf_fit(data) stdev = .05 * (cfit.max - cfit.min) smooth_cfit = gauss_smooth(cfit, stdev) stdev = smooth * (cfit.max - cfit.min) smoother_cfit = gauss_smooth(cfit, stdev) # Make PDF plots p = Plot() p.add_func("PDF", pfit, min_max) # Make smooth PDF p.add_func("Smooth PDF", smooth_pfit, min_max) if display: p.show(show=False) # Make CDF plots p = Plot() p.add_func("CDF", cfit, min_max) # Make CDF whose derivative is the default PDF. p.add_func("CDF for default PDF", smooth_cfit, min_max) # Make smoother cdf. p.add_func("Smooth CDF", smoother_cfit, min_max) if display: p.show(append=True) # Make an animation transitioning between two normal distributions. np.random.seed(0) d1 = np.random.normal(0, .5, size=(500,)) d2 = np.random.normal(3, 1, size=(500,)) f1 = cdf_fit(d1, smooth=.1) f2 = cdf_fit(d2, smooth=.1) p = Plot() for w in np.linspace(0,1,21): w = round(w,2) f3 = w*f1 + (1-w)*f2 p.add_func("0, 1/2", f1, f1(), frame=w) p.add_func("3, 1", f2, f2(), frame=w) p.add_func("weighted sum", f3, f3(), frame=w) if display: p.show(bounce=True, append=True) if display: print() if display: print("-"*70) def _test_samples(display=True, test_correctness=False): from util.math import Fraction from util.plot import Plot if display: for size in tuple(range(2,43,5))+(128, 129, 256, 257): p = Plot(f"Error at x with {size} samples") for confidence in (Fraction(9,10), Fraction(185,200), Fraction(95,100), Fraction(97,100), Fraction(99,100)): f = lambda x: samples(size=size, confidence=confidence, at=x) p.add_func(f"{confidence} confidence", f, [0, 1]) p.show(append=True, show=(size==2)) exit() if display: print() print("-"*70) print("Begin tests for 'samples'") print() key_values = [ (11, Fraction(3,10), Fraction(95,100)), (25, Fraction(2,10), Fraction(95,100)), (97, Fraction(1,10), Fraction(95,100)), (385, Fraction(5,100), Fraction(95,100)), (9604, Fraction(1,100), Fraction(95,100)), (19, Fraction(3,10), Fraction(99,100)), (42, Fraction(2,10), Fraction(99,100)), (166, Fraction(1,10), Fraction(99,100)), (664, Fraction(5,100), Fraction(99,100)), (16588, Fraction(1,100), Fraction(99,100)), (33733, Fraction(1,10), Fraction(999,1000)), (134930, Fraction(5,100), Fraction(999,1000)), (3373242, Fraction(1,100), Fraction(999,1000)), ] if display: print("samples (max error, confidence)") for (s, e,c) in key_values[:-3]: needed = samples(error=e, confidence=c) if display: print("needed: ",needed) print("%6d (%2.0f%%, %2.0f%%)"%(needed,100*e,100*c)) # if (s != None): assert(needed == s) if display: print() for n in (10, 25, 90, 350, 9000): print(f"With {n:4d} samples we are 95% confident in max CDF error <=", round(samples(n, confidence=.95), 1 if n < 350 else 2)) print() for n in (20, 40, 160, 660, 16000): print(f"With {n:5d} samples we are 99% confident in max CDF error <=", round(samples(n, confidence=.99), 1 if n < 600 else 2)) print("-"*70) if test_correctness: # Generate a random CDF from util import random from util.plot import Plot TESTS = 10000 DIFFS = 100 N = 100 fit = "linear" truth = random.cdf(nodes=5, fit=fit) max_error = samples(N, confidence=.99) if display: print("Largest expected error:", max_error) mid_error = [] errors = {(1/100):[], (1/4):[], (1/3):[], (1/2):[]} max_errors = [] mean_failed = [] for i in range(TESTS): sample = truth.inverse(np.random.random((N,))) guess = cdf_fit(sample, fit=fit) diff = truth - guess diff_func = lambda x: abs(truth(x) - guess(x)) diffs = diff_func(np.linspace(0,1,DIFFS)) mean_failed += [sum(diffs > max_error)] if display: print(f"Failed: {mean_failed[-1]:4d} {sum(mean_failed)/len(mean_failed):.0f}") max_errors.append(diff) for v in errors: errors[v].append(truth(v) - guess(v)) # if (diff > max_error): # print(i, N, diff, max_error) # p = Plot() # p.add_func("Truth", truth, truth()) # p.add_func("Guess", guess, guess()) # p.add_func("Error", diff_func, truth()) # p.show(show=False) # p = Plot() # p.add_func("Truth Inverse", truth.inverse, (0.,1.)) # p.add_func("Guess Inverse", guess.inverse, (0.,1.)) # p.show(show=False, append=True) # break total_failed = sum(e > max_error for e in max_errors) if display or (total_failed > 0): print(f"Failed {total_failed} out of {TESTS}, or {100*total_failed/TESTS:.1f}%.") p = Plot() # Add the distribution of maximum errors. f = cdf_fit(max_errors) p.add_func(f"{len(max_errors)} max errors", f, f()) # Add the distribution of errors at different values. for v in sorted(errors)[::-1]: mean = np.mean(errors[v]) std =
np.std(errors[v])
numpy.std
# Author: <NAME> # Date: 20 July 2019 # Project: RoadBuddy import json import oauth2 import threading import datetime import cherrypy import warnings import webbrowser import numpy as np from math import factorial from fitbit.api import Fitbit def golay_smoothing(y, window_size, order=2, deriv=0, rate=1): window_size = np.abs(np.int(window_size)) order = np.abs(np.int(order)) order_range = range(order+1) half_window = (window_size -1) // 2 # Precompute coefficients b = np.mat([[k**i for i in order_range] for k in range(-half_window, half_window+1)]) m = np.linalg.pinv(b).A[deriv] * rate**deriv * factorial(deriv) # Pad the signal at the extremes with values taken from the signal itself firstvals = y[0] -
np.abs( y[1:half_window+1][::-1] - y[0])
numpy.abs
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' :py:mod:`k2.py` - Main mission routines --------------------------------------- Implements several routines specific to the `K2` mission. ''' from __future__ import division, print_function, absolute_import, \ unicode_literals from . import sysrem from .utils import * from ...config import EVEREST_SRC, EVEREST_DAT, EVEREST_DEV, MAST_ROOT, \ EVEREST_MAJOR_MINOR from ...utils import DataContainer, sort_like, AP_COLLAPSED_PIXEL, \ AP_SATURATED_PIXEL from ...mathutils import SavGol, Interpolate, Scatter, Downbin try: import pyfits except ImportError: try: import astropy.io.fits as pyfits except ImportError: raise Exception('Please install the `pyfits` package.') import matplotlib.pyplot as pl from matplotlib.ticker import ScalarFormatter, MaxNLocator import k2plr as kplr kplr_client = kplr.API() from k2plr.config import KPLR_ROOT import numpy as np import george from tempfile import NamedTemporaryFile import random import os import sys import shutil import time import logging log = logging.getLogger(__name__) __all__ = ['Setup', 'Season', 'Breakpoints', 'GetData', 'GetNeighbors', 'Statistics', 'TargetDirectory', 'HasShortCadence', 'DVSFile', 'InjectionStatistics', 'HDUCards', 'CSVFile', 'FITSFile', 'FITSUrl', 'CDPP', 'GetTargetCBVs', 'FitCBVs', 'PlanetStatistics', 'StatsToCSV'] def Setup(): ''' Called when the code is installed. Sets up directories and downloads the K2 catalog. ''' if not os.path.exists(os.path.join(EVEREST_DAT, 'k2', 'cbv')): os.makedirs(os.path.join(EVEREST_DAT, 'k2', 'cbv')) GetK2Stars(clobber=False) def Season(EPIC, **kwargs): ''' Returns the campaign number for a given EPIC target. ''' return Campaign(EPIC, **kwargs) def Breakpoints(EPIC, season=None, cadence='lc', **kwargs): ''' Returns the location of the breakpoints for a given target. :param int EPIC: The EPIC ID number :param str cadence: The light curve cadence. Default `lc` .. note :: The number corresponding to a given breakpoint is the number \ of cadences *since the beginning of the campaign*. ''' # Get the campaign number if season is None: campaign = Season(EPIC) if hasattr(campaign, '__len__'): raise AttributeError( "Please choose a campaign/season for this target: %s." % campaign) else: campaign = season # Select LC or SC if cadence == 'lc': breakpoints = { 0: [665], # OK 1: [2210], # OK 2: [2042], # OK 3: [2140], # OK 4: [520, 2153], # OK 5: [1774], # OK 6: [2143], # OK 7: [1192, 2319], # OK 8: [1950], # OK 91: [], 92: [], 101: [], # NO DATA 102: [], # NO BREAKPOINT 111: [], 112: [], 12: [1900], # OK 13: [2157], # OK 14: [1950], # OK 15: [2150], # OK 16: [1945], # OK 17: [1640], # OK 18: [] # Short campaign } elif cadence == 'sc': breakpoints = { 0: np.array([3753, 11259, 15012, 18765, 60048, # OK 63801, 67554, 71307, 75060, 78815, 82566, 86319, 90072, 93825, 97578, 101331, 105084, 108837]), 1: np.array([8044, 12066, 16088, 20135, 24132, 28154, # OK 32176, 36198, 40220, 44242, 48264, 52286, 56308, 60330, 64352, 68374, 72396, 76418, 80440, 84462, 88509, 92506, 96528, 100550, 104572, 108594, 112616, 116638]), 2: np.array(np.linspace(0, 115680, 31)[1:-1], dtype=int), # OK 3: np.array([3316, 6772, 10158, 13694, 16930, 20316, # OK 23702, 27088, 30474, 33860, 37246, 40632, 44018, 47404, 50790, 54176, 57562, 60948, 64334, 67720, 71106, 74492, 77878, 81264, 84650, 88036, 91422, 94808, 98194]), 4: np.array(np.linspace(0, 101580, 31)[1:-1], dtype=int), # OK 5: np.array([3663, 7326, 10989, 14652, 18315, 21978, # OK 25641, 29304, 32967, 36630, 40293, 43956, 47619, 51282, 54945, 58608, 62271, 65934, 69597, 73260, 76923, 80646, 84249, 87912, 91575, 95238, 98901, 102564, 106227]), 6: np.array(np.linspace(0, 115890, 31)[1:-1], dtype=int), # OK 7: np.array(np.linspace(0, 121290, 31)[1:-1], dtype=int), # OK # Unclear 8: np.array(np.linspace(0, 115590, 31)[1:-1], dtype=int), 91: [], 92: [], 101: [], 102: [], 111: [], 112: [], 12: [], 13: [], 14: [], 15: [], 16: [], 17: [], 18: [] } else: raise ValueError("Invalid value for the cadence.") # Return if campaign in breakpoints: return breakpoints[campaign] else: return None def CDPP(flux, mask=[], cadence='lc'): ''' Compute the proxy 6-hr CDPP metric. :param array_like flux: The flux array to compute the CDPP for :param array_like mask: The indices to be masked :param str cadence: The light curve cadence. Default `lc` ''' # 13 cadences is 6.5 hours rmswin = 13 # Smooth the data on a 2 day timescale svgwin = 49 # If short cadence, need to downbin if cadence == 'sc': newsize = len(flux) // 30 flux = Downbin(flux, newsize, operation='mean') flux_savgol = SavGol(np.delete(flux, mask), win=svgwin) if len(flux_savgol): return Scatter(flux_savgol / np.nanmedian(flux_savgol), remove_outliers=True, win=rmswin) else: return np.nan def GetData(EPIC, season=None, cadence='lc', clobber=False, delete_raw=False, aperture_name='k2sff_15', saturated_aperture_name='k2sff_19', max_pixels=75, download_only=False, saturation_tolerance=-0.1, bad_bits=[1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 16, 17], get_hires=True, get_nearby=True, **kwargs): ''' Returns a :py:obj:`DataContainer` instance with the raw data for the target. :param int EPIC: The EPIC ID number :param int season: The observing season (campaign). Default :py:obj:`None` :param str cadence: The light curve cadence. Default `lc` :param bool clobber: Overwrite existing files? Default :py:obj:`False` :param bool delete_raw: Delete the FITS TPF after processing it? \ Default :py:obj:`False` :param str aperture_name: The name of the aperture to use. Select \ `custom` to call :py:func:`GetCustomAperture`. Default `k2sff_15` :param str saturated_aperture_name: The name of the aperture to use if \ the target is saturated. Default `k2sff_19` :param int max_pixels: Maximum number of pixels in the TPF. Default 75 :param bool download_only: Download raw TPF and return? Default \ :py:obj:`False` :param float saturation_tolerance: Target is considered saturated \ if flux is within this fraction of the pixel well depth. \ Default -0.1 :param array_like bad_bits: Flagged :py:obj`QUALITY` bits to consider \ outliers when computing the model. \ Default `[1,2,3,4,5,6,7,8,9,11,12,13,14,16,17]` :param bool get_hires: Download a high resolution image of the target? \ Default :py:obj:`True` :param bool get_nearby: Retrieve location of nearby sources? \ Default :py:obj:`True` ''' # Campaign no. if season is None: campaign = Season(EPIC) if hasattr(campaign, '__len__'): raise AttributeError( "Please choose a campaign/season for this target: %s." % campaign) else: campaign = season # Is there short cadence data available for this target? # DEBUG: Disabling short cadence for now! short_cadence = False #HasShortCadence(EPIC, season=campaign) if cadence == 'sc' and not short_cadence: raise ValueError("Short cadence data not available for this target.") # Local file name filename = os.path.join(EVEREST_DAT, 'k2', 'c%02d' % campaign, ('%09d' % EPIC)[:4] + '00000', ('%09d' % EPIC)[4:], 'data.npz') # Download? if clobber or not os.path.exists(filename): # Get the TPF tpf = os.path.join(KPLR_ROOT, 'data', 'k2', 'target_pixel_files', str(EPIC), 'ktwo%09d-c%02d_lpd-targ.fits.gz' % (EPIC, campaign)) sc_tpf = os.path.join(KPLR_ROOT, 'data', 'k2', 'target_pixel_files', str(EPIC), 'ktwo%09d-c%02d_spd-targ.fits.gz' % (EPIC, campaign)) if clobber or not os.path.exists(tpf): # DEBUG: Disabling short cadence for now! kplr_client.k2_star(EPIC).get_target_pixel_files(fetch=True, short_cadence=False) with pyfits.open(tpf) as f: qdata = f[1].data # Get the TPF aperture tpf_aperture = (f[2].data & 2) // 2 # Get the enlarged TPF aperture tpf_big_aperture = np.array(tpf_aperture) for i in range(tpf_big_aperture.shape[0]): for j in range(tpf_big_aperture.shape[1]): if f[2].data[i][j] == 1: for n in [(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)]: if n[0] >= 0 and n[0] < tpf_big_aperture.shape[0]: if n[1] >= 0 and n[1] < \ tpf_big_aperture.shape[1]: if tpf_aperture[n[0]][n[1]] == 1: tpf_big_aperture[i][j] = 1 # Is there short cadence data? if short_cadence: with pyfits.open(sc_tpf) as f: sc_qdata = f[1].data # Get K2SFF apertures try: k2sff = kplr.K2SFF(EPIC, sci_campaign=campaign) k2sff_apertures = k2sff.apertures if delete_raw: os.remove(k2sff._file) except: k2sff_apertures = [None for i in range(20)] # Make a dict of all our apertures # We're not getting K2SFF apertures 0-9 any more apertures = {'tpf': tpf_aperture, 'tpf_big': tpf_big_aperture} for i in range(10, 20): apertures.update({'k2sff_%02d' % i: k2sff_apertures[i]}) # Get the header info fitsheader = [pyfits.getheader(tpf, 0).cards, pyfits.getheader(tpf, 1).cards, pyfits.getheader(tpf, 2).cards] if short_cadence: sc_fitsheader = [pyfits.getheader(sc_tpf, 0).cards, pyfits.getheader(sc_tpf, 1).cards, pyfits.getheader(sc_tpf, 2).cards] else: sc_fitsheader = None # Get a hi res image of the target if get_hires: hires = GetHiResImage(EPIC) else: hires = None # Get nearby sources if get_nearby: nearby = GetSources(EPIC) else: nearby = [] # Delete? if delete_raw: os.remove(tpf) if short_cadence: os.remove(sc_tpf) # Get the arrays cadn = np.array(qdata.field('CADENCENO'), dtype='int32') time = np.array(qdata.field('TIME'), dtype='float64') fpix = np.array(qdata.field('FLUX'), dtype='float64') fpix_err = np.array(qdata.field('FLUX_ERR'), dtype='float64') qual = np.array(qdata.field('QUALITY'), dtype=int) # Get rid of NaNs in the time array by interpolating naninds = np.where(np.isnan(time)) time = Interpolate(np.arange(0, len(time)), naninds, time) # Get the motion vectors (if available!) pc1 = np.array(qdata.field('POS_CORR1'), dtype='float64') pc2 = np.array(qdata.field('POS_CORR2'), dtype='float64') if not np.all(np.isnan(pc1)) and not np.all(np.isnan(pc2)): pc1 = Interpolate(time, np.where(np.isnan(pc1)), pc1) pc2 = Interpolate(time, np.where(
np.isnan(pc2)
numpy.isnan
import pandas as pd import random from sklearn import preprocessing from sklearn import decomposition from sklearn.ensemble import AdaBoostClassifier from sklearn.tree import DecisionTreeClassifier from sklearn import svm from sklearn import feature_selection from sklearn import model_selection from sklearn import metrics from sklearn import tree from sklearn import linear_model import numpy as np def tradaboost(trans_S, trans_A, label_S, label_A, test, N): trans_data = np.concatenate((trans_A, trans_S), axis=0) trans_label = np.concatenate((label_A, label_S), axis=0) row_A = trans_A.shape[0] row_S = trans_S.shape[0] row_T = test.shape[0] test_data = np.concatenate((trans_data, test), axis=0) weights_A = np.ones([row_A, 1]) / row_A weights_S = np.ones([row_S, 1]) / row_S weights = np.concatenate((weights_A, weights_S), axis=0) bata = 1 / (1 + np.sqrt(2 * np.log(row_A / N))) bata_T = np.zeros([1, N]) result_label = np.ones([row_A + row_S + row_T, N]) predict = np.zeros([row_T]) print('params initial finished.') trans_data = np.asarray(trans_data, order='C') trans_label = np.asarray(trans_label, order='C') test_data = np.asarray(test_data, order='C') print(trans_data.shape, trans_label.shape) for i in range(N): P = calculate_P(weights, trans_label) result_label[:, i] = train_classify(trans_data, trans_label, test_data, P) print('result:', result_label[:, i], row_A, row_S, i, result_label.shape) error_rate = calculate_error_rate(label_S, result_label[row_A:row_A + row_S, i],weights[row_A:row_A + row_S, :]) print('Error rate:', error_rate) if error_rate > 0.5: error_rate = 0.5 if error_rate == 0: N = i break bata_T[0, i] = error_rate / (1 - error_rate) print(bata_T) for j in range(row_S): weights[row_A + j] = weights[row_A + j] * np.power(bata_T[0, i],(-np.abs(result_label[row_A + j, i] - label_S[j]))) for j in range(row_A): weights[j] = weights[j] * np.power(bata, np.abs(result_label[j, i] - label_A[j])) for i in range(row_T): left = np.sum(result_label[row_A + row_S + i, int(np.ceil(N / 2)):N] * np.log(1 / bata_T[0, int(np.ceil(N / 2)):N])) right = 0.5 * np.sum(np.log(1 / bata_T[0, int(np.ceil(N / 2)):N])) if left >= right: predict[i] = 1 else: predict[i] = 0 return predict def calculate_P(weights, label): total = np.sum(weights) return np.asarray(weights / total, order='C') def train_classify(trans_data, trans_label, test_data, P): clf = linear_model.SGDClassifier() # print(trans_label) clf.fit(trans_data, trans_label, sample_weight=P[:, 0]) pred = clf.predict(test_data) # for i in range(len(pred)): # if(abs(pred[i]-101)>=abs(pred[i]-112)): # pred[i] = 1 # else: # pred[i] = 0 return pred def calculate_error_rate(label_R, label_H, weight): total = np.sum(weight) # print(weight[:] / total) # print(np.abs(label_R - label_H)) return np.sum(weight[:, 0] / total *
np.abs(label_R - label_H)
numpy.abs
import argparse import numpy as np from elmoformanylangs import Embedder import keras from keras import optimizers from keras.callbacks import EarlyStopping, ModelCheckpoint from keras.preprocessing.sequence import pad_sequences from keras.models import Model from keras.layers import LSTM, Dense, Embedding, Bidirectional, TimeDistributed from keras.layers import Bidirectional, concatenate, SpatialDropout1D, GlobalMaxPooling1D, Input, add from seqeval.metrics import precision_score, recall_score, f1_score, classification_report from sklearn.metrics import classification_report as classrep # Defining arguments parser = argparse.ArgumentParser(description='Train and evaluate a named entity model e.g. for de-identification. Clinical DeID.') parser.add_argument('--path_train', type=str, help='Path to the CoNLL formated training file.') parser.add_argument('--path_test', type=str, help='Path to the CoNLL formated test file.') parser.add_argument('--mode', type=str, help='Select if you want to perform a -multiclass- or -binary- entity recognition task.') args = parser.parse_args() path_train = args.path_train path_test = args.path_test mode = args.mode # Defining the training and test data #path_train = 'data/deid_surrogate_train_all_version2.conll' #path_test = 'data/deid_surrogate_test_all_groundtruth_version2.conll' # Create data set def create_dataset(path, max_len=0): letters = [] letter = [] labels = [] label = [] tags = [] words = [] print('Extracting the text...') with open(path, 'r') as f: for line in f: line = line.split('\t') if len(line) > 1: if mode == 'binary': if line[1].strip() == 'O': label.append('O') tags.append('O') else: label.append('PHI') tags.append('PHI') else: label.append(line[1].strip()) tags.append(line[1].strip()) letter.append(line[0].strip()) words.append(line[0].strip()) else: letters.append(letter) labels.append(label) label = [] letter = [] print("Amount of words:") print(len(words)) words = list(set(words)) tags = list(set(tags)) if max_len != 0: max_len = max_len else: max_len = max([len(s) for s in letters]) word2idx = {w: i + 2 for i, w in enumerate(words)} word2idx["UNK"] = 1 word2idx["PAD"] = 0 tag2idx = {t: i for i, t in enumerate(tags)} print(tag2idx) y = [[tag2idx[w] for w in s] for s in labels] y = pad_sequences(maxlen=max_len, sequences=y, padding="post", value=tag2idx["O"]) new_X = [] for seq in letters: new_seq = [] for i in range(max_len): try: new_seq.append(seq[i]) except: new_seq.append("__PAD__") new_X.append(new_seq) X = new_X print("Lenght of X:") print(len(X)) return X, y, letters, words, max_len, tag2idx, tags X_train, y_tr, letters_train, words_train, max_len, tag2idx, tags = create_dataset(path_train) X_test, y_te, letters_test, _, _, _, _ = create_dataset(path_test, max_len=max_len) print('Generating train ELMo embeddings...') e = Embedder('configs/elmo') elmos_tr = e.sents2elmo(X_train) X_tr = np.array(elmos_tr) np.save('embeddings/elmo_train',X_tr) X_tr = np.load('embeddings/elmo_train.npy') print('Generating test ELMo embeddings...') elmos_te = e.sents2elmo(X_test) X_te = np.array(elmos_te) np.save('embeddings/elmo_test',X_te) X_te = np.load('embeddings/elmo_test.npy') # Creating character data set def create_char_dataset(data, words, max_len): max_len_char = 15 print('Generating character embeddings...') chars = set([w_i for w in words for w_i in w]) n_chars = len(chars) char2idx = {c: i + 2 for i, c in enumerate(chars)} char2idx["UNK"] = 1 char2idx["PAD"] = 0 X_char = [] for letter in data: sent_seq = [] for i in range(max_len): word_seq = [] for j in range(max_len_char): try: word_seq.append(char2idx.get(letter[i][j])) except: word_seq.append(char2idx.get("PAD")) sent_seq.append(word_seq) X_char.append(np.array(sent_seq)) return X_char, max_len_char, n_chars X_char_tr, max_len_char, n_chars = create_char_dataset(letters_train, words_train, max_len) X_char_te, _, _ = create_char_dataset(letters_test, words_train, max_len) idx2tag = {i: w for w, i in tag2idx.items()} print('Training the model') data_dim = 1024 timesteps = max_len num_classes = len(tags) batch_size = 128 epochs = 100 print(f"timesteps: {timesteps}") print(f"num_classes: {num_classes}") print(f"batch_size: {batch_size}") print(f"X_char_tr.shape: {np.array(X_char_tr).shape}") print(f"max_len_char: {max_len_char}") print(f"len(y_tr): {len(y_tr)}") print(f"max_len: {max_len}") print(f"X_tr.shape: {X_tr.shape}") word_in = Input(shape=(max_len,)) # Input and embedding for words word_input = Input(shape=(timesteps,data_dim)) # input and embeddings for characters char_in = Input(shape=(max_len, max_len_char,)) emb_char = TimeDistributed(Embedding(input_dim=n_chars + 2, output_dim=24, input_length=max_len_char, mask_zero=True))(char_in) # character LSTM to get word encodings by characters char_enc = TimeDistributed(LSTM(units=64, return_sequences=False, recurrent_dropout=0.5))(emb_char) # main LSTM x = concatenate([word_input, char_enc]) x = SpatialDropout1D(0.3)(x) x = Bidirectional(LSTM(units=50, return_sequences=True, recurrent_dropout=0.1))(x) out = TimeDistributed(Dense(num_classes, activation="softmax"))(x) model = Model([word_input, char_in], out) model.compile(optimizer="rmsprop", loss="sparse_categorical_crossentropy", metrics=["acc"]) # Set callback functions to early stop training and save the best model so far callbacks = [EarlyStopping(monitor='val_loss', patience=10), ModelCheckpoint(filepath='models/best_model_lstm_elmo.h5', monitor='val_loss', save_best_only=True)] print(model.summary()) history = model.fit([X_tr,
np.array(X_char_tr)
numpy.array
import numpy as np import matplotlib.pyplot as plt def volt(dBm): return np.sqrt(50*1e-3*(10**(dBm/10))) path = r'D:\data\20190718\155221_Qubit smart_two_tone2' cavity_path = r'D:\data\20190718\155221_cavity smart_two_tone2' data_name = path+path[16:]+r'.dat' cavity_data_name = cavity_path+cavity_path[16:]+r'.dat' data = np.loadtxt(data_name, unpack=True) cavity_data = np.loadtxt(cavity_data_name, unpack=True) n = 5 power= np.array_split(data[0],n) freq = np.array_split(data[1],n)[0] absol = np.array_split(data[4],n) cavity_absol = np.array_split(cavity_data[2],n) cavity_freq =
np.array_split(cavity_data[1],n)
numpy.array_split
# Project: AttractionRepulsionModel # Filename: arm.py # Authors: <NAME> (<EMAIL>). """ arm: An agent-based model of ideological polarization utilizing both attractive and repulsive interactions. """ import math import numpy as np from tqdm import trange def arm(N=100, D=1, E=[0.1], T=0.25, R=0.25, K=math.inf, S=500000, P=0, \ shock=(None, None), init='norm', seed=None, silent=False): """ Execute a simulation of the Attraction-Repulsion Model. Inputs: N (int): number of agents D (int): number of ideological dimensions E ([float]): list of exposures T (float): tolerance R (float): responsiveness K (float): steepness of stochastic attraction-repulsion S (int): number of steps to simulate P (float): self-interest probability shock ((float, float)): external shock step and strength init (str): 'norm' for Gaussian normal initialization, 'emp' for empirical seed (int): random seed silent (bool): True if progress should be shown on command line Returns (init_config, config, history): init_config: N x D array of initial agent ideological positions config: N x D array of agent ideological positions after S steps history: S x (D + 2) array detailing interaction history """ # Initialize the random number generation. rng = np.random.default_rng(seed) # Initialize the agent population and their initial ideological positions. if init == 'norm': if D == 1: config = np.zeros(N) for i in np.arange(N): while True: config[i] = rng.normal(0.5, 0.2) if 0 <= config[i] and config[i] <= 1: break config = config.reshape(-1, 1) else: # Higher dimensions. means, covs = 0.5 +
np.zeros(D)
numpy.zeros
import os import pickle import numpy as np import matplotlib.pyplot as plt from training_flags import FLAGS import tensorflow as tf from data_readers.bair_predictions_data_reader import BairPredictionsDataReader from action_inference.action_inference_model import action_inference_model from training_flags import FLAGS from tensorflow.python.keras.models import Model from tensorflow.python.keras.layers import Input from tensorflow.python.keras import backend as K from data_readers.bair_data_reader import BairDataReader from sklearn.metrics import r2_score SMALL_SIZE = 20 MEDIUM_SIZE =24 BIGGER_SIZE = 40 LINEWIDTH = 4.0 color_mean = ['orangered', 'mediumvioletred', 'teal', 'gold', 'mediumblue'] color_shading = ['lightpink', 'thistle', 'paleturquoise', 'lemonchiffon', 'azure'] def plot_mean_and_CI(mean, standard_deviation, n_samples, color_mean=None, color_shading=None, labels=None, start=2, end=30, step=1, linestyle='solid', linewidth=4.0): z = 1.96 # for 95% confidence interval ub = z * (standard_deviation / np.sqrt(n_samples)) # + mean lb = z * (standard_deviation / np.sqrt(n_samples)) # + mean # plt.fill_between(range(start, end, step), ub, lb, color=color_shading, alpha=.5) # plt.plot(range(start, end, step), mean, color_mean, label=labels, linestyle=linestyle, linewidth=linewidth) plt.errorbar(x=range(start, end, step), y=mean, yerr=[lb, ub], color=color_mean, label=labels, linestyle=linestyle, linewidth=linewidth) def configure_plt(): plt.rc('axes', titlesize=MEDIUM_SIZE) # fontsize of the axes title plt.rc('axes', labelsize=MEDIUM_SIZE) # fontsize of the x and y labels plt.rc('xtick', labelsize=SMALL_SIZE) # fontsize of the tick labels plt.rc('ytick', labelsize=SMALL_SIZE) # fontsize of the tick labels plt.rc('legend', fontsize=MEDIUM_SIZE) # legend fontsize plt.rc('figure', titlesize=BIGGER_SIZE) # fontsize of the figure title def make_plots_action_inference(model_list, results_dir, n_samples=256, vertical_sub_plots=False): configure_plt() if not os.path.isdir(results_dir + '/plots'): os.makedirs(results_dir + '/plots', exist_ok=True) avg_r2_list = np.zeros(len(model_list)) avg_l1_list = np.zeros(len(model_list)) if vertical_sub_plots: v_plots = 2 h_plots = 1 figsize = (12, 16) bbox = (0.5, -0.4) ncol = 3 else: v_plots = 1 h_plots = 2 figsize = (34, 8) bbox = (-0.1, -0.3) ncol = 7 r2_fig, r2_ax = plt.subplots(v_plots, h_plots, figsize=figsize) l1_fig, l1_ax = plt.subplots(v_plots, h_plots, figsize=figsize) for i, model_name in enumerate(model_list): if model_name == 'ours_savp': labels = 'savp' elif model_name == 'ours_vae': labels = 'savp_vae' else: labels = model_name inference_metrics_dir = os.path.join(results_dir, labels, 'inference_metrics.pickle') if model_name == 'svg': labels = 'svg-lp' labels = labels.replace("_", "-") # == R2 with open(inference_metrics_dir, 'rb') as f: abs_diff_by_step_mean, abs_diff_by_step_std, avg_r2_by_step_x, avg_r2_by_step_y, avg_r2, avg_l1 = pickle.load( f) avg_r2_list[i] = avg_r2 avg_l1_list[i] = avg_l1 plt.sca(r2_ax[0]) plt.plot(range(3, 27 + 3 - 1, 2), avg_r2_by_step_x[1::2], label=labels.upper(), color=color_mean[i], linewidth=LINEWIDTH) plt.scatter(range(3, 27 + 3 - 1, 2), avg_r2_by_step_x[1::2], color=color_mean[i], s=60) plt.plot(range(2, 27 + 2, 2), avg_r2_by_step_x[::2], linestyle='dashed', color=color_mean[i], linewidth=LINEWIDTH) plt.scatter(range(2, 27 + 2, 2), avg_r2_by_step_x[::2], color=color_mean[i], s=60) plt.sca(r2_ax[1]) plt.plot(range(3, 27 + 3 - 1, 2), avg_r2_by_step_y[1::2], label=labels.upper(), color=color_mean[i], linewidth=LINEWIDTH) plt.scatter(range(3, 27 + 3 - 1, 2), avg_r2_by_step_y[1::2], color=color_mean[i], s=60) plt.plot(range(2, 27 + 2, 2), avg_r2_by_step_y[::2], linestyle='dashed', color=color_mean[i], linewidth=LINEWIDTH) plt.scatter(range(2, 27 + 2, 2), avg_r2_by_step_y[::2], color=color_mean[i], s=60) # == L1 plt.sca(l1_ax[0]) plot_mean_and_CI(abs_diff_by_step_mean[1::2, 0], abs_diff_by_step_std[1::2, 0], n_samples, color_mean[i], color_shading[i], labels.upper(), start=3, end=29, step=2) plot_mean_and_CI(abs_diff_by_step_mean[::2, 0], abs_diff_by_step_std[::2, 0], n_samples, color_mean[i], color_shading[i], start=2, end=29, step=2, linestyle='dashed') plt.sca(l1_ax[1]) plot_mean_and_CI(abs_diff_by_step_mean[1::2, 1], abs_diff_by_step_std[1::2, 1], n_samples, color_mean[i], color_shading[i], labels.upper(), start=3, end=29, step=2) plot_mean_and_CI(abs_diff_by_step_mean[::2, 1], abs_diff_by_step_std[::2, 1], n_samples, color_mean[i], color_shading[i], start=2, end=29, step=2, linestyle='dashed') # ===== R2 L1 table r2_string = [str(avg_r2_list[i]) for i in range(len(model_list))] l1_string = [str(avg_l1_list[i]) for i in range(len(model_list))] table_fig = plt.figure(figsize=(10, 15)) plt.figure(table_fig.number) collabel = ['Model', 'R2 score', 'L1 score'] plt.axis('tight') plt.axis('off') names = model_list names = names[:len(model_list)] # assuming model_list has the order above the_table = plt.table( cellText=np.stack([np.array(names), np.array(r2_string), np.array(l1_string)], axis=0).transpose(), colLabels=collabel, loc='center', cellLoc='center', colWidths=[0.5, 0.5, 0.5]) plt.savefig(os.path.join(results_dir, 'plots', 'r2_l1.eps'), format='eps') plt.savefig(os.path.join(results_dir, 'plots', 'r2_l1.png'), format='png') # ===== R2 plt.sca(r2_ax[0]) plt.title(r'Average $R^{2}$ on the x axis') plt.xlabel('Time Step') plt.ylabel('Average $R^{2}$') plt.ylim(-0.2, 1) plt.xticks(range(0, 31, 2)) plt.yticks(np.arange(-0.2, 1.0, 0.2)) plt.axvline(x=12, zorder=-1, color='darkblue') plt.axhline(y=0, zorder=-1, color='black', linewidth=0.7) plt.grid() plt.sca(r2_ax[1]) plt.title(r'Average $R^{2}$ on the y axis') plt.xlabel('Time Step') plt.ylabel('Average $R^{2}$') plt.ylim(-0.2, 1) plt.xticks(range(0, 31, 2)) plt.yticks(np.arange(-0.2, 1.0, 0.2)) plt.axvline(x=12, zorder=-1, color='darkblue') plt.axhline(y=0, zorder=-1, color='black', linewidth=0.7) plt.plot(range(1), -10, color='black', linestyle='solid', label='odd time steps', linewidth=LINEWIDTH) plt.plot(range(1), -10, color='black', linestyle='dashed', label='even time steps', linewidth=LINEWIDTH) plt.grid() plt.figure(r2_fig.number) lgd = plt.legend(shadow=True, fancybox=True, loc='lower center', bbox_to_anchor=bbox, ncol=ncol) plt.subplots_adjust(hspace=0.25) plt.savefig(os.path.join(results_dir, 'plots', 'r2.eps'), format='eps', bbox_extra_artists=(lgd,), bbox_inches='tight') plt.savefig(os.path.join(results_dir, 'plots', 'r2.png'), format='png', bbox_extra_artists=(lgd,), bbox_inches='tight') # ===== L1 plt.sca(l1_ax[0]) plt.title(r'Average MAE on the x axis') plt.xlabel('Time Step') plt.ylabel('Average MAE') plt.xticks(range(0, 31, 2)) plt.axvline(x=12, zorder=-1, color='darkblue') plt.grid() plt.ylim(0.0, None) plt.sca(l1_ax[1]) plt.title(r'Average MAE on the y axis') plt.xlabel('Time Step') plt.ylabel('Average MAE') plt.xticks(range(0, 31, 2)) plt.axvline(x=12, zorder=-1, color='darkblue') plt.grid() plt.ylim(0.0, None) plt.plot(range(1), -10, color='black', linestyle='solid', label='odd time steps', linewidth=LINEWIDTH) plt.plot(range(1), -10, color='black', linestyle='dashed', label='even time steps', linewidth=LINEWIDTH) plt.figure(l1_fig.number) lgd = plt.legend(shadow=True, fancybox=True, loc='lower center', bbox_to_anchor=bbox, ncol=ncol) plt.subplots_adjust(hspace=0.25) plt.savefig(os.path.join(results_dir, 'plots', 'l1.eps'), format='eps', bbox_extra_artists=(lgd,), bbox_inches='tight') plt.savefig(os.path.join(results_dir, 'plots', 'l1.png'), format='png', bbox_extra_artists=(lgd,), bbox_inches='tight') def make_plots_vp_metrics(model_list, results_dir, n_samples=256, vertical_sub_plots=False): configure_plt() if not os.path.isdir(results_dir + '/plots'): os.makedirs(results_dir + '/plots', exist_ok=True) if vertical_sub_plots: v_plots = 2 h_plots = 1 figsize = (12, 12) bbox = (0.5, -0.4) ncol = 3 else: v_plots = 1 h_plots = 2 figsize = (34, 8) bbox = (-0.1, -0.3) ncol = 7 fvd_list = np.zeros(len(model_list)) psnr_ssim_fig, psnr_ssim_ax = plt.subplots(v_plots, h_plots, figsize=figsize) for i, model_name in enumerate(model_list): if model_name == 'ours_savp': labels = 'savp' elif model_name == 'ours_vae': labels = 'savp_vae' else: labels = model_name metrics_dir = os.path.join(results_dir, labels, 'metrics.pickle') if model_name == 'svg': labels = 'svg-lp' labels = labels.replace("_", "-") # ===== existing metrics with open(metrics_dir, 'rb') as f: psnr_mean, psnr_standard_dev, ssim_mean, ssim_standard_dev, fvd_val = pickle.load(f) # plot PSNR the data plt.sca(psnr_ssim_ax[0]) plot_mean_and_CI(psnr_mean, psnr_standard_dev, n_samples, color_mean[i], color_shading[i], labels.upper()) # plot SSIM the data plt.sca(psnr_ssim_ax[1]) plot_mean_and_CI(ssim_mean, ssim_standard_dev, n_samples, color_mean[i], color_shading[i], labels.upper()) fvd_list[i] = fvd_val # ===== FVD table fvd_string = [str(fvd_list[i]) for i in range(len(model_list))] table_fig = plt.figure(figsize=(10, 15)) plt.figure(table_fig.number) collabel = ['Model', 'FVD Score'] plt.axis('tight') plt.axis('off') names = model_list names = names[:len(model_list)] # assuming model_list has the order above the_table = plt.table(cellText=np.stack([np.array(names), np.array(fvd_string)], axis=0).transpose(), colLabels=collabel, loc='center', cellLoc='center', colWidths=[0.5, 0.5]) plt.savefig(os.path.join(results_dir, 'plots', 'fvd.eps'), format='eps') plt.savefig(os.path.join(results_dir, 'plots', 'fvd.png'), format='png') # ===== PSNR & SSIM plt.sca(psnr_ssim_ax[0]) plt.title('Average PSNR by prediction step') plt.xlabel('Time Step') plt.ylabel('Average PSNR') plt.xticks(range(0, 31, 2)) plt.grid() plt.axvline(x=12, zorder=-1, color='darkblue') plt.sca(psnr_ssim_ax[1]) plt.title('Average SSIM by prediction step') plt.xlabel('Time Step') plt.ylabel('Average SSIM') plt.xticks(range(0, 31, 2)) plt.grid() lgd = plt.legend(shadow=True, fancybox=True, loc='lower center', bbox_to_anchor=bbox, ncol=ncol) plt.axvline(x=12, zorder=-1, color='darkblue') plt.figure(psnr_ssim_fig.number) plt.subplots_adjust(hspace=0.35) plt.savefig(os.path.join(results_dir, 'plots', 'psnr_ssim.eps'), format='eps', bbox_extra_artists=(lgd,), bbox_inches='tight') plt.savefig(os.path.join(results_dir, 'plots', 'psnr_ssim.png'), format='png', bbox_extra_artists=(lgd,), bbox_inches='tight') def make_plots_regressions(model_list, results_dir, inference_models_dir, n_samples=256, vertical_sub_plots=False): FLAGS.batch_size = 1 FLAGS.train_val_split = 0.0 FLAGS.sequence_length_test = 28 sequence_length = FLAGS.sequence_length_test if vertical_sub_plots: v_plots = 2 h_plots = 1 figsize = (12, 12) bbox = (0.5, -0.4) ncol = 3 else: v_plots = 1 h_plots = 2 figsize = (34, 8) bbox = (-0.1, -0.3) ncol = 7 configure_plt() all_pred_seq = {name:
np.zeros([n_samples, sequence_length - 1, 2])
numpy.zeros
#-*- codeing=utf-8 -*- #@time: 2020/7/13 20:21 #@Author: <NAME> import numpy as np # deal with data import pandas as pd # deal with data import re # regular expression from bs4 import BeautifulSoup # resolver review from nltk.corpus import stopwords # Import the stop word list from gensim.models import word2vec# use word2Vec(skip-gram model) making wordfeature vetor from sklearn.model_selection import train_test_split # use trian data split train and test data import torch from torch.utils.data import Dataset,TensorDataset import torch.nn as nn from tqdm import tqdm from run_model.classifier import model from collections import Counter from imblearn.over_sampling import SMOTE from sklearn import metrics def review_to_wordlist(review,remove_stop_words=False): #1.remove HIML reivew_text=BeautifulSoup(review,'lxml').get_text() #2.Remove non-latters latters_only=re.sub("[^a-zA-Z]",' ',reivew_text) #3.Convert to lower case,split into individual words words=latters_only.lower().split() #4.Remove stop words if remove_stop_words: stop=set(stopwords.words('english')) words=[w for w in words if not w in stop] #5. reutrn a list of words return words # make features vector by each words def makeFeatureVec(words,model,num_features): featureVec = np.zeros((num_features,), dtype="float32") nwords=0 index2word_set = set(model.wv.index2word) #get name for word in words: if word in index2word_set: # if word in index2word and get it's feature nwords+=1 featureVec=np.add(featureVec,model[word]) if nwords == 0: pass else: featureVec=
np.divide(featureVec,nwords)
numpy.divide
# Utility Functions # Authors: <NAME> # Edited by: <NAME> ''' Used by the user to define channels that are hard coded for analysis. ''' # Imports necessary for this function import numpy as np import re from itertools import combinations def splitpatient(patient): stringtest = patient.find('seiz') if stringtest == -1: stringtest = patient.find('sz') if stringtest == -1: stringtest = patient.find('aw') if stringtest == -1: stringtest = patient.find('aslp') if stringtest == -1: stringtest = patient.find('_') if stringtest == -1: print("Not sz, seiz, aslp, or aw! Please add additional naming possibilities, or tell data gatherers to rename datasets.") else: pat_id = patient[0:stringtest] seiz_id = patient[stringtest:] # remove any underscores pat_id = re.sub('_', '', pat_id) seiz_id = re.sub('_', '', seiz_id) return pat_id, seiz_id def returnindices(pat_id, seiz_id=None): included_indices, onsetelecs, clinresult = returnnihindices( pat_id, seiz_id) if included_indices.size == 0: included_indices, onsetelecs, clinresult = returnlaindices( pat_id, seiz_id) if included_indices.size == 0: included_indices, onsetelecs, clinresult = returnummcindices( pat_id, seiz_id) if included_indices.size == 0: included_indices, onsetelecs, clinresult = returnjhuindices( pat_id, seiz_id) if included_indices.size == 0: included_indices, onsetelecs, clinresult = returntngindices( pat_id, seiz_id) return included_indices, onsetelecs, clinresult def returntngindices(pat_id, seiz_id): included_indices = np.array([]) onsetelecs = None clinresult = -1 if pat_id == 'id001ac': # included_indices = np.concatenate((np.arange(0,4), np.arange(5,55), # np.arange(56,77), np.arange(78,80))) included_indices = np.array([0, 1, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39, 40, 41, 42, 43, 45, 46, 47, 48, 49, 50, 51, 52, 53, 58, 59, 60, 61, 62, 63, 64, 65, 66, 68, 69, 70, 71, 72, 73, 74, 75, 76, 78, 79]) elif pat_id == 'id002cj': # included_indices = np.array(np.arange(0,184)) included_indices = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 30, 31, 32, 33, 34, 35, 36, 37, 38, 45, 46, 47, 48, 49, 50, 51, 52, 53, 60, 61, 62, 63, 64, 65, 66, 67, 70, 71, 72, 73, 74, 75, 76, 85, 86, 87, 88, 89, 90, 91, 92, 93, 100, 101, 102, 103, 104, 105, 106, 107, 108, 115, 116, 117, 118, 119, 120, 121, 122, 123, 129, 130, 131, 132, 133, 134, 135, 136, 137, # np.arange(143, 156) 143, 144, 145, 146, 147, 148, 149, 150, 151, 157, 158, 159, 160, 161, 162, 163, 164, 165, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182]) elif pat_id == 'id003cm': included_indices = np.concatenate((np.arange(0,13), np.arange(25,37), np.arange(40,50), np.arange(55,69), np.arange(70,79))) elif pat_id == 'id004cv': # removed OC'10, SC'5, CC'14/15 included_indices = np.concatenate((np.arange(0,23), np.arange(25,39), np.arange(40,59), np.arange(60,110))) elif pat_id == 'id005et': included_indices = np.concatenate((np.arange(0,39), np.arange(39,47), np.arange(52,62), np.arange(62,87))) elif pat_id == 'id006fb': included_indices = np.concatenate((np.arange(10,19), np.arange(40,50), np.arange(115,123))) elif pat_id == 'id008gc': included_indices = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 48, 49, 50, 51, 52, 53, 54, 56, 57, 58, 61, 62, 63, 64, 65, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 83, 84, 85, 86, 87, 88, 89, 90, 92, 93, 94, 95, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 110, 111]) elif pat_id == 'id009il': included_indices = np.concatenate((np.arange(0,10), np.arange(10,152))) elif pat_id == 'id010js': included_indices = np.concatenate((np.arange(0,14), np.arange(15,29), np.arange(30,42), np.arange(43,52), np.arange(53,65), np.arange(66,75), np.arange(76,80), np.arange(81,85), np.arange(86,94), np.arange(95,98), np.arange(99,111), np.arange(112,124))) elif pat_id == 'id011ml': included_indices = np.concatenate((np.arange(0,18), np.arange(21,68), np.arange(69,82), np.arange(82,125))) elif pat_id == 'id012pc': included_indices = np.concatenate((np.arange(0,4), np.arange(9,17), np.arange(18,28), np.arange(31,41), np.arange(44,56), np.arange(57,69), np.arange(70,82), np.arange(83,96), np.arange(97,153))) elif pat_id == 'id013pg': included_indices = np.array([2, 3, 4, 5, 15, 18, 19, 20, 21, 23, 24, 25, 30, 31, 32, 33, 34, 35, 36, 37, 38, 50, 51, 52, 53, 54, 55, 56, 57, 58, 60, 61, 62, 63, 64, 65, 66, 67, 68, 70, 71, 72, 73, 74, 75, 76, 77, 78]) elif pat_id == 'id014rb': included_indices = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 135, 136, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164]) elif pat_id == 'id015sf': included_indices = np.concatenate((np.arange(0,37), np.arange(38,77), np.arange(78,121))) return included_indices, onsetelecs, clinresult def returnnihindices(pat_id, seiz_id): included_indices = np.array([]) onsetelecs = None clinresult = -1 if pat_id == 'pt1': included_indices = np.concatenate((np.arange(0, 36), np.arange(41, 43), np.arange(45, 69), np.arange(71, 95))) onsetelecs = set(['ATT1', 'ATT2', 'AD1', 'AD2', 'AD3', 'AD4', 'PD1', 'PD2', 'PD3', 'PD4']) resectelecs = set(['ATT1', 'ATT2', 'ATT3', 'ATT4', 'ATT5', 'ATT6', 'ATT7', 'ATT8', 'AST1', 'AST2', 'AST3', 'AST4', 'PST1', 'PST2', 'PST3', 'PST4', 'AD1', 'AD2', 'AD3', 'AD4', 'PD1', 'PD2', 'PD3', 'PD4', 'PLT5', 'PLT6', 'SLT1']) clinresult = 1 elif pat_id == 'pt2': # [1:14 16:19 21:25 27:37 43 44 47:74] included_indices = np.concatenate((np.arange(0, 14), np.arange(15, 19), np.arange( 20, 25), np.arange( 26, 37), np.arange( 42, 44), np.arange(46, 74))) onsetelecs = set(['MST1', 'PST1', 'AST1', 'TT1']) resectelecs = set(['TT1', 'TT2', 'TT3', 'TT4', 'TT6', 'TT6', 'G1', 'G2', 'G3', 'G4', 'G9', 'G10', 'G11', 'G12', 'G18', 'G19', 'G20', 'G26', 'G27', 'AST1', 'AST2', 'AST3', 'AST4', 'MST1', 'MST2', 'MST3', 'MST4']) clinresult = 1 elif pat_id == 'pt3': # [1:19 21:37 42:43 46:69 71:107] included_indices = np.concatenate((np.arange(0, 19), np.arange(20, 37), np.arange(41, 43), np.arange(45, 69), np.arange(70, 107))) onsetelecs = set(['SFP1', 'SFP2', 'SFP3', 'IFP1', 'IFP2', 'IFP3', 'MFP2', 'MFP3', 'OF1', 'OF2', 'OF3', 'OF4']) resectelecs = set(['FG1', 'FG2', 'FG9', 'FG10', 'FG17', 'FG18', 'FG25', 'SFP1', 'SFP2', 'SFP3', 'SFP4', 'SFP5', 'SFP6', 'SFP7', 'SFP8', 'MFP1', 'MFP2', 'MFP3', 'MFP4', 'MFP5', 'MFP6', 'IFP1', 'IFP2', 'IFP3', 'IFP4', 'OF3', 'OF4']) clinresult = 1 elif pat_id == 'pt4': # [1:19 21:37 42:43 46:69 71:107] included_indices = np.concatenate((np.arange(0, 19), np.arange(20, 26), np.arange(28, 36))) onsetelecs = set([]) resectelecs = set([]) clinresult = -1 elif pat_id == 'pt5': included_indices = np.concatenate((np.arange(0, 19), np.arange(20, 26), np.arange(28, 36))) onsetelecs = set([]) resectelecs = set([]) clinresult = -1 elif pat_id == 'pt6': # [1:36 42:43 46 52:56 58:71 73:95] included_indices = np.concatenate((np.arange(0, 36), np.arange(41, 43), np.arange(45, 46), np.arange(51, 56), np.arange(57, 71), np.arange(72, 95))) onsetelecs = set(['LA1', 'LA2', 'LA3', 'LA4', 'LAH1', 'LAH2', 'LAH3', 'LAH4', 'LPH1', 'LPH2', 'LPH3', 'LPH4']) resectelecs = set(['LALT1', 'LALT2', 'LALT3', 'LALT4', 'LALT5', 'LALT6', 'LAST1', 'LAST2', 'LAST3', 'LAST4', 'LA1', 'LA2', 'LA3', 'LA4', 'LPST4', 'LAH1', 'LAH2', 'LAH3', 'LAH4', 'LPH1', 'LPH2']) clinresult = 2 elif pat_id == 'pt7': # [1:17 19:35 37:38 41:62 67:109] included_indices = np.concatenate((np.arange(0, 17), np.arange(18, 35), np.arange(36, 38), np.arange(40, 62), np.arange(66, 109))) onsetelecs = set(['MFP1', 'LFP3', 'PT2', 'PT3', 'PT4', 'PT5', 'MT2', 'MT3', 'AT3', 'AT4', 'G29', 'G30', 'G39', 'G40', 'G45', 'G46']) resectelecs = set(['G28', 'G29', 'G30', 'G36', 'G37', 'G38', 'G39', 'G41', 'G44', 'G45', 'G46', 'LFP1', 'LFP2', 'LSF3', 'LSF4']) clinresult = 3 elif pat_id == 'pt8': # [1:19 21 23 30:37 39:40 43:64 71:76] included_indices = np.concatenate((np.arange(0, 19), np.arange(20, 21), np.arange( 22, 23), np.arange( 29, 37), np.arange( 38, 40), np.arange(42, 64), np.arange(70, 76))) onsetelecs = set(['G19', 'G23', 'G29', 'G30', 'G31', 'TO6', 'TO5', 'MST3', 'MST4', 'O8', 'O9']) resectelecs = set(['G22', 'G23', 'G27', 'G28', 'G29', 'G30', 'G31', 'MST2', 'MST3', 'MST4', 'PST2', 'PST3', 'PST4']) clinresult = 1 elif pat_id == 'pt10': # [1:3 5:19 21:35 48:69] included_indices = np.concatenate((np.arange(0, 3), np.arange(4, 19), np.arange(20, 35),
np.arange(47, 69)
numpy.arange
#-*- coding: utf-8 -*- import numpy as n, random, os, sys, time from scipy.io import wavfile as w tfoo=time.time() H=n.hstack V=n.vstack f_a = 44100. # Hz, frequência de amostragem ############## 2.2.1 Tabela de busca (LUT) Lambda_tilde=Lt=1024.*16 # Senoide fooXY=n.linspace(0,2*n.pi,Lt,endpoint=False) S_i=n.sin(fooXY) # um período da senóide com T amostras # Quadrada: Q_i=n.hstack( ( n.ones(Lt/2)*-1 , n.ones(Lt/2) ) ) # Triangular: foo=n.linspace(-1,1,Lt/2,endpoint=False) Tr_i=n.hstack( ( foo , foo*-1 ) ) # Dente de Serra: D_i=n.linspace(-1,1,Lt) def v(f=220,d=2.,tab=S_i,fv=2.,nu=2.,tabv=S_i): if nu==13.789987: return n.zeros(int(fa*d)) Lambda=n.floor(f_a*d) ii=n.arange(Lambda) Lv=float(len(tabv)) Gammav_i=n.floor((ii*fv*Lv)/f_a) # índices para a LUT Gammav_i=n.array(Gammav_i,n.int) # padrão de variação do vibrato para cada amostra Tv_i=tabv[Gammav_i%int(Lv)] # frequência em Hz em cada amostra F_i=f*( 2.**( Tv_i*nu/12. ) ) # a movimentação na tabela por amostra D_gamma_i=F_i*(Lt/float(f_a)) Gamma_i=n.cumsum(D_gamma_i) # a movimentação na tabela total Gamma_i=n.floor( Gamma_i) # já os índices Gamma_i=n.array( Gamma_i, dtype=n.int) # já os índices return tab[Gamma_i%int(Lt)] # busca dos índices na tabela def A(fa=2.,V_dB=10.,d=2.,taba=S_i): # Use com: v(d=XXX)*A(d=XXX) Lambda=n.floor(f_a*d) ii=n.arange(Lambda) Lt=float(len(taba)) Gammaa_i=n.floor(ii*fa*Lt/f_a) # índices para a LUT Gammaa_i=n.array(Gammaa_i,n.int) # variação da amplitude em cada amostra A_i=taba[Gammaa_i%int(Lt)] A_i=1+A_i*(1- 10.**(V_dB/20.)) return A_i def adsr(som,A=10.,D=20.,S=-20.,R=100.,xi=1e-2): """Envelope ADSR com A ataque em milissegundos, D decay em milissegundos S sustain, com número de decibéis a menos R Release em milisegundos Atenção para que a duração total é dada pelo som em si e que a duração do trecho em sustain é a diferença entre a duração total e as durações das partes ADR.""" a_S=10**(S/20.) Lambda=len(som) Lambda_A=int(A*f_a*0.001) Lambda_D=int(D*f_a*0.001) Lambda_R=int(R*f_a*0.001) Lambda_S=Lambda - Lambda_A - Lambda_D - Lambda_R ii=n.arange(Lambda_A,dtype=n.float) A=ii/(Lambda_A-1) A_i=A # ok ii=n.arange(Lambda_A,Lambda_D+Lambda_A,dtype=n.float) D=1-(1-a_S)*( ( ii-Lambda_A )/( Lambda_D-1) ) A_i=n.hstack( (A_i, D ) ) S=n.ones(Lambda-Lambda_R-(Lambda_A+Lambda_D),dtype=n.float)*a_S A_i=n.hstack( ( A_i, S ) ) ii=n.arange(Lambda-Lambda_R,Lambda,dtype=n.float) R=a_S-a_S*((ii-(Lambda-Lambda_R))/(Lambda_R-1)) A_i=n.hstack( (A_i,R) ) return som*A_i triadeM=[0.,4.,7.] def ac(f=220.,notas=[0.,4.,7.,12.],tab=Q_i,d=2.,nu=0,fv=2.): acorde=adsr(v(tab=tab,d=d,f=f*2.**(notas[-1]/12.),nu=nu,fv=fv)) for na in notas[:-1]: acorde+=adsr(v(tab=tab,d=d,f=f*2**(na/12.),nu=nu,fv=fv)) return acorde*10 def N(arr,xx=1.): r=arr r = (((r-r.min())/(r.max()-r.min()))*2-1)*xx return n.int16(r * float(2**15-1)) def NN(arr): return 2*((arr-arr.min())/(arr.max()-arr.min()))-1 vozes="f3,f2,f1,f5,m5,m1,m3".split(",") def fala(frase="Semicondutor livre",ss=160): arq=frase.split()[0] #os.system("espeak -vpt-pt+%s -w%s.wav -g110 -p99 -s110 -b=1 '%s'"%(random.sample(vozes,1)[0],arq,frase)) os.system(u"espeak -vpt-pt+%s -w%s.wav -p99 -b=1 '%s' -s%i"%(random.sample(vozes,1)[0],arq,frase,ss)) #os.system(u"espeak "+ frase +(u" -vpt-pt+%s -w%s.wav -p99 -b=1 -s%i"%(random.sample(vozes,1)[0],arq,ss))) #os.system("espeak -vpt-pt+%s -w%s.wav -g110 -p99 -s130 -b=1 '%s'"%(random.sample(vozes,1)[0],arq,frase)) ff=w.read("%s.wav"%(arq,))[1] ff_=n.fft.fft(ff) s=ff2=n.fft.ifft( n.hstack((ff_,n.zeros(len(ff_)) )) ).real sc_aud=((s-s.min())/(s.max()-s.min()))*2.-1. return sc_aud*10 #### # ruidos Lambda = 100000 # Lambda sempre par # diferença das frequências entre coeficiêntes vizinhos: df = f_a/float(Lambda) coefs = n.exp(1j*n.random.uniform(0, 2*n.pi, Lambda)) # real par, imaginaria impar coefs[Lambda/2+1:] = n.real(coefs[1:Lambda/2])[::-1] - 1j * \ n.imag(coefs[1:Lambda/2])[::-1] coefs[0] = 0. # sem bias coefs[Lambda/2] = 1. # freq max eh real simplesmente # as frequências relativas a cada coeficiente # acima de Lambda/2 nao vale fi = n.arange(coefs.shape[0])*df f0 = 15. # iniciamos o ruido em 15 Hz i0 = n.floor(f0/df) # primeiro coef a valer coefs[:i0] = n.zeros(i0) f0 = fi[i0] # obtenção do ruído em suas amostras temporais ruido = n.fft.ifft(coefs) r = n.real(ruido) r = ((r-r.min())/(r.max()-r.min()))*2-1 rb=r r = n.int16(r * float(2**15-1)) w.write('branco.wav', f_a, r) fator = 10.**(-6/20.) alphai = fator**(n.log2(fi[i0:]/f0)) c = n.copy(coefs) c[i0:] = c[i0:]*alphai # real par, imaginaria impar c[Lambda/2+1:] = n.real(c[1:Lambda/2])[::-1] - 1j * \ n.imag(c[1:Lambda/2])[::-1] # realizando amostras temporais do ruído marrom ruido = n.fft.ifft(c) r = n.real(ruido) r = ((r-r.min())/(r.max()-r.min()))*2-1 rm=r r = n.int16(r * float(2**15-1)) w.write('marrom.wav', f_a, r) ### 2.53 Ruído azul # para cada oitava, ganhamos 3dB fator = 10.**(3/20.) alphai = fator**(n.log2(fi[i0:]/f0)) c = n.copy(coefs) c[i0:] = c[i0:]*alphai # real par, imaginaria impar c[Lambda/2+1:] = n.real(c[1:Lambda/2])[::-1] - 1j * \ n.imag(c[1:Lambda/2])[::-1] # realizando amostras temporais do ruído azul ruido = n.fft.ifft(c) r = n.real(ruido) r = ((r-r.min())/(r.max()-r.min()))*2-1 ra=r r = n.int16(r * float(2**15-1)) w.write('azul.wav', f_a, r) ### 2.54 Ruido violeta # a cada oitava, ganhamos 6dB fator = 10.**(6/20.) alphai = fator**(n.log2(fi[i0:]/f0)) c = n.copy(coefs) c[i0:] = c[i0:]*alphai # real par, imaginaria impar c[Lambda/2+1:] = n.real(c[1:Lambda/2])[::-1] - 1j * \ n.imag(c[1:Lambda/2])[::-1] ruido = n.fft.ifft(c) r = n.real(ruido) r = ((r-r.min())/(r.max()-r.min()))*2-1 rv=r r = n.int16(r * float(2**15-1)) w.write('violeta.wav', f_a, r) ### 2.51 Ruído rosa # a cada oitava, perde-se 3dB fator = 10.**(-3/20.) alphai = fator**(n.log2(fi[i0:]/f0)) c = n.copy(coefs) c[i0:] = coefs[i0:]*alphai # real par, imaginaria impar c[Lambda/2+1:] = n.real(c[1:Lambda/2])[::-1] - 1j * \ n.imag(c[1:Lambda/2])[::-1] ruido = n.fft.ifft(c) r = n.real(ruido) r = ((r-r.min())/(r.max()-r.min()))*2-1 rr=r r = n.int16(r * float(2**15-1)) w.write('rosa.wav', f_a, r) fator = 10.**(-9/20.) alphai = fator**(n.log2(fi[i0:]/f0)) c = n.copy(coefs) c[i0:] = c[i0:]*alphai # real par, imaginaria impar c[Lambda/2+1:] = n.real(c[1:Lambda/2])[::-1] - 1j * \ n.imag(c[1:Lambda/2])[::-1] # realizando amostras temporais do ruído marrom ruido = n.fft.ifft(c) r = n.real(ruido) r = ((r-r.min())/(r.max()-r.min()))*2-1 rp=r r = n.int16(r * float(2**15-1)) w.write('preto.wav', f_a, r) #w.write('respira.wav', f_a, N(H(( # rr[:int(f_a*.5)], # rm[:int(f_a*.5)], # rr[:int(f_a*.5)], # rm[:int(f_a*.5)], # rr[:int(f_a*.5)], # rm[:int(f_a*.5)], # )))) # #w.write('respira2.wav', f_a, N(H(( # rp[:int(f_a*.5)], # rm[:int(f_a*.5)], # rp[:int(f_a*.5)], # rm[:int(f_a*.5)], # rp[:int(f_a*.5)], # rm[:int(f_a*.5)], # )))) # # #w.write('respira3.wav', f_a, N(H(( # adsr(rr[:int(f_a*.5)],S=-.5,A=360.), # 5.*adsr(rm[:int(f_a*.5)],S=-.5,A=360.), # adsr(rr[:int(f_a*.5)],S=-.5,A=360.), # 5.*adsr(rm[:int(f_a*.5)],S=-.5,A=360.), # adsr(rr[:int(f_a*.5)],S=-.5,A=360.), # 5.*adsr(rm[:int(f_a*.5)],S=-.5,A=360.), # )))) # # #w.write('respira4.wav', f_a, N(H(( # adsr(rr[:int(f_a*.5)],S=-.5,A=360.), # adsr(rb[:int(f_a*.5)],S=-.5,A=360.), # adsr(rr[:int(f_a*.5)],S=-.5,A=360.), # adsr(rb[:int(f_a*.5)],S=-.5,A=360.), # adsr(rr[:int(f_a*.5)],S=-.5,A=360.), # adsr(rb[:int(f_a*.5)],S=-.5,A=360.), # )))) # # #w.write('respira5.wav', f_a, N(H(( # adsr(rr[:int(f_a*.5)],S=-.5,A=360.), # adsr(rv[:int(f_a*.5)],S=-.5,A=360.), # adsr(rr[:int(f_a*.5)],S=-.5,A=360.), # adsr(rv[:int(f_a*.5)],S=-.5,A=360.), # adsr(rr[:int(f_a*.5)],S=-.5,A=360.), # adsr(rv[:int(f_a*.5)],S=-.5,A=360.), # )))) # # #w.write('respira6.wav', f_a, N(H(( # adsr(rr[:int(f_a*.2)],S=-.5,A=160.,R=10.), # adsr(rv[:int(f_a*.2)],S=-.5,A=160.,R=10.), # adsr(rr[:int(f_a*.2)],S=-.5,A=160.,R=10.), # adsr(rv[:int(f_a*.2)],S=-.5,A=160.,R=10.), # adsr(rr[:int(f_a*.2)],S=-.5,A=160.,R=10.), # adsr(rv[:int(f_a*.2)],S=-.5,A=160.,R=10.), # adsr(rr[:int(f_a*.2)],S=-.5,A=160.,R=10.), # adsr(rv[:int(f_a*.2)],S=-.5,A=160.,R=10.), # adsr(rr[:int(f_a*.2)],S=-.5,A=160.,R=10.), # adsr(rv[:int(f_a*.2)],S=-.5,A=160.,R=10.), # adsr(rr[:int(f_a*.2)],S=-.5,A=160.,R=10.), # adsr(rv[:int(f_a*.2)],S=-.5,A=160.,R=10.), # adsr(rr[:int(f_a*.2)],S=-.5,A=160.,R=10.), # adsr(rv[:int(f_a*.2)],S=-.5,A=160.,R=10.), # adsr(rr[:int(f_a*.2)],S=-.5,A=160.,R=10.), # adsr(rv[:int(f_a*.2)],S=-.5,A=160.,R=10.), # )))) # # #f0=110. #s=n.zeros(4*f_a) #kk=(2*n.pi/10)*2. # uma volta #aa=20. # 10. dB #for i in xrange(10): # 10 harmonicas # ff=f0*(1+i) # n_oitavas=n.log2(ff/f0) # a_=10.**((n_oitavas*(-25.+aa*n.cos(kk*i))/20.)) # s+=v(f=ff,d=4.,nu=0.)*a_ # #w.write('pisca.wav', f_a, N(H(( # s[:f_a/2], n.zeros(f_a/2), # s[:f_a/2], n.zeros(f_a/2), # s[:f_a/2], n.zeros(f_a/2), # s[:f_a/2], n.zeros(f_a/2), # )))) # # # #f0=1100. #s=n.zeros(4*f_a) #kk=(2*n.pi/10)*2. # uma volta #aa=20. # 10. dB #for i in xrange(10): # 10 harmonicas # ff=f0*(1+i) # n_oitavas=n.log2(ff/f0) # a_=10.**((n_oitavas*(-25.+aa*n.cos(kk*i))/20.)) # s+=v(f=ff,d=4.,nu=0.)*a_ # #w.write('pisca2.wav', f_a, N(H(( # s[:f_a/2], n.zeros(f_a/2), # s[:f_a/2], n.zeros(f_a/2), # s[:f_a/2], n.zeros(f_a/2), # s[:f_a/2], n.zeros(f_a/2), # )))) # # # #f0=11000. #s=n.zeros(4*f_a) #kk=(2*n.pi/10)*2. # uma volta #aa=20. # 10. dB #for i in xrange(10): # 10 harmonicas # ff=f0*(1+i) # n_oitavas=n.log2(ff/f0) # a_=10.**((n_oitavas*(-25.+aa*n.cos(kk*i))/20.)) # s+=v(f=ff,d=4.,nu=0.)*a_ # #w.write('pisca3.wav', f_a, N(H(( # s[:f_a/2], n.zeros(f_a/2), # s[:f_a/2], n.zeros(f_a/2), # s[:f_a/2], n.zeros(f_a/2), # s[:f_a/2], n.zeros(f_a/2), # )))) # # # #f0=410. #s=n.zeros(4*f_a) #kk=(2*n.pi/10)*2. # uma volta #aa=20. # 10. dB #for i in xrange(10): # 10 harmonicas # ff=f0*(1+i) # n_oitavas=n.log2(ff/f0) # a_=10.**((n_oitavas*(-25.+aa*n.cos(kk*i))/20.)) # s+=adsr(v(f=ff,d=4.,nu=0.)*a_,S=-5.) # #w.write('pisca4.wav', f_a, N(H(( # s[:f_a/2], n.zeros(f_a/2), # s[:f_a/2], n.zeros(f_a/2), # s[:f_a/2], n.zeros(f_a/2), # s[:f_a/2], n.zeros(f_a/2), # )))) ##### PISCA TTMPPC #f0=110. #s=n.zeros(4*f_a) #kk=(2*n.pi/10)*2. # uma volta #aa=20. # 10. dB #for i in xrange(10): # 10 harmonicas # ff=f0*(1+i) # n_oitavas=n.log2(ff/f0) # a_=10.**((n_oitavas*(-25.+aa*n.cos(kk*i))/20.)) # s+=v(f=ff,d=4.,nu=0.)*a_ # #w.write('pisca_.wav', f_a, N(H(( # s[:f_a/8], n.zeros(f_a/2), # )))) # # # #f0=1100. #s=n.zeros(4*f_a) #kk=(2*n.pi/10)*2. # uma volta #aa=20. # 10. dB #for i in xrange(10): # 10 harmonicas # ff=f0*(1+i) # n_oitavas=n.log2(ff/f0) # a_=10.**((n_oitavas*(-25.+aa*n.cos(kk*i))/20.)) # s+=v(f=ff,d=4.,nu=0.)*a_ # #w.write('pisca2_.wav', f_a, N(H(( # s[:f_a/8], n.zeros(f_a/2), # )))) # # # #f0=11000. #s=n.zeros(4*f_a) #kk=(2*n.pi/10)*2. # uma volta #aa=20. # 10. dB #for i in xrange(10): # 10 harmonicas # ff=f0*(1+i) # n_oitavas=n.log2(ff/f0) # a_=10.**((n_oitavas*(-25.+aa*n.cos(kk*i))/20.)) # s+=v(f=ff,d=4.,nu=0.)*a_ # #w.write('pisca3_.wav', f_a, N(H(( # s[:f_a/8], n.zeros(f_a/2), # )))) # # # #f0=410. #s=n.zeros(4*f_a) #kk=(2*n.pi/10)*2. # uma volta #aa=20. # 10. dB #for i in xrange(10): # 10 harmonicas # ff=f0*(1+i) # n_oitavas=n.log2(ff/f0) # a_=10.**((n_oitavas*(-25.+aa*n.cos(kk*i))/20.)) # s+=adsr(v(f=ff,d=4.,nu=0.)*a_,S=-5.) # #w.write('pisca4_.wav', f_a, N(H(( # s[:f_a/8], n.zeros(f_a/2), # )))) # ##### END TTMPPC w.write('comendo6.wav', f_a, N(fala("O melhor que voce faz com a sua boca, eh servir de toca, para outra cabessa. Nao que voce meressa, esta oportunidade, que vem com a idade, de se curtir em mim.",ss=3500))) w.write('comendo7.wav', f_a, N(fala("Diga aonde voce vai, que eu vou varrendo, diga aonda voce vai, que eu vou varrendo. Vou varrendo, vou varrendo vou varrendo. Vou varrendo, vou varrendo, vou varrendo.",ss=3500))) # # #w.write('comendo.wav', f_a, N(fala("mahnamnahamhahamnahamhanhamnanhnahamha"))) #w.write('comendo2.wav', f_a, N(fala("manamnaamaamnaamanamnannaama"))) #w.write('comendo3.wav', f_a, N(fala("mnmnmmnmnmnnnm"))) #w.write('comendo4.wav', f_a, N(fala("mnmnmm nmnm nn nmnmnmn"))) #w.write('comendo5.wav', f_a, N(fala("mnhmnhmm nhmhnm nn nhmhnmhnhmn"))) # # #w.write('chorando_.wav', f_a, N(fala("bbbbuaaa bbbbbuaaa bbbbuaaa bbbuaaa"))) # # #w.write('chorando_2.wav', f_a, N(fala("buaaa bbuaaa buaaa buaaa"))) # # # #w.write('chorando_3.wav', f_a, N(fala("buaaa nheee ee ee nheeee e eeeee bbuaaa buaaa nheeeee eee eeeee buaaa"))) # # #w.write('chorando_4.wav', f_a, N(fala("buaaa nheee ee hhh hhh hhh ee nheeehhhh h hh hhe e eeeee bbuhhh h hh haaa buaaa nhhhh hhh eeeee eee hhhhhh h heeeee buaaa"))) # w.write('coma.wav', f_a, N(H(( v(f=1000.*(3./2),nu=0.,d=0.5), n.zeros(int(f_a*0.5)), v(f=1000.*(3./2),nu=0.,d=0.5), n.zeros(int(f_a*0.5)), v(f=1000.*(3./2),nu=0.,d=0.5), n.zeros(int(f_a*0.5)), v(f=1000.*(3./2),nu=0.,d=0.5), n.zeros(int(f_a*0.5)), )),.3)) w.write('coma2.wav', f_a, N(H(( v(f=1000.*2.*(3./2),nu=0.,d=0.5), n.zeros(int(f_a*0.5)), v(f=1000.*2.*(3./2),nu=0.,d=0.5), n.zeros(int(f_a*0.5)), v(f=1000.*2.*(3./2),nu=0.,d=0.5), n.zeros(int(f_a*0.5)), v(f=1000.*2.*(3./2),nu=0.,d=0.5), n.zeros(int(f_a*0.5)), )),.3)) w.write('coma3.wav', f_a, N(H(( v(f=1000.*2.*(3./2),nu=0.,d=0.1), v(f=1000.*2.*(3./2),nu=0.,d=0.3), n.zeros(int(f_a*1.5)), v(f=1000.*2.*(3./2),nu=0.,d=0.1), v(f=1000.*2.*(3./2),nu=0.,d=0.3), n.zeros(int(f_a*1.5)), v(f=1000.*2.*(3./2),nu=0.,d=0.1), v(f=1000.*2.*(3./2),nu=0.,d=0.3), n.zeros(int(f_a*1.5)), v(f=1000.*2.*(3./2),nu=0.,d=0.1), v(f=1000.*2.*(3./2),nu=0.,d=0.3), n.zeros(int(f_a*1.5)), )),.3)) w.write('coma4.wav', f_a, N(H(( v(f=1000.*2.*(3./2),nu=0.,d=0.1), n.zeros(int(f_a*0.1)), v(f=1000.*2.*(3./2),nu=0.,d=0.3), n.zeros(int(f_a*1.5)), v(f=1000.*2.*(3./2),nu=0.,d=0.1), n.zeros(int(f_a*0.1)), v(f=1000.*2.*(3./2),nu=0.,d=0.3), n.zeros(int(f_a*1.5)), v(f=1000.*2.*(3./2),nu=0.,d=0.1), n.zeros(int(f_a*0.1)), v(f=1000.*2.*(3./2),nu=0.,d=0.3), n.zeros(int(f_a*1.5)), v(f=1000.*2.*(3./2),nu=0.,d=0.1), n.zeros(int(f_a*0.1)), v(f=1000.*2.*(3./2),nu=0.,d=0.3), n.zeros(int(f_a*1.5)), )),.3)) w.write('coma5.wav', f_a, N(H(( v(f=1000.*2.*(3./2),nu=0.,d=0.1), n.zeros(int(f_a*1.5)), v(f=1000.*2.*(3./2),nu=0.,d=0.1), n.zeros(int(f_a*1.5)), v(f=1000.*2.*(3./2),nu=0.,d=0.1), n.zeros(int(f_a*1.5)), v(f=1000.*2.*(3./2),nu=0.,d=0.1), n.zeros(int(f_a*1.5)), )),.3)) w.write('coma6.wav', f_a, N(H(( v(f=1000.*2.*(3./2),nu=0.,d=0.1), n.zeros(int(f_a*2.5)), v(f=1000.*2.*(3./2),nu=0.,d=0.1), n.zeros(int(f_a*2.5)), v(f=1000.*2.*(3./2),nu=0.,d=0.1), n.zeros(int(f_a*2.5)), v(f=1000.*2.*(3./2),nu=0.,d=0.1), n.zeros(int(f_a*2.5)), )),.3)) w.write('coma7.wav', f_a, N(H(( v(f=1000.*2.*(3./2),nu=0.,d=0.1), n.zeros(int(f_a*3.5)), v(f=1000.*2.*(3./2),nu=0.,d=0.1), n.zeros(int(f_a*3.5)), v(f=1000.*2.*(3./2),nu=0.,d=0.1), n.zeros(int(f_a*3.5)), v(f=1000.*2.*(3./2),nu=0.,d=0.1), n.zeros(int(f_a*3.5)), )),.3)) w.write('coma8.wav', f_a, N(H(( v(f=1000.*2.*(3./2),nu=2.,d=0.1,tab=Tr_i), n.zeros(int(f_a*3.5)), v(f=1000.*2.*(3./2),nu=2.,d=0.1,tab=Tr_i), n.zeros(int(f_a*3.5)), v(f=1000.*2.*(3./2),nu=2.,d=0.1,tab=Tr_i), n.zeros(int(f_a*3.5)), v(f=1000.*2.*(3./2),nu=2.,d=0.1,tab=Tr_i), n.zeros(int(f_a*3.5)), )),.3)) w.write('respira7.wav', f_a, N(H(( adsr(rr[ :int(f_a*1.5)],S=-.5,A=360.), 5.*adsr(rm[:int(f_a*1.5)],S=-.5,A=360.), adsr(rr[ :int(f_a*1.5)],S=-.5,A=360.), 5.*adsr(rm[:int(f_a*1.5)],S=-.5,A=360.), adsr(rr[ :int(f_a*1.5)],S=-.5,A=360.), 5.*adsr(rm[:int(f_a*1.5)],S=-.5,A=360.), )))) w.write('respira8.wav', f_a, N(H(( adsr(rr[ :int(f_a*2.5)],S=-.5,A=360.), 5.*adsr(rm[:int(f_a*2.5)],S=-.5,A=360.), adsr(rr[ :int(f_a*2.5)],S=-.5,A=360.), 5.*adsr(rm[:int(f_a*2.5)],S=-.5,A=360.), adsr(rr[ :int(f_a*2.5)],S=-.5,A=360.), 5.*adsr(rm[:int(f_a*2.5)],S=-.5,A=360.), )))) w.write('respira9.wav', f_a, N(H(( adsr(rr[ :int(f_a*2.5)],S=-.5,A=1160.), adsr(rb[:int(f_a*2.5)],S=-.5,A=1160.), adsr(rr[ :int(f_a*2.5)],S=-.5,A=1160.), adsr(rb[:int(f_a*2.5)],S=-.5,A=1160.), adsr(rr[ :int(f_a*2.5)],S=-.5,A=1160.), adsr(rb[:int(f_a*2.5)],S=-.5,A=1160.), )))) w.write('respira91.wav', f_a, N(H(( adsr(ra[ :int(f_a*2.5)],S=-.5,A=1160.), adsr(rb[:int(f_a*2.5)],S=-.5,A=1160.), adsr(ra[ :int(f_a*2.5)],S=-.5,A=1160.), adsr(rb[:int(f_a*2.5)],S=-.5,A=1160.), adsr(ra[ :int(f_a*2.5)],S=-.5,A=1160.), adsr(rb[:int(f_a*2.5)],S=-.5,A=1160.), )))) w.write('respira92.wav', f_a, N(H(( adsr(ra[ :int(f_a*2.5)],S=-.5,A=1160.), adsr(rv[:int(f_a*2.5)],S=-.5,A=1160.), adsr(ra[ :int(f_a*2.5)],S=-.5,A=1160.), adsr(rv[:int(f_a*2.5)],S=-.5,A=1160.), adsr(ra[ :int(f_a*2.5)],S=-.5,A=1160.), adsr(rv[:int(f_a*2.5)],S=-.5,A=1160.), )))) w.write('dormindo.wav', f_a, N(H(( adsr(ra[ :int(f_a*2.5)],S=-.5,A=1160.), adsr(rv[:int(f_a*2.5)],S=-.5,A=1160.), adsr(ra[ :int(f_a*2.5)],S=-.5,A=1160.), adsr(rv[:int(f_a*2.5)],S=-.5,A=1160.), adsr(ra[ :int(f_a*2.5)],S=-.5,A=1160.), adsr(rv[:int(f_a*2.5)],S=-.5,A=1160.), )))) # arroto3 arroto6 arroto 9 92 w.write('dormindo2.wav', f_a, N(H(( adsr(ra,S=-.5,A=1760.), adsr(rv,S=-.5,A=1760.), adsr(ra,S=-.5,A=1760.), adsr(rv,S=-.5,A=1760.), adsr(ra,S=-.5,A=1760.), adsr(rv,S=-.5,A=1760.), )))) w.write('dormindo2.wav', f_a, N(H(( adsr(ra,S=-.5,A=1760.), adsr(rv,S=-.5,A=1760.), adsr(ra,S=-.5,A=1760.), adsr(rv,S=-.5,A=1760.), adsr(ra,S=-.5,A=1760.), adsr(rv,S=-.5,A=1760.), )))) ronco=H(( adsr(rp[:int(f_a*0.040)],A=3.,S=-3.,R=10.), adsr(rp[:int(f_a*0.040)],A=3.,S=-3.,R=10.), adsr(rp[:int(f_a*0.040)],A=3.,S=-3.,R=10.), adsr(rp[:int(f_a*0.040)],A=3.,S=-3.,R=10.), adsr(rp[:int(f_a*0.040)],A=3.,S=-3.,R=10.), adsr(rp[:int(f_a*0.040)],A=3.,S=-3.,R=10.), adsr(rp[:int(f_a*0.040)],A=3.,S=-3.,R=10.), )) w.write('dormindo3.wav', f_a, N(H(( ronco,n.zeros(f_a), ronco,n.zeros(f_a), ronco,n.zeros(f_a), ronco,n.zeros(f_a), ronco,n.zeros(f_a), )))) w.write('dormindo4.wav', f_a, N(H(( adsr(ra,S=-.5,A=1760.),ronco,n.zeros(f_a), adsr(rv,S=-.5,A=1760.),ronco,n.zeros(f_a), adsr(ra,S=-.5,A=1760.),ronco,n.zeros(f_a), adsr(rv,S=-.5,A=1760.),ronco,n.zeros(f_a), adsr(ra,S=-.5,A=1760.),ronco,n.zeros(f_a), adsr(rv,S=-.5,A=1760.),ronco,n.zeros(f_a), )))) w.write('dormindo5.wav', f_a, N(H(( adsr(ra,S=-.5,A=1760.),10*ronco,n.zeros(f_a), adsr(rv,S=-.5,A=1760.),10*ronco,n.zeros(f_a), adsr(ra,S=-.5,A=1760.),10*ronco,n.zeros(f_a), adsr(rv,S=-.5,A=1760.),10*ronco,n.zeros(f_a), adsr(ra,S=-.5,A=1760.),10*ronco,n.zeros(f_a), adsr(rv,S=-.5,A=1760.),10*ronco,n.zeros(f_a), )))) w.write('dormindo6.wav', f_a, N(H(( adsr(ra,S=-.5,A=1760.),5*ronco,n.zeros(f_a), adsr(rv,S=-.5,A=1760.),5*ronco,n.zeros(f_a), adsr(ra,S=-.5,A=1760.),5*ronco,n.zeros(f_a), adsr(rv,S=-.5,A=1760.),5*ronco,n.zeros(f_a), adsr(ra,S=-.5,A=1760.),5*ronco,n.zeros(f_a), adsr(rv,S=-.5,A=1760.),5*ronco,n.zeros(f_a), )))) w.write('dormindo7.wav', f_a, N(H(( adsr(ra,S=-.5,A=1760.)+H((n.zeros(len(ra)-len(ronco)),5*ronco)),n.zeros(f_a), adsr(rv,S=-.5,A=1760.)+H((n.zeros(len(ra)-len(ronco)),5*ronco)),n.zeros(f_a), adsr(ra,S=-.5,A=1760.)+H((n.zeros(len(ra)-len(ronco)),5*ronco)),
n.zeros(f_a)
numpy.zeros
import time import numpy as np from openmdao.test.mpiunittest import MPITestCase from openmdao.util.testutil import assert_rel_error from openmdao.main.api import Assembly, Component, set_as_top from openmdao.main.datatypes.api import Float, Array from openmdao.main.mpiwrap import MPI, mpiprint, set_print_rank from openmdao.lib.drivers.iterate import FixedPointIterator from openmdao.lib.optproblems import sellar class ABCDArrayComp(Component): delay = Float(0.01, iotype='in') def __init__(self, arr_size=9): super(ABCDArrayComp, self).__init__() self.add_trait('a', Array(
np.ones(arr_size, float)
numpy.ones
""" Test functions for linalg module """ import os import sys import itertools import traceback import textwrap import subprocess import pytest import numpy as np from numpy import array, single, double, csingle, cdouble, dot, identity, matmul from numpy import multiply, atleast_2d, inf, asarray from numpy import linalg from numpy.linalg import matrix_power, norm, matrix_rank, multi_dot, LinAlgError from numpy.linalg.linalg import _multi_dot_matrix_chain_order from numpy.testing import ( assert_, assert_equal, assert_raises, assert_array_equal, assert_almost_equal, assert_allclose, suppress_warnings, assert_raises_regex, HAS_LAPACK64, ) from numpy.testing._private.utils import requires_memory def consistent_subclass(out, in_): # For ndarray subclass input, our output should have the same subclass # (non-ndarray input gets converted to ndarray). return type(out) is (type(in_) if isinstance(in_, np.ndarray) else np.ndarray) old_assert_almost_equal = assert_almost_equal def assert_almost_equal(a, b, single_decimal=6, double_decimal=12, **kw): if asarray(a).dtype.type in (single, csingle): decimal = single_decimal else: decimal = double_decimal old_assert_almost_equal(a, b, decimal=decimal, **kw) def get_real_dtype(dtype): return {single: single, double: double, csingle: single, cdouble: double}[dtype] def get_complex_dtype(dtype): return {single: csingle, double: cdouble, csingle: csingle, cdouble: cdouble}[dtype] def get_rtol(dtype): # Choose a safe rtol if dtype in (single, csingle): return 1e-5 else: return 1e-11 # used to categorize tests all_tags = { 'square', 'nonsquare', 'hermitian', # mutually exclusive 'generalized', 'size-0', 'strided' # optional additions } class LinalgCase: def __init__(self, name, a, b, tags=set()): """ A bundle of arguments to be passed to a test case, with an identifying name, the operands a and b, and a set of tags to filter the tests """ assert_(isinstance(name, str)) self.name = name self.a = a self.b = b self.tags = frozenset(tags) # prevent shared tags def check(self, do): """ Run the function `do` on this test case, expanding arguments """ do(self.a, self.b, tags=self.tags) def __repr__(self): return f'<LinalgCase: {self.name}>' def apply_tag(tag, cases): """ Add the given tag (a string) to each of the cases (a list of LinalgCase objects) """ assert tag in all_tags, "Invalid tag" for case in cases: case.tags = case.tags | {tag} return cases # # Base test cases # np.random.seed(1234) CASES = [] # square test cases CASES += apply_tag('square', [ LinalgCase("single", array([[1., 2.], [3., 4.]], dtype=single), array([2., 1.], dtype=single)), LinalgCase("double", array([[1., 2.], [3., 4.]], dtype=double), array([2., 1.], dtype=double)), LinalgCase("double_2", array([[1., 2.], [3., 4.]], dtype=double), array([[2., 1., 4.], [3., 4., 6.]], dtype=double)), LinalgCase("csingle", array([[1. + 2j, 2 + 3j], [3 + 4j, 4 + 5j]], dtype=csingle), array([2. + 1j, 1. + 2j], dtype=csingle)), LinalgCase("cdouble", array([[1. + 2j, 2 + 3j], [3 + 4j, 4 + 5j]], dtype=cdouble), array([2. + 1j, 1. + 2j], dtype=cdouble)), LinalgCase("cdouble_2", array([[1. + 2j, 2 + 3j], [3 + 4j, 4 + 5j]], dtype=cdouble), array([[2. + 1j, 1. + 2j, 1 + 3j], [1 - 2j, 1 - 3j, 1 - 6j]], dtype=cdouble)), LinalgCase("0x0", np.empty((0, 0), dtype=double), np.empty((0,), dtype=double), tags={'size-0'}), LinalgCase("8x8", np.random.rand(8, 8), np.random.rand(8)), LinalgCase("1x1", np.random.rand(1, 1), np.random.rand(1)), LinalgCase("nonarray", [[1, 2], [3, 4]], [2, 1]), ]) # non-square test-cases CASES += apply_tag('nonsquare', [ LinalgCase("single_nsq_1", array([[1., 2., 3.], [3., 4., 6.]], dtype=single), array([2., 1.], dtype=single)), LinalgCase("single_nsq_2", array([[1., 2.], [3., 4.], [5., 6.]], dtype=single), array([2., 1., 3.], dtype=single)), LinalgCase("double_nsq_1", array([[1., 2., 3.], [3., 4., 6.]], dtype=double), array([2., 1.], dtype=double)), LinalgCase("double_nsq_2", array([[1., 2.], [3., 4.], [5., 6.]], dtype=double), array([2., 1., 3.], dtype=double)), LinalgCase("csingle_nsq_1", array( [[1. + 1j, 2. + 2j, 3. - 3j], [3. - 5j, 4. + 9j, 6. + 2j]], dtype=csingle), array([2. + 1j, 1. + 2j], dtype=csingle)), LinalgCase("csingle_nsq_2", array( [[1. + 1j, 2. + 2j], [3. - 3j, 4. - 9j], [5. - 4j, 6. + 8j]], dtype=csingle), array([2. + 1j, 1. + 2j, 3. - 3j], dtype=csingle)), LinalgCase("cdouble_nsq_1", array( [[1. + 1j, 2. + 2j, 3. - 3j], [3. - 5j, 4. + 9j, 6. + 2j]], dtype=cdouble), array([2. + 1j, 1. + 2j], dtype=cdouble)), LinalgCase("cdouble_nsq_2", array( [[1. + 1j, 2. + 2j], [3. - 3j, 4. - 9j], [5. - 4j, 6. + 8j]], dtype=cdouble), array([2. + 1j, 1. + 2j, 3. - 3j], dtype=cdouble)), LinalgCase("cdouble_nsq_1_2", array( [[1. + 1j, 2. + 2j, 3. - 3j], [3. - 5j, 4. + 9j, 6. + 2j]], dtype=cdouble), array([[2. + 1j, 1. + 2j], [1 - 1j, 2 - 2j]], dtype=cdouble)), LinalgCase("cdouble_nsq_2_2", array( [[1. + 1j, 2. + 2j], [3. - 3j, 4. - 9j], [5. - 4j, 6. + 8j]], dtype=cdouble), array([[2. + 1j, 1. + 2j], [1 - 1j, 2 - 2j], [1 - 1j, 2 - 2j]], dtype=cdouble)), LinalgCase("8x11", np.random.rand(8, 11), np.random.rand(8)), LinalgCase("1x5", np.random.rand(1, 5), np.random.rand(1)), LinalgCase("5x1", np.random.rand(5, 1), np.random.rand(5)), LinalgCase("0x4", np.random.rand(0, 4), np.random.rand(0), tags={'size-0'}), LinalgCase("4x0", np.random.rand(4, 0), np.random.rand(4), tags={'size-0'}), ]) # hermitian test-cases CASES += apply_tag('hermitian', [ LinalgCase("hsingle", array([[1., 2.], [2., 1.]], dtype=single), None), LinalgCase("hdouble", array([[1., 2.], [2., 1.]], dtype=double), None), LinalgCase("hcsingle", array([[1., 2 + 3j], [2 - 3j, 1]], dtype=csingle), None), LinalgCase("hcdouble", array([[1., 2 + 3j], [2 - 3j, 1]], dtype=cdouble), None), LinalgCase("hempty", np.empty((0, 0), dtype=double), None, tags={'size-0'}), LinalgCase("hnonarray", [[1, 2], [2, 1]], None), LinalgCase("matrix_b_only", array([[1., 2.], [2., 1.]]), None), LinalgCase("hmatrix_1x1", np.random.rand(1, 1), None), ]) # # Gufunc test cases # def _make_generalized_cases(): new_cases = [] for case in CASES: if not isinstance(case.a, np.ndarray): continue a = np.array([case.a, 2 * case.a, 3 * case.a]) if case.b is None: b = None else: b = np.array([case.b, 7 * case.b, 6 * case.b]) new_case = LinalgCase(case.name + "_tile3", a, b, tags=case.tags | {'generalized'}) new_cases.append(new_case) a = np.array([case.a] * 2 * 3).reshape((3, 2) + case.a.shape) if case.b is None: b = None else: b = np.array([case.b] * 2 * 3).reshape((3, 2) + case.b.shape) new_case = LinalgCase(case.name + "_tile213", a, b, tags=case.tags | {'generalized'}) new_cases.append(new_case) return new_cases CASES += _make_generalized_cases() # # Generate stride combination variations of the above # def _stride_comb_iter(x): """ Generate cartesian product of strides for all axes """ if not isinstance(x, np.ndarray): yield x, "nop" return stride_set = [(1,)] * x.ndim stride_set[-1] = (1, 3, -4) if x.ndim > 1: stride_set[-2] = (1, 3, -4) if x.ndim > 2: stride_set[-3] = (1, -4) for repeats in itertools.product(*tuple(stride_set)): new_shape = [abs(a * b) for a, b in zip(x.shape, repeats)] slices = tuple([slice(None, None, repeat) for repeat in repeats]) # new array with different strides, but same data xi = np.empty(new_shape, dtype=x.dtype) xi.view(np.uint32).fill(0xdeadbeef) xi = xi[slices] xi[...] = x xi = xi.view(x.__class__) assert_(np.all(xi == x)) yield xi, "stride_" + "_".join(["%+d" % j for j in repeats]) # generate also zero strides if possible if x.ndim >= 1 and x.shape[-1] == 1: s = list(x.strides) s[-1] = 0 xi = np.lib.stride_tricks.as_strided(x, strides=s) yield xi, "stride_xxx_0" if x.ndim >= 2 and x.shape[-2] == 1: s = list(x.strides) s[-2] = 0 xi = np.lib.stride_tricks.as_strided(x, strides=s) yield xi, "stride_xxx_0_x" if x.ndim >= 2 and x.shape[:-2] == (1, 1): s = list(x.strides) s[-1] = 0 s[-2] = 0 xi = np.lib.stride_tricks.as_strided(x, strides=s) yield xi, "stride_xxx_0_0" def _make_strided_cases(): new_cases = [] for case in CASES: for a, a_label in _stride_comb_iter(case.a): for b, b_label in _stride_comb_iter(case.b): new_case = LinalgCase(case.name + "_" + a_label + "_" + b_label, a, b, tags=case.tags | {'strided'}) new_cases.append(new_case) return new_cases CASES += _make_strided_cases() # # Test different routines against the above cases # class LinalgTestCase: TEST_CASES = CASES def check_cases(self, require=set(), exclude=set()): """ Run func on each of the cases with all of the tags in require, and none of the tags in exclude """ for case in self.TEST_CASES: # filter by require and exclude if case.tags & require != require: continue if case.tags & exclude: continue try: case.check(self.do) except Exception as e: msg = f'In test case: {case!r}\n\n' msg += traceback.format_exc() raise AssertionError(msg) from e class LinalgSquareTestCase(LinalgTestCase): def test_sq_cases(self): self.check_cases(require={'square'}, exclude={'generalized', 'size-0'}) def test_empty_sq_cases(self): self.check_cases(require={'square', 'size-0'}, exclude={'generalized'}) class LinalgNonsquareTestCase(LinalgTestCase): def test_nonsq_cases(self): self.check_cases(require={'nonsquare'}, exclude={'generalized', 'size-0'}) def test_empty_nonsq_cases(self): self.check_cases(require={'nonsquare', 'size-0'}, exclude={'generalized'}) class HermitianTestCase(LinalgTestCase): def test_herm_cases(self): self.check_cases(require={'hermitian'}, exclude={'generalized', 'size-0'}) def test_empty_herm_cases(self): self.check_cases(require={'hermitian', 'size-0'}, exclude={'generalized'}) class LinalgGeneralizedSquareTestCase(LinalgTestCase): @pytest.mark.slow def test_generalized_sq_cases(self): self.check_cases(require={'generalized', 'square'}, exclude={'size-0'}) @pytest.mark.slow def test_generalized_empty_sq_cases(self): self.check_cases(require={'generalized', 'square', 'size-0'}) class LinalgGeneralizedNonsquareTestCase(LinalgTestCase): @pytest.mark.slow def test_generalized_nonsq_cases(self): self.check_cases(require={'generalized', 'nonsquare'}, exclude={'size-0'}) @pytest.mark.slow def test_generalized_empty_nonsq_cases(self): self.check_cases(require={'generalized', 'nonsquare', 'size-0'}) class HermitianGeneralizedTestCase(LinalgTestCase): @pytest.mark.slow def test_generalized_herm_cases(self): self.check_cases(require={'generalized', 'hermitian'}, exclude={'size-0'}) @pytest.mark.slow def test_generalized_empty_herm_cases(self): self.check_cases(require={'generalized', 'hermitian', 'size-0'}, exclude={'none'}) def dot_generalized(a, b): a = asarray(a) if a.ndim >= 3: if a.ndim == b.ndim: # matrix x matrix new_shape = a.shape[:-1] + b.shape[-1:] elif a.ndim == b.ndim + 1: # matrix x vector new_shape = a.shape[:-1] else: raise ValueError("Not implemented...") r = np.empty(new_shape, dtype=np.common_type(a, b)) for c in itertools.product(*map(range, a.shape[:-2])): r[c] = dot(a[c], b[c]) return r else: return dot(a, b) def identity_like_generalized(a): a = asarray(a) if a.ndim >= 3: r = np.empty(a.shape, dtype=a.dtype) r[...] = identity(a.shape[-2]) return r else: return identity(a.shape[0]) class SolveCases(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase): # kept apart from TestSolve for use for testing with matrices. def do(self, a, b, tags): x = linalg.solve(a, b) assert_almost_equal(b, dot_generalized(a, x)) assert_(consistent_subclass(x, b)) class TestSolve(SolveCases): @pytest.mark.parametrize('dtype', [single, double, csingle, cdouble]) def test_types(self, dtype): x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype) assert_equal(linalg.solve(x, x).dtype, dtype) def test_0_size(self): class ArraySubclass(np.ndarray): pass # Test system of 0x0 matrices a = np.arange(8).reshape(2, 2, 2) b = np.arange(6).reshape(1, 2, 3).view(ArraySubclass) expected = linalg.solve(a, b)[:, 0:0, :] result = linalg.solve(a[:, 0:0, 0:0], b[:, 0:0, :]) assert_array_equal(result, expected) assert_(isinstance(result, ArraySubclass)) # Test errors for non-square and only b's dimension being 0 assert_raises(linalg.LinAlgError, linalg.solve, a[:, 0:0, 0:1], b) assert_raises(ValueError, linalg.solve, a, b[:, 0:0, :]) # Test broadcasting error b = np.arange(6).reshape(1, 3, 2) # broadcasting error assert_raises(ValueError, linalg.solve, a, b) assert_raises(ValueError, linalg.solve, a[0:0], b[0:0]) # Test zero "single equations" with 0x0 matrices. b = np.arange(2).reshape(1, 2).view(ArraySubclass) expected = linalg.solve(a, b)[:, 0:0] result = linalg.solve(a[:, 0:0, 0:0], b[:, 0:0]) assert_array_equal(result, expected) assert_(isinstance(result, ArraySubclass)) b = np.arange(3).reshape(1, 3) assert_raises(ValueError, linalg.solve, a, b) assert_raises(ValueError, linalg.solve, a[0:0], b[0:0]) assert_raises(ValueError, linalg.solve, a[:, 0:0, 0:0], b) def test_0_size_k(self): # test zero multiple equation (K=0) case. class ArraySubclass(np.ndarray): pass a = np.arange(4).reshape(1, 2, 2) b = np.arange(6).reshape(3, 2, 1).view(ArraySubclass) expected = linalg.solve(a, b)[:, :, 0:0] result = linalg.solve(a, b[:, :, 0:0]) assert_array_equal(result, expected) assert_(isinstance(result, ArraySubclass)) # test both zero. expected = linalg.solve(a, b)[:, 0:0, 0:0] result = linalg.solve(a[:, 0:0, 0:0], b[:, 0:0, 0:0]) assert_array_equal(result, expected) assert_(isinstance(result, ArraySubclass)) class InvCases(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase): def do(self, a, b, tags): a_inv = linalg.inv(a) assert_almost_equal(dot_generalized(a, a_inv), identity_like_generalized(a)) assert_(consistent_subclass(a_inv, a)) class TestInv(InvCases): @pytest.mark.parametrize('dtype', [single, double, csingle, cdouble]) def test_types(self, dtype): x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype) assert_equal(linalg.inv(x).dtype, dtype) def test_0_size(self): # Check that all kinds of 0-sized arrays work class ArraySubclass(np.ndarray): pass a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass) res = linalg.inv(a) assert_(res.dtype.type is np.float64) assert_equal(a.shape, res.shape) assert_(isinstance(res, ArraySubclass)) a = np.zeros((0, 0), dtype=np.complex64).view(ArraySubclass) res = linalg.inv(a) assert_(res.dtype.type is np.complex64) assert_equal(a.shape, res.shape) assert_(isinstance(res, ArraySubclass)) class EigvalsCases(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase): def do(self, a, b, tags): ev = linalg.eigvals(a) evalues, evectors = linalg.eig(a) assert_almost_equal(ev, evalues) class TestEigvals(EigvalsCases): @pytest.mark.parametrize('dtype', [single, double, csingle, cdouble]) def test_types(self, dtype): x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype) assert_equal(linalg.eigvals(x).dtype, dtype) x = np.array([[1, 0.5], [-1, 1]], dtype=dtype) assert_equal(linalg.eigvals(x).dtype, get_complex_dtype(dtype)) def test_0_size(self): # Check that all kinds of 0-sized arrays work class ArraySubclass(np.ndarray): pass a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass) res = linalg.eigvals(a) assert_(res.dtype.type is np.float64) assert_equal((0, 1), res.shape) # This is just for documentation, it might make sense to change: assert_(isinstance(res, np.ndarray)) a = np.zeros((0, 0), dtype=np.complex64).view(ArraySubclass) res = linalg.eigvals(a) assert_(res.dtype.type is np.complex64) assert_equal((0,), res.shape) # This is just for documentation, it might make sense to change: assert_(isinstance(res, np.ndarray)) class EigCases(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase): def do(self, a, b, tags): evalues, evectors = linalg.eig(a) assert_allclose(dot_generalized(a, evectors), np.asarray(evectors) * np.asarray(evalues)[..., None, :], rtol=get_rtol(evalues.dtype)) assert_(consistent_subclass(evectors, a)) class TestEig(EigCases): @pytest.mark.parametrize('dtype', [single, double, csingle, cdouble]) def test_types(self, dtype): x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype) w, v = np.linalg.eig(x) assert_equal(w.dtype, dtype) assert_equal(v.dtype, dtype) x = np.array([[1, 0.5], [-1, 1]], dtype=dtype) w, v = np.linalg.eig(x) assert_equal(w.dtype, get_complex_dtype(dtype)) assert_equal(v.dtype, get_complex_dtype(dtype)) def test_0_size(self): # Check that all kinds of 0-sized arrays work class ArraySubclass(np.ndarray): pass a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass) res, res_v = linalg.eig(a) assert_(res_v.dtype.type is np.float64)
assert_(res.dtype.type is np.float64)
numpy.testing.assert_
# deafrica_classificationtools.py ''' Description: This file contains a set of python functions for conducting machine learning classification on remote sensing data from Digital Earth Africa's Open Data Cube License: The code in this notebook is licensed under the Apache License, Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0). Digital Earth Africa data is licensed under the Creative Commons by Attribution 4.0 license (https://creativecommons.org/licenses/by/4.0/). Contact: If you need assistance, please post a question on the Open Data Cube Slack channel (http://slack.opendatacube.org/) or on the GIS Stack Exchange (https://gis.stackexchange.com/questions/ask?tags=open-data-cube) using the `open-data-cube` tag (you can view previously asked questions here: https://gis.stackexchange.com/questions/tagged/open-data-cube). If you would like to report an issue with this script, you can file one on Github https://github.com/digitalearthafrica/deafrica-sandbox-notebooks/issues Last modified: September 2020 ''' import os import sys import joblib import datacube import rasterio import numpy as np import xarray as xr from tqdm import tqdm import dask.array as da import geopandas as gpd from copy import deepcopy import multiprocessing as mp import dask.distributed as dd import matplotlib.pyplot as plt from matplotlib.patches import Patch from sklearn.cluster import KMeans from sklearn.base import clone from datacube.utils import masking from sklearn.base import BaseEstimator from sklearn.utils import check_random_state from abc import ABCMeta, abstractmethod from datacube.utils import geometry from sklearn.base import ClusterMixin from dask.diagnostics import ProgressBar from rasterio.features import rasterize from sklearn.impute import SimpleImputer from rasterio.features import geometry_mask from dask_ml.wrappers import ParallelPostFit from sklearn.mixture import GaussianMixture from datacube.utils.geometry import assign_crs from datacube_stats.statistics import GeoMedian from sklearn.cluster import AgglomerativeClustering from sklearn.model_selection import KFold, ShuffleSplit from sklearn.model_selection import BaseCrossValidator import warnings from dea_tools.spatial import xr_rasterize from dea_tools.bandindices import calculate_indices from dea_tools.datahandling import load_ard, mostcommon_crs def sklearn_flatten(input_xr): """ Reshape a DataArray or Dataset with spatial (and optionally temporal) structure into an np.array with the spatial and temporal dimensions flattened into one dimension. This flattening procedure enables DataArrays and Datasets to be used to train and predict with sklearn models. Last modified: September 2019 Parameters ---------- input_xr : xarray.DataArray or xarray.Dataset Must have dimensions 'x' and 'y', may have dimension 'time'. Dimensions other than 'x', 'y' and 'time' are unaffected by the flattening. Returns ---------- input_np : numpy.array A numpy array corresponding to input_xr.data (or input_xr.to_array().data), with dimensions 'x','y' and 'time' flattened into a single dimension, which is the first axis of the returned array. input_np contains no NaNs. """ # cast input Datasets to DataArray if isinstance(input_xr, xr.Dataset): input_xr = input_xr.to_array() # stack across pixel dimensions, handling timeseries if necessary if 'time' in input_xr.dims: stacked = input_xr.stack(z=['x', 'y', 'time']) else: stacked = input_xr.stack(z=['x', 'y']) # finding 'bands' dimensions in each pixel - these will not be # flattened as their context is important for sklearn pxdims = [] for dim in stacked.dims: if dim != 'z': pxdims.append(dim) # mask NaNs - we mask pixels with NaNs in *any* band, because # sklearn cannot accept NaNs as input mask = np.isnan(stacked) if len(pxdims) != 0: mask = mask.any(dim=pxdims) # turn the mask into a numpy array (boolean indexing with xarrays # acts weird) mask = mask.data # the dimension we are masking along ('z') needs to be the first # dimension in the underlying np array for the boolean indexing to work stacked = stacked.transpose('z', *pxdims) input_np = stacked.data[~mask] return input_np def sklearn_unflatten(output_np, input_xr): """ Reshape a numpy array with no 'missing' elements (NaNs) and 'flattened' spatiotemporal structure into a DataArray matching the spatiotemporal structure of the DataArray This enables an sklearn model's prediction to be remapped to the correct pixels in the input DataArray or Dataset. Last modified: September 2019 Parameters ---------- output_np : numpy.array The first dimension's length should correspond to the number of valid (non-NaN) pixels in input_xr. input_xr : xarray.DataArray or xarray.Dataset Must have dimensions 'x' and 'y', may have dimension 'time'. Dimensions other than 'x', 'y' and 'time' are unaffected by the flattening. Returns ---------- output_xr : xarray.DataArray An xarray.DataArray with the same dimensions 'x', 'y' and 'time' as input_xr, and the same valid (non-NaN) pixels. These pixels are set to match the data in output_np. """ # the output of a sklearn model prediction should just be a numpy array # with size matching x*y*time for the input DataArray/Dataset. # cast input Datasets to DataArray if isinstance(input_xr, xr.Dataset): input_xr = input_xr.to_array() # generate the same mask we used to create the input to the sklearn model if 'time' in input_xr.dims: stacked = input_xr.stack(z=['x', 'y', 'time']) else: stacked = input_xr.stack(z=['x', 'y']) pxdims = [] for dim in stacked.dims: if dim != 'z': pxdims.append(dim) mask = np.isnan(stacked) if len(pxdims) != 0: mask = mask.any(dim=pxdims) # handle multivariable output output_px_shape = () if len(output_np.shape[1:]): output_px_shape = output_np.shape[1:] # use the mask to put the data in all the right places output_ma = np.ma.empty((len(stacked.z), *output_px_shape)) output_ma[~mask] = output_np output_ma[mask] = np.ma.masked # set the stacked coordinate to match the input output_xr = xr.DataArray( output_ma, coords={'z': stacked['z']}, dims=[ 'z', *['output_dim_' + str(idx) for idx in range(len(output_px_shape))] ]) output_xr = output_xr.unstack() return output_xr def fit_xr(model, input_xr): """ Utilise our wrappers to fit a vanilla sklearn model. Last modified: September 2019 Parameters ---------- model : scikit-learn model or compatible object Must have a fit() method that takes numpy arrays. input_xr : xarray.DataArray or xarray.Dataset. Must have dimensions 'x' and 'y', may have dimension 'time'. Returns ---------- model : a scikit-learn model which has been fitted to the data in the pixels of input_xr. """ model = model.fit(sklearn_flatten(input_xr)) return model def predict_xr(model, input_xr, chunk_size=None, persist=False, proba=False, clean=False, return_input=False): """ Using dask-ml ParallelPostfit(), runs the parallel predict and predict_proba methods of sklearn estimators. Useful for running predictions on a larger-than-RAM datasets. Last modified: September 2020 Parameters ---------- model : scikit-learn model or compatible object Must have a .predict() method that takes numpy arrays. input_xr : xarray.DataArray or xarray.Dataset. Must have dimensions 'x' and 'y' chunk_size : int The dask chunk size to use on the flattened array. If this is left as None, then the chunks size is inferred from the .chunks method on the `input_xr` persist : bool If True, and proba=True, then 'input_xr' data will be loaded into distributed memory. This will ensure data is not loaded twice for the prediction of probabilities, but this will only work if the data is not larger than distributed RAM. proba : bool If True, predict probabilities clean : bool If True, remove Infs and NaNs from input and output arrays return_input : bool If True, then the data variables in the 'input_xr' dataset will be appended to the output xarray dataset. Returns ---------- output_xr : xarray.Dataset An xarray.Dataset containing the prediction output from model. if proba=True then dataset will also contain probabilites, and if return_input=True then dataset will have the input feature layers. Has the same spatiotemporal structure as input_xr. """ # if input_xr isn't dask, coerce it dask = True if not bool(input_xr.chunks): dask = False input_xr = input_xr.chunk({'x': len(input_xr.x), 'y': len(input_xr.y)}) #set chunk size if not supplied if chunk_size is None: chunk_size = int(input_xr.chunks['x'][0]) * \ int(input_xr.chunks['y'][0]) def _predict_func(model, input_xr, persist, proba, clean, return_input): x, y, crs = input_xr.x, input_xr.y, input_xr.geobox.crs input_data = [] for var_name in input_xr.data_vars: input_data.append(input_xr[var_name]) input_data_flattened = [] for arr in input_data: data = arr.data.flatten().rechunk(chunk_size) input_data_flattened.append(data) # reshape for prediction input_data_flattened = da.array(input_data_flattened).transpose() if clean == True: input_data_flattened = da.where(da.isfinite(input_data_flattened), input_data_flattened, 0) if (proba == True) & (persist == True): # persisting data so we don't require loading all the data twice input_data_flattened = input_data_flattened.persist() # apply the classification print('predicting...') out_class = model.predict(input_data_flattened) # Mask out NaN or Inf values in results if clean == True: out_class = da.where(da.isfinite(out_class), out_class, 0) # Reshape when writing out out_class = out_class.reshape(len(y), len(x)) # stack back into xarray output_xr = xr.DataArray(out_class, coords={ "x": x, "y": y }, dims=["y", "x"]) output_xr = output_xr.to_dataset(name='Predictions') if proba == True: print(" probabilities...") out_proba = model.predict_proba(input_data_flattened) # convert to % out_proba = da.max(out_proba, axis=1) * 100.0 if clean == True: out_proba = da.where(da.isfinite(out_proba), out_proba, 0) out_proba = out_proba.reshape(len(y), len(x)) out_proba = xr.DataArray(out_proba, coords={ "x": x, "y": y }, dims=["y", "x"]) output_xr['Probabilities'] = out_proba if return_input == True: print(" input features...") # unflatten the input_data_flattened array and append # to the output_xr containin the predictions arr = input_xr.to_array() stacked = arr.stack(z=['y', 'x']) # handle multivariable output output_px_shape = () if len(input_data_flattened.shape[1:]): output_px_shape = input_data_flattened.shape[1:] output_features = input_data_flattened.reshape( (len(stacked.z), *output_px_shape)) # set the stacked coordinate to match the input output_features = xr.DataArray( output_features, coords={ 'z': stacked['z'] }, dims=[ 'z', *[ 'output_dim_' + str(idx) for idx in range(len(output_px_shape)) ] ]).unstack() # convert to dataset and rename arrays output_features = output_features.to_dataset(dim='output_dim_0') data_vars = list(input_xr.data_vars) output_features = output_features.rename( {i: j for i, j in zip(output_features.data_vars, data_vars)}) # merge with predictions output_xr = xr.merge([output_xr, output_features], compat='override') return assign_crs(output_xr, str(crs)) if dask == True: # convert model to dask predict model = ParallelPostFit(model) with joblib.parallel_backend('dask'): output_xr = _predict_func(model, input_xr, persist, proba, clean, return_input) else: output_xr = _predict_func(model, input_xr, persist, proba, clean, return_input).compute() return output_xr class HiddenPrints: """ For concealing unwanted print statements called by other functions """ def __enter__(self): self._original_stdout = sys.stdout sys.stdout = open(os.devnull, 'w') def __exit__(self, exc_type, exc_val, exc_tb): sys.stdout.close() sys.stdout = self._original_stdout def _get_training_data_for_shp(gdf, index, row, out_arrs, out_vars, products, dc_query, return_coords, custom_func=None, field=None, calc_indices=None, reduce_func=None, drop=True, zonal_stats=None): """ This is the core function that is triggered by `collect_training_data`. The `collect_training_data` function loops through geometries in a geopandas geodataframe and runs the code within `_get_training_data_for_shp`. Parameters are inherited from `collect_training_data`. See that function for information on the other params not listed below. Parameters ---------- index, row : iterables inherited from geopandas object out_arrs : list An empty list into which the training data arrays are stored. out_vars : list An empty list into which the data varaible names are stored. Returns -------- Two lists, a list of numpy.arrays containing classes and extracted data for each pixel or polygon, and another containing the data variable names. """ # prevent function altering dictionary kwargs dc_query = deepcopy(dc_query) # remove dask chunks if supplied as using # mulitprocessing for parallization if 'dask_chunks' in dc_query.keys(): dc_query.pop('dask_chunks', None) # connect to datacube dc = datacube.Datacube(app='training_data') # set up query based on polygon geom = geometry.Geometry(geom=gdf.iloc[index].geometry, crs=gdf.crs) q = {"geopolygon": geom} # merge polygon query with user supplied query params dc_query.update(q) # load_ard doesn't handle derivative products, so check # products aren't one of those below others = [ 'ls5_nbart_geomedian_annual', 'ls7_nbart_geomedian_annual', 'ls8_nbart_geomedian_annual', 'ls5_nbart_tmad_annual', 'ls7_nbart_tmad_annual', 'ls8_nbart_tmad_annual', 'landsat_barest_earth', 'ls8_barest_earth_albers' ] if products[0] in others: ds = dc.load(product=products[0], **dc_query) ds = ds.where(ds != 0, np.nan) else: # load data with HiddenPrints(): ds = load_ard(dc=dc, products=products, **dc_query) # create polygon mask with HiddenPrints(): mask = xr_rasterize(gdf.iloc[[index]], ds) # Use custom function for training data if it exists if custom_func is not None: with HiddenPrints(): data = custom_func(ds) data = data.where(mask) else: # mask dataset ds = ds.where(mask) # first check enough variables are set to run functions if (len(ds.time.values) > 1) and (reduce_func == None): raise ValueError( "You're dataset has " + str(len(ds.time.values)) + " time-steps, please provide a time reduction function," + " e.g. reduce_func='mean'") if calc_indices is not None: # determine which collection is being loaded if products[0] in others: collection = 'ga_ls_2' elif '3' in products[0]: collection = 'ga_ls_3' elif 's2' in products[0]: collection = 'ga_s2_1' if len(ds.time.values) > 1: if reduce_func in ['mean', 'median', 'std', 'max', 'min']: with HiddenPrints(): data = calculate_indices(ds, index=calc_indices, drop=drop, collection=collection) # getattr is equivalent to calling data.reduce_func method_to_call = getattr(data, reduce_func) data = method_to_call(dim='time') elif reduce_func == 'geomedian': data = GeoMedian().compute(ds) with HiddenPrints(): data = calculate_indices(data, index=calc_indices, drop=drop, collection=collection) else: raise Exception( reduce_func + " is not one of the supported" + " reduce functions ('mean','median','std','max','min', 'geomedian')" ) else: with HiddenPrints(): data = calculate_indices(ds, index=calc_indices, drop=drop, collection=collection) # when band indices are not required, reduce the # dataset to a 2d array through means or (geo)medians if calc_indices is None: if len(ds.time.values) > 1: if reduce_func == 'geomedian': data = GeoMedian().compute(ds) elif reduce_func in ['mean', 'median', 'std', 'max', 'min']: method_to_call = getattr(ds, reduce_func) data = method_to_call('time') else: data = ds.squeeze() if return_coords == True: # turn coords into a variable in the ds data['x_coord'] = ds.x + 0 * ds.y data['y_coord'] = ds.y + 0 * ds.x if zonal_stats is None: # If no zonal stats were requested then extract all pixel values flat_train = sklearn_flatten(data) flat_val = np.repeat(row[field], flat_train.shape[0]) stacked = np.hstack((np.expand_dims(flat_val, axis=1), flat_train)) elif zonal_stats in ['mean', 'median', 'std', 'max', 'min']: method_to_call = getattr(data, zonal_stats) flat_train = method_to_call() flat_train = flat_train.to_array() stacked = np.hstack((row[field], flat_train)) else: raise Exception(zonal_stats + " is not one of the supported" + " reduce functions ('mean','median','std','max','min')") #return unique-id so we can index if load failed silently _id = gdf.iloc[index]['id'] # Append training data and labels to list out_arrs.append(np.append(stacked, _id)) out_vars.append([field] + list(data.data_vars) + ['id']) def _get_training_data_parallel(gdf, products, dc_query, ncpus, return_coords, custom_func=None, field=None, calc_indices=None, reduce_func=None, drop=True, zonal_stats=None): """ Function passing the '_get_training_data_for_shp' function to a mulitprocessing.Pool. Inherits variables from 'collect_training_data()'. """ # Check if dask-client is running try: zx = None zx = dd.get_client() except: pass if zx is not None: raise ValueError( "You have a Dask Client running, which prevents \n" "this function from multiprocessing. Close the client.") # instantiate lists that can be shared across processes manager = mp.Manager() results = manager.list() column_names = manager.list() # progress bar pbar = tqdm(total=len(gdf)) def update(*a): pbar.update() with mp.Pool(ncpus) as pool: for index, row in gdf.iterrows(): pool.apply_async(_get_training_data_for_shp, [ gdf, index, row, results, column_names, products, dc_query, return_coords, custom_func, field, calc_indices, reduce_func, drop, zonal_stats ], callback=update) pool.close() pool.join() pbar.close() return column_names, results def collect_training_data(gdf, products, dc_query, ncpus=1, return_coords=False, custom_func=None, field=None, calc_indices=None, reduce_func=None, drop=True, zonal_stats=None, clean=True, fail_threshold=0.02, max_retries=3): """ This function executes the training data functions and tidies the results into a 'model_input' object containing stacked training data arrays with all NaNs & Infs removed. In the instance where ncpus > 1, a parallel version of the function will be run (functions are passed to a mp.Pool()) This function provides a number of pre-defined feature layer methods, including calculating band indices, reducing time series using several summary statistics, and/or generating zonal statistics across polygons. The 'custom_func' parameter provides a method for the user to supply a custom function for generating features rather than using the pre-defined methods. Parameters ---------- gdf : geopandas geodataframe geometry data in the form of a geopandas geodataframe products : list a list of products to load from the datacube. e.g. ['ls8_usgs_sr_scene', 'ls7_usgs_sr_scene'] dc_query : dictionary Datacube query object, should not contain lat and long (x or y) variables as these are supplied by the 'gdf' variable ncpus : int The number of cpus/processes over which to parallelize the gathering of training data (only if ncpus is > 1). Use 'mp.cpu_count()' to determine the number of cpus available on a machine. Defaults to 1. return_coords : bool If True, then the training data will contain two extra columns 'x_coord' and 'y_coord' corresponding to the x,y coordinate of each sample. This variable can be useful for handling spatial autocorrelation between samples later in the ML workflow. custom_func : function, optional A custom function for generating feature layers. If this parameter is set, all other options (excluding 'zonal_stats'), will be ignored. The result of the 'custom_func' must be a single xarray dataset containing 2D coordinates (i.e x, y - no time dimension). The custom function has access to the datacube dataset extracted using the 'dc_query' params. To load other datasets, you can use the 'like=ds.geobox' parameter in dc.load field : str Name of the column in the gdf that contains the class labels calc_indices: list, optional If not using a custom func, then this parameter provides a method for calculating a number of remote sensing indices (e.g. `['NDWI', 'NDVI']`). reduce_func : string, optional Function to reduce the data from multiple time steps to a single timestep. Options are 'mean', 'median', 'std', 'max', 'min', 'geomedian'. Ignored if 'custom_func' is provided. drop : boolean, optional , If this variable is set to True, and 'calc_indices' are supplied, the spectral bands will be dropped from the dataset leaving only the band indices as data variables in the dataset. Default is True. zonal_stats : string, optional An optional string giving the names of zonal statistics to calculate for each polygon. Default is None (all pixel values are returned). Supported values are 'mean', 'median', 'max', 'min', and 'std'. Will work in conjuction with a 'custom_func'. clean : bool Whether or not to remove missing values in the training dataset. If True, training labels with any NaNs or Infs in the feature layers will be dropped from the dataset. fail_threshold : float, default 0.05 Silent read fails on S3 during multiprocessing can result in some rows of the returned data containing all NaN values. Set the 'fail_threshold' fraction to specify a minimum number of acceptable fails e.g. setting 'fail_threshold' to 0.05 means 5 % no-data in the returned dataset is acceptable. Above this fraction the function will attempt to recollect the samples that have failed. A sample is defined as having failed if it returns > 50 % NaN values. max_retries: int, default 3 Number of times to retry collecting a sample. This number is invoked if the 'fail_threshold' is not reached. Returns -------- Two lists, a list of numpy.arrays containing classes and extracted data for each pixel or polygon, and another containing the data variable names. """ # check the dtype of the class field if (gdf[field].dtype != np.int): raise ValueError( 'The "field" column of the input vector must contain integer dtypes' ) # set up some print statements if custom_func is not None: print("Reducing data using user supplied custom function") if calc_indices is not None and custom_func is None: print("Calculating indices: " + str(calc_indices)) if reduce_func is not None and custom_func is None: print("Reducing data using: " + reduce_func) if zonal_stats is not None: print("Taking zonal statistic: " + zonal_stats) #add unique id to gdf to help later with indexing failed rows #during muliprocessing gdf['id'] = range(0, len(gdf)) if ncpus == 1: # progress indicator print('Collecting training data in serial mode') i = 0 # list to store results results = [] column_names = [] # loop through polys and extract training data for index, row in gdf.iterrows(): print(" Feature {:04}/{:04}\r".format(i + 1, len(gdf)), end='') _get_training_data_for_shp(gdf, index, row, results, column_names, products, dc_query, return_coords, custom_func, field, calc_indices, reduce_func, drop, zonal_stats) i += 1 else: print('Collecting training data in parallel mode') column_names, results = _get_training_data_parallel( gdf=gdf, products=products, dc_query=dc_query, ncpus=ncpus, return_coords=return_coords, custom_func=custom_func, field=field, calc_indices=calc_indices, reduce_func=reduce_func, drop=drop, zonal_stats=zonal_stats) # column names are appeneded during each iteration # but they are identical, grab only the first instance column_names = column_names[0] # Stack the extracted training data for each feature into a single array model_input = np.vstack(results) # this code block iteratively retries failed rows # up to max_retries or until fail_threshold is # reached - whichever occurs first if ncpus > 1: i = 1 while (i <= max_retries): # Count number of fails num = np.count_nonzero(np.isnan(model_input), axis=1) > int( model_input.shape[1] * 0.5) num = num.sum() fail_rate = num / len(gdf) print('Percentage of possible fails after run ' + str(i) + ' = ' + str(round(fail_rate * 100, 2)) + ' %') if fail_rate > fail_threshold: print('Recollecting samples that failed') #find rows where NaNs account for more than half the values nans = model_input[np.count_nonzero( np.isnan(model_input), axis=1) > int(model_input.shape[1] * 0.5)] #remove nan rows from model_input object model_input = model_input[np.count_nonzero( np.isnan(model_input), axis=1) <= int(model_input.shape[1] * 0.5)] #get id of NaN rows and index original gdf idx_nans = nans[:, [-1]].flatten() gdf_rerun = gdf.loc[gdf['id'].isin(idx_nans)] gdf_rerun = gdf_rerun.reset_index(drop=True) time.sleep(60) #sleep for 60 sec to rest api column_names_again, results_again = _get_training_data_parallel( gdf=gdf_rerun, products=products, dc_query=dc_query, ncpus=ncpus, return_coords=return_coords, custom_func=custom_func, field=field, calc_indices=calc_indices, reduce_func=reduce_func, drop=drop, zonal_stats=zonal_stats) # Stack the extracted training data for each feature into a single array model_input_again = np.vstack(results_again) #merge results of the re-run with original run model_input = np.vstack((model_input, model_input_again)) i += 1 else: break if clean == True: num = np.count_nonzero(np.isnan(model_input).any(axis=1)) model_input = model_input[~np.isnan(model_input).any(axis=1)] model_input = model_input[~np.isinf(model_input).any(axis=1)] print("Removed " + str(num) + " rows wth NaNs &/or Infs") print('Output shape: ', model_input.shape) else: print('Returning data without cleaning') print('Output shape: ', model_input.shape) # remove id column idx_var = column_names[0:-1] model_col_indices = [column_names.index(var_name) for var_name in idx_var] model_input = model_input[:, model_col_indices] return column_names[0:-1], model_input class KMeans_tree(ClusterMixin): """ A hierarchical KMeans unsupervised clustering model. This class is a clustering model, so it inherits scikit-learn's ClusterMixin base class. Parameters ---------- n_levels : integer, default 2 number of levels in the tree of clustering models. n_clusters : integer, default 3 Number of clusters in each of the constituent KMeans models in the tree. **kwargs : optional Other keyword arguments to be passed directly to the KMeans initialiser. """ def __init__(self, n_levels=2, n_clusters=3, **kwargs): assert (n_levels >= 1) self.base_model = KMeans(n_clusters=3, **kwargs) self.n_levels = n_levels self.n_clusters = n_clusters # make child models if n_levels > 1: self.branches = [ KMeans_tree(n_levels=n_levels - 1, n_clusters=n_clusters, **kwargs) for _ in range(n_clusters) ] def fit(self, X, y=None, sample_weight=None): """ Fit the tree of KMeans models. All parameters mimic those of KMeans.fit(). Parameters ---------- X : array-like or sparse matrix, shape=(n_samples, n_features) Training instances to cluster. It must be noted that the data will be converted to C ordering, which will cause a memory copy if the given data is not C-contiguous. y : Ignored not used, present here for API consistency by convention. sample_weight : array-like, shape (n_samples,), optional The weights for each observation in X. If None, all observations are assigned equal weight (default: None) """ self.labels_ = self.base_model.fit(X, sample_weight=sample_weight).labels_ if self.n_levels > 1: labels_old = np.copy(self.labels_) # make room to add the sub-cluster labels self.labels_ *= (self.n_clusters)**(self.n_levels - 1) for clu in range(self.n_clusters): # fit child models on their corresponding partition of the training set self.branches[clu].fit( X[labels_old == clu], sample_weight=(sample_weight[labels_old == clu] if sample_weight is not None else None)) self.labels_[labels_old == clu] += self.branches[clu].labels_ return self def predict(self, X, sample_weight=None): """ Send X through the KMeans tree and predict the resultant cluster. Compatible with KMeans.predict(). Parameters ---------- X : {array-like, sparse matrix}, shape = [n_samples, n_features] New data to predict. sample_weight : array-like, shape (n_samples,), optional The weights for each observation in X. If None, all observations are assigned equal weight (default: None) Returns ------- labels : array, shape [n_samples,] Index of the cluster each sample belongs to. """ result = self.base_model.predict(X, sample_weight=sample_weight) if self.n_levels > 1: rescpy = np.copy(result) # make room to add the sub-cluster labels result *= (self.n_clusters)**(self.n_levels - 1) for clu in range(self.n_clusters): result[rescpy == clu] += self.branches[clu].predict( X[rescpy == clu], sample_weight=(sample_weight[rescpy == clu] if sample_weight is not None else None)) return result def spatial_clusters(coordinates, method='Hierarchical', max_distance=None, n_groups=None, verbose=False, **kwargs): """ Create spatial groups on coorindate data using either KMeans clustering or a Gaussian Mixture model Last modified: September 2020 Parameters ---------- n_groups : int The number of groups to create. This is passed as 'n_clusters=n_groups' for the KMeans algo, and 'n_components=n_groups' for the GMM. If using method='Hierarchical' then this paramter is ignored. coordinates : np.array A numpy array of coordinate values e.g. np.array([[3337270., 262400.], [3441390., -273060.], ...]) method : str Which algorithm to use to seperate data points. Either 'KMeans', 'GMM', or 'Hierarchical'. If using 'Hierarchical' then must set max_distance. max_distance : int If method is set to 'hierarchical' then maximum distance describes the maximum euclidean distances between all observations in a cluster. 'n_groups' is ignored in this case. **kwargs : optional, Additional keyword arguments to pass to sklearn.cluster.Kmeans or sklearn.mixture.GuassianMixture depending on the 'method' argument. Returns ------- labels : array, shape [n_samples,] Index of the cluster each sample belongs to. """ if method not in ['Hierarchical', 'KMeans', 'GMM']: raise ValueError( "method must be one of: 'Hierarchical','KMeans' or 'GMM'") if (method in ['GMM', 'KMeans']) & (n_groups is None): raise ValueError( "The 'GMM' and 'KMeans' methods requires explicitly setting 'n_groups'" ) if (method == 'Hierarchical') & (max_distance is None): raise ValueError( "The 'Hierarchical' method requires setting max_distance") if method == 'Hierarchical': cluster_label = AgglomerativeClustering( n_clusters=None, linkage='complete', distance_threshold=max_distance, **kwargs).fit_predict(coordinates) if method == 'KMeans': cluster_label = KMeans(n_clusters=n_groups, **kwargs).fit_predict(coordinates) if method == 'GMM': cluster_label = GaussianMixture(n_components=n_groups, **kwargs).fit_predict(coordinates) if verbose: print("n clusters = " + str(len(np.unique(cluster_label)))) return cluster_label def SKCV(coordinates, n_splits, cluster_method, kfold_method, test_size, balance, n_groups=None, max_distance=None, train_size=None, random_state=None, **kwargs): """ Generate spatial k-fold cross validation indices using coordinate data. This function wraps the 'SpatialShuffleSplit' and 'SpatialKFold' classes. These classes ingest coordinate data in the form of an np.array([[Eastings, northings]]) and assign samples to a spatial cluster using either a KMeans, Gaussain Mixture, or Agglomerative Clustering algorithm. This cross-validator is preferred over other sklearn.model_selection methods for spatial data to avoid overestimating cross-validation scores. This can happen because of the inherent spatial autocorrelation that is usually associated with this type of data. Last modified: Dec 2020 Parameters ---------- coordinates : np.array A numpy array of coordinate values e.g. np.array([[3337270., 262400.], [3441390., -273060.], ...]) n_splits : int The number of test-train cross validation splits to generate. cluster_method : str Which algorithm to use to seperate data points. Either 'KMeans', 'GMM', or 'Hierarchical' kfold_method : str One of either 'SpatialShuffleSplit' or 'SpatialKFold'. See the docs under class:_SpatialShuffleSplit and class: _SpatialKFold for more information on these options. test_size : float, int, None If float, should be between 0.0 and 1.0 and represent the proportion of the dataset to include in the test split. If int, represents the absolute number of test samples. If None, the value is set to the complement of the train size. If ``train_size`` is also None, it will be set to 0.15. balance : int or bool if setting kfold_method to 'SpatialShuffleSplit': int The number of splits generated per iteration to try to balance the amount of data in each set so that *test_size* and *train_size* are respected. If 1, then no extra splits are generated (essentially disabling the balacing). Must be >= 1. if setting kfold_method to 'SpatialKFold': bool Whether or not to split clusters into fold with approximately equal number of data points. If False, each fold will have the same number of clusters (which can have different number of data points in them). n_groups : int The number of groups to create. This is passed as 'n_clusters=n_groups' for the KMeans algo, and 'n_components=n_groups' for the GMM. If using cluster_method='Hierarchical' then this parameter is ignored. max_distance : int If method is set to 'hierarchical' then maximum distance describes the maximum euclidean distances between all observations in a cluster. 'n_groups' is ignored in this case. train_size : float, int, or None If float, should be between 0.0 and 1.0 and represent the proportion of the dataset to include in the train split. If int, represents the absolute number of train samples. If None, the value is automatically set to the complement of the test size. random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. **kwargs : optional, Additional keyword arguments to pass to sklearn.cluster.Kmeans or sklearn.mixture.GuassianMixture depending on the cluster_method argument. Returns -------- generator object _BaseSpatialCrossValidator.split """ # intiate a method if kfold_method == 'SpatialShuffleSplit': splitter = _SpatialShuffleSplit(n_groups=n_groups, method=cluster_method, coordinates=coordinates, max_distance=max_distance, test_size=test_size, train_size=train_size, n_splits=n_splits, random_state=random_state, balance=balance, **kwargs) if kfold_method == 'SpatialKFold': splitter = _SpatialKFold(n_groups=n_groups, coordinates=coordinates, max_distance=max_distance, method=cluster_method, test_size=test_size, n_splits=n_splits, random_state=random_state, balance=balance, **kwargs) return splitter def spatial_train_test_split(X, y, coordinates, cluster_method, kfold_method, balance, test_size=None, n_splits=None, n_groups=None, max_distance=None, train_size=None, random_state=None, **kwargs): """ Split arrays into random train and test subsets. Similar to `sklearn.model_selection.train_test_split` but instead works on spatial coordinate data. Coordinate data is grouped according to either a KMeans, Gaussain Mixture, or Agglomerative Clustering algorthim. Grouping by spatial clusters is preferred over plain random splits for spatial data to avoid overestimating validation scores due to spatial autocorrelation. Parameters ---------- X : np.array Training data features y : np.array Training data labels coordinates : np.array A numpy array of coordinate values e.g. np.array([[3337270., 262400.], [3441390., -273060.], ...]) cluster_method : str Which algorithm to use to seperate data points. Either 'KMeans', 'GMM', or 'Hierarchical' kfold_method : str One of either 'SpatialShuffleSplit' or 'SpatialKFold'. See the docs under class:_SpatialShuffleSplit and class: _SpatialKFold for more information on these options. balance : int or bool if setting kfold_method to 'SpatialShuffleSplit': int The number of splits generated per iteration to try to balance the amount of data in each set so that *test_size* and *train_size* are respected. If 1, then no extra splits are generated (essentially disabling the balacing). Must be >= 1. if setting kfold_method to 'SpatialKFold': bool Whether or not to split clusters into fold with approximately equal number of data points. If False, each fold will have the same number of clusters (which can have different number of data points in them). test_size : float, int, None If float, should be between 0.0 and 1.0 and represent the proportion of the dataset to include in the test split. If int, represents the absolute number of test samples. If None, the value is set to the complement of the train size. If ``train_size`` is also None, it will be set to 0.15. n_splits : int This parameter is invoked for the 'SpatialKFold' folding method, use this number to satisfy the train-test size ratio desired, as the 'test_size' parameter for the KFold method often fails to get the ratio right. n_groups : int The number of groups to create. This is passed as 'n_clusters=n_groups' for the KMeans algo, and 'n_components=n_groups' for the GMM. If using cluster_method='Hierarchical' then this parameter is ignored. max_distance : int If method is set to 'hierarchical' then maximum distance describes the maximum euclidean distances between all observations in a cluster. 'n_groups' is ignored in this case. train_size : float, int, or None If float, should be between 0.0 and 1.0 and represent the proportion of the dataset to include in the train split. If int, represents the absolute number of train samples. If None, the value is automatically set to the complement of the test size. random_state : int, RandomState instance or None, optional If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. **kwargs : optional, Additional keyword arguments to pass to sklearn.cluster.Kmeans or sklearn.mixture.GuassianMixture depending on the cluster_method argument. Returns ------- Tuple : Contains four arrays in the following order: X_train, X_test, y_train, y_test """ if kfold_method == 'SpatialShuffleSplit': splitter = _SpatialShuffleSplit( n_groups=n_groups, method=cluster_method, coordinates=coordinates, max_distance=max_distance, test_size=test_size, train_size=train_size, n_splits=1 if n_splits is None else n_splits, random_state=random_state, balance=balance, **kwargs) if kfold_method == 'SpatialKFold': if n_splits is None: raise ValueError( "n_splits parameter requires an integer value, eg. 'n_splits=5'" ) if (test_size is not None) or (train_size is not None): warnings.warn( "With the 'SpatialKFold' method, controlling the test/train ratio " "is better achieved using the 'n_splits' parameter" ) splitter = _SpatialKFold(n_groups=n_groups, coordinates=coordinates, max_distance=max_distance, method=cluster_method, n_splits=n_splits, random_state=random_state, balance=balance, **kwargs) lst = [] for train, test in splitter.split(coordinates): X_tr, X_tt = X[train, :], X[test, :] y_tr, y_tt = y[train], y[test] lst.extend([X_tr, X_tt, y_tr, y_tt]) return (lst[0], lst[1], lst[2], lst[3]) def _partition_by_sum(array, parts): """ Partition an array into parts of approximately equal sum. Does not change the order of the array elements. Produces the partition indices on the array. Use :func:`numpy.split` to divide the array along these indices. Parameters ---------- array : array or array-like The 1D array that will be partitioned. The array will be raveled before computations. parts : int Number of parts to split the array. Can be at most the number of elements in the array. Returns ------- indices : array The indices in which the array should be split. Notes ----- Solution from https://stackoverflow.com/a/54024280 """ array = np.atleast_1d(array).ravel() if parts > array.size: raise ValueError( "Cannot partition an array of size {} into {} parts of equal sum.". format(array.size, parts)) cumulative_sum = array.cumsum() # Ideally, we want each part to have the same number of points (total / # parts). ideal_sum = cumulative_sum[-1] // parts # If the parts are ideal, the cumulative sum of each part will be this ideal_cumsum = np.arange(1, parts) * ideal_sum indices = np.searchsorted(cumulative_sum, ideal_cumsum, side="right") # Check for repeated split points, which indicates that there is no way to # split the array. if np.unique(indices).size != indices.size: raise ValueError( "Could not find partition points to split the array into {} parts " "of equal sum.".format(parts)) return indices class _BaseSpatialCrossValidator(BaseCrossValidator, metaclass=ABCMeta): """ Base class for spatial cross-validators. Parameters ---------- n_groups : int The number of groups to create. This is passed as 'n_clusters=n_groups' for the KMeans algo, and 'n_components=n_groups' for the GMM. coordinates : np.array A numpy array of coordinate values e.g. np.array([[3337270., 262400.], [3441390., -273060.], ..., method : str Which algorithm to use to seperate data points. Either 'KMeans' or 'GMM' n_splits : int Number of splitting iterations. """ def __init__(self, n_groups=None, coordinates=None, method=None, max_distance=None, n_splits=None): self.n_groups = n_groups self.coordinates = coordinates self.method = method self.max_distance = max_distance self.n_splits = n_splits def split(self, X, y=None, groups=None): """ Generate indices to split data into training and test set. Parameters ---------- X : array-like, shape (n_samples, 2) Columns should be the easting and northing coordinates of data points, respectively. y : array-like, shape (n_samples,) The target variable for supervised learning problems. Always ignored. groups : array-like, with shape (n_samples,), optional Group labels for the samples used while splitting the dataset into train/test set. Always ignored. Yields ------ train : ndarray The training set indices for that split. test : ndarray The testing set indices for that split. """ if X.shape[1] != 2: raise ValueError( "X (the coordinate data) must have exactly 2 columns ({} given)." .format(X.shape[1])) for train, test in super().split(X, y, groups): yield train, test def get_n_splits(self, X=None, y=None, groups=None): """ Returns the number of splitting iterations in the cross-validator Parameters ---------- X : object Always ignored, exists for compatibility. y : object Always ignored, exists for compatibility. groups : object Always ignored, exists for compatibility. Returns ------- n_splits : int Returns the number of splitting iterations in the cross-validator. """ return self.n_splits @abstractmethod def _iter_test_indices(self, X=None, y=None, groups=None): """ Generates integer indices corresponding to test sets. MUST BE IMPLEMENTED BY DERIVED CLASSES. Parameters ---------- X : array-like, shape (n_samples, 2) Columns should be the easting and northing coordinates of data points, respectively. y : array-like, shape (n_samples,) The target variable for supervised learning problems. Always ignored. groups : array-like, with shape (n_samples,), optional Group labels for the samples used while splitting the dataset into train/test set. Always ignored. Yields ------ test : ndarray The testing set indices for that split. """ class _SpatialShuffleSplit(_BaseSpatialCrossValidator): """ Random permutation of spatial cross-validator. Yields indices to split data into training and test sets. Data are first grouped into clusters using either a KMeans or GMM algorithm and are then split into testing and training sets randomly. The proportion of clusters assigned to each set is controlled by *test_size* and/or *train_size*. However, the total amount of actual data points in each set could be different from these values since clusters can have a different number of data points inside them. To guarantee that the proportion of actual data is as close as possible to the proportion of clusters, this cross-validator generates an extra number of splits and selects the one with proportion of data points in each set closer to the desired amount. The number of balance splits per iteration is controlled by the *balance* argument. This cross-validator is preferred over `sklearn.model_selection.ShuffleSplit` for spatial data to avoid overestimating cross-validation scores. This can happen because of the inherent spatial autocorrelation. Parameters ---------- n_groups : int The number of groups to create. This is passed as 'n_clusters=n_groups' for the KMeans algo, and 'n_components=n_groups' for the GMM. If using cluster_method='Hierarchical' then this parameter is ignored. coordinates : np.array A numpy array of coordinate values e.g. np.array([[3337270., 262400.], [3441390., -273060.], ...]) cluster_method : str Which algorithm to use to seperate data points. Either 'KMeans', 'GMM', or 'Hierarchical' max_distance : int If method is set to 'hierarchical' then maximum distance describes the maximum euclidean distances between all observations in a cluster. 'n_groups' is ignored in this case. n_splits : int, Number of re-shuffling & splitting iterations. test_size : float, int, None If float, should be between 0.0 and 1.0 and represent the proportion of the dataset to include in the test split. If int, represents the absolute number of test samples. If None, the value is set to the complement of the train size. If ``train_size`` is also None, it will be set to 0.1. train_size : float, int, or None If float, should be between 0.0 and 1.0 and represent the proportion of the dataset to include in the train split. If int, represents the absolute number of train samples. If None, the value is automatically set to the complement of the test size. random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. balance : int The number of splits generated per iteration to try to balance the amount of data in each set so that *test_size* and *train_size* are respected. If 1, then no extra splits are generated (essentially disabling the balacing). Must be >= 1. **kwargs : optional, Additional keyword arguments to pass to sklearn.cluster.Kmeans or sklearn.mixture.GuassianMixture depending on the cluster_method argument. Returns -------- generator containing indices to split data into training and test sets """ def __init__(self, n_groups=None, coordinates=None, method='Heirachical', max_distance=None, n_splits=None, test_size=0.15, train_size=None, random_state=None, balance=10, **kwargs): super().__init__(n_groups=n_groups, coordinates=coordinates, method=method, max_distance=max_distance, n_splits=n_splits, **kwargs) if balance < 1: raise ValueError( "The *balance* argument must be >= 1. To disable balance, use 1." ) self.test_size = test_size self.train_size = train_size self.random_state = random_state self.balance = balance self.kwargs = kwargs def _iter_test_indices(self, X=None, y=None, groups=None): """ Generates integer indices corresponding to test sets. Runs several iterations until a split is found that yields clusters with the right amount of data points in it. Parameters ---------- X : array-like, shape (n_samples, 2) Columns should be the easting and northing coordinates of data points, respectively. y : array-like, shape (n_samples,) The target variable for supervised learning problems. Always ignored. groups : array-like, with shape (n_samples,), optional Group labels for the samples used while splitting the dataset into train/test set. Always ignored. Yields ------ test : ndarray The testing set indices for that split. """ labels = spatial_clusters(n_groups=self.n_groups, coordinates=self.coordinates, method=self.method, max_distance=self.max_distance, **self.kwargs) cluster_ids = np.unique(labels) # Generate many more splits so that we can pick and choose the ones # that have the right balance of training and testing data. shuffle = ShuffleSplit( n_splits=self.n_splits * self.balance, test_size=self.test_size, train_size=self.train_size, random_state=self.random_state, ).split(cluster_ids) for _ in range(self.n_splits): test_sets, balance = [], [] for _ in range(self.balance): # This is a false positive in pylint which is why the warning # is disabled at the top of this file: # https://github.com/PyCQA/pylint/issues/1830 # pylint: disable=stop-iteration-return train_clusters, test_clusters = next(shuffle) # pylint: enable=stop-iteration-return train_points = np.where( np.isin(labels, cluster_ids[train_clusters]))[0] test_points = np.where( np.isin(labels, cluster_ids[test_clusters]))[0] # The proportion of data points assigned to each group should # be close the proportion of clusters assigned to each group. balance.append( abs(train_points.size / test_points.size - train_clusters.size / test_clusters.size)) test_sets.append(test_points) best =
np.argmin(balance)
numpy.argmin
# 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])
numpy.array
#Author: <NAME>. Email: <EMAIL> #Packaged by: <NAME>, Email: <EMAIL> #This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. #To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/4.0/ or send a letter to Creative Commons, #PO Box 1866, Mountain View, CA 94042, USA. # Use as example script to learn the parameters of the gmm and to visualize the bout types and their kinematics # Datasets of each condition should be of size nbouts x nfeatures # In addition storing the features, the tail angles can be useful in order to visualize the bout types found # Recfactoring analyze_kinematics() to suit specific datasets can help with the visualization of the bout types import argparse import sys sys.path.append('./BASS/') sys.path.append('./Utils/') import os import time #data format library #numpy and scipy import numpy as np import pandas as pd import matplotlib.pyplot as plt #data processing functions from GMM import GMM_model def train(args, datasets, n_cluster): """ Learn a GMM on datasets with a set number of clusters and save the parameters: Parameters: args: Argparse object containing general arguments datasets: A list of datasets over which to learn GMM. Size of list should be number of conditions/experiments Each dataset in the list should be num_bouts x n_features.. n_cluster: Chosen number of clusters. default type - int """ model_fit = GMM_model(n_cluster) if args.Load == False: length_min = np.min([len(data) for data in datasets]) split_size = int((2/3)*length_min) # 60% train/val split datasets_train = np.zeros((len(datasets),split_size,datasets[0].shape[1])) # 3d array for subsampled dataset for s in range(len(datasets)): subsample = np.random.choice(len(datasets[s]),split_size) datasets_train[s] = datasets[s][subsample] model_fit.solve(datasets_train) model_fit._save_params(args.PathGMM + args.GMMName) return model_fit elif args.Load == True: if os.path.exists(args.PathGMM) is not True: print('Path to GMM ' + args.PathData + ' does not exist, folders created') exit() means_ = np.load(args.PathGMM + args.GMMName + "_means.npy") covars_ = np.load(args.PathGMM + args.GMMName + "_covars.npy") weights_ = np.load(args.PathGMM + args.GMMName + "_weights.npy") model_fit._read_params(means_,covars_,weights_) return model_fit def val(args, datasets,clusters,n_reps): """ Train a Gaussian Mixture models and plot the log likelihood for selected range of clusters in order to select the number of clusters Parameters: args: Argparse object containing general arguments datasets: A list of datasets over which to learn GMM. Size of list should be number of conditions/experiments Each dataset in the list should be num_bouts x n_features. clusters: a list/numpy array of the range of clusters to test upon n_reps: Number of repititions to perform for error bars """ np.random.seed(args.Seed) LLs = [] for i in clusters: print('clusters = ',i) LLs += [[]] for j in range(n_reps): print('iter = ', j) model_fit = GMM_model(i) length_min = np.min([len(data) for data in datasets]) split_size = int((2/3)*length_min) # 60% train/val split datasets_train = np.zeros((len(datasets),split_size,datasets[0].shape[1])) # 3d array for subsampled dataset datasets_test = np.zeros((len(datasets),length_min - split_size,datasets[0].shape[1])) for s in range(len(datasets)): subsample = np.random.choice(len(datasets[s]),split_size) datasets_train[s] = datasets[s][subsample] datasets_test[s] =
np.delete(datasets[s],subsample,axis=0)
numpy.delete
import numpy as np from numpy.testing import run_module_suite, assert_almost_equal import scipy.sparse.linalg as spla def test_gmres_basic(): A = np.vander(
np.arange(10)
numpy.arange
import numpy as np import numpy.testing as npt import pytest from copy import deepcopy from collections import OrderedDict as ODict from pulse2percept.stimuli import Stimulus, PulseTrain def test_Stimulus(): # One electrode: stim = Stimulus(3) npt.assert_equal(stim.shape, (1, 1)) npt.assert_equal(stim.electrodes, [0]) npt.assert_equal(stim.time, None) # One electrode with a name: stim = Stimulus(3, electrodes='AA001') npt.assert_equal(stim.shape, (1, 1)) npt.assert_equal(stim.electrodes, ['AA001']) npt.assert_equal(stim.time, None) # Ten electrodes, one will be trimmed: stim = Stimulus(np.arange(10), compress=True) npt.assert_equal(stim.shape, (9, 1)) npt.assert_equal(stim.electrodes, np.arange(1, 10)) npt.assert_equal(stim.time, None) # Electrodes + specific time, time will be trimmed: stim = Stimulus(np.ones((4, 3)), time=[-3, -2, -1], compress=True) npt.assert_equal(stim.shape, (4, 2)) npt.assert_equal(stim.time, [-3, -1]) # Electrodes + specific time, but don't trim: stim = Stimulus(np.ones((4, 3)), time=[-3, -2, -1], compress=False) npt.assert_equal(stim.shape, (4, 3)) npt.assert_equal(stim.time, [-3, -2, -1]) # Specific names: stim = Stimulus({'A1': 3, 'C5': 8}) npt.assert_equal(stim.shape, (2, 1)) npt.assert_equal(np.sort(stim.electrodes), np.sort(['A1', 'C5'])) npt.assert_equal(stim.time, None) # Specific names, renamed: stim = Stimulus({'A1': 3, 'C5': 8}, electrodes=['B7', 'B8']) npt.assert_equal(stim.shape, (2, 1)) npt.assert_equal(np.sort(stim.electrodes), np.sort(['B7', 'B8'])) npt.assert_equal(stim.time, None) # Electrodes x time, time will be trimmed: stim = Stimulus(np.ones((6, 100)), compress=True) npt.assert_equal(stim.shape, (6, 2)) # Single electrode in time: stim = Stimulus(PulseTrain(0.01 / 1000, dur=0.005), compress=False) npt.assert_equal(stim.electrodes, [0]) npt.assert_equal(stim.shape, (1, 500)) stim = Stimulus(PulseTrain(0.01 / 1000, dur=0.005), compress=True) npt.assert_equal(stim.electrodes, [0]) npt.assert_equal(stim.shape, (1, 8)) # Specific electrode in time: stim = Stimulus({'C3': PulseTrain(0.01 / 1000, dur=0.004)}, compress=False) npt.assert_equal(stim.electrodes, ['C3']) npt.assert_equal(stim.shape, (1, 400)) stim = Stimulus({'C3': PulseTrain(0.01 / 1000, dur=0.004)}, compress=True) npt.assert_equal(stim.electrodes, ['C3']) npt.assert_equal(stim.shape, (1, 8)) # Multiple specific electrodes in time: stim = Stimulus({'C3': PulseTrain(0.01 / 1000, dur=0.004), 'F4': PulseTrain(0.01 / 1000, delay=0.0001, dur=0.004)}, compress=True) # Stimulus from a Stimulus (might happen in ProsthesisSystem): stim = Stimulus(Stimulus(4), electrodes='B3') npt.assert_equal(stim.shape, (1, 1)) npt.assert_equal(stim.electrodes, ['B3']) npt.assert_equal(stim.time, None) # Saves metadata: metadata = {'a': 0, 'b': 1} stim = Stimulus(3, metadata=metadata) npt.assert_equal(stim.metadata, metadata) # List of lists instead of 2D NumPy array: stim = Stimulus([[1, 1, 1, 1, 1], [1, 1, 1, 1, 1]], compress=True) npt.assert_equal(stim.shape, (2, 2)) npt.assert_equal(stim.electrodes, [0, 1]) npt.assert_equal(stim.time, [0, 4]) # Tuple of tuples instead of 2D NumPy array: stim = Stimulus(((1, 1, 1, 1, 1), (1, 1, 1, 1, 1)), compress=True) npt.assert_equal(stim.shape, (2, 2)) npt.assert_equal(stim.electrodes, [0, 1]) npt.assert_equal(stim.time, [0, 4]) # Zero activation: source = np.zeros((2, 4)) stim = Stimulus(source, compress=True) npt.assert_equal(stim.shape, (0, 2)) npt.assert_equal(stim.time, [0, source.shape[1] - 1]) stim = Stimulus(source, compress=False) npt.assert_equal(stim.shape, source.shape) npt.assert_equal(stim.time, np.arange(source.shape[1])) # Annoying but possible: stim = Stimulus([]) npt.assert_equal(stim.time, None) npt.assert_equal(len(stim.data), 0) npt.assert_equal(len(stim.electrodes), 0) npt.assert_equal(stim.shape, (0,)) # Rename electrodes: stim = Stimulus(np.ones((2, 5)), compress=True) npt.assert_equal(stim.electrodes, [0, 1]) stim = Stimulus(stim, electrodes=['A3', 'B8']) npt.assert_equal(stim.electrodes, ['A3', 'B8']) npt.assert_equal(stim.time, [0, 4]) # Specify new time points: stim = Stimulus(np.ones((2, 5)), compress=True) npt.assert_equal(stim.time, [0, 4]) stim = Stimulus(stim, time=np.array(stim.time) / 10.0) npt.assert_equal(stim.electrodes, [0, 1]) npt.assert_equal(stim.time, [0, 0.4]) # Not allowed: with pytest.raises(ValueError): # Multiple electrodes in time, different time stamps: stim = Stimulus([PulseTrain(0.01 / 1000, dur=0.004), PulseTrain(0.005 / 1000, dur=0.002)]) with pytest.raises(ValueError): # First one doesn't have time: stim = Stimulus({'A2': 1, 'C3': PulseTrain(0.01 / 1000, dur=0.004)}) with pytest.raises(ValueError): # Invalid source type: stim = Stimulus(np.ones((3, 4, 5, 6))) with pytest.raises(TypeError): # Invalid source type: stim = Stimulus("invalid") with pytest.raises(ValueError): # Wrong number of electrodes: stim = Stimulus([3, 4], electrodes='A1') with pytest.raises(ValueError): # Wrong number of time points: stim = Stimulus(np.ones((3, 5)), time=[0, 1, 2]) with pytest.raises(ValueError): # Can't force time: stim = Stimulus(3, time=[0.4]) @pytest.mark.parametrize('tsample', (5e-6, 1e-7)) def test_Stimulus_compress(tsample): # Single pulse train: pdur = 0.00045 pt = PulseTrain(tsample, pulse_dur=pdur, dur=0.005) idata = pt.data.reshape((1, -1)) ielec = np.array([0]) itime = np.arange(idata.shape[-1]) * pt.tsample stim = Stimulus(idata, electrodes=ielec, time=itime, compress=False) # Compress the data. The original `tsample` shouldn't matter as long as the # resolution is fine enough to capture all of the pulse train: stim.compress() npt.assert_equal(stim.shape, (1, 8)) # Electrodes are unchanged: npt.assert_equal(ielec, stim.electrodes) # First and last time step are always preserved: npt.assert_almost_equal(itime[0], stim.time[0]) npt.assert_almost_equal(itime[-1], stim.time[-1]) # The first rising edge happens at t=`pdur`: npt.assert_almost_equal(stim.time[1], pdur - tsample) npt.assert_almost_equal(stim.data[0, 1], -20) npt.assert_almost_equal(stim.time[2], pdur) npt.assert_almost_equal(stim.data[0, 2], 0) # Two pulse trains with slight delay/offset, and a third that's all 0: delay = 0.0001 pt = PulseTrain(tsample, delay=0, dur=0.005) pt2 = PulseTrain(tsample, delay=delay, dur=0.005) pt3 = PulseTrain(tsample, amp=0, dur=0.005) idata = np.vstack((pt.data, pt2.data, pt3.data)) ielec = np.array([0, 1, 2]) itime = np.arange(idata.shape[-1]) * pt.tsample stim = Stimulus(idata, electrodes=ielec, time=itime, compress=False) # Compress the data: stim.compress() npt.assert_equal(stim.shape, (2, 16)) # Zero electrodes should be deselected: npt.assert_equal(stim.electrodes, np.array([0, 1])) # First and last time step are always preserved: npt.assert_almost_equal(itime[0], stim.time[0]) npt.assert_almost_equal(itime[-1], stim.time[-1]) # The first rising edge happens at t=`delay`: npt.assert_almost_equal(stim.time[1], delay - tsample) npt.assert_almost_equal(stim.data[0, 1], -20) npt.assert_almost_equal(stim.data[1, 1], 0) npt.assert_almost_equal(stim.time[2], delay) npt.assert_almost_equal(stim.data[0, 2], -20) npt.assert_almost_equal(stim.data[1, 2], -20) # Repeated calls to compress won't change the result: idata = stim.data ielec = stim.electrodes itime = stim.time stim.compress() npt.assert_equal(idata, stim.data) npt.assert_equal(ielec, stim.electrodes) npt.assert_equal(itime, stim.time) def test_Stimulus__stim(): stim = Stimulus(3) # User could try and motify the data container after the constructor, which # would lead to inconsistencies between data, electrodes, time. The new # property setting mechanism prevents that. # Requires dict: with pytest.raises(TypeError): stim._stim = np.array([0, 1]) # Dict must have all required fields: fields = ['data', 'electrodes', 'time'] for field in fields: _fields = deepcopy(fields) _fields.remove(field) with pytest.raises(AttributeError): stim._stim = {f: None for f in _fields} # Data must be a 2-D NumPy array: data = {f: None for f in fields} with pytest.raises(TypeError): data['data'] = [1, 2] stim._stim = data with pytest.raises(ValueError): data['data'] = np.ones(3) stim._stim = data # Data rows must match electrodes: with pytest.raises(ValueError): data['data'] = np.ones((3, 4)) data['time'] = np.arange(4) data['electrodes'] = np.arange(2) stim._stim = data # Data columns must match time: with pytest.raises(ValueError): data['data'] = np.ones((3, 4)) data['electrodes'] = np.arange(3) data['time'] = np.arange(7) stim._stim = data # But if you do all the things right, you can reset the stimulus by hand: data['data'] = np.ones((3, 1)) data['electrodes'] = np.arange(3) data['time'] = None stim._stim = data data['data'] = np.ones((3, 1)) data['electrodes'] = np.arange(3) data['time'] = np.arange(1) stim._stim = data data['data'] = np.ones((3, 7)) data['electrodes'] = np.arange(3) data['time'] = np.ones(7) stim._stim = data def test_Stimulus___eq__(): # Two Stimulus objects created from the same source data are considered # equal: for source in [3, [], np.ones(3), [3, 4, 5], np.ones((3, 6))]: npt.assert_equal(Stimulus(source) == Stimulus(source), True) stim = Stimulus(np.ones((2, 3)), compress=True) # Compressed vs uncompressed: npt.assert_equal(stim == Stimulus(np.ones((2, 3)), compress=False), False) npt.assert_equal(stim != Stimulus(np.ones((2, 3)), compress=False), True) # Different electrode names: npt.assert_equal(stim == Stimulus(stim, electrodes=[0, 'A2']), False) # Different time points: npt.assert_equal(stim == Stimulus(stim, time=[0, 3], compress=True), False) # Different data shape: npt.assert_equal(stim == Stimulus(np.ones((2, 4))), False) npt.assert_equal(stim == Stimulus(np.ones(2)), False) # Different data points: npt.assert_equal(stim == Stimulus(np.ones((2, 3)) * 1.1), False) # Different type: npt.assert_equal(stim == np.ones((2, 3)), False) npt.assert_equal(stim != np.ones((2, 3)), True) # Annoying but possible: npt.assert_equal(Stimulus([]), Stimulus(())) def test_Stimulus___getitem__(): stim = Stimulus(np.arange(12).reshape((3, 4))) # Slicing: npt.assert_equal(stim[:], stim.data) npt.assert_equal(stim[...], stim.data) npt.assert_equal(stim[:, :], stim.data) npt.assert_equal(stim[:2], stim.data[:2]) npt.assert_equal(stim[:, 0], stim.data[:, 0]) npt.assert_equal(stim[0, :], stim.data[0, :]) npt.assert_equal(stim[0, ...], stim.data[0, ...]) npt.assert_equal(stim[..., 0], stim.data[..., 0]) # Single element: npt.assert_equal(stim[0, 0], stim.data[0, 0]) # Interpolating time: npt.assert_almost_equal(stim[0, 2.6], 2.6) npt.assert_almost_equal(stim[..., 2.3], np.array([[2.3], [6.3], [10.3]])) # "Valid" index errors: with pytest.raises(IndexError): stim[10, :] with pytest.raises(TypeError): stim[3.3, 0] # Extrapolating should be disabled by default: with pytest.raises(ValueError): stim[0, 9.9] # But you can enable it: stim = Stimulus(np.arange(12).reshape((3, 4)), extrapolate=True) npt.assert_almost_equal(stim[0, 9.9], 9.9) # If time=None, you cannot interpolate/extrapolate: stim = Stimulus([3, 4, 5], extrapolate=True) npt.assert_almost_equal(stim[0], stim.data[0, 0]) with pytest.raises(ValueError): stim[0, 0.2] # With a single time point, interpolate is still possible: stim = Stimulus(np.arange(3).reshape((-1, 1)), extrapolate=False) npt.assert_almost_equal(stim[0], stim.data[0, 0]) npt.assert_almost_equal(stim[0, 0], stim.data[0, 0]) with pytest.raises(ValueError): stim[0, 3.33] stim = Stimulus(np.arange(3).reshape((-1, 1)), extrapolate=True)
npt.assert_almost_equal(stim[0, 3.33], stim.data[0, 0])
numpy.testing.assert_almost_equal
################################################################################ # Copyright (C) 2013-2014 <NAME> # # This file is licensed under the MIT License. ################################################################################ """ Unit tests for `dot` module. """ import unittest import numpy as np import scipy from numpy import testing from ..dot import Dot, SumMultiply from ..gaussian import Gaussian, GaussianARD from bayespy.nodes import GaussianGamma from ...vmp import VB from bayespy.utils import misc from bayespy.utils import linalg from bayespy.utils import random from bayespy.utils.misc import TestCase class TestSumMultiply(TestCase): def test_parent_validity(self): """ Test that the parent nodes are validated properly in SumMultiply """ V = GaussianARD(1, 1) X = Gaussian(np.ones(1), np.identity(1)) Y = Gaussian(np.ones(3), np.identity(3)) Z = Gaussian(np.ones(5),
np.identity(5)
numpy.identity
"""ageo - active geolocation library: core. """ __all__ = ('Location', 'Map', 'Observation') import bisect import functools import itertools import numpy as np import pyproj from scipy import sparse from shapely.geometry import Point, MultiPoint, Polygon, box as Box from shapely.ops import transform as sh_transform import tables import math import sys # scipy.sparse.find() materializes vectors which, in several cases # below, can be enormous. This is slower, but more memory-efficient. # Code from https://stackoverflow.com/a/31244368/388520 with minor # modifications. def iter_csr_nonzero(matrix): irepeat = itertools.repeat return zip( # reconstruct the row indices itertools.chain.from_iterable( irepeat(i, r) for (i,r) in enumerate(matrix.indptr[1:] - matrix.indptr[:-1]) ), # matrix.indices gives the column indices as-is matrix.indices, matrix.data ) def Disk(x, y, radius): return Point(x, y).buffer(radius) # Important note: pyproj consistently takes coordinates in lon/lat # order and distances in meters. lon/lat order makes sense for # probability matrices, because longitudes are horizontal = columns, # latitudes are vertical = rows, and scipy matrices are column-major # (blech). Therefore, this library also consistently uses lon/lat # order and meters. # Coordinate transformations used by Location.centroid() wgs_proj = pyproj.Proj("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs") gcen_proj = pyproj.Proj("+proj=geocent +datum=WGS84 +units=m +no_defs") wgs_to_gcen = functools.partial(pyproj.transform, wgs_proj, gcen_proj) gcen_to_wgs = functools.partial(pyproj.transform, gcen_proj, wgs_proj) # ... and Location.area() cea_proj = pyproj.Proj(proj='cea', ellps='WGS84', lon_0=0, lat_ts=0) wgs_to_cea = functools.partial(pyproj.transform, wgs_proj, cea_proj) # Smooth over warts in pyproj.Geod.inv(), which is vectorized # internally, but does not support numpy-style broadcasting, and # returns things we don't need. The prebound _Inv and _Bcast are # strictly performance hacks. _WGS84geod = pyproj.Geod(ellps='WGS84') def WGS84dist(lon1, lat1, lon2, lat2, *, _Inv = _WGS84geod.inv, _Bcast = np.broadcast_arrays): _, _, dist = _Inv(*_Bcast(lon1, lat1, lon2, lat2)) return dist def cartesian2(a, b): """Cartesian product of two 1D vectors A and B.""" return np.tile(a, len(b)), np.repeat(b, len(a)) def mask_ij(bounds, longitudes, latitudes): """Given a rectangle-tuple BOUNDS (west, south, east, north; as returned by shapely .bounds properties), and sorted grid index vectors LONGITUDES, LATITUDES, return vectors I, J which give the x- and y-indices of every grid point within the rectangle. LATITUDES and LONGITUDES must be sorted. """ try: (west, south, east, north) = bounds except ValueError as e: raise ValueError("invalid bounds argument {!r}".format(bounds)) from e min_i = bisect.bisect_left(longitudes, west) max_i = bisect.bisect_right(longitudes, east) min_j = bisect.bisect_left(latitudes, south) max_j = bisect.bisect_right(latitudes, north) I = np.array(range(min_i, max_i)) J = np.array(range(min_j, max_j)) return cartesian2(I, J) def mask_matrix(bounds, longitudes, latitudes): """Construct a sparse matrix which is 1 at all latitude+longitude grid points inside the rectangle BOUNDS, 0 outside. LATITUDES and LONGITUDES must be sorted. """ I, J = mask_ij(bounds, longitudes, latitudes) return sparse.csr_matrix((np.ones_like(I), (I, J)), shape=(len(longitudes), len(latitudes))) class LocationRowOnDisk(tables.IsDescription): """The row format of the pytables table used to save Location objects on disk. See Location.save and Location.load.""" grid_x = tables.UInt32Col() grid_y = tables.UInt32Col() longitude = tables.Float64Col() latitude = tables.Float64Col() prob_mass = tables.Float32Col() class Location: """An estimated location for a host. This is represented by a probability mass function over the surface of the Earth, quantized to a cell grid, and stored as a sparse matrix. Properties: resolution - Grid resolution, in meters at the equator lon_spacing - East-west (longitude) grid resolution, in decimal degrees lat_spacing - North-south (latitude) grid resolution, in decimal degrees fuzz - Coastline uncertainty factor, in meters at the equator north - Northernmost latitude covered by the grid south - Southernmost latitude ditto east - Easternmost longitude ditto west - Westernmost longitude ditto latitudes - Vector of latitude values corresponding to grid points longitudes - Vector of longitude values ditto probability - Probability mass matrix (may be lazily computed) bounds - Bounding region of the nonzero portion of the probability mass matrix (may be lazily computed) centroid - Centroid of the nonzero &c area - Weighted area of the nonzero &c covariance - Covariance matrix of the nonzero &c (relative to the centroid) rep_pt - "Representative point" of the nonzero &c; see docstring for exactly what this means annotations - Dictionary of arbitrary additional metadata; saved and loaded but not otherwise inspected by this code You will normally not construct bare Location objects directly, only Map and Observation objects (these are subclasses). However, any two Locations can be _intersected_ to produce a new one. A Location is _vacuous_ if it has no nonzero entries in its probability matrix. """ def __init__(self, *, resolution, fuzz, lon_spacing, lat_spacing, north, south, east, west, longitudes, latitudes, probability=None, vacuity=None, bounds=None, centroid=None, covariance=None, rep_pt=None, loaded_from=None, annotations=None ): self.resolution = resolution self.fuzz = fuzz self.north = north self.south = south self.east = east self.west = west self.lon_spacing = lon_spacing self.lat_spacing = lat_spacing self.longitudes = longitudes self.latitudes = latitudes self._probability = probability self._vacuous = vacuity self._bounds = bounds self._centroid = centroid self._covariance = covariance self._rep_pt = rep_pt self._loaded_from = loaded_from self._area = None self.annotations = annotations if annotations is not None else {} @property def probability(self): if self._probability is None: self.compute_probability_matrix_now() return self._probability @property def vacuous(self): if self._vacuous is None: self.compute_probability_matrix_now() return self._vacuous @property def centroid(self): if self._centroid is None: self.compute_centroid_now() return self._centroid @property def covariance(self): if self._covariance is None: self.compute_centroid_now() return self._covariance @property def area(self): """Weighted area of the nonzero region of the probability matrix.""" if self._area is None: # Notionally, each grid point should be treated as a # rectangle of parallels and meridians _centered_ on the # point. The area of such a rectangle, however, only # depends on its latitude and its breadth; the actual # longitude values don't matter. Since the grid is # equally spaced, we can use [0],[1] always, and then we # do not have to worry about crossing the discontinuity at ±180. west = self.longitudes[0] east = self.longitudes[1] # For latitude, the actual values do matter, but the map # never goes all the way to the poles, and the grid is # equally spaced, so we can precompute the north-south # delta from any pair of latitudes and not have to worry # about running off the ends of the array. d_lat = (self.latitudes[1] - self.latitudes[0]) / 2 # We don't need X, so throw it away immediately. (We # don't use iter_csr_nonzero here because we need to # modify V.) X, Y, V = sparse.find(self.probability); X = None # The value vector is supposed to be normalized, but make # sure it is, and then adjust from 1-overall to 1-per-cell # normalization. assert len(V.shape) == 1 S = V.sum() if S == 0: return 0 if S != 1: V /= S V *= V.shape[0] area = 0 for y, v in zip(Y, V): north = self.latitudes[y] + d_lat south = self.latitudes[y] - d_lat if not (-90 <= south < north <= 90): raise AssertionError("expected -90 <= {} < {} <= 90" .format(south, north)) tile = sh_transform(wgs_to_cea, Box(west, south, east, north)) area += v * tile.area self._area = area return self._area @property def rep_pt(self, epsilon=1e-8): """Representative point of the nonzero region of the probability matrix. This is, of all points with the greatest probability, the one closest to the centroid. """ if self._rep_pt is None: lons = self.longitudes lats = self.latitudes cen = self.centroid aeqd_cen = pyproj.Proj(proj='aeqd', ellps='WGS84', datum='WGS84', lon_0=cen[0], lat_0=cen[1]) wgs_to_aeqd = functools.partial(pyproj.transform, wgs_proj, aeqd_cen) # mathematically, wgs_to_aeqd(Point(lon, lat)) == Point(0, 0); # the latter is faster and more precise cen_pt = Point(0,0) # It is unacceptably costly to construct a shapely MultiPoint # out of some locations with large regions (can require more than # 32GB of scratch memory). Instead, iterate over the points # one at a time. max_prob = 0 min_dist = math.inf rep_pt = None for x, y, v in iter_csr_nonzero(self.probability): lon = lons[x] lat = lats[y] if rep_pt is None or v > max_prob - epsilon: dist = WGS84dist(cen[0], cen[1], lon, lat) # v < max_prob has already been excluded if (rep_pt is None or v > max_prob or (v > max_prob - epsilon and dist < min_dist)): rep_pt = [lon, lat] max_prob = max(max_prob, v) min_dist = dist if rep_pt is None: rep_pt = cen else: rep_pt =
np.array(rep_pt)
numpy.array
# -*- coding: utf-8 -*- """ Created on Thu Oct 31 15:15:12 2019 @author: bwc """ # standard imports import numpy as np import matplotlib.pyplot as plt # custom imports import apt_fileio import peak_param_determination as ppd from histogram_functions import bin_dat import scipy.interpolate import image_registration.register_images #import sel_align_m2q_log_xcorr import scaling_correction import time import m2q_calib from voltage_and_bowl import do_voltage_and_bowl import voltage_and_bowl import colorcet as cc import matplotlib._color_data as mcd import matplotlib FIGURE_SCALE_FACTOR = 2 def colorbar(): fig = plt.gcf() ax = fig.gca() # # norm = matplotlib.colors.Normalize(vmin=0, vmax=1, clip=False) # fig.colorbar() return None def extents(f): delta = f[1] - f[0] return [f[0] - delta/2, f[-1] + delta/2] def create_histogram(ys,cts_per_slice=2**10,y_roi=None,delta_y=0.1): # even number num_y = int(np.ceil(np.abs(np.diff(y_roi))/delta_y/2)*2) num_x = int(ys.size/cts_per_slice) xs = np.arange(ys.size) N,x_edges,y_edges = np.histogram2d(xs,ys,bins=[num_x,num_y],range=[[1,ys.size],y_roi],density=False) return (N,x_edges,y_edges) def edges_to_centers(*edges): centers = [] for es in edges: centers.append((es[0:-1]+es[1:])/2) if len(centers)==1: centers = centers[0] return centers def plot_2d_histo(ax,N,x_edges,y_edges): pos1 = ax.imshow(np.log10(1+1*np.transpose(N)), aspect='auto', extent=extents(x_edges) + extents(y_edges), origin='lower', cmap=cc.cm.CET_L8, interpolation='bicubic') ax.set_xticks([0,100000,200000,300000,400000])# ax.set_xticklabels(["\n".join(x) for x in data.index]) return pos1 def steel(): # Load and subsample data (for easier processing) fn = r"Q:\NIST_Projects\EUV_APT_IMS\BWC\R44_02203-v01.epos" epos = apt_fileio.read_epos_numpy(fn) epos = epos[100000::10] # Voltage and bowl correct ToF data p_volt = np.array([]) p_bowl = np.array([]) t_i = time.time() tof_corr, p_volt, p_bowl = do_voltage_and_bowl(epos,p_volt,p_bowl) print("time to voltage and bowl correct: "+str(time.time()-t_i)+" seconds") # Only apply bowl correction tof_bcorr = voltage_and_bowl.mod_geometric_bowl_correction(p_bowl,epos['tof'],epos['x_det'],epos['y_det']) # Plot histogram for steel fig = plt.figure(figsize=(FIGURE_SCALE_FACTOR*3.14961,FIGURE_SCALE_FACTOR*3.14961),num=1,dpi=100) plt.clf() ax1, ax2 = fig.subplots(2,1,sharex=True) N,x_edges,y_edges = create_histogram(tof_bcorr,y_roi=[400,600],cts_per_slice=2**9,delta_y=0.25) im = plot_2d_histo(ax1,N,x_edges,y_edges) # plt.colorbar(im) ax1.set(ylabel='flight time (ns)') ax1twin = ax1.twinx() ax1twin.plot(epos['v_dc'],'-', linewidth=2, color=mcd.XKCD_COLORS['xkcd:white']) ax1twin.set(ylabel='applied voltage (volts)',ylim=[0, 6000],xlim=[0, 400000]) N,x_edges,y_edges = create_histogram(tof_corr,y_roi=[425,475],cts_per_slice=2**9,delta_y=0.25) im = plot_2d_histo(ax2,N,x_edges,y_edges) # plt.colorbar(im) ax2.set(xlabel='ion sequence',ylabel='corrected flight time (ns)') fig.tight_layout() fig.savefig(r'Q:\users\bwc\APT\scale_corr_paper\metal_not_wandering.pdf', format='pdf', dpi=600) return 0 def sio2_R45(): fn = r"Q:\NIST_Projects\EUV_APT_IMS\BWC\R45_data\R45_04472-v02_allVfromAnn.epos" epos = apt_fileio.read_epos_numpy(fn) epos = epos[25000:] # Voltage and bowl correct ToF data p_volt = np.array([]) p_bowl = np.array([]) t_i = time.time() tof_corr, p_volt, p_bowl = do_voltage_and_bowl(epos,p_volt,p_bowl) print("time to voltage and bowl correct: "+str(time.time()-t_i)+" seconds") # Only apply bowl correction tof_bcorr = voltage_and_bowl.mod_geometric_bowl_correction(p_bowl,epos['tof'],epos['x_det'],epos['y_det']) # Plot histogram for sio2 fig = plt.figure(figsize=(FIGURE_SCALE_FACTOR*3.14961,FIGURE_SCALE_FACTOR*3.14961),num=2,dpi=100) plt.clf() ax1, ax2 = fig.subplots(2,1,sharex=True) N,x_edges,y_edges = create_histogram(tof_bcorr,y_roi=[280,360],cts_per_slice=2**9,delta_y=.25) im = plot_2d_histo(ax1,N,x_edges,y_edges) plt.colorbar(im) ax1.set(ylabel='flight time (ns)') ax1twin = ax1.twinx() ax1twin.plot(epos['v_dc'],'-', linewidth=2, color=mcd.XKCD_COLORS['xkcd:white']) ax1twin.set(ylabel='applied voltage (volts)',ylim=[0000, 8000],xlim=[0, 400000]) N,x_edges,y_edges = create_histogram(tof_corr,y_roi=[280,360],cts_per_slice=2**9,delta_y=.25) im = plot_2d_histo(ax2,N,x_edges,y_edges) plt.colorbar(im) ax2.set(xlabel='ion sequence',ylabel='corrected flight time (ns)') fig.tight_layout() fig.savefig(r'Q:\users\bwc\APT\scale_corr_paper\SiO2_NUV_wandering.pdf', format='pdf', dpi=600) return 0 def sio2_R44(): fn = r"C:\Users\bwc\Documents\NetBeansProjects\R44_03200\recons\recon-v02\default\R44_03200-v02.epos" epos = apt_fileio.read_epos_numpy(fn) # Voltage and bowl correct ToF data p_volt = np.array([]) p_bowl = np.array([]) t_i = time.time() tof_corr, p_volt, p_bowl = do_voltage_and_bowl(epos,p_volt,p_bowl) print("time to voltage and bowl correct: "+str(time.time()-t_i)+" seconds") # Only apply bowl correction tof_bcorr = voltage_and_bowl.mod_geometric_bowl_correction(p_bowl,epos['tof'],epos['x_det'],epos['y_det']) # Plot histogram for sio2 fig = plt.figure(figsize=(FIGURE_SCALE_FACTOR*3.14961,FIGURE_SCALE_FACTOR*3.14961),num=3,dpi=100) plt.clf() ax1, ax2 = fig.subplots(2,1,sharex=True) roi = [1400000,1800000] N,x_edges,y_edges = create_histogram(tof_bcorr[roi[0]:roi[1]],y_roi=[300,310],cts_per_slice=2**7,delta_y=.2) im = plot_2d_histo(ax1,N,x_edges,y_edges) plt.colorbar(im) ax1.set(ylabel='flight time (ns)') ax1twin = ax1.twinx() ax1twin.plot(epos['v_dc'][roi[0]:roi[1]],'-', linewidth=2, color=mcd.XKCD_COLORS['xkcd:white']) ax1twin.set(ylabel='applied voltage (volts)',ylim=[0000, 7000],xlim=[0,None]) N,x_edges,y_edges = create_histogram(tof_corr[roi[0]:roi[1]],y_roi=[300,310],cts_per_slice=2**7,delta_y=0.2) im = plot_2d_histo(ax2,N,x_edges,y_edges) plt.colorbar(im) ax2.set(xlabel='ion sequence',ylabel='corrected flight time (ns)') ax2.set_xlim(0,roi[1]-roi[0]) fig.tight_layout() fig.savefig(r'Q:\users\bwc\APT\scale_corr_paper\Figure_R44NUV.pdf', format='pdf', dpi=600) return 0 def sio2_R20(): fn = r"Q:\NIST_Projects\EUV_APT_IMS\BWC\R20_07080-v01.epos" epos = apt_fileio.read_epos_numpy(fn) #epos = epos[165000:582000] # Voltage and bowl correct ToF data p_volt = np.array([]) p_bowl = np.array([]) t_i = time.time() tof_corr, p_volt, p_bowl = do_voltage_and_bowl(epos,p_volt,p_bowl) print("time to voltage and bowl correct: "+str(time.time()-t_i)+" seconds") # Only apply bowl correction tof_bcorr = voltage_and_bowl.mod_geometric_bowl_correction(p_bowl,epos['tof'],epos['x_det'],epos['y_det']) # Plot histogram for sio2 fig = plt.figure(figsize=(FIGURE_SCALE_FACTOR*3.14961,FIGURE_SCALE_FACTOR*3.14961),num=4,dpi=100) plt.clf() ax1, ax2 = fig.subplots(2,1,sharex=True) N,x_edges,y_edges = create_histogram(tof_bcorr,y_roi=[320,380],cts_per_slice=2**9,delta_y=.25) plot_2d_histo(ax1,N,x_edges,y_edges) ax1.set(ylabel='flight time (ns)') ax1twin = ax1.twinx() ax1twin.plot(epos['v_dc'],'-', linewidth=2, color=mcd.XKCD_COLORS['xkcd:white']) ax1twin.set(ylabel='applied voltage (volts)',ylim=[0000, 5000],xlim=[0, 400000]) N,x_edges,y_edges = create_histogram(tof_corr,y_roi=[320,380],cts_per_slice=2**9,delta_y=.25) plot_2d_histo(ax2,N,x_edges,y_edges) ax2.set(xlabel='ion sequence',ylabel='corrected flight time (ns)') fig.tight_layout() fig.savefig(r'Q:\users\bwc\APT\scale_corr_paper\SiO2_EUV_wandering.pdf', format='pdf', dpi=600) return 0 def corr_idea(): fig = plt.figure(num=5) plt.close(fig) fig = plt.figure(constrained_layout=True,figsize=(FIGURE_SCALE_FACTOR*3.14961,FIGURE_SCALE_FACTOR*1.5*3.14961),num=5,dpi=100) gs = fig.add_gridspec(3, 1) ax2 = fig.add_subplot(gs[:2, :]) ax1 = fig.add_subplot(gs[2, :]) def shaded_plot(ax,x,y,idx,col_idx=None): if col_idx is None: col_idx = idx sc = 50 cols = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'] xlim = ax.get_xlim() idxs = np.nonzero((x>=xlim[0]) & (x<=xlim[1])) ax.fill_between(x[idxs], y[idxs]+idx*sc, (idx-0.005)*sc, color=cols[col_idx]) # ax.plot(x,y+idx*sc, color='k') return fn = r"Q:\NIST_Projects\EUV_APT_IMS\BWC\R45_data\R45_04472-v02_allVfromAnn.epos" epos = apt_fileio.read_epos_numpy(fn) epos = epos[25000:] # Voltage and bowl correct ToF data p_volt = np.array([]) p_bowl = np.array([]) t_i = time.time() tof_corr, p_volt, p_bowl = do_voltage_and_bowl(epos,p_volt,p_bowl) print("time to voltage and bowl correct: "+str(time.time()-t_i)+" seconds") # Plot histogram for sio2 # fig = plt.figure(figsize=(2*3.14961,2*3.14961),num=654321,dpi=100) # plt.clf() # ax2 = fig.subplots(1,1) N,x_edges,y_edges = create_histogram(tof_corr,y_roi=[80,400],cts_per_slice=2**10,delta_y=0.0625) #ax1.imshow(np.log10(1+1*np.transpose(N)), aspect='auto', # extent=extents(x_edges) + extents(y_edges), origin='lower', cmap=cc.cm.CET_L8, # interpolation='bilinear') event_idx_range_ref = [0, 0+1024] event_idx_range_mov = [124000, 124000+1024] x_centers = edges_to_centers(x_edges) idxs_ref = (x_centers>=event_idx_range_ref[0]) & (x_centers<=event_idx_range_ref[1]) idxs_mov = (x_centers>=event_idx_range_mov[0]) & (x_centers<=event_idx_range_mov[1]) ref_hist =
np.sum(N[idxs_ref,:],axis=0)
numpy.sum
# @Author: yican, yelanlan # @Date: 2020-05-27 22:58:45 # @Last Modified by: yican # @Last Modified time: 2020-05-27 22:58:45 # Standard libraries import os from time import time import sys sys.path.append('./') import pytorch_lightning as pl # Third party libraries import cv2 import numpy as np import pandas as pd from sklearn.model_selection import KFold import torch import albumentations from albumentations import (Compose, GaussianBlur, HorizontalFlip, MedianBlur, MotionBlur, Normalize, OneOf, RandomBrightness, RandomContrast, RandomBrightnessContrast, Resize, ShiftScaleRotate, VerticalFlip, LongestMaxSize, PadIfNeeded) from torchvision import transforms from torch.utils.data import DataLoader, Dataset from PIL import Image # User defined libraries from utils import * from torchvision.utils import save_image from os.path import basename as bsn from os.path import dirname from torch.utils.data.distributed import DistributedSampler # for fast read data # from utils import NPY_FOLDER class MySampler(DistributedSampler): def __init__(self, dataset: Dataset, num_replicas: Optional[int] = None, rank: Optional[int] = None, shuffle: bool = True, seed: int = 0, drop_last: bool = False) -> None: super().__init__(dataset, num_replicas, rank, shuffle, seed, drop_last) def __len__(self) -> int: # print(f'Pid {os.getpid()}, {super().__len__()}') return super().__len__() class OpticalCandlingDataset(Dataset): """ Do normal training """ def __init__(self, hparams, data, soft_labels_filename=None, transforms=None): self.hparams = hparams self.data_folder = self.hparams.data_folder # self.data = data[-8:] self.data = data self.transforms = transforms if soft_labels_filename == "": self.soft_labels = None else: self.soft_labels = pd.read_csv(soft_labels_filename) def __getitem__(self, index): start_time = time() # Read image # solution-1: read from raw image filename = self.data.iloc[index, 0] path = os.path.join(self.data_folder, filename) # image = cv2.cvtColor(cv2.imread(path),cv2.COLOR_BGR2RGB) image = Image.open(path).convert("RGB") # solution-2: read from npy file which can speed the data load time. # image = np.load(os.path.join(NPY_FO21LDER, "raw", self.data.iloc[index, 0] + ".npy")) if image is None: raise Exception('') # Convert if not the right shape # if image.shape != IMG_SHAPE: # image = image.transpose(1, 0, 2) # print(image.shape) # Do data augmentation if self.transforms is not None and isinstance(self.transforms, albumentations.Compose): image = np.array(image) image = self.transforms(image=image)["image"].transpose(2, 0, 1) elif self.transforms is not None and isinstance( self.transforms, transforms.Compose): image = self.transforms(image) # Soft label if self.soft_labels is not None: label = torch.FloatTensor( (self.data.iloc[index, 1:].values * 0.7).astype(np.float) + (self.soft_labels.iloc[index, 1:].values * 0.3).astype(np.float)) else: label = torch.FloatTensor(self.data.iloc[index, 1:].values.astype( np.int64)) return image, [], [], label, time() - start_time, filename def __len__(self): return len(self.data) # class AnchorSet(OpticalCandlingDataset): # def __init__(self, # hparams, # data, # soft_labels_filename=None, # transforms=None, # sample_num=10): # super().__init__(hparams, data, soft_labels_filename, transforms) # # filename = self.data.iloc[index,0] # self.data = pd.concat([ # self.data.loc[self.data['filename'].str.startswith( # class_name)].head(sample_num) for class_name in CLASS_NAMES # ]) class OpticalCandingWithMaskSet(OpticalCandlingDataset): def __init__(self, hparams, data, soft_labels_filename=None, transforms=None, sample_num=10): super().__init__(hparams, data, soft_labels_filename, transforms) self.data_mask = self.hparams.data_mask # filename = self.data.iloc[index,0] def __getitem__(self, index): start_time = time() # Read image # solution-1: read from raw image filename = self.data.iloc[index, 0] path = os.path.join(self.data_folder, filename) roi_mask_path = os.path.join(self.data_mask, bsn(dirname(filename)), 'egg_mask', bsn(filename)) ar_mask_path = os.path.join(self.data_mask, bsn(dirname(filename)), 'ar_mask', bsn(filename)) # image = cv2.cvtColor(cv2.imread(path),cv2.COLOR_BGR2RGB) image = Image.open(path).convert("RGB") roi_mask = Image.open(roi_mask_path) ar_mask = Image.open(ar_mask_path) # solution-2: read from npy file which can speed the data load time. # image = np.load(os.path.join(NPY_FO21LDER, "raw", self.data.iloc[index, 0] + ".npy")) if image is None: raise Exception('') # Convert if not the right shape # if image.shape != IMG_SHAPE: # image = image.transpose(1, 0, 2) # print(image.shape) # Do data augmentation if self.transforms is not None and isinstance(self.transforms, albumentations.Compose): image =
np.array(image)
numpy.array
import cv2 import fitz import numpy as np import os from api.document_helpers.field_helper_geometry import detect_fillable_boxes, filter_non_lines, define_line_objects, find_closest from api.classes.Geometry import Point import glob def pix2np(pix): im = np.frombuffer(pix.samples, dtype=np.uint8).reshape(pix.h, pix.w, pix.n) im =
np.ascontiguousarray(im[..., [2, 1, 0]])
numpy.ascontiguousarray
import os, subprocess import click import glob import numpy as np, pandas as pd #import impyute from functools import reduce import pickle from pymethylprocess.PreProcessDataTypes import * from pymethylprocess.MethylationDataTypes import * CONTEXT_SETTINGS = dict(help_option_names=['-h','--help'], max_content_width=90) @click.group(context_settings= CONTEXT_SETTINGS) @click.version_option(version='0.1') def preprocess(): pass #### COMMANDS #### ## Download ## @preprocess.command() @click.option('-o', '--output_dir', default='./tcga_idats/', help='Output directory for exported idats.', type=click.Path(exists=False), show_default=True) def download_tcga(output_dir): """Download all tcga 450k data.""" os.makedirs(output_dir, exist_ok=True) downloader = TCGADownloader() downloader.download_tcga(output_dir) @preprocess.command() @click.option('-o', '--output_dir', default='./tcga_idats/', help='Output directory for exported idats.', type=click.Path(exists=False), show_default=True) def download_clinical(output_dir): """Download all TCGA 450k clinical info.""" os.makedirs(output_dir, exist_ok=True) downloader = TCGADownloader() downloader.download_clinical(output_dir) @preprocess.command() @click.option('-g', '--geo_query', default='', help='GEO study to query.', type=click.Path(exists=False), show_default=True) @click.option('-o', '--output_dir', default='./geo_idats/', help='Output directory for exported idats.', type=click.Path(exists=False), show_default=True) def download_geo(geo_query,output_dir): """Download geo methylation study idats and clinical info.""" os.makedirs(output_dir, exist_ok=True) downloader = TCGADownloader() downloader.download_geo(geo_query,output_dir) ## prepare @preprocess.command() @click.option('-is', '--input_sample_sheet', default='./tcga_idats/clinical_info.csv', help='Clinical information downloaded from tcga/geo/custom.', type=click.Path(exists=False), show_default=True) @click.option('-s', '--source_type', default='tcga', help='Source type of data.', type=click.Choice(['tcga','geo','custom']), show_default=True) @click.option('-i', '--idat_dir', default='./tcga_idats/', help='Idat directory.', type=click.Path(exists=False), show_default=True) @click.option('-os', '--output_sample_sheet', default='./tcga_idats/minfiSheet.csv', help='CSV for minfi input.', type=click.Path(exists=False), show_default=True) @click.option('-m', '--mapping_file', default='./idat_filename_case.txt', help='Mapping file from uuid to TCGA barcode. Downloaded using download_tcga.', type=click.Path(exists=False), show_default=True) @click.option('-l', '--header_line', default=0, help='Line to begin reading csv/xlsx.', show_default=True) @click.option('-d', '--disease_class_column', default="methylation class:ch1", help='Disease classification column, for custom and geo datasets.', type=click.Path(exists=False), show_default=True) @click.option('-b', '--basename_col', default="Sentrix ID (.idat)", help='Basename classification column, for custom datasets.', type=click.Path(exists=False), show_default=True) @click.option('-c', '--include_columns_file', default="", help='Custom columns file containing columns to keep, separated by \\n. Add a tab for each line if you wish to rename columns: original_name \\t new_column_name', type=click.Path(exists=False), show_default=True) def create_sample_sheet(input_sample_sheet, source_type, idat_dir, output_sample_sheet, mapping_file, header_line, disease_class_column, basename_col, include_columns_file): """Create sample sheet for input to minfi, meffil, or enmix.""" os.makedirs(output_sample_sheet[:output_sample_sheet.rfind('/')], exist_ok=True) pheno_sheet = PreProcessPhenoData(input_sample_sheet, idat_dir, header_line= (0 if source_type != 'custom' else header_line)) if include_columns_file: include_columns=np.loadtxt(include_columns_file,dtype=str,delimiter='\t') if '\t' in open(include_columns_file).read() and len(include_columns.shape)<2: include_columns=dict(include_columns[np.newaxis,:].tolist()) elif len(include_columns.shape)<2: include_columns=dict(zip(include_columns,include_columns)) else: include_columns=dict(include_columns.tolist()) else: include_columns={} if source_type == 'tcga': pheno_sheet.format_tcga(mapping_file) elif source_type == 'geo': pheno_sheet.format_geo(disease_class_column, include_columns) else: pheno_sheet.format_custom(basename_col, disease_class_column, include_columns) pheno_sheet.export(output_sample_sheet) print("Please remove {} from {}, if it exists in that directory.".format(input_sample_sheet, idat_dir)) @preprocess.command() @click.option('-is', '--input_sample_sheet', default='./tcga_idats/minfiSheet.csv', help='CSV for minfi input.', type=click.Path(exists=False), show_default=True) @click.option('-os', '--output_sample_sheet', default='./tcga_idats/minfiSheet.csv', help='CSV for minfi input.', type=click.Path(exists=False), show_default=True) def meffil_encode(input_sample_sheet,output_sample_sheet): """Reformat file for meffil input.""" from collections import defaultdict pheno=pd.read_csv(input_sample_sheet) sex_dict=defaultdict(lambda:'NA') sex_dict.update({'m':'M','f':'F','M':'M','F':'F','male':'M','female':'F','nan':'NA',np.nan:'NA'}) k='Sex' if 'Sex' in list(pheno) else 'sex' if k in list(pheno): pheno.loc[:,k] = pheno[k].map(lambda x: sex_dict[str(x).lower()]) pheno = pheno[[col for col in list(pheno) if not col.startswith('Unnamed:')]].rename(columns={'sex':'Sex'}) if 'Sex' in list(pheno): d=defaultdict(lambda:'NA') d.update({'M':'M','F':'F'}) pheno.loc[:,'Sex'] = pheno['Sex'].map(d) if (pheno['Sex']==pheno['Sex'].mode().values[0][0]).all(): pheno=pheno.rename(columns={'Sex':'gender'}) pheno.to_csv(output_sample_sheet) @preprocess.command() @click.option('-s1', '--sample_sheet1', default='./tcga_idats/clinical_info1.csv', help='Clinical information downloaded from tcga/geo/custom, formatted using create_sample_sheet.', type=click.Path(exists=False), show_default=True) @click.option('-s2', '--sample_sheet2', default='./tcga_idats/clinical_info2.csv', help='Clinical information downloaded from tcga/geo/custom, formatted using create_sample_sheet.', type=click.Path(exists=False), show_default=True) @click.option('-os', '--output_sample_sheet', default='./tcga_idats/minfiSheet.csv', help='CSV for minfi input.', type=click.Path(exists=False), show_default=True) @click.option('-d', '--second_sheet_disease', is_flag=True, help='Use second sheet\'s disease column.') @click.option('-nd', '--no_disease_merge', is_flag=True, help='Don\'t merge disease columns.') def merge_sample_sheets(sample_sheet1, sample_sheet2, output_sample_sheet, second_sheet_disease,no_disease_merge): """Merge two sample files for more fields for minfi+ input.""" s1 = PreProcessPhenoData(sample_sheet1, idat_dir='', header_line=0) s2 = PreProcessPhenoData(sample_sheet2, idat_dir='', header_line=0) s1.merge(s2,second_sheet_disease, no_disease_merge=no_disease_merge) s1.export(output_sample_sheet) @preprocess.command() @click.option('-s1', '--sample_sheet1', default='./tcga_idats/clinical_info1.csv', help='Clinical information downloaded from tcga/geo/custom, formatted using create_sample_sheet.', type=click.Path(exists=False), show_default=True) @click.option('-s2', '--sample_sheet2', default='./tcga_idats/clinical_info2.csv', help='Clinical information downloaded from tcga/geo/custom, formatted using create_sample_sheet.', type=click.Path(exists=False), show_default=True) @click.option('-os', '--output_sample_sheet', default='./tcga_idats/minfiSheet.csv', help='CSV for minfi input.', type=click.Path(exists=False), show_default=True) def concat_sample_sheets(sample_sheet1, sample_sheet2, output_sample_sheet): """Concat two sample files for more fields for minfi+ input, adds more samples.""" # FIXME add ability to concat more sample sheets; dump to sql!!! s1 = PreProcessPhenoData(sample_sheet1, idat_dir='', header_line=0) s2 = PreProcessPhenoData(sample_sheet2, idat_dir='', header_line=0) s1.concat(s2) s1.export(output_sample_sheet) @preprocess.command() @click.option('-is', '--formatted_sample_sheet', default='./tcga_idats/minfiSheet.csv', help='Clinical information downloaded from tcga/geo/custom, formatted using create_sample_sheet.', type=click.Path(exists=False), show_default=True) @click.option('-k', '--key', multiple=True, default=['disease'], help='Column of csv to print statistics for.', type=click.Path(exists=False), show_default=True) @click.option('-d', '--disease_only', is_flag=True, help='Only look at disease, or text before subtype_delimiter.') @click.option('-sd', '--subtype_delimiter', default=',', help='Delimiter for disease extraction.', type=click.Path(exists=False), show_default=True) def get_categorical_distribution(formatted_sample_sheet,key,disease_only=False,subtype_delimiter=','): """Get categorical distribution of columns of sample sheet.""" if len(key) == 1: key=key[0] print('\n'.join('{}:{}'.format(k,v) for k,v in PreProcessPhenoData(formatted_sample_sheet, idat_dir='', header_line=0).get_categorical_distribution(key,disease_only,subtype_delimiter).items())) @preprocess.command() @click.option('-is', '--formatted_sample_sheet', default='./tcga_idats/clinical_info.csv', help='Clinical information downloaded from tcga/geo/custom, formatted using create_sample_sheet.', type=click.Path(exists=False), show_default=True) @click.option('-e', '--exclude_disease_list', default='', help='List of conditions to exclude, from disease column, comma delimited.', type=click.Path(exists=False), show_default=True) @click.option('-os', '--output_sheet_name', default='./tcga_idats/minfiSheet.csv', help='CSV for minfi input.', type=click.Path(exists=False), show_default=True) @click.option('-l', '--low_count', default=0, help='Remove diseases if they are below a certain count, default this is not used.', type=click.Path(exists=False), show_default=True) @click.option('-d', '--disease_only', is_flag=True, help='Only look at disease, or text before subtype_delimiter.') @click.option('-sd', '--subtype_delimiter', default=',', help='Delimiter for disease extraction.', type=click.Path(exists=False), show_default=True) def remove_diseases(formatted_sample_sheet, exclude_disease_list, output_sheet_name, low_count, disease_only=False,subtype_delimiter=','): """Exclude diseases from study by count number or exclusion list.""" exclude_disease_list = exclude_disease_list.split(',') pData = PreProcessPhenoData(formatted_sample_sheet, idat_dir='', header_line=0) pData.remove_diseases(exclude_disease_list,low_count, disease_only,subtype_delimiter) pData.export(output_sheet_name) print("Please remove {} from idat directory, if it exists in that directory.".format(formatted_sample_sheet)) ## preprocess ## @preprocess.command() @click.option('-i', '--idat_csv', default='./tcga_idats/minfiSheet.csv', help='Idat csv for one sample sheet, alternatively can be your phenotype sample sheet.', type=click.Path(exists=False), show_default=True) @click.option('-d', '--disease_only', is_flag=True, help='Only look at disease, or text before subtype_delimiter.') @click.option('-sd', '--subtype_delimiter', default=',', help='Delimiter for disease extraction.', type=click.Path(exists=False), show_default=True) @click.option('-o', '--subtype_output_dir', default='./preprocess_outputs/', help='Output subtypes pheno csv.', type=click.Path(exists=False), show_default=True) def split_preprocess_input_by_subtype(idat_csv,disease_only,subtype_delimiter, subtype_output_dir): """Split preprocess input samplesheet by disease subtype.""" from collections import defaultdict subtype_delimiter=subtype_delimiter.replace('"','').replace("'","") os.makedirs(subtype_output_dir,exist_ok=True) pData=PreProcessPhenoData(idat_csv,'') idat_csv_basename = idat_csv.split('/')[-1] group_by_key = (pData.split_key('disease',subtype_delimiter) if disease_only else 'disease') pData_grouped = pData.pheno_sheet.groupby(group_by_key) default_qc_df=[] for name, group in pData_grouped: name=name.replace(' ','') new_sheet = idat_csv_basename.replace('.csv','_{}.csv'.format(name)) new_out_dir = '{}/{}/'.format(subtype_output_dir,name) os.makedirs(new_out_dir, exist_ok=True) print(new_out_dir) if 'Sex' in list(group): d=defaultdict(lambda:'NA') d.update({'M':'M','F':'F'}) group.loc[:,'Sex'] = group['Sex'].map(d) if (group['Sex']==group['Sex'].mode().values[0][0]).all(): group=group.rename(columns={'Sex':'gender'}) group.to_csv('{}/{}'.format(new_out_dir,new_sheet)) default_qc_df.append([name,-1,0.05,0.05,0.05,0.05,5,-2]) pd.DataFrame(default_qc_df,columns=['subtype','n_pcs','p_beadnum_samples','p_detection_samples','p_beadnum_cpgs','p_detection_cpgs','sex_sd','sex_cutoff']).to_csv(os.path.join(subtype_output_dir,'pc_qc_parameters.csv')) @preprocess.command() @click.option('-n', '--n_cores', default=6, help='Number cores to use for preprocessing.', show_default=True) @click.option('-i', '--subtype_output_dir', default='./preprocess_outputs/', help='Output subtypes pheno csv.', type=click.Path(exists=False), show_default=True) @click.option('-m', '--meffil', is_flag=True, help='Preprocess using meffil.') @click.option('-t', '--torque', is_flag=True, help='Job submission torque.') @click.option('-r', '--run', is_flag=True, help='Actually run local job or just print out command.') @click.option('-s', '--series', is_flag=True, help='Run commands in series.') @click.option('-p', '--pc_qc_parameters_csv', default='./preprocess_outputs/pc_qc_parameters.csv', show_default=True, help='For meffil, qc parameters and pcs for final qc and functional normalization.') @click.option('-u', '--use_cache', is_flag=True, help='If this is selected, loads qc results rather than running qc again. Only works for meffil selection.') @click.option('-qc', '--qc_only', is_flag=True, help='Only perform QC for meffil pipeline, caches results into rds file for loading again, only works if use_cache is false.') @click.option('-c', '--chunk_size', default=-1, help='If not series, chunk up and run these number of commands at once.. -1 means all commands at once.') def batch_deploy_preprocess(n_cores,subtype_output_dir,meffil,torque,run,series, pc_qc_parameters_csv, use_cache, qc_only, chunk_size): """Deploy multiple preprocessing jobs in series or parallel.""" pheno_csvs = glob.glob(os.path.join(subtype_output_dir,'*','*.csv')) opts = {'-n':n_cores} try: pc_qc_parameters = pd.read_csv(pc_qc_parameters).drop_duplicates().set_index('subtype') except: pc_qc_parameters = pd.DataFrame([[name,-1,0.05,0.05,0.05,0.05,5,-2] for name in np.vectorize(lambda x: x.split('/')[-2])(pheno_csvs)], columns=['subtype','n_pcs','p_beadnum_samples','p_detection_samples','p_beadnum_cpgs','p_detection_cpgs','sex_sd','sex_cutoff']).drop_duplicates().set_index('subtype') if meffil: opts['-m']='' if use_cache: opts['-u']='' if qc_only: opts['-qc']='' commands=[] for pheno_csv in pheno_csvs: pheno_path = os.path.abspath(pheno_csv) subtype=pheno_path.split('/')[-2] opts['-pc'] = int(pc_qc_parameters.loc[subtype,'n_pcs']) opts['-bns'] = pc_qc_parameters.loc[subtype,'p_beadnum_samples'] opts['-pds'] = pc_qc_parameters.loc[subtype,'p_detection_samples'] opts['-bnc'] = pc_qc_parameters.loc[subtype,'p_beadnum_cpgs'] opts['-pdc'] = pc_qc_parameters.loc[subtype,'p_detection_cpgs'] opts['-sc'] = pc_qc_parameters.loc[subtype,'sex_cutoff'] opts['-sd'] = pc_qc_parameters.loc[subtype,'sex_sd'] opts['-i']=pheno_path[:pheno_path.rfind('/')+1] opts['-o']=pheno_path[:pheno_path.rfind('/')+1]+'methyl_array.pkl' command='pymethyl-preprocess preprocess_pipeline {}'.format(' '.join('{} {}'.format(k,v) for k,v in opts.items())) commands.append(command) if not torque: if not series and chunk_size != -1: #commands = np.array_split(commands,len(commands)//chunk_size) print(commands) with open('commands.txt','w') as f: f.write('\n'.join(commands)) subprocess.call('cat commands.txt | xargs -L 1 -I CMD -P {} bash -c CMD'.format(chunk_size),shell=True) # https://www.gnu.org/software/parallel/sem.html """for command_list in commands: subprocess.call('run_parallel {}'.format(' '.join(['"{}"'.format(command) for command in command_list])),shell=True)""" else: for command in commands: if not series: command="nohup {} &".format(command) if not run: click.echo(command) else: subprocess.call(command,shell=True) else: run_command = lambda command: subprocess.call('module load cuda && module load python/3-Anaconda && source activate py36 && {}'.format(command),shell=True) from pyina.schedulers import Torque from pyina.launchers import Mpi config = {'nodes':'1:ppn=6', 'queue':'default', 'timelimit':'01:00:00'} torque = Torque(**config) pool = Mpi(scheduler=torque) pool.map(run_command, commands) @preprocess.command() @click.option('-i', '--idat_dir', default='./tcga_idats/', help='Idat dir for one sample sheet, alternatively can be your phenotype sample sheet.', type=click.Path(exists=False), show_default=True) @click.option('-n', '--n_cores', default=6, help='Number cores to use for preprocessing.', show_default=True) @click.option('-o', '--output_pkl', default='./preprocess_outputs/methyl_array.pkl', help='Output database for beta and phenotype data.', type=click.Path(exists=False), show_default=True) @click.option('-m', '--meffil', is_flag=True, help='Preprocess using meffil.') @click.option('-pc', '--n_pcs', default=-1, show_default=True, help='For meffil, number of principal components for functional normalization. If set to -1, then PCs are selected using elbow method.') @click.option('-p', '--pipeline', default='enmix', show_default=True, help='If not meffil, preprocess using minfi or enmix.', type=click.Choice(['minfi','enmix'])) @click.option('-noob', '--noob_norm', is_flag=True, help='Run noob normalization of minfi selected.') @click.option('-u', '--use_cache', is_flag=True, help='If this is selected, loads qc results rather than running qc again and update with new qc parameters. Only works for meffil selection. Minfi and enmix just loads RG Set.') @click.option('-qc', '--qc_only', is_flag=True, help='Only perform QC for meffil pipeline, caches results into rds file for loading again, only works if use_cache is false. Minfi and enmix just saves the RGSet before preprocessing.') @click.option('-bns', '--p_beadnum_samples', default=0.05, show_default=True, help='From meffil documentation, "fraction of probes that failed the threshold of 3 beads".') @click.option('-pds', '--p_detection_samples', default=0.05, show_default=True, help='From meffil documentation, "fraction of probes that failed a detection.pvalue threshold of 0.01".') @click.option('-bnc', '--p_beadnum_cpgs', default=0.05, show_default=True, help='From meffil documentation, "fraction of samples that failed the threshold of 3 beads".') @click.option('-pdc', '--p_detection_cpgs', default=0.05, show_default=True, help='From meffil documentation, "fraction of samples that failed a detection.pvalue threshold of 0.01".') @click.option('-sc', '--sex_cutoff', default=-2, show_default=True, help='From meffil documentation, "difference of total median intensity for Y chromosome probes and X chromosome probes".') @click.option('-sd', '--sex_sd', default=5, show_default=True, help='From meffil documentation, "sex detection outliers if outside this range".') def preprocess_pipeline(idat_dir, n_cores, output_pkl, meffil, n_pcs, pipeline, noob_norm, use_cache, qc_only, p_beadnum_samples, p_detection_samples, p_beadnum_cpgs, p_detection_cpgs, sex_cutoff, sex_sd): """Perform preprocessing of idats using enmix or meffil.""" output_dir = output_pkl[:output_pkl.rfind('/')] os.makedirs(output_dir,exist_ok=True) preprocesser = PreProcessIDAT(idat_dir) if meffil: qc_parameters={'p.beadnum.samples':p_beadnum_samples,'p.detection.samples':p_detection_samples,'p.detection.cpgs':p_detection_cpgs,'p.beadnum.cpgs':p_beadnum_cpgs,'sex.cutoff':sex_cutoff, 'sex.outlier.sd':sex_sd} preprocesser.preprocessMeffil(n_cores=n_cores,n_pcs=n_pcs,qc_report_fname=os.path.join(output_dir,'qc.report.html'), normalization_report_fname=os.path.join(output_dir,'norm.report.html'), pc_plot_fname=os.path.join(output_dir,'pc.plot.pdf'), useCache=use_cache, qc_only=qc_only, qc_parameters=qc_parameters) else: preprocesser.preprocess_enmix_pipeline(n_cores=n_cores, pipeline=pipeline, noob=noob_norm, use_cache=use_cache, qc_only=qc_only) try: preprocesser.plot_qc_metrics(output_dir) except: pass preprocesser.output_pheno_beta(meffil=meffil) preprocesser.to_methyl_array('').write_pickle(output_pkl) @preprocess.command() @click.option('-i', '--input_pkls', default=['./preprocess_outputs/methyl_array.pkl'], multiple=True, help='Input pickles for beta and phenotype data.', type=click.Path(exists=False), show_default=True) @click.option('-d', '--optional_input_pkl_dir', default='', help='Auto grab input pkls.', type=click.Path(exists=False), show_default=True) @click.option('-o', '--output_pkl', default='./combined_outputs/methyl_array.pkl', help='Output database for beta and phenotype data.', type=click.Path(exists=False), show_default=True) @click.option('-e', '--exclude', default=[], multiple=True, help='If -d selected, these diseases will be excluded from study.', show_default=True) def combine_methylation_arrays(input_pkls, optional_input_pkl_dir, output_pkl, exclude): """If split MethylationArrays by subtype for either preprocessing or imputation, can use to recombine data for downstream step.""" os.makedirs(output_pkl[:output_pkl.rfind('/')],exist_ok=True) if optional_input_pkl_dir: input_pkls=glob.glob(os.path.join(optional_input_pkl_dir,'*','methyl_array.pkl')) if exclude: input_pkls=(
np.array(input_pkls)
numpy.array
import numpy as np from pyquil.simulation.matrices import ( QUANTUM_GATES, relaxation_operators, dephasing_operators, depolarizing_operators, bit_flip_operators, phase_flip_operators, bitphase_flip_operators, ) def test_singleq(): assert np.isclose(QUANTUM_GATES["I"], np.eye(2)).all() assert np.isclose(QUANTUM_GATES["X"], np.array([[0, 1], [1, 0]])).all() assert np.isclose(QUANTUM_GATES["Y"], np.array([[0, -1j], [1j, 0]])).all() assert np.isclose(QUANTUM_GATES["Z"], np.array([[1, 0], [0, -1]])).all() assert np.isclose(QUANTUM_GATES["H"], (1.0 / np.sqrt(2)) * np.array([[1, 1], [1, -1]])).all() assert np.isclose(QUANTUM_GATES["S"], np.array([[1.0, 0], [0, 1j]])).all() assert np.isclose(QUANTUM_GATES["T"], np.array([[1.0, 0.0], [0.0, np.exp(1.0j * np.pi / 4.0)]])).all() def test_parametric(): phi_range = np.linspace(0, 2 * np.pi, 120) for phi in phi_range: assert np.isclose(QUANTUM_GATES["PHASE"](phi), np.array([[1.0, 0.0], [0.0, np.exp(1j * phi)]])).all() assert np.isclose( QUANTUM_GATES["RX"](phi), np.array( [ [np.cos(phi / 2.0), -1j * np.sin(phi / 2.0)], [-1j * np.sin(phi / 2.0), np.cos(phi / 2.0)], ] ), ).all() assert np.isclose( QUANTUM_GATES["RY"](phi), np.array([[np.cos(phi / 2.0), -np.sin(phi / 2.0)], [np.sin(phi / 2.0), np.cos(phi / 2.0)]]), ).all() assert np.isclose( QUANTUM_GATES["RZ"](phi), np.array( [ [np.cos(phi / 2.0) - 1j *
np.sin(phi / 2.0)
numpy.sin
# -*- coding: utf-8 -*- """ Created on Thu Oct 4 13:30:06 2018 @author: gregz """ import time import numpy as np import os.path as op import glob import warnings from astropy.io import fits from utils import biweight_location from scipy.signal import savgol_filter, medfilt2d from scipy.interpolate import interp1d, interp2d from input_utils import setup_logging from astrometry import Astrometry dither_pattern = np.array([[0., 0.], [1.27, -0.73], [1.27, 0.73]]) virus_amps = ['LL', 'LU', 'RU', 'RL'] lrs2_amps = [['LL', 'LU'], ['RL', 'RU']] fplane_file = '/work/03730/gregz/maverick/fplane.txt' flt_obs = '%07d' % 15 twi_obs = '%07d' % 1 sci_obs = '%07d' % 13 twi_date = '20170205' sci_date = twi_date flt_date = twi_date # FOR LRS2 instrument = 'lrs2' AMPS = lrs2_amps[0] dither_pattern = np.zeros((10, 2)) log = setup_logging('panacea_quicklook') basered = '/work/03730/gregz/maverick' baseraw = '/work/03946/hetdex/maverick' twi_path = op.join(basered, 'reductions', twi_date, '%s', '%s%s', 'exp01', '%s', 'multi_*_%s_*_LL.fits') sci_path = op.join(baseraw, sci_date, '%s', '%s%s', 'exp%s', '%s', '2*_%sLL*.fits') flt_path = op.join(baseraw, flt_date, '%s', '%s%s', 'exp*', '%s', '2*_%sLL*.fits') sciflt_path = op.join(baseraw, twi_date, '%s', '%s%s', 'exp*', '%s', '2*_%sLL_twi.fits') bias_path = op.join(baseraw, twi_date, '%s', '%s%s', 'exp*', '%s', '2*_%sLL_zro.fits') def get_cal_info(twi_path, amp): F = fits.open(glob.glob(twi_path.replace('LL', amp))[0]) return (np.array(F['ifupos'].data, dtype=float), np.array(F['trace'].data, dtype=float), np.array(F['wavelength'].data, dtype=float)) def orient_image(image, amp, ampname): ''' Orient the images from blue to red (left to right) Fibers are oriented to match configuration files ''' if amp == "LU": image[:] = image[::-1, ::-1] if amp == "RL": image[:] = image[::-1, ::-1] if ampname is not None: if ampname == 'LR' or ampname == 'UL': image[:] = image[:, ::-1] return image def make_avg_spec(wave, spec, binsize=35, per=50): ind = np.argsort(wave.ravel()) T = 1 for p in wave.shape: T *= p wchunks = np.array_split(wave.ravel()[ind], T / binsize) schunks = np.array_split(spec.ravel()[ind], T / binsize) nwave = np.array([np.mean(chunk) for chunk in wchunks]) nspec = np.array([np.percentile(chunk, per) for chunk in schunks]) nwave, nind = np.unique(nwave, return_index=True) return nwave, nspec[nind] def base_reduction(filename): a = fits.open(filename) image = np.array(a[0].data, dtype=float) # overscan sub overscan_length = 32 * (image.shape[1] / 1064) O = biweight_location(image[:, -(overscan_length-2):]) image[:] = image - O # trim image image = image[:, :-overscan_length] try: ampname = a[0].header['AMPNAME'] except: ampname = None a = orient_image(image, amp, ampname) return a def get_sciflat_field(flt_path, amp, array_wave, array_trace, common_wave, masterbias, log): files = glob.glob(flt_path.replace('LL', amp)) listflat = [] array_flt = base_reduction(files[0]) bigW = np.zeros(array_flt.shape) Y, X = np.indices(array_wave.shape) YY, XX = np.indices(array_flt.shape) for x, at, aw, xx, yy in zip(np.array_split(X, 2, axis=0), np.array_split(array_trace, 2, axis=0), np.array_split(array_wave, 2, axis=0), np.array_split(XX, 2, axis=0), np.array_split(YY, 2, axis=0)): for j in np.arange(at.shape[1]): with warnings.catch_warnings(): warnings.simplefilter("ignore") p0 = np.polyfit(at[:, j], aw[:, j], 7) bigW[yy[:, j], j] = np.polyval(p0, yy[:, j]) listspec = [] for filename in files: log.info('Working on sciflat %s' % filename) array_flt = base_reduction(filename) - masterbias x = np.arange(array_wave.shape[1]) spectrum = array_trace * 0. for fiber in np.arange(array_wave.shape[0]): indl = np.floor(array_trace[fiber]).astype(int) indh = np.ceil(array_trace[fiber]).astype(int) spectrum[fiber] = array_flt[indl, x] / 2. + array_flt[indh, x] / 2. smooth = savgol_filter(spectrum, 315, 1, axis=1) avg = biweight_location(smooth, axis=(0,)) norm = biweight_location(smooth / avg, axis=(1,)) nw, ns = make_avg_spec(array_wave, spectrum / norm[:, np.newaxis], binsize=41, per=95) I = interp1d(nw, ns, kind='linear', fill_value='extrapolate') ftf = spectrum * 0. for fiber in np.arange(array_wave.shape[0]): model = I(array_wave[fiber]) ftf[fiber] = savgol_filter(spectrum[fiber] / model, 151, 1) nw1, ns1 = make_avg_spec(array_wave, spectrum / ftf, binsize=41, per=95) I = interp1d(nw1, ns1, kind='quadratic', fill_value='extrapolate') modelimage = I(bigW) flat = array_flt / modelimage listflat.append(flat) listspec.append(I(common_wave)) flat = np.median(listflat, axis=(0,)) flat[~np.isfinite(flat)] = 0.0 flat[flat < 0.0] = 0.0 return flat, bigW, np.nanmedian(listspec, axis=0) def safe_division(num, denom, eps=1e-8, fillval=0.0): good = np.isfinite(denom) * (np.abs(denom) > eps) div = num * 0. if num.ndim == denom.ndim: div[good] = num[good] / denom[good] div[~good] = fillval else: div[:, good] = num[:, good] / denom[good] div[:, ~good] = fillval return div def find_cosmics(Y, E, thresh=8.): A = medfilt2d(Y, (5, 1)) S = safe_division((Y - A), E) P = S - medfilt2d(S, (1, 15)) x, y = np.where(P > thresh) xx, yy = ([], []) for i in np.arange(-1, 2): for j in np.arange(-1, 2): sel = ((x + i) >= 0) * ((x + i) < Y.shape[0]) sel2 = ((y + j) >= 0) * ((y + j) < Y.shape[1]) sel = sel * sel2 xx.append((x + i)[sel]) yy.append((y + j)[sel]) xx = np.hstack(xx) yy = np.hstack(yy) inds = np.ravel_multi_index([xx, yy], Y.shape) inds = np.unique(inds) C = np.zeros(Y.shape, dtype=bool).ravel() C[inds] = True C = C.reshape(Y.shape) log.info('Number of pixels affected by cosmics: %i' % len(x)) log.info('Fraction of pixels affected by cosmics: %0.5f' % (1.*len(inds)/Y.shape[0]/Y.shape[1])) return C def weighted_extraction(image, flat, trace): gain = 0.83 rdnoise = 3. I = image * 1. I[I < 0.] = 0. E = np.sqrt(rdnoise**2 + gain * I) / gain E = safe_division(E, flat) E[E < 1e-8] = 1e9 Y = safe_division(image, flat) cosmics = find_cosmics(Y, E) x = np.arange(trace.shape[1]) spectrum = 0. * trace TT = np.zeros((trace.shape[0], 3, trace.shape[1], 4)) for fiber in np.arange(trace.shape[0]): T = np.zeros((3, trace.shape[1], 4)) indl = np.floor(trace[fiber]).astype(int) flag = False for ss, k in enumerate(np.arange(-1, 3)): try: T[0, :, ss] = Y[indl+k, x] T[1, :, ss] = 1. / E[indl+k, x]**2 T[2, :, ss] = ~cosmics[indl+k, x] except: v = indl+k sel = np.where((v >= 0) * (v < Y.shape[0]))[0] T[0, sel, ss] = Y[v[sel], x[sel]] T[1, sel, ss] = 1. / E[v[sel], x[sel]]**2 T[2, sel, ss] = ~cosmics[v[sel], x[sel]] flag = True if flag: if np.mean(indl) > (Y.shape[0]/2.): k = 2 else: k = -1 v = indl+k sel = np.where((v >= 0) * (v < len(x)))[0] a = np.sum(T[0, sel] * T[1, sel] * T[2, sel], axis=1) b = np.sum(T[1, sel] * T[2, sel], axis=1) spectrum[fiber, sel] = safe_division(a, b) else: a = np.sum(T[0] * T[1] * T[2], axis=1) b = np.sum(T[1] * T[2], axis=1) spectrum[fiber] = safe_division(a, b) TT[fiber] = T fits.PrimaryHDU(TT).writeto('wtf2.fits', overwrite=True) return spectrum def get_trace_shift(sci_array, flat, array_trace, Yx): YM, XM = np.indices(flat.shape) inds = np.zeros((3, array_trace.shape[0], array_trace.shape[1])) XN = np.round(array_trace) inds[0] = XN - 1. inds[1] = XN + 0. inds[2] = XN + 1. inds = np.array(inds, dtype=int) Trace = array_trace * 0. FlatTrace = array_trace * 0. N = YM.max() x = np.arange(array_trace.shape[1]) for i in np.arange(Trace.shape[0]): sel = YM[inds[0, i, :], x] >= 0. sel = sel * (YM[inds[2, i, :], x] < N) xmax = (YM[inds[1, i, sel], x[sel]] - (sci_array[inds[2, i, sel], x[sel]] - sci_array[inds[0, i, sel], x[sel]]) / (2. * (sci_array[inds[2, i, sel], x[sel]] - 2. * sci_array[inds[1, i, sel], x[sel]] + sci_array[inds[0, i, sel], x[sel]]))) Trace[i, sel] = xmax xmax = (YM[inds[1, i, sel], x[sel]] - (flat[inds[2, i, sel], x[sel]] - flat[inds[0, i, sel], x[sel]]) / (2. * (flat[inds[2, i, sel], x[sel]] - 2. * flat[inds[1, i, sel], x[sel]] + flat[inds[0, i, sel], x[sel]]))) FlatTrace[i, sel] = xmax shifts = np.nanmedian(FlatTrace - Trace, axis=1) shifts = np.polyval(np.polyfit(np.nanmedian(FlatTrace, axis=1), shifts, 1), Yx) fits.HDUList([fits.PrimaryHDU(FlatTrace), fits.ImageHDU(Trace)]).writeto('test_trace.fits', overwrite=True) return shifts def subtract_sci(sci_path, flat, array_trace, array_wave, bigW, masterbias): files = sorted(glob.glob(sci_path.replace('LL', amp))) array_list = [] for filename in files: log.info('Skysubtracting sci %s' % filename) array_flt = base_reduction(filename) - masterbias array_list.append(array_flt) sci_array = np.sum(array_list, axis=0) Xx = np.arange(flat.shape[1]) Yx =
np.arange(flat.shape[0])
numpy.arange
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.3.1 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Optimization benchmarking # Plotting benchmark result. # + import sys import numpy as np import matplotlib.pyplot as plt import seaborn as sns import copy sys.path.append('../') from qwopt.compiler import composer from qwopt.benchmark import fidelity as fid from numpy import pi from qiskit import transpile from qiskit import QuantumRegister, QuantumCircuit, ClassicalRegister from qiskit import Aer, execute from qiskit.providers.aer.noise import NoiseModel from qiskit.providers.aer.noise.errors import depolarizing_error from tqdm import tqdm, trange from mpl_toolkits.mplot3d import Axes3D import warnings warnings.simplefilter('ignore') # - # ## 1. Multi step of 4 node graph with one partition # ## Target graph and probability transition matrix # + alpha = 0.85 target_graph = np.array([[0, 1, 0, 1], [0, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]) E = np.array([[1/4, 1/2, 0, 1/2], [1/4, 0, 1/2, 0], [1/4, 1/2, 0, 1/2], [1/4, 0, 1/2, 0]]) # use google matrix prob_dist = alpha*E + ((1-alpha)/4)*np.ones((4, 4)) init_state = 1/2*np.array([np.sqrt(prob_dist[j][i]) for i in range(4) for j in range(4)]) # - # ### Check points # - How to decrease the fidelity over the number of steps # - The number of operations # ### Count operations # #### Without any optimizations # + # Circuit def four_node(opt, step): rotation = np.radians(31.788) cq = QuantumRegister(2, 'control') tq = QuantumRegister(2, 'target') c = ClassicalRegister(2, 'classical') if opt: anc = QuantumRegister(2, 'ancilla') qc = QuantumCircuit(cq, tq, anc, c) else: qc = QuantumCircuit(cq, tq, c) # initialize with probability distribution matrix initial = 1/2*np.array([np.sqrt(prob_dist[j][i]) for i in range(4) for j in range(4)]) qc.initialize(initial, [*cq, *tq]) for t in range(step): # Ti operation qc.x(cq[1]) qc.ccx(cq[0], cq[1], tq[1]) qc.x(cq[1]) qc.barrier() # Kdg operation if opt: qc.x(cq) qc.rccx(cq[0], cq[1], anc[0]) qc.barrier() qc.ch(anc[0], tq[0]) qc.ch(anc[0], tq[1]) qc.x(anc[0]) qc.cry(-rotation, anc[0], tq[1]) qc.ch(anc[0], tq[0]) qc.barrier() else: qc.x(cq) qc.mcry(-pi/2, cq, tq[0], None) qc.mcry(-pi/2, cq, tq[1], None) qc.x(cq) qc.barrier() # qc.x(cq[1]) # qc.mcry(-pi/2, cq, tq[0], None) # qc.mcry(-rotation, cq, tq[1], None) # qc.x(cq[1]) # qc.barrier() qc.x(cq[0]) qc.mcry(-pi/2, cq, tq[0], None) qc.mcry(-rotation, cq, tq[1], None) qc.x(cq[0]) qc.barrier() qc.cry(-pi/2, cq[0], tq[0]) qc.cry(-rotation, cq[0], tq[1]) qc.barrier() # qc.mcry(-pi/2, cq, tq[0], None) # qc.mcry(-rotation, cq, tq[1], None) # qc.barrier() # D operation qc.x(tq) qc.cz(tq[0], tq[1]) qc.x(tq) qc.barrier() # K operation if opt: qc.ch(anc[0], tq[0]) qc.cry(rotation, anc[0], tq[1]) qc.x(anc[0]) qc.ch(anc[0], tq[1]) qc.ch(anc[0], tq[0]) qc.rccx(cq[0], cq[1], anc[0]) qc.x(cq) qc.barrier() else: # previous, and naive imple # qc.mcry(pi/2, cq, tq[0], None) # qc.mcry(rotation, cq, tq[1], None) # qc.barrier() qc.cry(pi/2, cq[0], tq[0]) qc.cry(rotation, cq[0], tq[1]) qc.barrier() qc.x(cq[0]) qc.mcry(pi/2, cq, tq[0], None) qc.mcry(rotation, cq, tq[1], None) qc.x(cq[0]) qc.barrier() # qc.x(cq[1]) # qc.mcry(pi/2, cq, tq[0], None) # qc.mcry(rotation, cq, tq[1], None) # qc.x(cq[1]) # qc.barrier() qc.x(cq) qc.mcry(pi/2, cq, tq[0], None) qc.mcry(pi/2, cq, tq[1], None) qc.x(cq) qc.barrier() # Tidg operation qc.x(cq[1]) qc.ccx(cq[0], cq[1], tq[1]) qc.x(cq[1]) qc.barrier() # swap qc.swap(tq[0], cq[0]) qc.swap(tq[1], cq[1]) qc.measure(tq, c) return qc # - qc = four_node(True, 1) backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend=backend, shots=10000) count = job.result().get_counts(qc) print(count) qc.draw(output='mpl') # ### The number of operations in steps # + ex1_cx = [] ex1_u3 = [] ex2_cx = [] ex2_u3 = [] ex3_cx = [] ex3_u3 = [] ex4_cx = [] ex4_u3 = [] for step in trange(1, 11): opt_qc = transpile(four_node(True, step), basis_gates=['cx', 'u3'], optimization_level=0) ncx = opt_qc.count_ops().get('cx', 0) nu3 = opt_qc.count_ops().get('u3', 0) + opt_qc.count_ops().get('u2', 0) + opt_qc.count_ops().get('u1', 0) ex1_cx.append(ncx) ex1_u3.append(nu3) # ex2 opt_qc = transpile(four_node(True, step), basis_gates=['cx', 'u3'], optimization_level=3) ncx = opt_qc.count_ops().get('cx', 0) nu3 = opt_qc.count_ops().get('u3', 0) + opt_qc.count_ops().get('u2', 0) + opt_qc.count_ops().get('u1', 0) ex2_cx.append(ncx) ex2_u3.append(nu3) # ex3 opt_qc = transpile(four_node(False, step), basis_gates=['cx', 'u3'], optimization_level=3) ncx = opt_qc.count_ops().get('cx', 0) nu3 = opt_qc.count_ops().get('u3', 0) + opt_qc.count_ops().get('u2', 0) + opt_qc.count_ops().get('u1', 0) ex3_cx.append(ncx) ex3_u3.append(nu3) # ex4 nopt_qc = transpile(four_node(False, step), basis_gates=['cx', 'u3'], optimization_level=0) ncx = nopt_qc.count_ops().get('cx', 0) nu3 = nopt_qc.count_ops().get('u3', 0) + nopt_qc.count_ops().get('u2', 0) + nopt_qc.count_ops().get('u1', 0) ex4_cx.append(ncx) ex4_u3.append(nu3) # - cx = [ex1_cx, ex2_cx, ex3_cx, ex4_cx] u3 = [ex1_u3, ex2_u3, ex3_u3, ex4_u3] # color = ['#C23685', '#E38692', '#6BBED5', '#3EBA2B'] # labels = ['with my optimizations', 'with my and qiskit optimizations', 'with qiskit optimizations', 'without optimizations'] steps = range(1, 11) fig = plt.figure(figsize=(20, 10)) ax = fig.add_subplot(111) sns.set() plt.xlabel('the number of steps', fontsize=30) plt.xticks([i for i in range(11)]) plt.ylabel('the number of operations', fontsize=30) plt.title('the nuber of operations over steps', fontsize=30) plt.tick_params(labelsize=20) plt.plot(steps, ex4_cx, color='#3EBA2B', label='# of CX without optimizations', linewidth=3) plt.plot(steps, ex4_u3, color='#6BBED5', label='# of single qubit operations without optimizations', linewidth=3) plt.legend(fontsize=25) cx = [ex1_cx, ex2_cx, ex3_cx, ex4_cx] u3 = [ex1_u3, ex2_u3, ex3_u3, ex4_u3] color = ['#C23685', '#E38692', '#6BBED5', '#3EBA2B'] labels = ['with my optimizations', 'with my and qiskit optimizations', 'with qiskit optimizations', 'without optimizations'] steps = range(1, 11) fig = plt.figure(figsize=(20, 10)) ax = fig.add_subplot(111) sns.set() plt.xlabel('the number of steps', fontsize=30) plt.xticks([i for i in range(11)]) plt.ylabel('the number of cx', fontsize=30) plt.title('the nuber of operations over steps', fontsize=30) plt.tick_params(labelsize=20) print(list(steps)) for cs, col, lab in zip(cx, color, labels): plt.plot(steps, cs, color=col, label=lab, linewidth=3) plt.legend(fontsize=25) # ## Error rate transition import warnings warnings.simplefilter('ignore') # + qasm_sim = Aer.get_backend('qasm_simulator') def KL_divergence(p, q, torelance=10e-9): ''' p: np.array or list q: np.array or list ''' parray =
np.array(p)
numpy.array
import os.path import numpy as np import itertools import Tools from scipy import signal #from pylab import figure, clf, plot, xlabel, ylabel, xlim, ylim, title, grid, axes, show,semilogx, semilogy import math # Those patterns are used for tests and benchmarks. # For tests, there is the need to add tests for saturation def cartesian(*somelists): r=[] for element in itertools.product(*somelists): r.append(element) return(r) def writeBenchmarks(config): NBSAMPLES=512 # 512 for stereo NUMSTAGES = 4 samples=np.random.randn(NBSAMPLES) coefs=np.random.randn(NUMSTAGES*5) samples = Tools.normalize(samples) coefs = Tools.normalize(coefs) # Used for benchmarks config.writeInput(1, samples,"Samples") config.writeInput(1, coefs,"Coefs") def getCoefs(n,sos,format): if format==15: coefs=np.reshape(np.hstack((np.insert(sos[:,:3],1,0.0,axis=1),-sos[:,4:])),n*6) else: coefs=np.reshape(np.hstack((sos[:,:3],-sos[:,4:])),n*5) if format==31: # Postshift must be 2 in the tests coefs = coefs / 4.0 if format==15: # Postshift must be 2 in the tests coefs = coefs / 4.0 return(coefs) def genSos(numTaps): zeros=[] poles=[] for i in range(0,numTaps): phase = np.random.rand()*2.0 * math.pi z = np.exp(1j*phase) phase = np.random.rand()*2.0 * math.pi amplitude = np.random.rand()*0.7 p = np.exp(1j*phase) * amplitude zeros += [z,np.conj(z)] poles += [p,np.conj(p)] g = 0.02 sos = signal.zpk2sos(zeros,poles,g) return(sos) def writeTests(config,format): # Write test with fixed and known patterns NB = 100 t = np.linspace(0, 1,NB) sig = Tools.normalize(np.sin(2*np.pi*5*t)+np.random.randn(len(t)) * 0.2 + 0.4*np.sin(2*np.pi*20*t)) if format==31: sig = 1.0*sig / (1 << 2) #if format==15: # sig = 1.0*sig / 2.0 p0 = np.exp(1j*0.05) * 0.98 p1 = np.exp(1j*0.25) * 0.9 p2 = np.exp(1j*0.45) * 0.97 z0 = np.exp(1j*0.02) z1 = np.exp(1j*0.65) z2 = np.exp(1j*1.0) g = 0.02 sos = signal.zpk2sos( [z0,np.conj(z0),z1,np.conj(z1),z2,np.conj(z2)] ,[p0, np.conj(p0),p1, np.conj(p1),p2, np.conj(p2)] ,g) coefs=getCoefs(3,sos,format) res=signal.sosfilt(sos,sig) config.writeInput(1, sig,"BiquadInput") config.writeInput(1, res,"BiquadOutput") config.writeInput(1, coefs,"BiquadCoefs") #if format==0: # figure() # plot(sig) # figure() # plot(res) # show() # Now random patterns to test different tail sizes # and number of loops numStages = [Tools.loopnb(format,Tools.TAILONLY), Tools.loopnb(format,Tools.BODYONLY), Tools.loopnb(format,Tools.BODYANDTAIL) ] blockSize=[Tools.loopnb(format,Tools.TAILONLY), Tools.loopnb(format,Tools.BODYONLY), Tools.loopnb(format,Tools.BODYANDTAIL) ] allConfigs = cartesian(numStages, blockSize) allconf=[] allcoefs=[] allsamples=[] allStereo=[] alloutputs=[] allStereoOutputs=[] for (n,b) in allConfigs: samples=
np.random.randn(b)
numpy.random.randn
from .ldft_model import LdftModel import numpy as np import scipy.optimize as op import matplotlib.pyplot as plt from functools import reduce class LG2dAOHighl(LdftModel): """This class describes a single component lattice gas in 2d with sticky next neighbour attractions on a simple cubic lattice. The description is done within the framework of lattice density functional theory (ldft). The free energy functional was constructed by translating the model to the Asakura-Oosawa (AO) model and then setting up the functional of the resulting colloid-polymer dispersion by the Highlander version of dft. Therefor this class works with three species instead of one, namely the species of the extended AO-model (colloid, polymer clusters species accounting for attraction in x-direction and polymer for the attraction in y-direction). The free energy functional is the one for the three species. It differs from the free energy functional of the AO-model just by a correction term accounting for the zero- and one-body interaction of the polymers. If one wants the free energy of the lattice gas, one would have to calculate the semi-grand potential of the previous free energy, where the polymer clusters are treated grand-canonically and the colloids canonically. In this class extra functions are supported for this. The colloids correspond to the species in the lattice gas. Parameters ---------- size : `tuple` of `int` Shape of the systems simulation box. Expects a `Tuple` of two integers, each for one dimensional axis. epsi : `float` Attraction strength of the lattice gas particles (multiplied with the inverse temperature to make it's dimension 1). From this the value of the chemical potential of the polymer clusters is calculated. mu_fix_c : `bool`, optional: default = False Determines whether or not the system is treated canonical or grand canonical. Meant is the lattice gas system. This parameter therefore only steers the colloid-species. The others are set `True` by default. `False` for canonical. mu_c : `float`, optional: default = `None` The chemical potential for the colloid species (multiplied with the inverse temperature to make it's dimension 1). Just required when ``mu_fix==True``. The chemical potential of the polymer clusters is determined by the value of ``epsi``. dens_c : `float`, optional: default = `None` The average density of the colloids. Just required when ``mu_fix``==`False`. The average density of the polymer clusters is not required, as for those ``mu_fix`` is set `True`. v_ext_c : `numpy.ndarray`, optional: default=`None` An external potential for the colloids. Shape must be of the same shape as chosen in ``size``. This class does not consider the possibility of sticky walls. Therefore the external potential of polymers is set zero by default. bound_cond : `string`, optional: default='periodic' The boundary condition. Supports 'periodic' for periodic boundary conditions and '11_if' for a 45° tilted system with respect to the lattice. The latter is for creating slab interface with (11) orientation. If '11_if' is chosen then one dimension has to be chosen twice as the other dimension in the ``size`` parameter e.g. (64, 128). Default value is 'periodic'. r : `List` of `np.array`; Optional: default = `None` Density profile for all three species arranged in a `List`. Choose `None` in case you hand over the ``r_hist``-parameter or in case you do not want to set the variable yet. r_hist : `List` of `List` of `np.array`; Optional: default = `None` Picard-history of a density profile. It contains the density profiles for certain picard-steps of a system which has already been evolved through picard iteration. Caution! Every entry is of the format of the ``_r``-instance variable, which is a list itself containing the profile for each species. Therefore in our case the list is of length one. Use `None` if the system has no history yet. err_hist : `List` of `Tuple` of `Float`; Optional: default = `None` Contains the error at the picard-steps corresponding to the entries of `r_hist`. The entries are tuples containing an error for every species. Use `None` if no history available. it_hist : `List`; Optional: default = `None` List of the picard-steps corresponding to the density profiles at the ``r_hist``-parameter. Use `None` if no history available. Note: if ``r_hist`` is given then also this argument should be assigned with an appropriate list. """ def __init__(self, size, epsi, mu_fix_c=False, mu_c=None,\ dens_c=None, v_ext_c=None, bound_cond='periodic', r=None,\ r_hist=None, err_hist=None, it_hist=None): mu_pc=self.translate_epsi_to_mu_pc(epsi) v_ext_pc = np.zeros(size) v_ext_c = v_ext_pc if type(v_ext_c)==type(None) else v_ext_c super().__init__(size=size, mu_fix=[mu_fix_c, True, True], mu=[mu_c, mu_pc, mu_pc], dens=[dens_c, None, None], v_ext=[v_ext_c, v_ext_pc, v_ext_pc], r=r, r_hist=r_hist, err_hist=err_hist, it_hist=it_hist, bound_cond=bound_cond) def __str__(self): descrLG2dHighl = 'This is a Lattice gas described with lattice'\ +' DFT. It was translated to the AO-model and the'\ +' functional was constructed by the Highlander method'\ +' It is an object of the Type \'LG2dAOHighl\' and has'\ +' the following properties:' epsiStr='{0:<40s}: {1}\n'.format('Attr. strength \'epsi\'',\ self.epsi) motherClass = 'It inherits from \'LdftModel\', with the'\ +' following properties:' descrLdftModel=super().__str__() return descrLG2dHighl+'\n\n'+epsiStr+'\n'+motherClass+\ '\n\n'+descrLdftModel #################################################################### #Protected descriptors for internal use. These are for a more #convenient addressing of the species specific instance variables. #Important to notice: do not override the protected variables of the #super class LdftModel. Otherwise the functionality of the instance #methods in LdftModel can not be secured. #################################################################### @property def _mu_c(self): """The chemical potential of the colloid species (times the inverse temperature to make its dimension 1) (`float`, read-only). """ return self._mu[0] @property def _mu_pc1(self): """The chemical potential of the polymer species in x-direction (times the inverse temperature to make its dimension 1). (`float`, read-only) """ return self._mu[1] @property def _mu_pc2(self): """The chemical potential of the polymer species in y-direction (times the inverse temperature to make its dimension 1). (`float`, read-only) """ return self._mu[2] @property def _dens_c(self): """The average density of the colloid species (`float`, read-only). """ return self._dens[0] @property def _dens_pc1(self): """The average density of the polymer species in x-direction (`float`, read-only). """ return self._dens[1] @property def _dens_pc2(self): """The average density of the polymer species in x-direction (`float`, read-only). """ return self._dens[2] @property def _v_ext_c(self): """The external potential acting on the colloids (`np.array`, read-only) """ return self._v_ext[0] @property def _v_ext_pc1(self): """The external potential acting on the polymer clusters in x-direction. (`np.array`, read-only) """ return self._v_ext[1] @property def _v_ext_pc2(self): """The external potential acting on the polymer clusters in y-direction. (`np.array`, read-only) """ return self._v_ext[2] @property def _r_c(self): """The density profile of the colloid species. (`numpy.ndarray`, read-only) """ return self._r[0] @property def _r_pc1(self): """The density profile of the polymer species in x-direction. (`numpy.ndarray`, read-only) """ return self._r[1] @property def _r_pc2(self): """The density profile of the polymer species in y-direction. (`numpy.ndarray`, read-only) """ return self._r[2] #################################################################### #Public descriptors. These are for the user to access the variables #of interest. Some are already defined in the super class. Some of #them are reused, but others are overwritten. #################################################################### @property def epsi(self): """The attraction strength between the lattice-particles of the lattice gas. (`Float`, read-only) """ return self.translate_mu_pc_to_epsi(self._mu_pc1) @property def mu_c(self): """The chemical potential of the colloids (times the inverse temperature to make its dimension 1). It is equals the chemical potential of the particles of the lattice gas. (`float`) """ return self._mu[0] @mu_c.setter def mu_c(self, mu_c): self._mu[0]=mu_c mu_pc1=_mu_pc1 """The chemical potential of the polymer-cluster in x-direction (times the inverse temperature to make its dimension 1). (`float`, read-only) """ mu_pc2=_mu_pc2 """The chemical potential of the polymer-cluster in y-direction (times the inverse temperature to make its dimension 1). (`float`, read-only) """ @LdftModel.mu.setter def mu(self, mu): print('This setter has been deactivated in favour for \`mu_c\`') @property def dens_c(self): """The average density of the colloids. It is equals the average density in the lattice gas. (`float`) """ return self._dens[0] dens_pc1=_dens_pc1 """The average density of the polymer clusters in x-direction. (`float`, read-only) """ dens_pc2=_dens_pc2 """The average density of the polymer clusters in x-direction. (`float`, read-only) """ @LdftModel.dens.setter def dens(self, dens): print('This setter has been deactivated in favour for \ \`dens_c\`') @property def mu_fix_c(self): """Flag which determines Wether the colloids (a.k. the particles of the lattice gas) are treated canonical (`False`) or grand canonical (`True`). (`Bool`) """ return self._mu_fix[0] @mu_fix_c.setter def mu_fix_c(self, mu_fix_c): self._mu_fix[0]=mu_fix_c @LdftModel.mu_fix.setter def mu_fix(self, mu_fix): print('This setter has been deactivated in favour for \ \`mu_fix_c\`') @property def v_ext_c(self): """External potential acting on the colloids (a.k. the particles of the lattice gas). (`np.array`) """ return self._v_ext[0] @v_ext_c.setter def v_ext_c(self, v_ext_c): self._v_ext[0]=v_ext_c @LdftModel.v_ext.setter def v_ext(self, v_ext): print('This setter has been deactivated in favour for \ \`v_ext_c\`') @property def r_c(self): """The density profile of the colloids (a.k. the particles of the lattice gas). (`np.array`, read-only) """ return self._r[0] r_pc1=_r_pc1 """The density profile of the polymer clusters in x-direction. (`np.array`, read-only) """ r_pc2=_r_pc2 """The density profile of the polymer clusters in y-direction. (`np.array`, read-only) """ @property def r_c_hist(self): """Iteration history of the density profile of the colloids (a.k. the particles of the lattice gas). (`List`, read-only) """ r_c_hist = [r[0] for r in self._r_hist] return r_c_hist @property def err_c_hist(self): """Iteration history of the picard-error at the colloidal density profile. (`List`, read-only) """ err_hist =[err[0] for err in self._err_hist] return err_hist #################################################################### #Map the lattice gas to the AO-model: #################################################################### @staticmethod def translate_epsi_to_mu_pc(epsi): """Maps the attraction strength of the lattice gas ``epsi`` to the corresponding polymer cluster chemical potential. Parameters ---------- epsi : `float` The attraction strength (multiplied with the inverse temperature to make the quantity dimensionless). Returns ------- mu_pc : The chemical potential (multiplied with the inverse temperature to make the quantity dimensionless). (`float`) """ mu_pc=np.log(np.exp(epsi)-1) return mu_pc @staticmethod def translate_mu_pc_to_epsi(mu_pc): """Maps the polymer cluster chemical potential to the attraction strength of the lattice gas ``epsi``. Parameters ---------- mu_pc : `float` The polymer chemical potential (multiplied with the inverse temperature to make the quantity dimensionless). Returns ------- epsi : The attraction strength (multiplied with the inverse temperature to make the quantity dimensionless). (`float`) """ epsi=np.log(np.exp(mu_pc)+1) return epsi #################################################################### #The inhomogeneous functional: #In this section all the functions concerning the model specific #free energy functional are defined. #################################################################### def _cal_n(self): """Calculates the weighted densities necessary for the calculation of the free energy and the excess chemical potential. Returns ------- Result : `tuple` of `numpy.ndaray` """ n1 = self._r_c + self._r_pc1 n2 = self._boundary_roll(self._r_c, -1, axis=1) + self._r_pc1 n3 = self._r_c + self._r_pc2 n4 = self._boundary_roll(self._r_c, -1, axis=0) + self._r_pc2 n5 = self._r_pc1 n6 = self._r_pc2 n7 = self._r_c return n1, n2, n3, n4, n5, n6, n7 def _cal_Phi_ex_AO(self): """Calculates the excess free energy of the AO-model. Returns ------- Result : `np.array` Free energy density of the AO-model. """ n=self._cal_n() n1=n[0] n2=n[1] n3=n[2] n4=n[3] n5=n[4] n6=n[5] n7=n[6] Phi0=self._cal_Phi_0 Phi_ex = Phi0(n1)+Phi0(n2)+Phi0(n3)+Phi0(n4)-Phi0(n5)-Phi0(n6)\ -3*Phi0(n7) return Phi_ex def cal_F(self): """Calculates the free energy of the three component system. It differs from the free energy functional of the AO-model just by a correction term accounting for the zero- and one-body interaction of the polymers (see description of the class). For getting the free energy of the lattice gas use ``cal_F_lg``, which is the semi-grand potential, where the polymer clusters are treated grand canonically and the colloids canonically. Returns ------- Result : `float` Free energy of the three component system (times the inverse temperature to make the results dimension 1). """ z_pc1 = np.exp(self._mu_pc1) z_pc2 = np.exp(self._mu_pc2) r_c = self._r_c r_pc1 = self._r_pc1 r_pc2 = self._r_pc2 Phi_id = self._cal_Phi_id() Phi_ex = self._cal_Phi_ex_AO() F_id = np.sum(Phi_id) F_ex_AO = np.sum(Phi_ex) F = (F_id + F_ex_AO - np.log(z_pc1+1) *np.sum(-1+r_c+self._boundary_roll(r_c, -1, axis=1)) - np.log(z_pc2+1) *np.sum(-1+r_c+self._boundary_roll(r_c, -1, axis=0))) return F def cal_F_lg(self): """Calculates the free energy of the lattice gas. If ``self.mu_fix==False`` this should give the same result as the ``cal_semi_Om``-function. Returns ------- Result : `float` Free energy of the lattice gas. """ F_lg = self.cal_F() mu_pc1 = self._mu_pc1 mu_pc2 = self._mu_pc2 r_pc1 = self._r_pc1 r_pc2 = self._r_pc2 F_lg -= (mu_pc1*np.sum(r_pc1)+mu_pc2*np.sum(r_pc2)) return F_lg @LdftModel._RespectBoundaryCondition() def cal_mu_ex(self): n = self._cal_n() n1=n[0] n2=n[1] n3=n[2] n4=n[3] n5=n[4] n6=n[5] n7=n[6] z_pc = np.exp(self._mu_pc1) mu_c_ex = np.log((1-n1)*(1-self._boundary_roll(n2, 1, axis=1))\ *(1-n3)*(1-self._boundary_roll(n4, 1, axis=0))\ /(1-n7)**3) + 4*np.log(z_pc+1) mu_pc1_ex = np.log((1-n1)*(1-n2)/(1-n5)) mu_pc2_ex = np.log((1-n3)*(1-n4)/(1-n6)) return mu_c_ex, mu_pc1_ex, mu_pc2_ex #################################################################### #The homogeneous methods: #The following section contains all the methods concerning the bulk #properties of the system. #################################################################### @classmethod def _cal_bulk_r_pc(cls, r_c, epsi): """Calculates the bulk polymer cluster density in dependence of the colloid density and the chosen attraction strength Parameters ---------- r_c : `float` or `np.ndarray` The colloid density. epsi : `float` Attraction strength (times inverse temperature). Returns ------- r_pc : `float` or `np.ndarray` The polymer cluster density. """ mu_pc = cls.translate_epsi_to_mu_pc(epsi) z_pc = np.exp(mu_pc) r_pc = ((1+2*z_pc*(1-r_c))/(2*(z_pc+1)) - 1/(2*(z_pc+1))*np.sqrt((1+2*z_pc*(1-r_c))**2 - 4*z_pc*(z_pc+1)*(1-r_c)**2)) return r_pc @classmethod def _cal_bulk_dr_pc(cls, r_c, epsi): """Calculates the derivative of the bulk polymer cluster density with respect to the colloidal density in dependence of the colloid density and the chosen attraction strength Parameters ---------- r_c : `float` or `np.ndarray` The colloid density. epsi : `float` Attraction strength (times inverse temperature). Returns ------- dr_pc : `float` or `np.ndarray` The derivative of the polymer cluster density. """ mu_pc = cls.translate_epsi_to_mu_pc(epsi) z_pc = np.exp(mu_pc) dr_pc = -z_pc/(z_pc+1)\ *(1+(1-2*r_c)/np.sqrt(4*z_pc*(1-r_c)*r_c+1)) return dr_pc @classmethod def cal_bulk_mu_lg(cls, r_c, epsi): """Calculates the chemical potential for a bulk lattice gas. Parameters ---------- r_c : `Float` or `np.ndarray` The colloidal density. epsi : `Float` Attraction strength Returns ------- mu : `Float` or `np.ndarray` The chemical potential for the lattice gas. """ r_pc = cls._cal_bulk_r_pc(r_c, epsi) mu_pc = cls.translate_epsi_to_mu_pc(epsi) z_pc = np.exp(mu_pc) mu_c = (np.log(r_c) +4*cls._cal_dPhi_0(r_c+r_pc) -3*cls._cal_dPhi_0(r_c)-4*np.log(z_pc+1)) return mu_c @classmethod def cal_bulk_dmu_lg(cls, r_c, epsi): """Calculates the derivative of the chemical potential from the bulk lattice gas with respect to the colloidal density. Parameters ---------- r_c : `Float` or `np.ndarray` The colloidal density. epsi : `Float` Attraction strength Returns ------- dmu : `Float` or `np.ndarray` The derivative of the chemical potential from the lattice gas. """ r_pc = cls._cal_bulk_r_pc(r_c, epsi) dr_pc = cls._cal_bulk_dr_pc(r_c, epsi) mu_pc = cls.translate_epsi_to_mu_pc(epsi) z_pc = np.exp(mu_pc) dmu = 1/r_c + 4*cls._cal_d2Phi_0(r_c+r_pc)*(1+dr_pc)\ -3*cls._cal_d2Phi_0(r_c) return dmu @classmethod def _cal_bulk_f_AO_id(cls, r_c, r_pc): """Calculates the ideal gas part of the free energy density of a bulk AO-system under given colloid and polymer cluster density. Parameters ---------- r_c : `float` Colloid density r_pc : `float` Polymer cluster density Returns ------- f_id : `float` The idea gas part of the free energy density. """ f_id = r_c*(np.log(r_c)-1) +2*r_pc*(np.log(r_pc)-1) return f_id @classmethod def _cal_bulk_f_AO_ex(cls, r_c, r_pc): """Calculates the excess part of the free energy density of a bulk AO-system under given colloid and polymer cluster density. Parameters ---------- r_c : `float` Colloid density r_pc : `float` Polymer cluster density Returns ------- f_ex : `float` The excess part of the free energy density. """ n1 = n2 = n3 = n4= r_c+r_pc n5 = n6 = r_pc n7 = r_c f_ex = (cls._cal_Phi_0(n1)+cls._cal_Phi_0(n2)+cls._cal_Phi_0(n3) +cls._cal_Phi_0(n4)-3*cls._cal_Phi_0(n7) -cls._cal_Phi_0(n5)-cls._cal_Phi_0(n6)) return f_ex @classmethod def cal_bulk_f_lg(cls, r_c, epsi): """Calculates the free energy density of the bulk lattice gas under given density. (The function is the same as in ``cal_F_lg`` but simplified for bulk systems.) Parameters ---------- r_c: `float` or `np.ndarray` Density epsi: `float` Attraction strength (times inverse temperature) Returns ------- f : `float` or `np.ndarray` The free energy density of a bulk lattice gas. """ r_pc = cls._cal_bulk_r_pc(r_c, epsi) f_AO_id = cls._cal_bulk_f_AO_id(r_c, r_pc) f_AO_ex = cls._cal_bulk_f_AO_ex(r_c, r_pc) mu_pc = cls.translate_epsi_to_mu_pc(epsi) z_pc = np.exp(mu_pc) f_tilde = f_AO_id+f_AO_ex-2*np.log(z_pc+1)*(2*r_c-1) f_eff = f_tilde-2*r_pc*np.log(z_pc) return f_eff @classmethod def cal_bulk_om_lg(cls, r, epsi): """Calculates the grand potential density for a bulk lattice gas under given densities. Parameters ---------- r : `float` or `np.ndarray` The density. epsi : `float` The attraction strength (times inverse temperature). Returns ------- om : `Float` The grand potential density """ f = cls.cal_bulk_f_lg(r, epsi) mu = cls.cal_bulk_mu_lg(r, epsi) om = f-mu*r return om @classmethod def cal_bulk_p(cls, r, epsi): """Calculates the pressure of a bulk lattice gas under given density. Parameters ---------- r : `float` or `np.ndarray` The density. epsi : `float` The attraction strength (times inverse temperature). Returns ------- The pressure : `Float` """ p = -cls.cal_bulk_om_lg(r, epsi) return p @classmethod def _cal_difMu(cls, r_c, *args): """Calculates the difference between a certain chemical potential of the lattice gas and the chemical potential belonging to a certain density. This is a help-function for the function ``cal_bulk_coex_dens``. Parameters ---------- r_c : `float` The colloid density of the system *args: First argument: Attraction strength (times inverse temperature). (`float`) Second argument: The reference chemical potential which the chemical potential for at density r_c should be compared to. (`float`) Returns ------- difMu : `float` The difference between the two colloidal chem. pot. """ epsi = args[0] mu_c = args[1] mu = cls.cal_bulk_mu_lg(r_c, epsi) return mu-mu_c @classmethod def cal_bulk_coex_dens(cls, mu, epsi, init_min=0.01, init_max=0.99): """Calculates the coexisting densities of a bulk system lattice gas system under given chemical potential. Parameters ---------- mu : `Float` The chemical potential of the lattice gas. epsi : `Float` The attraction strength (times inverse temperature). Returns ------- r_coex : `Tuple` The coexisting densities arranged in a tuple of the shape (vapour_dens, liquid_dens) """ def dmu(rc, *args): epsi = args[0] mu_c = args[1] return np.diag(cls.cal_bulk_dmu_lg(rc, epsi)) if (init_max-init_min < 0.5 or init_min<=0 or init_max>=1 or abs(init_max+init_min-1)>0.01): init_min=0.01 init_max=0.99 r_coex = op.fsolve(cls._cal_difMu, np.array([init_min, init_max]), args=(epsi, mu), fprime=dmu) r_coex = tuple(r_coex) if (cls._cal_difMu(r_coex[0], epsi, mu)>10**-7 or cls._cal_difMu(r_coex[1], epsi, mu)>10**-7): init_min = init_min/2 init_max = (init_max+1)/2 r_coex = cls.cal_bulk_coex_dens(mu, epsi, init_min=init_min, init_max=init_max) return r_coex #################################################################### #In the following section the abc-methods concerning the surface #properties of the mother class are overridden. #################################################################### def _cal_p(self, dens): epsi = self.epsi r = dens[0] p = self.cal_bulk_p(r, epsi) return p def _cal_coex_dens(self): mu = self._mu[0] epsi = self.epsi if self._r: init_min = np.min(self._r[0]) init_max = np.max(self._r[0]) r_c_coex = self.cal_bulk_coex_dens(mu, epsi, init_min=init_min, init_max=init_max) else: r_c_coex = self.cal_bulk_coex_dens(mu, epsi) r_pc_coex = self._cal_bulk_r_pc(np.array(r_c_coex), epsi) r_pc_coex = tuple(r_pc_coex) return [r_c_coex, r_pc_coex, r_pc_coex] class _CorrectIftAtPaddedBoundary(): """This is a decorator class. In order to fulfill the Gibbs-Adsorption equation, additional terms need to be added to the definition of the surface tension, at the Highlander functional. This decorator takes care of them. Please decorate the functions, which calculate the surface tension with it. """ def __init__(self): pass def __call__(self, func): def funcWraper(self, arg=None): if self._bound_cond == 'pad': Phi_id = lambda r: r*(
np.log(r)
numpy.log
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Apr 10 14:15:37 2020 @author: <NAME> """ import numpy as np import matplotlib.pyplot as plt import scipy.io as sio import sklearn from sklearn.model_selection import train_test_split, StratifiedKFold import seaborn as sns # from tabulate import tabulate # from imblearn import under_sampling, over_sampling def normalize(pressure): """ Scales each array of the given array of arrays to the range [0, 1] Only considers values in the same tactile frame """ normalized_p = np.copy(pressure) for i in range(pressure.shape[0]): min_p = np.min(pressure[i]) normalized_p[i] = (pressure[i] - min_p) / np.max(pressure[i] - min_p) return normalized_p def normalize_per_pixel(pressure): """ Scales each element of the given array of arrays to the range [0, 1] Considers values in all tactile frames """ normalized_p = np.copy(pressure) # First scale values to [0, 1] min_p = np.min(pressure) normalized_p = (pressure - min_p) / np.max(pressure - min_p) # Then subtract the mean for each pixel pixel_mean = np.mean(normalized_p, axis=0) # pixel_mean should be shaped like normalized_p normalized_p = normalized_p - pixel_mean return normalized_p seed = 333 n_classes = 17 split = 'session' plot = True filename = '../../Data_Collection/3kOhm_FB/data_MT_FabianGeiger_5sess.mat' split = 'session' data = sio.loadmat(filename, squeeze_me=True) # Use only frames in which objects were touched valid_mask = data['valid_flag'] == 1 pressure = data['tactile_data'][valid_mask] # Scale data to the range [0, 1] pressure = np.clip((pressure.astype(np.float32)-1510)/(3000-1510), 0.0, 1.0) object_id = data['object_id'][valid_mask] if split == 'random': # Only use valid and balanced data train_data, test_data,\ train_labels, test_labels = train_test_split(pressure, object_id, test_size=0.306, random_state=seed, shuffle=True, stratify=object_id) mean_train = [] mean_test = [] for i in range(n_classes): mask = train_labels == i samples = train_data[mask] if(len(samples) != 0): mean_train.append(np.mean(samples, axis=0).reshape((32,32))) mask = test_labels == i samples = test_data[mask] if(len(samples) != 0): mean_test.append(np.mean(samples, axis=0).reshape((32,32))) if plot: # Plot the mean pressure frames for a random data split #fname = '/home/fabian/Documents/Master_thesis/Python_Code/results/stag/compare_sessions_realData/random_' fname = '../results/stag/compare_sessions_realData/random_' fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 6), sharey=True) cbar_ax = fig.add_axes([.91, .15, .03, .7]) for j in range(n_classes): vmax = np.max([mean_train[j], mean_test[j]]) sns.heatmap(mean_train[j], vmax=vmax, square=True, ax=ax1, cbar=False) ax1.title.set_text('Training') sns.heatmap(mean_test[j], vmax=vmax, square=True, ax=ax2, cbar_ax=cbar_ax) ax2.title.set_text('Test') fig.suptitle('Random split Class {:d}'.format(j), fontsize=16) plt.savefig(fname=(fname + 'class' + str(j))) elif split == 'session': num_sessions = len(np.unique(data['session_id'])) x = [] y = [] valid_sessions = data['session_id'][valid_mask] for i in range(num_sessions): session_mask = valid_sessions == i x.append(pressure[session_mask]) y.append(object_id[session_mask]) mean_1 = [] mean_2 = [] mean_3 = [] mean_4 = [] mean_5 = [] for i in range(n_classes): mask = y[0] == i samples = x[0][mask] if(len(samples) != 0): mean_1.append(np.mean(samples, axis=0).reshape((32,32))) else: mean_1.append(np.zeros((32,32))) mask = y[1] == i samples = x[1][mask] if(len(samples) != 0): mean_2.append(
np.mean(samples, axis=0)
numpy.mean
# -*- coding: utf-8 -*- """Developer convenience functions for ibs (detections). TODO: need to split up into sub modules: consistency_checks feasibility_fixes move the export stuff to dbio then there are also convineience functions that need to be ordered at least within this file """ import logging from os.path import exists, expanduser, join, abspath import numpy as np import utool as ut import cv2 from wbia.control import controller_inject from wbia.other.detectfuncs import ( general_parse_gt, general_get_imageset_gids, localizer_parse_pred, general_overlap, ) from wbia.other.detectcore import ( nms, classifier_visualize_training_localizations, _bootstrap_mine, ) # Inject utool functions (print, rrr, profile) = ut.inject2(__name__, '[other.detectgrave]') logger = logging.getLogger('wbia') CLASS_INJECT_KEY, register_ibs_method = controller_inject.make_ibs_register_decorator( __name__ ) @register_ibs_method def bootstrap_pca_train( ibs, dims=64, pca_limit=500000, ann_batch=50, output_path=None, **kwargs ): from sklearn.preprocessing import StandardScaler from sklearn.decomposition import IncrementalPCA from annoy import AnnoyIndex import numpy as np import random def _get_data(depc, gid_list, limit=None, shuffle=False): gid_list_ = gid_list[:] if shuffle: random.shuffle(gid_list_) config = { 'algo': '_COMBINED', 'features': True, 'feature2_algo': 'resnet', } total = 0 features_list = [] index_list = [] gid_iter = ut.ProgIter(gid_list_, lbl='collect feature vectors', bs=True) for gid in gid_iter: if limit is not None and total >= limit: break feature_list = depc.get_property( 'localizations_features', gid, 'vector', config=config ) total += len(feature_list) index_list += [(gid, offset) for offset in range(len(feature_list))] features_list.append(feature_list) logger.info('\nUsed %d images to mine %d features' % (len(features_list), total)) data_list = np.vstack(features_list) if len(data_list) > limit: data_list = data_list[:limit] index_list = index_list[:limit] assert len(data_list) == len(index_list) features_list = None return total, data_list, index_list # gid_list = ibs.get_valid_gids() gid_list = general_get_imageset_gids(ibs, 'TRAIN_SET', **kwargs) # gid_list = gid_list[:200] # Get data depc = ibs.depc_image total, data_list, index_list = _get_data(depc, gid_list, pca_limit, True) logger.info(data_list.shape) # Normalize data logger.info('Fit Scaler') scaler = StandardScaler() scaler.fit(data_list) data_list = scaler.transform(data_list) # Fit PCA logger.info('Fit PCA') pca_model = IncrementalPCA(n_components=dims) pca_model.fit(data_list) pca_quality = pca_model.explained_variance_ratio_.sum() * 100.0 logger.info('PCA Variance Quality: %0.04f %%' % (pca_quality,)) # Fit ANN for PCA's vectors index = 0 ann_model = AnnoyIndex(dims) # Length of item vector that will be indexed ann_rounds = int(np.ceil(float(len(gid_list)) / ann_batch)) manifest_dict = {} for ann_round in range(ann_rounds): start_index = ann_round * ann_batch stop_index = (ann_round + 1) * ann_batch assert start_index < len(gid_list) stop_index = min(stop_index, len(gid_list)) logger.info('Slicing index range: [%r, %r)' % (start_index, stop_index)) # Slice gids and get feature data gid_list_ = gid_list[start_index:stop_index] total, data_list, index_list = _get_data(depc, gid_list_) # Scaler data_list = scaler.transform(data_list) # Transform data to smaller vectors data_list_ = pca_model.transform(data_list) zipped = zip(index_list, data_list_) data_iter = ut.ProgIter(zipped, lbl='add vectors to ANN model', bs=True) for (gid, offset), feature in data_iter: ann_model.add_item(index, feature) manifest_dict[index] = ( gid, offset, ) index += 1 # Build forest trees = index // 100000 logger.info('Build ANN model using %d feature vectors and %d trees' % (index, trees)) ann_model.build(trees) # Save forest if output_path is None: output_path = abspath(expanduser(join('~', 'code', 'wbia', 'models'))) scaler_filename = 'forest.pca' scaler_filepath = join(output_path, scaler_filename) logger.info('Saving scaler model to: %r' % (scaler_filepath,)) model_tup = ( pca_model, scaler, manifest_dict, ) ut.save_cPkl(scaler_filepath, model_tup) forest_filename = 'forest.ann' forest_filepath = join(output_path, forest_filename) logger.info('Saving ANN model to: %r' % (forest_filepath,)) ann_model.save(forest_filepath) # ibs.bootstrap_pca_test(model_path=output_path) return output_path @register_ibs_method def bootstrap_pca_test( ibs, dims=64, pca_limit=500000, ann_batch=50, model_path=None, output_path=None, neighbors=1000, nms_thresh=0.5, min_confidence=0.3, **kwargs, ): from annoy import AnnoyIndex import random if output_path is None: output_path = abspath(expanduser(join('~', 'Desktop', 'output-ann'))) ut.ensuredir(output_path) # gid_list = ibs.get_valid_gids() gid_list = general_get_imageset_gids(ibs, 'TRAIN_SET', **kwargs) random.shuffle(gid_list) # gid_list = gid_list[:100] # Load forest if model_path is None: model_path = abspath(expanduser(join('~', 'code', 'wbia', 'models'))) scaler_filename = 'forest.pca' scaler_filepath = join(model_path, scaler_filename) logger.info('Loading scaler model from: %r' % (scaler_filepath,)) model_tup = ut.load_cPkl(scaler_filepath) pca_model, scaler, manifest_dict = model_tup forest_filename = 'forest.ann' forest_filepath = join(model_path, forest_filename) logger.info('Loading ANN model from: %r' % (forest_filepath,)) ann_model = AnnoyIndex(dims) ann_model.load(forest_filepath) config = { 'algo': '_COMBINED', 'features': True, 'feature2_algo': 'resnet', 'classify': True, 'classifier_algo': 'svm', 'classifier_weight_filepath': '/home/jason/code/wbia/models-bootstrap/classifier.svm.image.zebra.pkl', } logger.info('\tGather Ground-Truth') gt_dict = general_parse_gt(ibs, test_gid_list=gid_list, **config) logger.info('\tGather Predictions') pred_dict = localizer_parse_pred(ibs, test_gid_list=gid_list, **config) for image_uuid in gt_dict: # Get the gt and prediction list gt_list = gt_dict[image_uuid] pred_list = pred_dict[image_uuid] # Calculate overlap overlap = general_overlap(gt_list, pred_list) num_gt, num_pred = overlap.shape max_overlap = np.max(overlap, axis=0) index_list = np.argsort(max_overlap) example_limit = 1 worst_idx_list = index_list[:example_limit] best_idx_list = index_list[-1 * example_limit :] logger.info('Worst ovelap: %r' % (overlap[:, worst_idx_list],)) logger.info('Best ovelap: %r' % (overlap[:, best_idx_list],)) for idx_list in [best_idx_list, worst_idx_list]: example_list = ut.take(pred_list, idx_list) interpolation = cv2.INTER_LANCZOS4 warpkw = dict(interpolation=interpolation) for example, offset in zip(example_list, idx_list): gid = example['gid'] feature_list = np.array([example['feature']]) data_list = scaler.transform(feature_list) data_list_ = pca_model.transform(data_list)[0] neighbor_index_list = ann_model.get_nns_by_vector(data_list_, neighbors) neighbor_manifest_list = list( set( [ manifest_dict[neighbor_index] for neighbor_index in neighbor_index_list ] ) ) neighbor_gid_list_ = ut.take_column(neighbor_manifest_list, 0) neighbor_gid_list_ = [gid] + neighbor_gid_list_ neighbor_uuid_list_ = ibs.get_image_uuids(neighbor_gid_list_) neighbor_offset_list_ = ut.take_column(neighbor_manifest_list, 1) neighbor_offset_list_ = [offset] + neighbor_offset_list_ neighbor_gid_set_ = list(set(neighbor_gid_list_)) neighbor_image_list = ibs.get_images(neighbor_gid_set_) neighbor_image_dict = { gid: image for gid, image in zip(neighbor_gid_set_, neighbor_image_list) } neighbor_pred_dict = localizer_parse_pred( ibs, test_gid_list=neighbor_gid_set_, **config ) neighbor_dict = {} zipped = zip( neighbor_gid_list_, neighbor_uuid_list_, neighbor_offset_list_ ) for neighbor_gid, neighbor_uuid, neighbor_offset in zipped: if neighbor_gid not in neighbor_dict: neighbor_dict[neighbor_gid] = [] neighbor_pred = neighbor_pred_dict[neighbor_uuid][neighbor_offset] neighbor_dict[neighbor_gid].append(neighbor_pred) # Perform NMS chip_list = [] query_image = ibs.get_images(gid) xbr = example['xbr'] ybr = example['ybr'] xtl = example['xtl'] ytl = example['ytl'] height, width = query_image.shape[:2] xbr = int(xbr * width) ybr = int(ybr * height) xtl = int(xtl * width) ytl = int(ytl * height) # Get chips try: chip = query_image[ytl:ybr, xtl:xbr, :] chip = cv2.resize(chip, (192, 192), **warpkw) chip_list.append(chip) except Exception: pass chip_list.append(np.zeros((192, 10, 3))) for neighbor_gid in neighbor_dict: neighbor_list = neighbor_dict[neighbor_gid] # Compile coordinate list of (xtl, ytl, xbr, ybr) instead of (xtl, ytl, w, h) coord_list = [] confs_list = [] for neighbor in neighbor_list: xbr = neighbor['xbr'] ybr = neighbor['ybr'] xtl = neighbor['xtl'] ytl = neighbor['ytl'] conf = neighbor['confidence'] coord_list.append([xtl, ytl, xbr, ybr]) confs_list.append(conf) coord_list = np.vstack(coord_list) confs_list = np.array(confs_list) # Perform NMS keep_indices_list = nms(coord_list, confs_list, nms_thresh) keep_indices_set = set(keep_indices_list) neighbor_list_ = [ neighbor for index, neighbor in enumerate(neighbor_list) if index in keep_indices_set ] neighbor_image = neighbor_image_dict[neighbor_gid] for neightbor_ in neighbor_list_: xbr = neightbor_['xbr'] ybr = neightbor_['ybr'] xtl = neightbor_['xtl'] ytl = neightbor_['ytl'] conf = neighbor['confidence'] height, width = neighbor_image.shape[:2] xbr = int(xbr * width) ybr = int(ybr * height) xtl = int(xtl * width) ytl = int(ytl * height) # Get chips try: chip = neighbor_image[ytl:ybr, xtl:xbr, :] chip = cv2.resize(chip, (192, 192), **warpkw) color = (0, 255, 0) if conf >= min_confidence else (0, 0, 255) cv2.rectangle(chip, (0, 0), (192, 192), color, 10) chip_list.append(chip) except Exception: pass min_chips = 16 if len(chip_list) < min_chips: continue chip_list = chip_list[:min_chips] canvas = np.hstack(chip_list) output_filename = 'neighbors_%d_%d.png' % (gid, offset) output_filepath = join(output_path, output_filename) cv2.imwrite(output_filepath, canvas) @register_ibs_method def bootstrap( ibs, species_list=['zebra'], N=10, rounds=20, scheme=2, ensemble=9, output_path=None, precompute=True, precompute_test=True, recompute=False, visualize=True, C=1.0, kernel='rbf', **kwargs, ): from sklearn import svm, preprocessing # Establish variables kernel = str(kernel.lower()) species_list = [species.lower() for species in species_list] species_list_str = '.'.join(species_list) assert scheme in [1, 2], 'Invalid scheme' if output_path is None: # species_list_str = '+'.join(species_list) # args = (N, rounds, scheme, species_list_str, ) # output_path_ = 'models-bootstrap-%s-%s-%s-%s' % args output_path_ = 'models-bootstrap' output_path = abspath(expanduser(join('~', 'code', 'wbia', output_path_))) logger.info('Using output_path = %r' % (output_path,)) if recompute: ut.delete(output_path) ut.ensuredir(output_path) # Get the test images for later depc = ibs.depc_image test_gid_list = general_get_imageset_gids(ibs, 'TEST_SET', **kwargs) wic_model_filepath = ibs.classifier_train_image_svm( species_list, output_path=output_path, dryrun=True ) is_wic_model_trained = exists(wic_model_filepath) ###################################################################################### # Step 1: train whole-image classifier # this will compute and cache any ResNet features that # haven't been computed if not is_wic_model_trained: wic_model_filepath = ibs.classifier_train_image_svm( species_list, output_path=output_path ) # Load model pickle model_tup = ut.load_cPkl(wic_model_filepath) model, scaler = model_tup ###################################################################################### # Step 2: sort all test images based on whole image classifier # establish a review ordering based on classification probability # Get scores vals = get_classifier_svm_data_labels(ibs, 'TRAIN_SET', species_list) train_gid_set, data_list, label_list = vals # Normalize data data_list = scaler.transform(data_list) # score_list_ = model.decision_function(data_list) # NOQA score_list_ = model.predict_proba(data_list) score_list_ = score_list_[:, 1] # Sort gids by scores (initial ranking) comb_list = sorted(list(zip(score_list_, train_gid_set)), reverse=True) sorted_gid_list = [comb[1] for comb in comb_list] config = { 'algo': '_COMBINED', 'species_set': set(species_list), 'features': True, 'feature2_algo': 'resnet', 'classify': True, 'classifier_algo': 'svm', 'classifier_weight_filepath': wic_model_filepath, 'nms': True, 'nms_thresh': 0.50, # 'thresh' : True, # 'index_thresh' : 0.25, } config_list = [config.copy()] ###################################################################################### # Step 2.5: pre-compute localizations and ResNet features (without loading to memory) # if precompute: needed = N * rounds needed = min(needed, len(sorted_gid_list)) sorted_gid_list_ = sorted_gid_list[:needed] depc.get_rowids('localizations_features', sorted_gid_list_, config=config) # Precompute test features if precompute and precompute_test: # depc.get_rowids('localizations_features', test_gid_list, config=config) if not is_wic_model_trained: depc.delete_property('localizations_classifier', test_gid_list, config=config) depc.get_rowids('localizations_classifier', test_gid_list, config=config) # return ###################################################################################### # Step 3: for each bootstrapping round, ask user for input # The initial classifier is the whole image classifier reviewed_gid_dict = {} for current_round in range(rounds): logger.info('------------------------------------------------------') logger.info('Current Round %r' % (current_round,)) ################################################################################## # Step 4: gather the (unreviewed) images to review for this round round_gid_list = [] temp_index = 0 while len(round_gid_list) < N and temp_index < len(sorted_gid_list): temp_gid = sorted_gid_list[temp_index] if temp_gid not in reviewed_gid_dict: round_gid_list.append(temp_gid) temp_index += 1 args = ( len(round_gid_list), round_gid_list, ) logger.info('Found %d unreviewed gids: %r' % args) ################################################################################## # Step 5: add any images reviewed from a previous round reviewed_gid_list = reviewed_gid_dict.keys() args = ( len(reviewed_gid_list), reviewed_gid_list, ) logger.info('Adding %d previously reviewed gids: %r' % args) # All gids that have been reviewed round_gid_list = reviewed_gid_list + round_gid_list # Get model ensemble path limit = len(round_gid_list) args = ( species_list_str, limit, kernel, C, ) output_filename = 'classifier.svm.localization.%s.%d.%s.%s' % args svm_model_path = join(output_path, output_filename) is_svm_model_trained = exists(svm_model_path) ut.ensuredir(svm_model_path) ################################################################################## # Step 6: gather gt (simulate user interaction) logger.info('\tGather Ground-Truth') gt_dict = general_parse_gt(ibs, test_gid_list=round_gid_list, **config) ################################################################################## # Step 7: gather predictions from all algorithms combined if not is_svm_model_trained: logger.info('\tDelete Old Classifications') depc.delete_property( 'localizations_classifier', round_gid_list, config=config ) logger.info('\tGather Predictions') pred_dict = localizer_parse_pred(ibs, test_gid_list=round_gid_list, **config) ################################################################################## # Step 8: train SVM ensemble using fresh mined data for each ensemble # Train models, one-by-one for current_ensemble in range(1, ensemble + 1): # Mine for a new set of (static) positives and (random) negatives values = _bootstrap_mine( ibs, gt_dict, pred_dict, scheme, reviewed_gid_dict, **kwargs ) mined_gid_list, mined_gt_list, mined_pos_list, mined_neg_list = values if visualize: output_visualize_path = join(svm_model_path, 'visualize') ut.ensuredir(output_visualize_path) output_visualize_path = join( output_visualize_path, '%s' % (current_ensemble,) ) ut.ensuredir(output_visualize_path) classifier_visualize_training_localizations( ibs, None, output_path=output_visualize_path, values=values ) # Get the confidences of the selected positives and negatives pos_conf_list = [] neg_conf_list = [] for pos in mined_pos_list: pos_conf_list.append(pos['confidence']) for neg in mined_neg_list: neg_conf_list.append(neg['confidence']) pos_conf_list = np.array(pos_conf_list) args = ( np.min(pos_conf_list), np.mean(pos_conf_list), np.std(pos_conf_list), np.max(pos_conf_list), ) logger.info( 'Positive Confidences: %0.02f min, %0.02f avg, %0.02f std, %0.02f max' % args ) neg_conf_list = np.array(neg_conf_list) args = ( np.min(neg_conf_list), np.mean(neg_conf_list),
np.std(neg_conf_list)
numpy.std
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.]) self.op = np.array([0., 1., -0.33333333]) self.amounts_to_sell = np.array([0., 0., -3333.3333]) self.cash_to_spend = np.array([0., 20000., 0.]) self.prices = np.array([10., 20., 10.]) self.r = qt.Cost(0.0) def test_rate_creation(self): """测试对象生成""" print('testing rates objects\n') self.assertIsInstance(self.r, qt.Cost, 'Type should be Rate') self.assertEqual(self.r.buy_fix, 0) self.assertEqual(self.r.sell_fix, 0) def test_rate_operations(self): """测试交易费率对象""" self.assertEqual(self.r['buy_fix'], 0.0, 'Item got is incorrect') self.assertEqual(self.r['sell_fix'], 0.0, 'Item got is wrong') self.assertEqual(self.r['buy_rate'], 0.003, 'Item got is incorrect') self.assertEqual(self.r['sell_rate'], 0.001, 'Item got is incorrect') self.assertEqual(self.r['buy_min'], 5., 'Item got is incorrect') self.assertEqual(self.r['sell_min'], 0.0, 'Item got is incorrect') self.assertEqual(self.r['slipage'], 0.0, 'Item got is incorrect') self.assertEqual(np.allclose(self.r.calculate(self.amounts), [0.003, 0.003, 0.003]), True, 'fee calculation wrong') def test_rate_fee(self): """测试买卖交易费率""" self.r.buy_rate = 0.003 self.r.sell_rate = 0.001 self.r.buy_fix = 0. self.r.sell_fix = 0. self.r.buy_min = 0. self.r.sell_min = 0. self.r.slipage = 0. print('\nSell result with fixed rate = 0.001 and moq = 0:') print(self.r.get_selling_result(self.prices, self.amounts_to_sell)) test_rate_fee_result = self.r.get_selling_result(self.prices, self.amounts_to_sell) self.assertIs(np.allclose(test_rate_fee_result[0], [0., 0., -3333.3333]), True, 'result incorrect') self.assertAlmostEqual(test_rate_fee_result[1], 33299.999667, msg='result incorrect') self.assertAlmostEqual(test_rate_fee_result[2], 33.333332999999996, msg='result incorrect') print('\nSell result with fixed rate = 0.001 and moq = 1:') print(self.r.get_selling_result(self.prices, self.amounts_to_sell, 1.)) test_rate_fee_result = self.r.get_selling_result(self.prices, self.amounts_to_sell, 1) self.assertIs(np.allclose(test_rate_fee_result[0], [0., 0., -3333]), True, 'result incorrect') self.assertAlmostEqual(test_rate_fee_result[1], 33296.67, msg='result incorrect') self.assertAlmostEqual(test_rate_fee_result[2], 33.33, msg='result incorrect') print('\nSell result with fixed rate = 0.001 and moq = 100:') print(self.r.get_selling_result(self.prices, self.amounts_to_sell, 100)) test_rate_fee_result = self.r.get_selling_result(self.prices, self.amounts_to_sell, 100) self.assertIs(np.allclose(test_rate_fee_result[0], [0., 0., -3300]), True, 'result incorrect') self.assertAlmostEqual(test_rate_fee_result[1], 32967.0, msg='result incorrect') self.assertAlmostEqual(test_rate_fee_result[2], 33, msg='result incorrect') print('\nPurchase result with fixed rate = 0.003 and moq = 0:') print(self.r.get_purchase_result(self.prices, self.cash_to_spend, 0)) test_rate_fee_result = self.r.get_purchase_result(self.prices, self.cash_to_spend, 0) self.assertIs(np.allclose(test_rate_fee_result[0], [0., 997.00897308, 0.]), True, 'result incorrect') self.assertAlmostEqual(test_rate_fee_result[1], -20000.0, msg='result incorrect') self.assertAlmostEqual(test_rate_fee_result[2], 59.82053838484547, msg='result incorrect') print('\nPurchase result with fixed rate = 0.003 and moq = 1:') print(self.r.get_purchase_result(self.prices, self.cash_to_spend, 1)) test_rate_fee_result = self.r.get_purchase_result(self.prices, self.cash_to_spend, 1) self.assertIs(np.allclose(test_rate_fee_result[0], [0., 997., 0.]), True, 'result incorrect') self.assertAlmostEqual(test_rate_fee_result[1], -19999.82, msg='result incorrect') self.assertAlmostEqual(test_rate_fee_result[2], 59.82, msg='result incorrect') print('\nPurchase result with fixed rate = 0.003 and moq = 100:') print(self.r.get_purchase_result(self.prices, self.cash_to_spend, 100)) test_rate_fee_result = self.r.get_purchase_result(self.prices, self.cash_to_spend, 100) self.assertIs(np.allclose(test_rate_fee_result[0], [0., 900., 0.]), True, 'result incorrect') self.assertAlmostEqual(test_rate_fee_result[1], -18054., msg='result incorrect') self.assertAlmostEqual(test_rate_fee_result[2], 54.0, msg='result incorrect') def test_min_fee(self): """测试最低交易费用""" self.r.buy_rate = 0. self.r.sell_rate = 0. self.r.buy_fix = 0. self.r.sell_fix = 0. self.r.buy_min = 300 self.r.sell_min = 300 self.r.slipage = 0. print('\npurchase result with fixed cost rate with min fee = 300 and moq = 0:') print(self.r.get_purchase_result(self.prices, self.cash_to_spend, 0)) test_min_fee_result = self.r.get_purchase_result(self.prices, self.cash_to_spend, 0) self.assertIs(np.allclose(test_min_fee_result[0], [0., 985, 0.]), True, 'result incorrect') self.assertAlmostEqual(test_min_fee_result[1], -20000.0, msg='result incorrect') self.assertAlmostEqual(test_min_fee_result[2], 300.0, msg='result incorrect') print('\npurchase result with fixed cost rate with min fee = 300 and moq = 10:') print(self.r.get_purchase_result(self.prices, self.cash_to_spend, 10)) test_min_fee_result = self.r.get_purchase_result(self.prices, self.cash_to_spend, 10) self.assertIs(np.allclose(test_min_fee_result[0], [0., 980, 0.]), True, 'result incorrect') self.assertAlmostEqual(test_min_fee_result[1], -19900.0, msg='result incorrect') self.assertAlmostEqual(test_min_fee_result[2], 300.0, msg='result incorrect') print('\npurchase result with fixed cost rate with min fee = 300 and moq = 100:') print(self.r.get_purchase_result(self.prices, self.cash_to_spend, 100)) test_min_fee_result = self.r.get_purchase_result(self.prices, self.cash_to_spend, 100) self.assertIs(np.allclose(test_min_fee_result[0], [0., 900, 0.]), True, 'result incorrect') self.assertAlmostEqual(test_min_fee_result[1], -18300.0, msg='result incorrect') self.assertAlmostEqual(test_min_fee_result[2], 300.0, msg='result incorrect') print('\nselling result with fixed cost rate with min fee = 300 and moq = 0:') print(self.r.get_selling_result(self.prices, self.amounts_to_sell)) test_min_fee_result = self.r.get_selling_result(self.prices, self.amounts_to_sell) self.assertIs(np.allclose(test_min_fee_result[0], [0, 0, -3333.3333]), True, 'result incorrect') self.assertAlmostEqual(test_min_fee_result[1], 33033.333) self.assertAlmostEqual(test_min_fee_result[2], 300.0) print('\nselling result with fixed cost rate with min fee = 300 and moq = 1:') print(self.r.get_selling_result(self.prices, self.amounts_to_sell, 1)) test_min_fee_result = self.r.get_selling_result(self.prices, self.amounts_to_sell, 1) self.assertIs(np.allclose(test_min_fee_result[0], [0, 0, -3333]), True, 'result incorrect') self.assertAlmostEqual(test_min_fee_result[1], 33030) self.assertAlmostEqual(test_min_fee_result[2], 300.0) print('\nselling result with fixed cost rate with min fee = 300 and moq = 100:') print(self.r.get_selling_result(self.prices, self.amounts_to_sell, 100)) test_min_fee_result = self.r.get_selling_result(self.prices, self.amounts_to_sell, 100) self.assertIs(np.allclose(test_min_fee_result[0], [0, 0, -3300]), True, 'result incorrect') self.assertAlmostEqual(test_min_fee_result[1], 32700) self.assertAlmostEqual(test_min_fee_result[2], 300.0) def test_rate_with_min(self): """测试最低交易费用对其他交易费率参数的影响""" self.r.buy_rate = 0.0153 self.r.sell_rate = 0.01 self.r.buy_fix = 0. self.r.sell_fix = 0. self.r.buy_min = 300 self.r.sell_min = 333 self.r.slipage = 0. print('\npurchase result with fixed cost rate with buy_rate = 0.0153, min fee = 300 and moq = 0:') print(self.r.get_purchase_result(self.prices, self.cash_to_spend, 0)) test_rate_with_min_result = self.r.get_purchase_result(self.prices, self.cash_to_spend, 0) self.assertIs(np.allclose(test_rate_with_min_result[0], [0., 984.9305624, 0.]), True, 'result incorrect') self.assertAlmostEqual(test_rate_with_min_result[1], -20000.0, msg='result incorrect') self.assertAlmostEqual(test_rate_with_min_result[2], 301.3887520929774, msg='result incorrect') print('\npurchase result with fixed cost rate with buy_rate = 0.0153, min fee = 300 and moq = 10:') print(self.r.get_purchase_result(self.prices, self.cash_to_spend, 10)) test_rate_with_min_result = self.r.get_purchase_result(self.prices, self.cash_to_spend, 10) self.assertIs(np.allclose(test_rate_with_min_result[0], [0., 980, 0.]), True, 'result incorrect') self.assertAlmostEqual(test_rate_with_min_result[1], -19900.0, msg='result incorrect') self.assertAlmostEqual(test_rate_with_min_result[2], 300.0, msg='result incorrect') print('\npurchase result with fixed cost rate with buy_rate = 0.0153, min fee = 300 and moq = 100:') print(self.r.get_purchase_result(self.prices, self.cash_to_spend, 100)) test_rate_with_min_result = self.r.get_purchase_result(self.prices, self.cash_to_spend, 100) self.assertIs(np.allclose(test_rate_with_min_result[0], [0., 900, 0.]), True, 'result incorrect') self.assertAlmostEqual(test_rate_with_min_result[1], -18300.0, msg='result incorrect') self.assertAlmostEqual(test_rate_with_min_result[2], 300.0, msg='result incorrect') print('\nselling result with fixed cost rate with sell_rate = 0.01, min fee = 333 and moq = 0:') print(self.r.get_selling_result(self.prices, self.amounts_to_sell)) test_rate_with_min_result = self.r.get_selling_result(self.prices, self.amounts_to_sell) self.assertIs(np.allclose(test_rate_with_min_result[0], [0, 0, -3333.3333]), True, 'result incorrect') self.assertAlmostEqual(test_rate_with_min_result[1], 32999.99967) self.assertAlmostEqual(test_rate_with_min_result[2], 333.33333) print('\nselling result with fixed cost rate with sell_rate = 0.01, min fee = 333 and moq = 1:') print(self.r.get_selling_result(self.prices, self.amounts_to_sell, 1)) test_rate_with_min_result = self.r.get_selling_result(self.prices, self.amounts_to_sell, 1) self.assertIs(np.allclose(test_rate_with_min_result[0], [0, 0, -3333]), True, 'result incorrect') self.assertAlmostEqual(test_rate_with_min_result[1], 32996.7) self.assertAlmostEqual(test_rate_with_min_result[2], 333.3) print('\nselling result with fixed cost rate with sell_rate = 0.01, min fee = 333 and moq = 100:') print(self.r.get_selling_result(self.prices, self.amounts_to_sell, 100)) test_rate_with_min_result = self.r.get_selling_result(self.prices, self.amounts_to_sell, 100) self.assertIs(np.allclose(test_rate_with_min_result[0], [0, 0, -3300]), True, 'result incorrect') self.assertAlmostEqual(test_rate_with_min_result[1], 32667.0) self.assertAlmostEqual(test_rate_with_min_result[2], 333.0) def test_fixed_fee(self): """测试固定交易费用""" self.r.buy_rate = 0. self.r.sell_rate = 0. self.r.buy_fix = 200 self.r.sell_fix = 150 self.r.buy_min = 0 self.r.sell_min = 0 self.r.slipage = 0 print('\nselling result of fixed cost with fixed fee = 150 and moq=0:') print(self.r.get_selling_result(self.prices, self.amounts_to_sell, 0)) test_fixed_fee_result = self.r.get_selling_result(self.prices, self.amounts_to_sell) self.assertIs(np.allclose(test_fixed_fee_result[0], [0, 0, -3333.3333]), True, 'result incorrect') self.assertAlmostEqual(test_fixed_fee_result[1], 33183.333, msg='result incorrect') self.assertAlmostEqual(test_fixed_fee_result[2], 150.0, msg='result incorrect') print('\nselling result of fixed cost with fixed fee = 150 and moq=100:') print(self.r.get_selling_result(self.prices, self.amounts_to_sell, 100)) test_fixed_fee_result = self.r.get_selling_result(self.prices, self.amounts_to_sell, 100) self.assertIs(np.allclose(test_fixed_fee_result[0], [0, 0, -3300.]), True, f'result incorrect, {test_fixed_fee_result[0]} does not equal to [0,0,-3400]') self.assertAlmostEqual(test_fixed_fee_result[1], 32850., msg='result incorrect') self.assertAlmostEqual(test_fixed_fee_result[2], 150., msg='result incorrect') print('\npurchase result of fixed cost with fixed fee = 200:') print(self.r.get_purchase_result(self.prices, self.cash_to_spend, 0)) test_fixed_fee_result = self.r.get_purchase_result(self.prices, self.cash_to_spend, 0) self.assertIs(np.allclose(test_fixed_fee_result[0], [0., 990., 0.]), True, 'result incorrect') self.assertAlmostEqual(test_fixed_fee_result[1], -20000.0, msg='result incorrect') self.assertAlmostEqual(test_fixed_fee_result[2], 200.0, msg='result incorrect') print('\npurchase result of fixed cost with fixed fee = 200:') print(self.r.get_purchase_result(self.prices, self.cash_to_spend, 100)) test_fixed_fee_result = self.r.get_purchase_result(self.prices, self.cash_to_spend, 100) self.assertIs(np.allclose(test_fixed_fee_result[0], [0., 900., 0.]), True, 'result incorrect') self.assertAlmostEqual(test_fixed_fee_result[1], -18200.0, msg='result incorrect') self.assertAlmostEqual(test_fixed_fee_result[2], 200.0, msg='result incorrect') def test_slipage(self): """测试交易滑点""" self.r.buy_fix = 0 self.r.sell_fix = 0 self.r.buy_min = 0 self.r.sell_min = 0 self.r.buy_rate = 0.003 self.r.sell_rate = 0.001 self.r.slipage = 1E-9 print('\npurchase result of fixed rate = 0.003 and slipage = 1E-10 and moq = 0:') print(self.r.get_purchase_result(self.prices, self.cash_to_spend, 0)) print('\npurchase result of fixed rate = 0.003 and slipage = 1E-10 and moq = 100:') print(self.r.get_purchase_result(self.prices, self.cash_to_spend, 100)) print('\nselling result with fixed rate = 0.001 and slipage = 1E-10:') print(self.r.get_selling_result(self.prices, self.amounts_to_sell)) test_fixed_fee_result = self.r.get_selling_result(self.prices, self.amounts_to_sell) self.assertIs(np.allclose(test_fixed_fee_result[0], [0, 0, -3333.3333]), True, f'{test_fixed_fee_result[0]} does not equal to [0, 0, -10000]') self.assertAlmostEqual(test_fixed_fee_result[1], 33298.88855591, msg=f'{test_fixed_fee_result[1]} does not equal to 99890.') self.assertAlmostEqual(test_fixed_fee_result[2], 34.44444409, msg=f'{test_fixed_fee_result[2]} does not equal to -36.666663.') test_fixed_fee_result = self.r.get_purchase_result(self.prices, self.cash_to_spend, 0) self.assertIs(np.allclose(test_fixed_fee_result[0], [0., 996.98909294, 0.]), True, 'result incorrect') self.assertAlmostEqual(test_fixed_fee_result[1], -20000.0, msg='result incorrect') self.assertAlmostEqual(test_fixed_fee_result[2], 60.21814121353513, msg='result incorrect') test_fixed_fee_result = self.r.get_purchase_result(self.prices, self.cash_to_spend, 100) self.assertIs(np.allclose(test_fixed_fee_result[0], [0., 900., 0.]), True, 'result incorrect') self.assertAlmostEqual(test_fixed_fee_result[1], -18054.36, msg='result incorrect') self.assertAlmostEqual(test_fixed_fee_result[2], 54.36, msg='result incorrect') class TestSpace(unittest.TestCase): def test_creation(self): """ test if creation of space object is fine """ # first group of inputs, output Space with two discr axis from [0,10] print('testing space objects\n') # pars_list = [[(0, 10), (0, 10)], # [[0, 10], [0, 10]]] # # types_list = ['discr', # ['discr', 'discr']] # # input_pars = itertools.product(pars_list, types_list) # for p in input_pars: # # print(p) # s = qt.Space(*p) # b = s.boes # t = s.types # # print(s, t) # self.assertIsInstance(s, qt.Space) # self.assertEqual(b, [(0, 10), (0, 10)], 'boes incorrect!') # self.assertEqual(t, ['discr', 'discr'], 'types incorrect') # pars_list = [[(0, 10), (0, 10)], [[0, 10], [0, 10]]] types_list = ['foo, bar', ['foo', 'bar']] input_pars = itertools.product(pars_list, types_list) for p in input_pars: # print(p) s = Space(*p) b = s.boes t = s.types # print(s, t) self.assertEqual(b, [(0, 10), (0, 10)], 'boes incorrect!') self.assertEqual(t, ['enum', 'enum'], 'types incorrect') pars_list = [[(0, 10), (0, 10)], [[0, 10], [0, 10]]] types_list = [['discr', 'foobar']] input_pars = itertools.product(pars_list, types_list) for p in input_pars: # print(p) s = Space(*p) b = s.boes t = s.types # print(s, t) self.assertEqual(b, [(0, 10), (0, 10)], 'boes incorrect!') self.assertEqual(t, ['discr', 'enum'], 'types incorrect') pars_list = [(0., 10), (0, 10)] s = Space(pars=pars_list, par_types=None) self.assertEqual(s.types, ['conti', 'discr']) self.assertEqual(s.dim, 2) self.assertEqual(s.size, (10.0, 11)) self.assertEqual(s.shape, (np.inf, 11)) self.assertEqual(s.count, np.inf) self.assertEqual(s.boes, [(0., 10), (0, 10)]) pars_list = [(0., 10), (0, 10)] s = Space(pars=pars_list, par_types='conti, enum') self.assertEqual(s.types, ['conti', 'enum']) self.assertEqual(s.dim, 2) self.assertEqual(s.size, (10.0, 2)) self.assertEqual(s.shape, (np.inf, 2)) self.assertEqual(s.count, np.inf) self.assertEqual(s.boes, [(0., 10), (0, 10)]) pars_list = [(1, 2), (2, 3), (3, 4)] s = Space(pars=pars_list) self.assertEqual(s.types, ['discr', 'discr', 'discr']) self.assertEqual(s.dim, 3) self.assertEqual(s.size, (2, 2, 2)) self.assertEqual(s.shape, (2, 2, 2)) self.assertEqual(s.count, 8) self.assertEqual(s.boes, [(1, 2), (2, 3), (3, 4)]) pars_list = [(1, 2, 3), (2, 3, 4), (3, 4, 5)] s = Space(pars=pars_list) self.assertEqual(s.types, ['enum', 'enum', 'enum']) self.assertEqual(s.dim, 3) self.assertEqual(s.size, (3, 3, 3)) self.assertEqual(s.shape, (3, 3, 3)) self.assertEqual(s.count, 27) self.assertEqual(s.boes, [(1, 2, 3), (2, 3, 4), (3, 4, 5)]) pars_list = [((1, 2, 3), (2, 3, 4), (3, 4, 5))] s = Space(pars=pars_list) self.assertEqual(s.types, ['enum']) self.assertEqual(s.dim, 1) self.assertEqual(s.size, (3,)) self.assertEqual(s.shape, (3,)) self.assertEqual(s.count, 3) pars_list = ((1, 2, 3), (2, 3, 4), (3, 4, 5)) s = Space(pars=pars_list) self.assertEqual(s.types, ['enum', 'enum', 'enum']) self.assertEqual(s.dim, 3) self.assertEqual(s.size, (3, 3, 3)) self.assertEqual(s.shape, (3, 3, 3)) self.assertEqual(s.count, 27) self.assertEqual(s.boes, [(1, 2, 3), (2, 3, 4), (3, 4, 5)]) def test_extract(self): """ :return: """ pars_list = [(0, 10), (0, 10)] types_list = ['discr', 'discr'] s = Space(pars=pars_list, par_types=types_list) extracted_int, count = s.extract(3, 'interval') extracted_int_list = list(extracted_int) print('extracted int\n', extracted_int_list) self.assertEqual(count, 16, 'extraction count wrong!') self.assertEqual(extracted_int_list, [(0, 0), (0, 3), (0, 6), (0, 9), (3, 0), (3, 3), (3, 6), (3, 9), (6, 0), (6, 3), (6, 6), (6, 9), (9, 0), (9, 3), (9, 6), (9, 9)], 'space extraction wrong!') extracted_rand, count = s.extract(10, 'rand') extracted_rand_list = list(extracted_rand) self.assertEqual(count, 10, 'extraction count wrong!') print('extracted rand\n', extracted_rand_list) for point in list(extracted_rand_list): self.assertEqual(len(point), 2) self.assertLessEqual(point[0], 10) self.assertGreaterEqual(point[0], 0) self.assertLessEqual(point[1], 10) self.assertGreaterEqual(point[1], 0) pars_list = [(0., 10), (0, 10)] s = Space(pars=pars_list, par_types=None) extracted_int2, count = s.extract(3, 'interval') self.assertEqual(count, 16, 'extraction count wrong!') extracted_int_list2 = list(extracted_int2) self.assertEqual(extracted_int_list2, [(0, 0), (0, 3), (0, 6), (0, 9), (3, 0), (3, 3), (3, 6), (3, 9), (6, 0), (6, 3), (6, 6), (6, 9), (9, 0), (9, 3), (9, 6), (9, 9)], 'space extraction wrong!') print('extracted int list 2\n', extracted_int_list2) self.assertIsInstance(extracted_int_list2[0][0], float) self.assertIsInstance(extracted_int_list2[0][1], (int, int64)) extracted_rand2, count = s.extract(10, 'rand') self.assertEqual(count, 10, 'extraction count wrong!') extracted_rand_list2 = list(extracted_rand2) print('extracted rand list 2:\n', extracted_rand_list2) for point in extracted_rand_list2: self.assertEqual(len(point), 2) self.assertIsInstance(point[0], float) self.assertLessEqual(point[0], 10) self.assertGreaterEqual(point[0], 0) self.assertIsInstance(point[1], (int, int64)) self.assertLessEqual(point[1], 10) self.assertGreaterEqual(point[1], 0) pars_list = [(0., 10), ('a', 'b')] s = Space(pars=pars_list, par_types='enum, enum') extracted_int3, count = s.extract(1, 'interval') self.assertEqual(count, 4, 'extraction count wrong!') extracted_int_list3 = list(extracted_int3) self.assertEqual(extracted_int_list3, [(0., 'a'), (0., 'b'), (10, 'a'), (10, 'b')], 'space extraction wrong!') print('extracted int list 3\n', extracted_int_list3) self.assertIsInstance(extracted_int_list3[0][0], float) self.assertIsInstance(extracted_int_list3[0][1], str) extracted_rand3, count = s.extract(3, 'rand') self.assertEqual(count, 3, 'extraction count wrong!') extracted_rand_list3 = list(extracted_rand3) print('extracted rand list 3:\n', extracted_rand_list3) for point in extracted_rand_list3: self.assertEqual(len(point), 2) self.assertIsInstance(point[0], (float, int)) self.assertLessEqual(point[0], 10) self.assertGreaterEqual(point[0], 0) self.assertIsInstance(point[1], str) self.assertIn(point[1], ['a', 'b']) pars_list = [((0, 10), (1, 'c'), ('a', 'b'), (1, 14))] s = Space(pars=pars_list, par_types='enum') extracted_int4, count = s.extract(1, 'interval') self.assertEqual(count, 4, 'extraction count wrong!') extracted_int_list4 = list(extracted_int4) it = zip(extracted_int_list4, [(0, 10), (1, 'c'), (0, 'b'), (1, 14)]) for item, item2 in it: print(item, item2) self.assertTrue(all([tuple(ext_item) == item for ext_item, item in it])) print('extracted int list 4\n', extracted_int_list4) self.assertIsInstance(extracted_int_list4[0], tuple) extracted_rand4, count = s.extract(3, 'rand') self.assertEqual(count, 3, 'extraction count wrong!') extracted_rand_list4 = list(extracted_rand4) print('extracted rand list 4:\n', extracted_rand_list4) for point in extracted_rand_list4: self.assertEqual(len(point), 2) self.assertIsInstance(point[0], (int, str)) self.assertIn(point[0], [0, 1, 'a']) self.assertIsInstance(point[1], (int, str)) self.assertIn(point[1], [10, 14, 'b', 'c']) self.assertIn(point, [(0., 10), (1, 'c'), ('a', 'b'), (1, 14)]) pars_list = [((0, 10), (1, 'c'), ('a', 'b'), (1, 14)), (1, 4)] s = Space(pars=pars_list, par_types='enum, discr') extracted_int5, count = s.extract(1, 'interval') self.assertEqual(count, 16, 'extraction count wrong!') extracted_int_list5 = list(extracted_int5) for item, item2 in extracted_int_list5: print(item, item2) self.assertTrue(all([tuple(ext_item) == item for ext_item, item in it])) print('extracted int list 5\n', extracted_int_list5) self.assertIsInstance(extracted_int_list5[0], tuple) extracted_rand5, count = s.extract(5, 'rand') self.assertEqual(count, 5, 'extraction count wrong!') extracted_rand_list5 = list(extracted_rand5) print('extracted rand list 5:\n', extracted_rand_list5) for point in extracted_rand_list5: self.assertEqual(len(point), 2) self.assertIsInstance(point[0], tuple) print(f'type of point[1] is {type(point[1])}') self.assertIsInstance(point[1], (int, np.int64)) self.assertIn(point[0], [(0., 10), (1, 'c'), ('a', 'b'), (1, 14)]) print(f'test incremental extraction') pars_list = [(10., 250), (10., 250), (10., 250), (10., 250), (10., 250), (10., 250)] s = Space(pars_list) ext, count = s.extract(64, 'interval') self.assertEqual(count, 4096) points = list(ext) # 已经取出所有的点,围绕其中10个点生成十个subspaces # 检查是否每个subspace都为Space,是否都在s范围内,使用32生成点集,检查生成数量是否正确 for point in points[1000:1010]: subspace = s.from_point(point, 64) self.assertIsInstance(subspace, Space) self.assertTrue(subspace in s) self.assertEqual(subspace.dim, 6) self.assertEqual(subspace.types, ['conti', 'conti', 'conti', 'conti', 'conti', 'conti']) ext, count = subspace.extract(32) points = list(ext) self.assertGreaterEqual(count, 512) self.assertLessEqual(count, 4096) print(f'\n---------------------------------' f'\nthe space created around point <{point}> is' f'\n{subspace.boes}' f'\nand extracted {count} points, the first 5 are:' f'\n{points[:5]}') def test_axis_extract(self): # test axis object with conti type axis = Axis((0., 5)) self.assertIsInstance(axis, Axis) self.assertEqual(axis.axis_type, 'conti') self.assertEqual(axis.axis_boe, (0., 5.)) self.assertEqual(axis.count, np.inf) self.assertEqual(axis.size, 5.0) self.assertTrue(np.allclose(axis.extract(1, 'int'), [0., 1., 2., 3., 4.])) self.assertTrue(np.allclose(axis.extract(0.5, 'int'), [0., 0.5, 1., 1.5, 2., 2.5, 3., 3.5, 4., 4.5])) extracted = axis.extract(8, 'rand') self.assertEqual(len(extracted), 8) self.assertTrue(all([(0 <= item <= 5) for item in extracted])) # test axis object with discrete type axis = Axis((1, 5)) self.assertIsInstance(axis, Axis) self.assertEqual(axis.axis_type, 'discr') self.assertEqual(axis.axis_boe, (1, 5)) self.assertEqual(axis.count, 5) self.assertEqual(axis.size, 5) self.assertTrue(np.allclose(axis.extract(1, 'int'), [1, 2, 3, 4, 5])) self.assertRaises(ValueError, axis.extract, 0.5, 'int') extracted = axis.extract(8, 'rand') self.assertEqual(len(extracted), 8) self.assertTrue(all([(item in [1, 2, 3, 4, 5]) for item in extracted])) # test axis object with enumerate type axis = Axis((1, 5, 7, 10, 'A', 'F')) self.assertIsInstance(axis, Axis) self.assertEqual(axis.axis_type, 'enum') self.assertEqual(axis.axis_boe, (1, 5, 7, 10, 'A', 'F')) self.assertEqual(axis.count, 6) self.assertEqual(axis.size, 6) self.assertEqual(axis.extract(1, 'int'), [1, 5, 7, 10, 'A', 'F']) self.assertRaises(ValueError, axis.extract, 0.5, 'int') extracted = axis.extract(8, 'rand') self.assertEqual(len(extracted), 8) self.assertTrue(all([(item in [1, 5, 7, 10, 'A', 'F']) for item in extracted])) def test_from_point(self): """测试从一个点生成一个space""" # 生成一个space,指定space中的一个点以及distance,生成一个sub-space pars_list = [(0., 10), (0, 10)] s = Space(pars=pars_list, par_types=None) self.assertEqual(s.types, ['conti', 'discr']) self.assertEqual(s.dim, 2) self.assertEqual(s.size, (10., 11)) self.assertEqual(s.shape, (np.inf, 11)) self.assertEqual(s.count, np.inf) self.assertEqual(s.boes, [(0., 10), (0, 10)]) print('create subspace from a point in space') p = (3, 3) distance = 2 subspace = s.from_point(p, distance) self.assertIsInstance(subspace, Space) self.assertEqual(subspace.types, ['conti', 'discr']) self.assertEqual(subspace.dim, 2) self.assertEqual(subspace.size, (4.0, 5)) self.assertEqual(subspace.shape, (np.inf, 5)) self.assertEqual(subspace.count, np.inf) self.assertEqual(subspace.boes, [(1, 5), (1, 5)]) print('create subspace from a 6 dimensional discrete space') s = Space(pars=[(10, 250), (10, 250), (10, 250), (10, 250), (10, 250), (10, 250)]) p = (15, 200, 150, 150, 150, 150) d = 10 subspace = s.from_point(p, d) self.assertIsInstance(subspace, Space) self.assertEqual(subspace.types, ['discr', 'discr', 'discr', 'discr', 'discr', 'discr']) self.assertEqual(subspace.dim, 6) self.assertEqual(subspace.volume, 65345616) self.assertEqual(subspace.size, (16, 21, 21, 21, 21, 21)) self.assertEqual(subspace.shape, (16, 21, 21, 21, 21, 21)) self.assertEqual(subspace.count, 65345616) self.assertEqual(subspace.boes, [(10, 25), (190, 210), (140, 160), (140, 160), (140, 160), (140, 160)]) print('create subspace from a 6 dimensional continuous space') s = Space(pars=[(10., 250), (10., 250), (10., 250), (10., 250), (10., 250), (10., 250)]) p = (15, 200, 150, 150, 150, 150) d = 10 subspace = s.from_point(p, d) self.assertIsInstance(subspace, Space) self.assertEqual(subspace.types, ['conti', 'conti', 'conti', 'conti', 'conti', 'conti']) self.assertEqual(subspace.dim, 6) self.assertEqual(subspace.volume, 48000000) self.assertEqual(subspace.size, (15.0, 20.0, 20.0, 20.0, 20.0, 20.0)) self.assertEqual(subspace.shape, (np.inf, np.inf, np.inf, np.inf, np.inf, np.inf)) self.assertEqual(subspace.count, np.inf) self.assertEqual(subspace.boes, [(10, 25), (190, 210), (140, 160), (140, 160), (140, 160), (140, 160)]) print('create subspace with different distances on each dimension') s = Space(pars=[(10., 250), (10., 250), (10., 250), (10., 250), (10., 250), (10., 250)]) p = (15, 200, 150, 150, 150, 150) d = [10, 5, 5, 10, 10, 5] subspace = s.from_point(p, d) self.assertIsInstance(subspace, Space) self.assertEqual(subspace.types, ['conti', 'conti', 'conti', 'conti', 'conti', 'conti']) self.assertEqual(subspace.dim, 6) self.assertEqual(subspace.volume, 6000000) self.assertEqual(subspace.size, (15.0, 10.0, 10.0, 20.0, 20.0, 10.0)) self.assertEqual(subspace.shape, (np.inf, np.inf, np.inf, np.inf, np.inf, np.inf)) self.assertEqual(subspace.count, np.inf) self.assertEqual(subspace.boes, [(10, 25), (195, 205), (145, 155), (140, 160), (140, 160), (145, 155)]) class TestCashPlan(unittest.TestCase): def setUp(self): self.cp1 = qt.CashPlan(['2012-01-01', '2010-01-01'], [10000, 20000], 0.1) self.cp1.info() self.cp2 = qt.CashPlan(['20100501'], 10000) self.cp2.info() self.cp3 = qt.CashPlan(pd.date_range(start='2019-01-01', freq='Y', periods=12), [i * 1000 + 10000 for i in range(12)], 0.035) self.cp3.info() def test_creation(self): self.assertIsInstance(self.cp1, qt.CashPlan, 'CashPlan object creation wrong') self.assertIsInstance(self.cp2, qt.CashPlan, 'CashPlan object creation wrong') self.assertIsInstance(self.cp3, qt.CashPlan, 'CashPlan object creation wrong') # test __repr__() print(self.cp1) print(self.cp2) print(self.cp3) # test __str__() self.cp1.info() self.cp2.info() self.cp3.info() # test assersion errors self.assertRaises(AssertionError, qt.CashPlan, '2016-01-01', [10000, 10000]) self.assertRaises(KeyError, qt.CashPlan, '2020-20-20', 10000) def test_properties(self): self.assertEqual(self.cp1.amounts, [20000, 10000], 'property wrong') self.assertEqual(self.cp1.first_day, Timestamp('2010-01-01')) self.assertEqual(self.cp1.last_day, Timestamp('2012-01-01')) self.assertEqual(self.cp1.investment_count, 2) self.assertEqual(self.cp1.period, 730) self.assertEqual(self.cp1.dates, [Timestamp('2010-01-01'), Timestamp('2012-01-01')]) self.assertEqual(self.cp1.ir, 0.1) self.assertAlmostEqual(self.cp1.closing_value, 34200) self.assertAlmostEqual(self.cp2.closing_value, 10000) self.assertAlmostEqual(self.cp3.closing_value, 220385.3483685) self.assertIsInstance(self.cp1.plan, pd.DataFrame) self.assertIsInstance(self.cp2.plan, pd.DataFrame) self.assertIsInstance(self.cp3.plan, pd.DataFrame) def test_operation(self): cp_self_add = self.cp1 + self.cp1 cp_add = self.cp1 + self.cp2 cp_add_int = self.cp1 + 10000 cp_mul_int = self.cp1 * 2 cp_mul_float = self.cp2 * 1.5 cp_mul_time = 3 * self.cp2 cp_mul_time2 = 2 * self.cp1 cp_mul_time3 = 2 * self.cp3 cp_mul_float2 = 2. * self.cp3 self.assertIsInstance(cp_self_add, qt.CashPlan) self.assertEqual(cp_self_add.amounts, [40000, 20000]) self.assertEqual(cp_add.amounts, [20000, 10000, 10000]) self.assertEqual(cp_add_int.amounts, [30000, 20000]) self.assertEqual(cp_mul_int.amounts, [40000, 20000]) self.assertEqual(cp_mul_float.amounts, [15000]) self.assertEqual(cp_mul_float.dates, [Timestamp('2010-05-01')]) self.assertEqual(cp_mul_time.amounts, [10000, 10000, 10000]) self.assertEqual(cp_mul_time.dates, [Timestamp('2010-05-01'), Timestamp('2011-05-01'), Timestamp('2012-04-30')]) self.assertEqual(cp_mul_time2.amounts, [20000, 10000, 20000, 10000]) self.assertEqual(cp_mul_time2.dates, [Timestamp('2010-01-01'), Timestamp('2012-01-01'), Timestamp('2014-01-01'), Timestamp('2016-01-01')]) self.assertEqual(cp_mul_time3.dates, [Timestamp('2019-12-31'), Timestamp('2020-12-31'), Timestamp('2021-12-31'), Timestamp('2022-12-31'), Timestamp('2023-12-31'), Timestamp('2024-12-31'), Timestamp('2025-12-31'), Timestamp('2026-12-31'), Timestamp('2027-12-31'), Timestamp('2028-12-31'), Timestamp('2029-12-31'), Timestamp('2030-12-31'), Timestamp('2031-12-29'), Timestamp('2032-12-29'), Timestamp('2033-12-29'), Timestamp('2034-12-29'), Timestamp('2035-12-29'), Timestamp('2036-12-29'), Timestamp('2037-12-29'), Timestamp('2038-12-29'), Timestamp('2039-12-29'), Timestamp('2040-12-29'), Timestamp('2041-12-29'), Timestamp('2042-12-29')]) self.assertEqual(cp_mul_float2.dates, [Timestamp('2019-12-31'), Timestamp('2020-12-31'), Timestamp('2021-12-31'), Timestamp('2022-12-31'), Timestamp('2023-12-31'), Timestamp('2024-12-31'), Timestamp('2025-12-31'), Timestamp('2026-12-31'), Timestamp('2027-12-31'), Timestamp('2028-12-31'), Timestamp('2029-12-31'), Timestamp('2030-12-31')]) self.assertEqual(cp_mul_float2.amounts, [20000.0, 22000.0, 24000.0, 26000.0, 28000.0, 30000.0, 32000.0, 34000.0, 36000.0, 38000.0, 40000.0, 42000.0]) class TestPool(unittest.TestCase): def setUp(self): self.p = ResultPool(5) self.items = ['first', 'second', (1, 2, 3), 'this', 24] self.perfs = [1, 2, 3, 4, 5] self.additional_result1 = ('abc', 12) self.additional_result2 = ([1, 2], -1) self.additional_result3 = (12, 5) def test_create(self): self.assertIsInstance(self.p, ResultPool) def test_operation(self): self.p.in_pool(self.additional_result1[0], self.additional_result1[1]) self.p.cut() self.assertEqual(self.p.item_count, 1) self.assertEqual(self.p.items, ['abc']) for item, perf in zip(self.items, self.perfs): self.p.in_pool(item, perf) self.assertEqual(self.p.item_count, 6) self.assertEqual(self.p.items, ['abc', 'first', 'second', (1, 2, 3), 'this', 24]) self.p.cut() self.assertEqual(self.p.items, ['second', (1, 2, 3), 'this', 24, 'abc']) self.assertEqual(self.p.perfs, [2, 3, 4, 5, 12]) self.p.in_pool(self.additional_result2[0], self.additional_result2[1]) self.p.in_pool(self.additional_result3[0], self.additional_result3[1]) self.assertEqual(self.p.item_count, 7) self.p.cut(keep_largest=False) self.assertEqual(self.p.items, [[1, 2], 'second', (1, 2, 3), 'this', 24]) self.assertEqual(self.p.perfs, [-1, 2, 3, 4, 5]) class TestCoreSubFuncs(unittest.TestCase): """Test all functions in core.py""" def setUp(self): pass def test_input_to_list(self): print('Testing input_to_list() function') input_str = 'first' self.assertEqual(qt.utilfuncs.input_to_list(input_str, 3), ['first', 'first', 'first']) self.assertEqual(qt.utilfuncs.input_to_list(input_str, 4), ['first', 'first', 'first', 'first']) self.assertEqual(qt.utilfuncs.input_to_list(input_str, 2, None), ['first', 'first']) input_list = ['first', 'second'] self.assertEqual(qt.utilfuncs.input_to_list(input_list, 3), ['first', 'second', None]) self.assertEqual(qt.utilfuncs.input_to_list(input_list, 4, 'padder'), ['first', 'second', 'padder', 'padder']) self.assertEqual(qt.utilfuncs.input_to_list(input_list, 1), ['first', 'second']) self.assertEqual(qt.utilfuncs.input_to_list(input_list, -5), ['first', 'second']) def test_point_in_space(self): sp = Space([(0., 10.), (0., 10.), (0., 10.)]) p1 = (5.5, 3.2, 7) p2 = (-1, 3, 10) self.assertTrue(p1 in sp) print(f'point {p1} is in space {sp}') self.assertFalse(p2 in sp) print(f'point {p2} is not in space {sp}') sp = Space([(0., 10.), (0., 10.), range(40, 3, -2)], 'conti, conti, enum') p1 = (5.5, 3.2, 8) self.assertTrue(p1 in sp) print(f'point {p1} is in space {sp}') def test_space_in_space(self): print('test if a space is in another space') sp = Space([(0., 10.), (0., 10.), (0., 10.)]) sp2 = Space([(0., 10.), (0., 10.), (0., 10.)]) self.assertTrue(sp2 in sp) self.assertTrue(sp in sp2) print(f'space {sp2} is in space {sp}\n' f'and space {sp} is in space {sp2}\n' f'they are equal to each other\n') sp2 = Space([(0, 5.), (2, 7.), (3., 9.)]) self.assertTrue(sp2 in sp) self.assertFalse(sp in sp2) print(f'space {sp2} is in space {sp}\n' f'and space {sp} is not in space {sp2}\n' f'{sp2} is a sub space of {sp}\n') sp2 = Space([(0, 5), (2, 7), (3., 9)]) self.assertFalse(sp2 in sp) self.assertFalse(sp in sp2) print(f'space {sp2} is not in space {sp}\n' f'and space {sp} is not in space {sp2}\n' f'they have different types of axes\n') sp = Space([(0., 10.), (0., 10.), range(40, 3, -2)]) self.assertFalse(sp in sp2) self.assertFalse(sp2 in sp) print(f'space {sp2} is not in space {sp}\n' f'and space {sp} is not in space {sp2}\n' f'they have different types of axes\n') def test_space_around_centre(self): sp = Space([(0., 10.), (0., 10.), (0., 10.)]) p1 = (5.5, 3.2, 7) ssp = space_around_centre(space=sp, centre=p1, radius=1.2) print(ssp.boes) print('\ntest multiple diameters:') self.assertEqual(ssp.boes, [(4.3, 6.7), (2.0, 4.4), (5.8, 8.2)]) ssp = space_around_centre(space=sp, centre=p1, radius=[1, 2, 1]) print(ssp.boes) self.assertEqual(ssp.boes, [(4.5, 6.5), (1.2000000000000002, 5.2), (6.0, 8.0)]) print('\ntest points on edge:') p2 = (5.5, 3.2, 10) ssp = space_around_centre(space=sp, centre=p1, radius=3.9) print(ssp.boes) self.assertEqual(ssp.boes, [(1.6, 9.4), (0.0, 7.1), (3.1, 10.0)]) print('\ntest enum spaces') sp = Space([(0, 100), range(40, 3, -2)], 'discr, enum') p1 = [34, 12] ssp = space_around_centre(space=sp, centre=p1, radius=5, ignore_enums=False) self.assertEqual(ssp.boes, [(29, 39), (22, 20, 18, 16, 14, 12, 10, 8, 6, 4)]) print(ssp.boes) print('\ntest enum space and ignore enum axis') ssp = space_around_centre(space=sp, centre=p1, radius=5) self.assertEqual(ssp.boes, [(29, 39), (40, 38, 36, 34, 32, 30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4)]) print(sp.boes) def test_get_stock_pool(self): print(f'start test building stock pool function\n') share_basics = stock_basic(fields='ts_code,symbol,name,area,industry,market,list_date,exchange') print(f'\nselect all stocks by area') stock_pool = qt.get_stock_pool(area='上海') print(f'{len(stock_pool)} shares selected, first 5 are: {stock_pool[0:5]}\n' f'check if all stock areas are "上海"\n' f'{share_basics[np.isin(share_basics.ts_code, stock_pool)].head()}') self.assertTrue(share_basics[np.isin(share_basics.ts_code, stock_pool)]['area'].eq('上海').all()) print(f'\nselect all stocks by multiple areas') stock_pool = qt.get_stock_pool(area='贵州,北京,天津') print(f'\n{len(stock_pool)} shares selected, first 5 are: {stock_pool[0:5]}\n' f'check if all stock areas are in list of ["贵州", "北京", "天津"]\n' f'{share_basics[np.isin(share_basics.ts_code, stock_pool)].head()}') self.assertTrue(share_basics[np.isin(share_basics.ts_code, stock_pool)]['area'].isin(['贵州', '北京', '天津']).all()) print(f'\nselect all stocks by area and industry') stock_pool = qt.get_stock_pool(area='四川', industry='银行, 金融') print(f'\n{len(stock_pool)} shares selected, first 5 are: {stock_pool[0:5]}\n' f'check if all stock areas are "四川", and industry in ["银行", "金融"]\n' f'{share_basics[np.isin(share_basics.ts_code, stock_pool)].head()}') self.assertTrue(share_basics[np.isin(share_basics.ts_code, stock_pool)]['industry'].isin(['银行', '金融']).all()) self.assertTrue(share_basics[np.isin(share_basics.ts_code, stock_pool)]['area'].isin(['四川']).all()) print(f'\nselect all stocks by industry') stock_pool = qt.get_stock_pool(industry='银行, 金融') print(f'\n{len(stock_pool)} shares selected, first 5 are: {stock_pool[0:5]}\n' f'check if all stocks industry in ["银行", "金融"]\n' f'{share_basics[np.isin(share_basics.ts_code, stock_pool)].head()}') self.assertTrue(share_basics[np.isin(share_basics.ts_code, stock_pool)]['industry'].isin(['银行', '金融']).all()) print(f'\nselect all stocks by market') stock_pool = qt.get_stock_pool(market='主板') print(f'\n{len(stock_pool)} shares selected, first 5 are: {stock_pool[0:5]}\n' f'check if all stock market is "主板"\n' f'{share_basics[np.isin(share_basics.ts_code, stock_pool)].head()}') self.assertTrue(share_basics[np.isin(share_basics.ts_code, stock_pool)]['market'].isin(['主板']).all()) print(f'\nselect all stocks by market and list date') stock_pool = qt.get_stock_pool(date='2000-01-01', market='主板') print(f'\n{len(stock_pool)} shares selected, first 5 are: {stock_pool[0:5]}\n' f'check if all stock market is "主板", and list date after "2000-01-01"\n' f'{share_basics[np.isin(share_basics.ts_code, stock_pool)].head()}') self.assertTrue(share_basics[np.isin(share_basics.ts_code, stock_pool)]['market'].isin(['主板']).all()) self.assertTrue(share_basics[np.isin(share_basics.ts_code, stock_pool)]['list_date'].le('2000-01-01').all()) print(f'\nselect all stocks by list date') stock_pool = qt.get_stock_pool(date='1997-01-01') print(f'\n{len(stock_pool)} shares selected, first 5 are: {stock_pool[0:5]}\n' f'check if all list date after "1997-01-01"\n' f'{share_basics[np.isin(share_basics.ts_code, stock_pool)].head()}') self.assertTrue(share_basics[np.isin(share_basics.ts_code, stock_pool)]['list_date'].le('1997-01-01').all()) print(f'\nselect all stocks by exchange') stock_pool = qt.get_stock_pool(exchange='SSE') print(f'\n{len(stock_pool)} shares selected, first 5 are: {stock_pool[0:5]}\n' f'check if all exchanges are "SSE"\n' f'{share_basics[np.isin(share_basics.ts_code, stock_pool)].head()}') self.assertTrue(share_basics[np.isin(share_basics.ts_code, stock_pool)]['exchange'].eq('SSE').all()) print(f'\nselect all stocks by industry, area and list date') industry_list = ['银行', '全国地产', '互联网', '环境保护', '区域地产', '酒店餐饮', '运输设备', '综合类', '建筑工程', '玻璃', '家用电器', '文教休闲', '其他商业', '元器件', 'IT设备', '其他建材', '汽车服务', '火力发电', '医药商业', '汽车配件', '广告包装', '轻工机械', '新型电力', '多元金融', '饲料'] area_list = ['深圳', '北京', '吉林', '江苏', '辽宁', '广东', '安徽', '四川', '浙江', '湖南', '河北', '新疆', '山东', '河南', '山西', '江西', '青海', '湖北', '内蒙', '海南', '重庆', '陕西', '福建', '广西', '上海'] stock_pool = qt.get_stock_pool(date='19980101', industry=industry_list, area=area_list) print(f'\n{len(stock_pool)} shares selected, first 5 are: {stock_pool[0:5]}\n' f'check if all exchanges are "SSE"\n' f'{share_basics[np.isin(share_basics.ts_code, stock_pool)].head()}') self.assertTrue(share_basics[np.isin(share_basics.ts_code, stock_pool)]['list_date'].le('1998-01-01').all()) self.assertTrue(share_basics[np.isin(share_basics.ts_code, stock_pool)]['industry'].isin(industry_list).all()) self.assertTrue(share_basics[np.isin(share_basics.ts_code, stock_pool)]['area'].isin(area_list).all()) self.assertRaises(KeyError, qt.get_stock_pool, industry=25) self.assertRaises(KeyError, qt.get_stock_pool, share_name='000300.SH') self.assertRaises(KeyError, qt.get_stock_pool, markets='SSE') class TestEvaluations(unittest.TestCase): """Test all evaluation functions in core.py""" # 以下手动计算结果在Excel文件中 def setUp(self): """用np.random生成测试用数据,使用cumsum()模拟股票走势""" self.test_data1 = pd.DataFrame([5.34892759, 5.65768696, 5.79227076, 5.56266871, 5.88189632, 6.24795001, 5.92755558, 6.38748165, 6.31331899, 5.86001665, 5.61048472, 5.30696736, 5.40406792, 5.03180571, 5.37886353, 5.78608307, 6.26540339, 6.59348026, 6.90943801, 6.70911677, 6.33015954, 6.06697417, 5.9752499, 6.45786408, 6.95273763, 6.7691991, 6.70355481, 6.28048969, 6.61344541, 6.24620003, 6.47409983, 6.4522311, 6.8773094, 6.99727832, 6.59262674, 6.59014938, 6.63758237, 6.38331869, 6.09902105, 6.35390109, 6.51993567, 6.87244592, 6.83963485, 7.08797815, 6.88003144, 6.83657323, 6.97819483, 7.01600276, 7.12554256, 7.58941523, 7.61014457, 7.21224091, 7.48174399, 7.66490854, 7.51371968, 7.11586198, 6.97147399, 6.67453301, 6.2042138, 6.33967015, 6.22187938, 5.98426993, 6.37096079, 6.55897161, 6.26422645, 6.69363762, 7.12668015, 6.83232926, 7.30524081, 7.4262041, 7.54031383, 7.17545919, 7.20659257, 7.44886016, 7.37094393, 6.88011022, 7.08142491, 6.74992833, 6.5967097, 6.21336693, 6.35565105, 6.82347596, 6.44773408, 6.84538053, 6.47966466, 6.09699528, 5.63927014, 6.01081024, 6.20585303, 6.60528206, 7.01594726, 7.03684251, 6.76574977, 7.08740846, 6.65336462, 7.07126686, 6.80058956, 6.79241977, 6.47843472, 6.39245474], columns=['value']) self.test_data2 = pd.DataFrame([5.09276527, 4.83828592, 4.6000911, 4.63170487, 4.63566451, 4.50546921, 4.96390044, 4.64557907, 4.25787855, 3.76585551, 3.38826334, 3.76243422, 4.06365426, 3.87084726, 3.91400935, 4.13438822, 4.27064542, 4.56776104, 5.03800296, 5.31070529, 5.39902276, 5.21186286, 5.05683114, 4.68842046, 5.11895168, 5.27151571, 5.72294993, 6.09961056, 6.26569635, 6.48806151, 6.16058885, 6.2582459, 6.38934791, 6.57831057, 6.19508831, 5.70155153, 5.20435735, 5.36538825, 5.40450056, 5.2227697, 5.37828693, 5.53058991, 6.02996797, 5.76802181, 5.66166713, 6.07988994, 5.61794367, 5.63218151, 6.10728013, 6.0324168, 6.27164431, 6.27551239, 6.52329665, 7.00470007, 7.34163113, 7.33699083, 7.67661334, 8.09395749, 7.68086668, 7.58341161, 7.46219819, 7.58671899, 7.19348298, 7.40088323, 7.47562005, 7.93342043, 8.2286081, 8.3521632, 8.43590025, 8.34977395, 8.57563095, 8.81586328, 9.08738649, 9.01542031, 8.8653815, 9.21763111, 9.04233017, 8.59533999, 8.47590075, 8.70857222, 8.78890756, 8.92697606, 9.35743773, 9.68280866, 10.15622021, 10.55908549, 10.6337894, 10.55197128, 10.65435176, 10.54611045, 10.19432562, 10.48320884, 10.36176768, 10.03186854, 10.23656092, 10.0062843, 10.13669686, 10.30758958, 9.87904176, 10.05126375], columns=['value']) self.test_data3 = pd.DataFrame([5.02851874, 5.20700348, 5.02410709, 5.49836387, 5.06834371, 5.10956737, 5.15314979, 5.02256472, 5.09746382, 5.23909247, 4.93410336, 4.96316186, 5.40026682, 5.7353255, 5.53438319, 5.79092139, 5.67528173, 5.89840855, 5.75379463, 6.10855386, 5.77322365, 5.84538021, 5.6103973, 5.7518655, 5.49729695, 5.13610628, 5.30524121, 5.68093462, 5.73251319, 6.04420783, 6.26929843, 6.59610234, 6.09872345, 6.25475121, 6.72927396, 6.91395783, 7.00693283, 7.36217783, 7.71516676, 7.67580263, 7.62477511, 7.73600568, 7.53457914, 7.46170277, 7.83658014, 8.11481319, 8.03705544, 7.64948845, 7.52043731, 7.67247943, 7.46511982, 7.43541798, 7.58856517, 7.9392717, 8.25406287, 7.77031632, 8.03223447, 7.86799055, 7.57630999, 7.33230519, 7.22378732, 6.85972264, 7.17548456, 7.5387846, 7.2392632, 6.8455644, 6.59557185, 6.6496796, 6.73685623, 7.18598015, 7.13619128, 6.88060157, 7.1399681, 7.30308077, 6.94942434, 7.0247815, 7.37567798, 7.50080197, 7.59719284, 7.14520561, 7.29913484, 7.79551341, 8.15497781, 8.40456095, 8.86516528, 8.53042688, 8.94268762, 8.52048006, 8.80036284, 8.91602364, 9.19953385, 8.70828953, 8.24613093, 8.18770453, 7.79548389, 7.68627967, 7.23205036, 6.98302636, 7.06515819, 6.95068113], columns=['value']) self.test_data4 = pd.DataFrame([4.97926539, 5.44016005, 5.45122915, 5.74485615, 5.45600553, 5.44858945, 5.2435413, 5.47315161, 5.58464303, 5.36179749, 5.38236326, 5.29614981, 5.76523508, 5.75102892, 6.15316618, 6.03852528, 6.01442228, 5.70510182, 5.22748133, 5.46762379, 5.78926267, 5.8221362, 5.61236849, 5.30615725, 5.24200611, 5.41042642, 5.59940342, 5.28306781, 4.99451932, 5.08799266, 5.38865647, 5.58229139, 5.33492845, 5.48206276, 5.09721379, 5.39190493, 5.29965087, 5.0374415, 5.50798022, 5.43107577, 5.22759507, 4.991809, 5.43153084, 5.39966868, 5.59916352, 5.66412137, 6.00611838, 5.63564902, 5.66723484, 5.29863863, 4.91115153, 5.3749929, 5.75082334, 6.08308148, 6.58091182, 6.77848803, 7.19588758, 7.64862286, 7.99818347, 7.91824794, 8.30341071, 8.45984973, 7.98700002, 8.18924931, 8.60755649, 8.66233396, 8.91018407, 9.0782739, 9.33515448, 8.95870245, 8.98426422, 8.50340317, 8.64916085, 8.93592407, 8.63145745, 8.65322862, 8.39543204, 8.37969997, 8.23394504, 8.04062872, 7.91259763, 7.57252171, 7.72670114, 7.74486117, 8.06908188, 7.99166889, 7.92155906, 8.39956136, 8.80181323, 8.47464091, 8.06557064, 7.87145573, 8.0237959, 8.39481998, 8.68525692, 8.81185461, 8.98632237, 9.0989835, 8.89787405, 8.86508591], columns=['value']) self.test_data5 = pd.DataFrame([4.50258923, 4.35142568, 4.07459514, 3.87791297, 3.73715985, 3.98455684, 4.07587908, 4.00042472, 4.28276612, 4.01362051, 4.13713565, 4.49312372, 4.48633159, 4.4641207, 4.13444605, 3.79107217, 4.22941629, 4.56548511, 4.92472163, 5.27723158, 5.67409193, 6.00176917, 5.88889928, 5.55256103, 5.39308314, 5.2610492, 5.30738908, 5.22222408, 4.90332238, 4.57499908, 4.96097146, 4.81531011, 4.39115442, 4.63200662, 5.04588813, 4.67866025, 5.01705123, 4.83562258, 4.60381702, 4.66187576, 4.41292828, 4.86604507, 4.42280124, 4.07517294, 4.16317319, 4.10316596, 4.42913598, 4.06609666, 3.96725913, 4.15965746, 4.12379564, 4.04054068, 3.84342851, 3.45902867, 3.17649855, 3.09773586, 3.5502119, 3.66396995, 3.66306483, 3.29131401, 2.79558533, 2.88319542, 3.03671098, 3.44645857, 3.88167161, 3.57961874, 3.60180276, 3.96702102, 4.05429995, 4.40056979, 4.05653231, 3.59600456, 3.60792477, 4.09989922, 3.73503663, 4.01892626, 3.94597242, 3.81466605, 3.71417992, 3.93767156, 4.42806557, 4.06988106, 4.03713636, 4.34408673, 4.79810156, 5.18115011, 4.89798406, 5.3960077, 5.72504875, 5.61894017, 5.1958197, 4.85275896, 5.17550207, 4.71548987, 4.62408567, 4.55488535, 4.36532649, 4.26031979, 4.25225607, 4.58627048], columns=['value']) self.test_data6 = pd.DataFrame([5.08639513, 5.05761083, 4.76160923, 4.62166504, 4.62923183, 4.25070173, 4.13447513, 3.90890013, 3.76687608, 3.43342482, 3.67648224, 3.6274775, 3.9385404, 4.39771627, 4.03199346, 3.93265288, 3.50059789, 3.3851961, 3.29743973, 3.2544872, 2.93692949, 2.70893003, 2.55461976, 2.20922332, 2.29054475, 2.2144714, 2.03726827, 2.39007617, 2.29866155, 2.40607111, 2.40440444, 2.79374649, 2.66541922, 2.27018079, 2.08505127, 2.55478864, 2.22415625, 2.58517923, 2.58802256, 2.94870959, 2.69301739, 2.19991535, 2.69473146, 2.64704637, 2.62753542, 2.14240825, 2.38565154, 1.94592117, 2.32243877, 2.69337246, 2.51283854, 2.62484451, 2.15559054, 2.35410875, 2.31219177, 1.96018265, 2.34711266, 2.58083322, 2.40290041, 2.20439791, 2.31472425, 2.16228248, 2.16439749, 2.20080737, 1.73293206, 1.9264407, 2.25089861, 2.69269101, 2.59296687, 2.1420998, 1.67819153, 1.98419023, 2.14479494, 1.89055376, 1.96720648, 1.9916694, 2.37227761, 2.14446036, 2.34573903, 1.86162546, 2.1410721, 2.39204939, 2.52529064, 2.47079939, 2.9299031, 3.09452923, 2.93276708, 3.21731309, 3.06248964, 2.90413406, 2.67844632, 2.45621213, 2.41463398, 2.7373913, 3.14917045, 3.4033949, 3.82283446, 4.02285451, 3.7619638, 4.10346795], columns=['value']) self.test_data7 = pd.DataFrame([4.75233583, 4.47668283, 4.55894263, 4.61765848, 4.622892, 4.58941116, 4.32535872, 3.88112797, 3.47237806, 3.50898953, 3.82530406, 3.6718017, 3.78918195, 4.1800752, 4.01818557, 4.40822582, 4.65474654, 4.89287256, 4.40879274, 4.65505126, 4.36876403, 4.58418934, 4.75687172, 4.3689799, 4.16126498, 4.0203982, 3.77148242, 3.38198096, 3.07261764, 2.9014741, 2.5049543, 2.756105, 2.28779058, 2.16986991, 1.8415962, 1.83319008, 2.20898291, 2.00128981, 1.75747025, 1.26676663, 1.40316876, 1.11126484, 1.60376367, 1.22523829, 1.58816681, 1.49705679, 1.80244138, 1.55128293, 1.35339409, 1.50985759, 1.0808451, 1.05892796, 1.43414812, 1.43039101, 1.73631655, 1.43940867, 1.82864425, 1.71088265, 2.12015154, 2.45417128, 2.84777618, 2.7925612, 2.90975121, 3.25920745, 3.13801182, 3.52733677, 3.65468491, 3.69395211, 3.49862035, 3.24786017, 3.64463138, 4.00331929, 3.62509565, 3.78013949, 3.4174012, 3.76312271, 3.62054004, 3.67206716, 3.60596058, 3.38636199, 3.42580676, 3.32921095, 3.02976759, 3.28258676, 3.45760838, 3.24917528, 2.94618304, 2.86980011, 2.63191259, 2.39566759, 2.53159917, 2.96273967, 3.25626185, 2.97425402, 3.16412191, 3.58280763, 3.23257727, 3.62353556, 3.12806399, 2.92532313], columns=['value']) # 建立一个长度为 500 个数据点的测试数据, 用于测试数据点多于250个的情况下的评价过程 self.long_data = pd.DataFrame([9.879, 9.916, 10.109, 10.214, 10.361, 10.768, 10.594, 10.288, 10.082, 9.994, 10.125, 10.126, 10.384, 10.734, 10.4, 10.87, 11.338, 11.061, 11.415, 11.724, 12.077, 12.196, 12.064, 12.423, 12.19, 11.729, 11.677, 11.448, 11.485, 10.989, 11.242, 11.239, 11.113, 11.075, 11.471, 11.745, 11.754, 11.782, 12.079, 11.97, 12.178, 11.95, 12.438, 12.612, 12.804, 12.952, 12.612, 12.867, 12.832, 12.832, 13.015, 13.315, 13.249, 12.904, 12.776, 12.64, 12.543, 12.287, 12.225, 11.844, 11.985, 11.945, 11.542, 11.871, 12.245, 12.228, 12.362, 11.899, 11.962, 12.374, 12.816, 12.649, 12.252, 12.579, 12.3, 11.988, 12.177, 12.312, 12.744, 12.599, 12.524, 12.82, 12.67, 12.876, 12.986, 13.271, 13.606, 13.82, 14.161, 13.833, 13.831, 14.137, 13.705, 13.414, 13.037, 12.759, 12.642, 12.948, 13.297, 13.483, 13.836, 14.179, 13.709, 13.655, 13.198, 13.508, 13.953, 14.387, 14.043, 13.987, 13.561, 13.391, 12.923, 12.555, 12.503, 12.292, 11.877, 12.34, 12.141, 11.687, 11.992, 12.458, 12.131, 11.75, 11.739, 11.263, 11.762, 11.976, 11.578, 11.854, 12.136, 12.422, 12.311, 12.56, 12.879, 12.861, 12.973, 13.235, 13.53, 13.531, 13.137, 13.166, 13.31, 13.103, 13.007, 12.643, 12.69, 12.216, 12.385, 12.046, 12.321, 11.9, 11.772, 11.816, 11.871, 11.59, 11.518, 11.94, 11.803, 11.924, 12.183, 12.136, 12.361, 12.406, 11.932, 11.684, 11.292, 11.388, 11.874, 12.184, 12.002, 12.16, 11.741, 11.26, 11.123, 11.534, 11.777, 11.407, 11.275, 11.679, 11.62, 11.218, 11.235, 11.352, 11.366, 11.061, 10.661, 10.582, 10.899, 11.352, 11.792, 11.475, 11.263, 11.538, 11.183, 10.936, 11.399, 11.171, 11.214, 10.89, 10.728, 11.191, 11.646, 11.62, 11.195, 11.178, 11.18, 10.956, 11.205, 10.87, 11.098, 10.639, 10.487, 10.507, 10.92, 10.558, 10.119, 9.882, 9.573, 9.515, 9.845, 9.852, 9.495, 9.726, 10.116, 10.452, 10.77, 11.225, 10.92, 10.824, 11.096, 11.542, 11.06, 10.568, 10.585, 10.884, 10.401, 10.068, 9.964, 10.285, 10.239, 10.036, 10.417, 10.132, 9.839, 9.556, 9.084, 9.239, 9.304, 9.067, 8.587, 8.471, 8.007, 8.321, 8.55, 9.008, 9.138, 9.088, 9.434, 9.156, 9.65, 9.431, 9.654, 10.079, 10.411, 10.865, 10.51, 10.205, 10.519, 10.367, 10.855, 10.642, 10.298, 10.622, 10.173, 9.792, 9.995, 9.904, 9.771, 9.597, 9.506, 9.212, 9.688, 10.032, 9.723, 9.839, 9.918, 10.332, 10.236, 9.989, 10.192, 10.685, 10.908, 11.275, 11.72, 12.158, 12.045, 12.244, 12.333, 12.246, 12.552, 12.958, 13.11, 13.53, 13.123, 13.138, 13.57, 13.389, 13.511, 13.759, 13.698, 13.744, 13.467, 13.795, 13.665, 13.377, 13.423, 13.772, 13.295, 13.073, 12.718, 12.388, 12.399, 12.185, 11.941, 11.818, 11.465, 11.811, 12.163, 11.86, 11.935, 11.809, 12.145, 12.624, 12.768, 12.321, 12.277, 11.889, 12.11, 12.606, 12.943, 12.945, 13.112, 13.199, 13.664, 14.051, 14.189, 14.339, 14.611, 14.656, 15.112, 15.086, 15.263, 15.021, 15.346, 15.572, 15.607, 15.983, 16.151, 16.215, 16.096, 16.089, 16.32, 16.59, 16.657, 16.752, 16.583, 16.743, 16.373, 16.662, 16.243, 16.163, 16.491, 16.958, 16.977, 17.225, 17.637, 17.344, 17.684, 17.892, 18.036, 18.182, 17.803, 17.588, 17.101, 17.538, 17.124, 16.787, 17.167, 17.138, 16.955, 17.148, 17.135, 17.635, 17.718, 17.675, 17.622, 17.358, 17.754, 17.729, 17.576, 17.772, 18.239, 18.441, 18.729, 18.319, 18.608, 18.493, 18.069, 18.122, 18.314, 18.423, 18.709, 18.548, 18.384, 18.391, 17.988, 17.986, 17.653, 17.249, 17.298, 17.06, 17.36, 17.108, 17.348, 17.596, 17.46, 17.635, 17.275, 17.291, 16.933, 17.337, 17.231, 17.146, 17.148, 16.751, 16.891, 17.038, 16.735, 16.64, 16.231, 15.957, 15.977, 16.077, 16.054, 15.797, 15.67, 15.911, 16.077, 16.17, 15.722, 15.258, 14.877, 15.138, 15., 14.811, 14.698, 14.407, 14.583, 14.704, 15.153, 15.436, 15.634, 15.453, 15.877, 15.696, 15.563, 15.927, 16.255, 16.696, 16.266, 16.698, 16.365, 16.493, 16.973, 16.71, 16.327, 16.605, 16.486, 16.846, 16.935, 17.21, 17.389, 17.546, 17.773, 17.641, 17.485, 17.794, 17.354, 16.904, 16.675, 16.43, 16.898, 16.819, 16.921, 17.201, 17.617, 17.368, 17.864, 17.484], columns=['value']) self.long_bench = pd.DataFrame([9.7, 10.179, 10.321, 9.855, 9.936, 10.096, 10.331, 10.662, 10.59, 11.031, 11.154, 10.945, 10.625, 10.233, 10.284, 10.252, 10.221, 10.352, 10.444, 10.773, 10.904, 11.104, 10.797, 10.55, 10.943, 11.352, 11.641, 11.983, 11.696, 12.138, 12.365, 12.379, 11.969, 12.454, 12.947, 13.119, 13.013, 12.763, 12.632, 13.034, 12.681, 12.561, 12.938, 12.867, 13.202, 13.132, 13.539, 13.91, 13.456, 13.692, 13.771, 13.904, 14.069, 13.728, 13.97, 14.228, 13.84, 14.041, 13.963, 13.689, 13.543, 13.858, 14.118, 13.987, 13.611, 14.028, 14.229, 14.41, 14.74, 15.03, 14.915, 15.207, 15.354, 15.665, 15.877, 15.682, 15.625, 15.175, 15.105, 14.893, 14.86, 15.097, 15.178, 15.293, 15.238, 15., 15.283, 14.994, 14.907, 14.664, 14.888, 15.297, 15.313, 15.368, 14.956, 14.802, 14.506, 14.257, 14.619, 15.019, 15.049, 14.625, 14.894, 14.978, 15.434, 15.578, 16.038, 16.107, 16.277, 16.365, 16.204, 16.465, 16.401, 16.895, 17.057, 16.621, 16.225, 16.075, 15.863, 16.292, 16.551, 16.724, 16.817, 16.81, 17.192, 16.86, 16.745, 16.707, 16.552, 16.133, 16.301, 16.08, 15.81, 15.75, 15.909, 16.127, 16.457, 16.204, 16.329, 16.748, 16.624, 17.011, 16.548, 16.831, 16.653, 16.791, 16.57, 16.778, 16.928, 16.932, 17.22, 16.876, 17.301, 17.422, 17.689, 17.316, 17.547, 17.534, 17.409, 17.669, 17.416, 17.859, 17.477, 17.307, 17.245, 17.352, 17.851, 17.412, 17.144, 17.138, 17.085, 16.926, 16.674, 16.854, 17.064, 16.95, 16.609, 16.957, 16.498, 16.552, 16.175, 15.858, 15.697, 15.781, 15.583, 15.36, 15.558, 16.046, 15.968, 15.905, 16.358, 16.783, 17.048, 16.762, 17.224, 17.363, 17.246, 16.79, 16.608, 16.423, 15.991, 15.527, 15.147, 14.759, 14.792, 15.206, 15.148, 15.046, 15.429, 14.999, 15.407, 15.124, 14.72, 14.713, 15.022, 15.092, 14.982, 15.001, 14.734, 14.713, 14.841, 14.562, 15.005, 15.483, 15.472, 15.277, 15.503, 15.116, 15.12, 15.442, 15.476, 15.789, 15.36, 15.764, 16.218, 16.493, 16.642, 17.088, 16.816, 16.645, 16.336, 16.511, 16.2, 15.994, 15.86, 15.929, 16.316, 16.416, 16.746, 17.173, 17.531, 17.627, 17.407, 17.49, 17.768, 17.509, 17.795, 18.147, 18.63, 18.945, 19.021, 19.518, 19.6, 19.744, 19.63, 19.32, 18.933, 19.297, 19.598, 19.446, 19.236, 19.198, 19.144, 19.159, 19.065, 19.032, 18.586, 18.272, 18.119, 18.3, 17.894, 17.744, 17.5, 17.083, 17.092, 16.864, 16.453, 16.31, 16.681, 16.342, 16.447, 16.715, 17.068, 17.067, 16.822, 16.673, 16.675, 16.592, 16.686, 16.397, 15.902, 15.597, 15.357, 15.162, 15.348, 15.603, 15.283, 15.257, 15.082, 14.621, 14.366, 14.039, 13.957, 14.141, 13.854, 14.243, 14.414, 14.033, 13.93, 14.104, 14.461, 14.249, 14.053, 14.165, 14.035, 14.408, 14.501, 14.019, 14.265, 14.67, 14.797, 14.42, 14.681, 15.16, 14.715, 14.292, 14.411, 14.656, 15.094, 15.366, 15.055, 15.198, 14.762, 14.294, 13.854, 13.811, 13.549, 13.927, 13.897, 13.421, 13.037, 13.32, 13.721, 13.511, 13.999, 13.529, 13.418, 13.881, 14.326, 14.362, 13.987, 14.015, 13.599, 13.343, 13.307, 13.689, 13.851, 13.404, 13.577, 13.395, 13.619, 13.195, 12.904, 12.553, 12.294, 12.649, 12.425, 11.967, 12.062, 11.71, 11.645, 12.058, 12.136, 11.749, 11.953, 12.401, 12.044, 11.901, 11.631, 11.396, 11.036, 11.244, 10.864, 11.207, 11.135, 11.39, 11.723, 12.084, 11.8, 11.471, 11.33, 11.504, 11.295, 11.3, 10.901, 10.494, 10.825, 11.054, 10.866, 10.713, 10.875, 10.846, 10.947, 11.422, 11.158, 10.94, 10.521, 10.36, 10.411, 10.792, 10.472, 10.305, 10.525, 10.853, 10.556, 10.72, 10.54, 10.583, 10.299, 10.061, 10.004, 9.903, 9.796, 9.472, 9.246, 9.54, 9.456, 9.177, 9.484, 9.557, 9.493, 9.968, 9.536, 9.39, 8.922, 8.423, 8.518, 8.686, 8.771, 9.098, 9.281, 8.858, 9.027, 8.553, 8.784, 8.996, 9.379, 9.846, 9.855, 9.502, 9.608, 9.761, 9.409, 9.4, 9.332, 9.34, 9.284, 8.844, 8.722, 8.376, 8.775, 8.293, 8.144, 8.63, 8.831, 8.957, 9.18, 9.601, 9.695, 10.018, 9.841, 9.743, 9.292, 8.85, 9.316, 9.288, 9.519, 9.738, 9.289, 9.785, 9.804, 10.06, 10.188, 10.095, 9.739, 9.881, 9.7, 9.991, 10.391, 10.002], columns=['value']) def test_performance_stats(self): """test the function performance_statistics() """ pass def test_fv(self): print(f'test with test data and empty DataFrame') self.assertAlmostEqual(eval_fv(self.test_data1), 6.39245474) self.assertAlmostEqual(eval_fv(self.test_data2), 10.05126375) self.assertAlmostEqual(eval_fv(self.test_data3), 6.95068113) self.assertAlmostEqual(eval_fv(self.test_data4), 8.86508591) self.assertAlmostEqual(eval_fv(self.test_data5), 4.58627048) self.assertAlmostEqual(eval_fv(self.test_data6), 4.10346795) self.assertAlmostEqual(eval_fv(self.test_data7), 2.92532313) self.assertAlmostEqual(eval_fv(pd.DataFrame()), -np.inf) print(f'Error testing') self.assertRaises(AssertionError, eval_fv, 15) self.assertRaises(KeyError, eval_fv, pd.DataFrame([1, 2, 3], columns=['non_value'])) def test_max_drawdown(self): print(f'test with test data and empty DataFrame') self.assertAlmostEqual(eval_max_drawdown(self.test_data1)[0], 0.264274308) self.assertEqual(eval_max_drawdown(self.test_data1)[1], 53) self.assertEqual(eval_max_drawdown(self.test_data1)[2], 86) self.assertTrue(np.isnan(eval_max_drawdown(self.test_data1)[3])) self.assertAlmostEqual(eval_max_drawdown(self.test_data2)[0], 0.334690849) self.assertEqual(eval_max_drawdown(self.test_data2)[1], 0) self.assertEqual(eval_max_drawdown(self.test_data2)[2], 10) self.assertEqual(eval_max_drawdown(self.test_data2)[3], 19) self.assertAlmostEqual(eval_max_drawdown(self.test_data3)[0], 0.244452899) self.assertEqual(eval_max_drawdown(self.test_data3)[1], 90) self.assertEqual(eval_max_drawdown(self.test_data3)[2], 99) self.assertTrue(np.isnan(eval_max_drawdown(self.test_data3)[3])) self.assertAlmostEqual(eval_max_drawdown(self.test_data4)[0], 0.201849684) self.assertEqual(eval_max_drawdown(self.test_data4)[1], 14) self.assertEqual(eval_max_drawdown(self.test_data4)[2], 50) self.assertEqual(eval_max_drawdown(self.test_data4)[3], 54) self.assertAlmostEqual(eval_max_drawdown(self.test_data5)[0], 0.534206456) self.assertEqual(eval_max_drawdown(self.test_data5)[1], 21) self.assertEqual(eval_max_drawdown(self.test_data5)[2], 60) self.assertTrue(np.isnan(eval_max_drawdown(self.test_data5)[3])) self.assertAlmostEqual(eval_max_drawdown(self.test_data6)[0], 0.670062689) self.assertEqual(eval_max_drawdown(self.test_data6)[1], 0) self.assertEqual(eval_max_drawdown(self.test_data6)[2], 70) self.assertTrue(np.isnan(eval_max_drawdown(self.test_data6)[3])) self.assertAlmostEqual(eval_max_drawdown(self.test_data7)[0], 0.783577449) self.assertEqual(eval_max_drawdown(self.test_data7)[1], 17) self.assertEqual(eval_max_drawdown(self.test_data7)[2], 51) self.assertTrue(np.isnan(eval_max_drawdown(self.test_data7)[3])) self.assertEqual(eval_max_drawdown(pd.DataFrame()), -np.inf) print(f'Error testing') self.assertRaises(AssertionError, eval_fv, 15) self.assertRaises(KeyError, eval_fv, pd.DataFrame([1, 2, 3], columns=['non_value'])) # test max drawdown == 0: # TODO: investigate: how does divide by zero change? self.assertAlmostEqual(eval_max_drawdown(self.test_data4 - 5)[0], 1.0770474121951792) self.assertEqual(eval_max_drawdown(self.test_data4 - 5)[1], 14) self.assertEqual(eval_max_drawdown(self.test_data4 - 5)[2], 50) def test_info_ratio(self): reference = self.test_data1 self.assertAlmostEqual(eval_info_ratio(self.test_data2, reference, 'value'), 0.075553316) self.assertAlmostEqual(eval_info_ratio(self.test_data3, reference, 'value'), 0.018949457) self.assertAlmostEqual(eval_info_ratio(self.test_data4, reference, 'value'), 0.056328143) self.assertAlmostEqual(eval_info_ratio(self.test_data5, reference, 'value'), -0.004270068) self.assertAlmostEqual(eval_info_ratio(self.test_data6, reference, 'value'), 0.009198027) self.assertAlmostEqual(eval_info_ratio(self.test_data7, reference, 'value'), -0.000890283) def test_volatility(self): self.assertAlmostEqual(eval_volatility(self.test_data1), 0.748646166) self.assertAlmostEqual(eval_volatility(self.test_data2), 0.75527442) self.assertAlmostEqual(eval_volatility(self.test_data3), 0.654188853) self.assertAlmostEqual(eval_volatility(self.test_data4), 0.688375814) self.assertAlmostEqual(eval_volatility(self.test_data5), 1.089989522) self.assertAlmostEqual(eval_volatility(self.test_data6), 1.775419308) self.assertAlmostEqual(eval_volatility(self.test_data7), 1.962758406) self.assertAlmostEqual(eval_volatility(self.test_data1, logarithm=False), 0.750993311) self.assertAlmostEqual(eval_volatility(self.test_data2, logarithm=False), 0.75571473) self.assertAlmostEqual(eval_volatility(self.test_data3, logarithm=False), 0.655331424) self.assertAlmostEqual(eval_volatility(self.test_data4, logarithm=False), 0.692683021) self.assertAlmostEqual(eval_volatility(self.test_data5, logarithm=False), 1.09602969) self.assertAlmostEqual(eval_volatility(self.test_data6, logarithm=False), 1.774789504) self.assertAlmostEqual(eval_volatility(self.test_data7, logarithm=False), 2.003329156) self.assertEqual(eval_volatility(pd.DataFrame()), -np.inf) self.assertRaises(AssertionError, eval_volatility, [1, 2, 3]) # 测试长数据的Volatility计算 expected_volatility = np.array([np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, 0.39955371, 0.39974258, 0.40309866, 0.40486593, 0.4055514, 0.40710639, 0.40708157, 0.40609006, 0.4073625, 0.40835305, 0.41155304, 0.41218193, 0.41207489, 0.41300276, 0.41308415, 0.41292392, 0.41207645, 0.41238397, 0.41229291, 0.41164056, 0.41316317, 0.41348842, 0.41462249, 0.41474574, 0.41652625, 0.41649176, 0.41701556, 0.4166593, 0.41684221, 0.41491689, 0.41435209, 0.41549087, 0.41849338, 0.41998049, 0.41959106, 0.41907311, 0.41916103, 0.42120773, 0.42052391, 0.42111225, 0.42124589, 0.42356445, 0.42214672, 0.42324022, 0.42476639, 0.42621689, 0.42549439, 0.42533678, 0.42539414, 0.42545038, 0.42593637, 0.42652095, 0.42665489, 0.42699563, 0.42798159, 0.42784512, 0.42898006, 0.42868781, 0.42874188, 0.42789631, 0.4277768, 0.42776827, 0.42685216, 0.42660989, 0.42563155, 0.42618281, 0.42606281, 0.42505222, 0.42653242, 0.42555378, 0.42500842, 0.42561939, 0.42442059, 0.42395414, 0.42384356, 0.42319135, 0.42397497, 0.42488579, 0.42449729, 0.42508766, 0.42509878, 0.42456616, 0.42535577, 0.42681884, 0.42688552, 0.42779918, 0.42706058, 0.42792887, 0.42762114, 0.42894045, 0.42977398, 0.42919859, 0.42829041, 0.42780946, 0.42825318, 0.42858952, 0.42858315, 0.42805601, 0.42764751, 0.42744107, 0.42775518, 0.42707283, 0.4258592, 0.42615335, 0.42526286, 0.4248906, 0.42368986, 0.4232565, 0.42265079, 0.42263954, 0.42153046, 0.42132051, 0.41995353, 0.41916605, 0.41914271, 0.41876945, 0.41740175, 0.41583884, 0.41614026, 0.41457908, 0.41472411, 0.41310876, 0.41261041, 0.41212369, 0.41211677, 0.4100645, 0.40852504, 0.40860297, 0.40745338, 0.40698661, 0.40644546, 0.40591375, 0.40640744, 0.40620663, 0.40656649, 0.40727154, 0.40797605, 0.40807137, 0.40808913, 0.40809676, 0.40711767, 0.40724628, 0.40713077, 0.40772698, 0.40765157, 0.40658297, 0.4065991, 0.405011, 0.40537645, 0.40432626, 0.40390177, 0.40237701, 0.40291623, 0.40301797, 0.40324145, 0.40312864, 0.40328316, 0.40190955, 0.40246506, 0.40237663, 0.40198407, 0.401969, 0.40185623, 0.40198313, 0.40005643, 0.39940743, 0.39850438, 0.39845398, 0.39695093, 0.39697295, 0.39663201, 0.39675444, 0.39538699, 0.39331959, 0.39326074, 0.39193287, 0.39157266, 0.39021327, 0.39062591, 0.38917591, 0.38976991, 0.38864187, 0.38872158, 0.38868096, 0.38868377, 0.38842057, 0.38654784, 0.38649517, 0.38600464, 0.38408115, 0.38323049, 0.38260215, 0.38207663, 0.38142669, 0.38003262, 0.37969367, 0.37768092, 0.37732108, 0.37741991, 0.37617779, 0.37698504, 0.37606784, 0.37499276, 0.37533731, 0.37350437, 0.37375172, 0.37385382, 0.37384003, 0.37338938, 0.37212288, 0.37273075, 0.370559, 0.37038506, 0.37062153, 0.36964661, 0.36818564, 0.3656634, 0.36539259, 0.36428672, 0.36502487, 0.3647148, 0.36551435, 0.36409919, 0.36348181, 0.36254383, 0.36166601, 0.36142665, 0.35954942, 0.35846915, 0.35886759, 0.35813867, 0.35642888, 0.35375231, 0.35061783, 0.35078463, 0.34995508, 0.34688918, 0.34548257, 0.34633158, 0.34622833, 0.34652111, 0.34622774, 0.34540951, 0.34418809, 0.34276593, 0.34160916, 0.33811193, 0.33822709, 0.3391685, 0.33883381]) test_volatility = eval_volatility(self.long_data) test_volatility_roll = self.long_data['volatility'].values self.assertAlmostEqual(test_volatility, np.nanmean(expected_volatility)) self.assertTrue(np.allclose(expected_volatility, test_volatility_roll, equal_nan=True)) def test_sharp(self): self.assertAlmostEqual(eval_sharp(self.test_data1, 5, 0), 0.06135557) self.assertAlmostEqual(eval_sharp(self.test_data2, 5, 0), 0.167858667) self.assertAlmostEqual(eval_sharp(self.test_data3, 5, 0), 0.09950547) self.assertAlmostEqual(eval_sharp(self.test_data4, 5, 0), 0.154928241) self.assertAlmostEqual(eval_sharp(self.test_data5, 5, 0.002), 0.007868673) self.assertAlmostEqual(eval_sharp(self.test_data6, 5, 0.002), 0.018306537) self.assertAlmostEqual(eval_sharp(self.test_data7, 5, 0.002), 0.006259971) # 测试长数据的sharp率计算 expected_sharp = np.array([np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, -0.02346815, -0.02618783, -0.03763912, -0.03296276, -0.03085698, -0.02851101, -0.02375842, -0.02016746, -0.01107885, -0.01426613, -0.00787204, -0.01135784, -0.01164232, -0.01003481, -0.00022512, -0.00046792, -0.01209378, -0.01278892, -0.01298135, -0.01938214, -0.01671044, -0.02120509, -0.0244281, -0.02416067, -0.02763238, -0.027579, -0.02372774, -0.02215294, -0.02467094, -0.02091266, -0.02590194, -0.03049876, -0.02077131, -0.01483653, -0.02488144, -0.02671638, -0.02561547, -0.01957986, -0.02479803, -0.02703162, -0.02658087, -0.01641755, -0.01946472, -0.01647757, -0.01280889, -0.00893643, -0.00643275, -0.00698457, -0.00549962, -0.00654677, -0.00494757, -0.0035633, -0.00109037, 0.00750654, 0.00451208, 0.00625502, 0.01221367, 0.01326454, 0.01535037, 0.02269538, 0.02028715, 0.02127712, 0.02333264, 0.02273159, 0.01670643, 0.01376513, 0.01265342, 0.02211647, 0.01612449, 0.00856706, -0.00077147, -0.00268848, 0.00210993, -0.00443934, -0.00411912, -0.0018756, -0.00867461, -0.00581601, -0.00660835, -0.00861137, -0.00678614, -0.01188408, -0.00589617, -0.00244323, -0.00201891, -0.01042846, -0.01471016, -0.02167034, -0.02258554, -0.01306809, -0.00909086, -0.01233746, -0.00595166, -0.00184208, 0.00750497, 0.01481886, 0.01761972, 0.01562886, 0.01446414, 0.01285826, 0.01357719, 0.00967613, 0.01636272, 0.01458437, 0.02280183, 0.02151903, 0.01700276, 0.01597368, 0.02114336, 0.02233297, 0.02585631, 0.02768459, 0.03519235, 0.04204535, 0.04328161, 0.04672855, 0.05046191, 0.04619848, 0.04525853, 0.05381529, 0.04598861, 0.03947394, 0.04665006, 0.05586077, 0.05617728, 0.06495018, 0.06205172, 0.05665466, 0.06500615, 0.0632062, 0.06084328, 0.05851466, 0.05659229, 0.05159347, 0.0432977, 0.0474047, 0.04231723, 0.03613176, 0.03618391, 0.03591012, 0.03885674, 0.0402686, 0.03846423, 0.04534014, 0.04721458, 0.05130912, 0.05026281, 0.05394312, 0.05529349, 0.05949243, 0.05463304, 0.06195165, 0.06767606, 0.06880985, 0.07048996, 0.07078815, 0.07420767, 0.06773439, 0.0658441, 0.06470875, 0.06302349, 0.06456876, 0.06411282, 0.06216669, 0.067094, 0.07055075, 0.07254976, 0.07119253, 0.06173308, 0.05393352, 0.05681246, 0.05250643, 0.06099845, 0.0655544, 0.06977334, 0.06636514, 0.06177949, 0.06869908, 0.06719767, 0.06178738, 0.05915714, 0.06882277, 0.06756821, 0.06507994, 0.06489791, 0.06553941, 0.073123, 0.07576757, 0.06805446, 0.06063571, 0.05033801, 0.05206971, 0.05540306, 0.05249118, 0.05755587, 0.0586174, 0.05051288, 0.0564852, 0.05757284, 0.06358355, 0.06130082, 0.04925482, 0.03834472, 0.04163981, 0.04648316, 0.04457858, 0.04324626, 0.04328791, 0.04156207, 0.04818652, 0.04972634, 0.06024123, 0.06489556, 0.06255485, 0.06069815, 0.06466389, 0.07081163, 0.07895358, 0.0881782, 0.09374151, 0.08336506, 0.08764795, 0.09080174, 0.08808926, 0.08641158, 0.07811943, 0.06885318, 0.06479503, 0.06851185, 0.07382819, 0.07047903, 0.06658251, 0.07638379, 0.08667974, 0.08867918, 0.08245323, 0.08961866, 0.09905298, 0.0961908, 0.08562706, 0.0839014, 0.0849072, 0.08338395, 0.08783487, 0.09463609, 0.10332336, 0.11806497, 0.11220297, 0.11589097, 0.11678405]) test_sharp = eval_sharp(self.long_data, 5, 0.00035) self.assertAlmostEqual(np.nanmean(expected_sharp), test_sharp) self.assertTrue(np.allclose(self.long_data['sharp'].values, expected_sharp, equal_nan=True)) def test_beta(self): reference = self.test_data1 self.assertAlmostEqual(eval_beta(self.test_data2, reference, 'value'), -0.017148939) self.assertAlmostEqual(eval_beta(self.test_data3, reference, 'value'), -0.042204233) self.assertAlmostEqual(eval_beta(self.test_data4, reference, 'value'), -0.15652986) self.assertAlmostEqual(eval_beta(self.test_data5, reference, 'value'), -0.049195532) self.assertAlmostEqual(eval_beta(self.test_data6, reference, 'value'), -0.026995082) self.assertAlmostEqual(eval_beta(self.test_data7, reference, 'value'), -0.01147809) self.assertRaises(TypeError, eval_beta, [1, 2, 3], reference, 'value') self.assertRaises(TypeError, eval_beta, self.test_data3, [1, 2, 3], 'value') self.assertRaises(KeyError, eval_beta, self.test_data3, reference, 'not_found_value') # 测试长数据的beta计算 expected_beta = np.array([np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, -0.04988841, -0.05127618, -0.04692104, -0.04272652, -0.04080598, -0.0493347, -0.0460858, -0.0416761, -0.03691527, -0.03724924, -0.03678865, -0.03987324, -0.03488321, -0.02567672, -0.02690303, -0.03010128, -0.02437967, -0.02571932, -0.02455681, -0.02839811, -0.03358653, -0.03396697, -0.03466321, -0.03050966, -0.0247583, -0.01629325, -0.01880895, -0.01480403, -0.01348783, -0.00544294, -0.00648176, -0.00467036, -0.01135331, -0.0156841, -0.02340763, -0.02615705, -0.02730771, -0.02906174, -0.02860664, -0.02412914, -0.02066416, -0.01744816, -0.02185133, -0.02145285, -0.02681765, -0.02827694, -0.02394581, -0.02744096, -0.02778825, -0.02703065, -0.03160023, -0.03615371, -0.03681072, -0.04265126, -0.04344738, -0.04232421, -0.04705272, -0.04533344, -0.04605934, -0.05272737, -0.05156463, -0.05134196, -0.04730733, -0.04425352, -0.03869831, -0.04159571, -0.04223998, -0.04346747, -0.04229844, -0.04740093, -0.04992507, -0.04621232, -0.04477644, -0.0486915, -0.04598224, -0.04943463, -0.05006391, -0.05362256, -0.04994067, -0.05464769, -0.05443275, -0.05513493, -0.05173594, -0.04500994, -0.04662891, -0.03903505, -0.0419592, -0.04307773, -0.03925718, -0.03711574, -0.03992631, -0.0433058, -0.04533641, -0.0461183, -0.05600344, -0.05758377, -0.05959874, -0.05605942, -0.06002859, -0.06253002, -0.06747014, -0.06427915, -0.05931947, -0.05769974, -0.04791515, -0.05175088, -0.05748039, -0.05385232, -0.05072975, -0.05052637, -0.05125567, -0.05005785, -0.05325104, -0.04977727, -0.04947867, -0.05148544, -0.05739156, -0.05742069, -0.06047279, -0.0558414, -0.06086126, -0.06265151, -0.06411129, -0.06828052, -0.06781762, -0.07083409, -0.07211207, -0.06799162, -0.06913295, -0.06775162, -0.0696265, -0.06678248, -0.06867502, -0.06581961, -0.07055823, -0.06448184, -0.06097973, -0.05795587, -0.0618383, -0.06130145, -0.06050652, -0.05936661, -0.05749424, -0.0499, -0.05050495, -0.04962687, -0.05033439, -0.05070116, -0.05422009, -0.05369759, -0.05548943, -0.05907353, -0.05933035, -0.05927918, -0.06227663, -0.06011455, -0.05650432, -0.05828134, -0.05620949, -0.05715323, -0.05482478, -0.05387113, -0.05095559, -0.05377999, -0.05334267, -0.05220438, -0.04001521, -0.03892434, -0.03660782, -0.04282708, -0.04324623, -0.04127048, -0.04227559, -0.04275226, -0.04347049, -0.04125853, -0.03806295, -0.0330632, -0.03155531, -0.03277152, -0.03304518, -0.03878731, -0.03830672, -0.03727434, -0.0370571, -0.04509224, -0.04207632, -0.04116198, -0.04545179, -0.04584584, -0.05287341, -0.05417433, -0.05175836, -0.05005509, -0.04268674, -0.03442321, -0.03457309, -0.03613426, -0.03524391, -0.03629479, -0.04361312, -0.02626705, -0.02406115, -0.03046384, -0.03181044, -0.03375164, -0.03661673, -0.04520779, -0.04926951, -0.05726738, -0.0584486, -0.06220608, -0.06800563, -0.06797431, -0.07562211, -0.07481996, -0.07731229, -0.08413381, -0.09031826, -0.09691925, -0.11018071, -0.11952675, -0.10826026, -0.11173895, -0.10756359, -0.10775916, -0.11664559, -0.10505051, -0.10606547, -0.09855355, -0.10004159, -0.10857084, -0.12209301, -0.11605758, -0.11105113, -0.1155195, -0.11569505, -0.10513348, -0.09611072, -0.10719791, -0.10843965, -0.11025856, -0.10247839, -0.10554044, -0.10927647, -0.10645088, -0.09982498, -0.10542734, -0.09631372, -0.08229695]) test_beta_mean = eval_beta(self.long_data, self.long_bench, 'value') test_beta_roll = self.long_data['beta'].values self.assertAlmostEqual(test_beta_mean, np.nanmean(expected_beta)) self.assertTrue(np.allclose(test_beta_roll, expected_beta, equal_nan=True)) def test_alpha(self): reference = self.test_data1 self.assertAlmostEqual(eval_alpha(self.test_data2, 5, reference, 'value', 0.5), 11.63072977) self.assertAlmostEqual(eval_alpha(self.test_data3, 5, reference, 'value', 0.5), 1.886590071) self.assertAlmostEqual(eval_alpha(self.test_data4, 5, reference, 'value', 0.5), 6.827021872) self.assertAlmostEqual(eval_alpha(self.test_data5, 5, reference, 'value', 0.92), -1.192265168) self.assertAlmostEqual(eval_alpha(self.test_data6, 5, reference, 'value', 0.92), -1.437142359) self.assertAlmostEqual(eval_alpha(self.test_data7, 5, reference, 'value', 0.92), -1.781311545) # 测试长数据的alpha计算 expected_alpha = np.array([np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, -0.09418119, -0.11188463, -0.17938358, -0.15588172, -0.1462678, -0.13089586, -0.10780125, -0.09102891, -0.03987585, -0.06075686, -0.02459503, -0.04104284, -0.0444565, -0.04074585, 0.02191275, 0.02255955, -0.05583375, -0.05875539, -0.06055551, -0.09648245, -0.07913737, -0.10627829, -0.12320965, -0.12368335, -0.1506743, -0.15768033, -0.13638829, -0.13065298, -0.14537834, -0.127428, -0.15504529, -0.18184636, -0.12652146, -0.09190138, -0.14847221, -0.15840648, -0.1525789, -0.11859418, -0.14700954, -0.16295761, -0.16051645, -0.10364859, -0.11961134, -0.10258267, -0.08090148, -0.05727746, -0.0429945, -0.04672356, -0.03581408, -0.0439215, -0.03429495, -0.0260362, -0.01075022, 0.04931808, 0.02779388, 0.03984083, 0.08311951, 0.08995566, 0.10522428, 0.16159058, 0.14238174, 0.14759783, 0.16257712, 0.158908, 0.11302115, 0.0909566, 0.08272888, 0.15261884, 0.10546376, 0.04990313, -0.01284111, -0.02720704, 0.00454725, -0.03965491, -0.03818265, -0.02186992, -0.06574751, -0.04846454, -0.05204211, -0.06316498, -0.05095099, -0.08502656, -0.04681162, -0.02362027, -0.02205091, -0.07706374, -0.10371841, -0.14434688, -0.14797935, -0.09055402, -0.06739549, -0.08824959, -0.04855888, -0.02291244, 0.04027138, 0.09370505, 0.11472939, 0.10243593, 0.0921445, 0.07662648, 0.07946651, 0.05450718, 0.10497677, 0.09068334, 0.15462924, 0.14231034, 0.10544952, 0.09980256, 0.14035223, 0.14942974, 0.17624102, 0.19035477, 0.2500807, 0.30724652, 0.31768915, 0.35007521, 0.38412975, 0.34356521, 0.33614463, 0.41206165, 0.33999177, 0.28045963, 0.34076789, 0.42220356, 0.42314636, 0.50790423, 0.47713348, 0.42520169, 0.50488411, 0.48705211, 0.46252601, 0.44325578, 0.42640573, 0.37986783, 0.30652822, 0.34503393, 0.2999069, 0.24928617, 0.24730218, 0.24326897, 0.26657905, 0.27861168, 0.26392824, 0.32552649, 0.34177792, 0.37837011, 0.37025267, 0.4030612, 0.41339361, 0.45076809, 0.40383354, 0.47093422, 0.52505036, 0.53614256, 0.5500943, 0.55319293, 0.59021451, 0.52358459, 0.50605947, 0.49359168, 0.47895956, 0.49320243, 0.4908336, 0.47310767, 0.51821564, 0.55105932, 0.57291504, 0.5599809, 0.46868842, 0.39620087, 0.42086934, 0.38317217, 0.45934108, 0.50048866, 0.53941991, 0.50676751, 0.46500915, 0.52993663, 0.51668366, 0.46405428, 0.44100603, 0.52726147, 0.51565458, 0.49186248, 0.49001081, 0.49367648, 0.56422294, 0.58882785, 0.51334664, 0.44386256, 0.35056709, 0.36490029, 0.39205071, 0.3677061, 0.41134736, 0.42315067, 0.35356394, 0.40324562, 0.41340007, 0.46503322, 0.44355762, 0.34854314, 0.26412842, 0.28633753, 0.32335224, 0.30761141, 0.29709569, 0.29570487, 0.28000063, 0.32802547, 0.33967726, 0.42511212, 0.46252357, 0.44244974, 0.42152907, 0.45436727, 0.50482359, 0.57339198, 0.6573356, 0.70912003, 0.60328917, 0.6395092, 0.67015805, 0.64241557, 0.62779142, 0.55028063, 0.46448736, 0.43709245, 0.46777983, 0.51789439, 0.48594916, 0.4456216, 0.52008189, 0.60548684, 0.62792473, 0.56645031, 0.62766439, 0.71829315, 0.69481356, 0.59550329, 0.58133754, 0.59014148, 0.58026655, 0.61719273, 0.67373203, 0.75573056, 0.89501633, 0.8347253, 0.87964685, 0.89015835]) test_alpha_mean = eval_alpha(self.long_data, 100, self.long_bench, 'value') test_alpha_roll = self.long_data['alpha'].values self.assertAlmostEqual(test_alpha_mean, np.nanmean(expected_alpha)) self.assertTrue(np.allclose(test_alpha_roll, expected_alpha, equal_nan=True)) def test_calmar(self): """test evaluate function eval_calmar()""" pass def test_benchmark(self): reference = self.test_data1 tr, yr = eval_benchmark(self.test_data2, reference, 'value') self.assertAlmostEqual(tr, 0.19509091) self.assertAlmostEqual(yr, 0.929154957) tr, yr = eval_benchmark(self.test_data3, reference, 'value') self.assertAlmostEqual(tr, 0.19509091) self.assertAlmostEqual(yr, 0.929154957) tr, yr = eval_benchmark(self.test_data4, reference, 'value') self.assertAlmostEqual(tr, 0.19509091) self.assertAlmostEqual(yr, 0.929154957) tr, yr = eval_benchmark(self.test_data5, reference, 'value') self.assertAlmostEqual(tr, 0.19509091) self.assertAlmostEqual(yr, 0.929154957) tr, yr = eval_benchmark(self.test_data6, reference, 'value') self.assertAlmostEqual(tr, 0.19509091) self.assertAlmostEqual(yr, 0.929154957) tr, yr = eval_benchmark(self.test_data7, reference, 'value') self.assertAlmostEqual(tr, 0.19509091) self.assertAlmostEqual(yr, 0.929154957) def test_evaluate(self): pass class TestLoop(unittest.TestCase): """通过一个假设但精心设计的例子来测试loop_step以及loop方法的正确性""" def setUp(self): # 精心设计的模拟股票名称、交易日期、以及股票价格 self.shares = ['share1', 'share2', 'share3', 'share4', 'share5', 'share6', 'share7'] self.dates = ['2016/07/01', '2016/07/04', '2016/07/05', '2016/07/06', '2016/07/07', '2016/07/08', '2016/07/11', '2016/07/12', '2016/07/13', '2016/07/14', '2016/07/15', '2016/07/18', '2016/07/19', '2016/07/20', '2016/07/21', '2016/07/22', '2016/07/25', '2016/07/26', '2016/07/27', '2016/07/28', '2016/07/29', '2016/08/01', '2016/08/02', '2016/08/03', '2016/08/04', '2016/08/05', '2016/08/08', '2016/08/09', '2016/08/10', '2016/08/11', '2016/08/12', '2016/08/15', '2016/08/16', '2016/08/17', '2016/08/18', '2016/08/19', '2016/08/22', '2016/08/23', '2016/08/24', '2016/08/25', '2016/08/26', '2016/08/29', '2016/08/30', '2016/08/31', '2016/09/01', '2016/09/02', '2016/09/05', '2016/09/06', '2016/09/07', '2016/09/08', '2016/09/09', '2016/09/12', '2016/09/13', '2016/09/14', '2016/09/15', '2016/09/16', '2016/09/19', '2016/09/20', '2016/09/21', '2016/09/22', '2016/09/23', '2016/09/26', '2016/09/27', '2016/09/28', '2016/09/29', '2016/09/30', '2016/10/10', '2016/10/11', '2016/10/12', '2016/10/13', '2016/10/14', '2016/10/17', '2016/10/18', '2016/10/19', '2016/10/20', '2016/10/21', '2016/10/23', '2016/10/24', '2016/10/25', '2016/10/26', '2016/10/27', '2016/10/29', '2016/10/30', '2016/10/31', '2016/11/01', '2016/11/02', '2016/11/05', '2016/11/06', '2016/11/07', '2016/11/08', '2016/11/09', '2016/11/12', '2016/11/13', '2016/11/14', '2016/11/15', '2016/11/16', '2016/11/19', '2016/11/20', '2016/11/21', '2016/11/22'] self.dates = [pd.Timestamp(date_text) for date_text in self.dates] self.prices = np.array([[5.35, 5.09, 5.03, 4.98, 4.50, 5.09, 4.75], [5.66, 4.84, 5.21, 5.44, 4.35, 5.06, 4.48], [5.79, 4.60, 5.02, 5.45, 4.07, 4.76, 4.56], [5.56, 4.63, 5.50, 5.74, 3.88, 4.62, 4.62], [5.88, 4.64, 5.07, 5.46, 3.74, 4.63, 4.62], [6.25, 4.51, 5.11, 5.45, 3.98, 4.25, 4.59], [5.93, 4.96, 5.15, 5.24, 4.08, 4.13, 4.33], [6.39, 4.65, 5.02, 5.47, 4.00, 3.91, 3.88], [6.31, 4.26, 5.10, 5.58, 4.28, 3.77, 3.47], [5.86, 3.77, 5.24, 5.36, 4.01, 3.43, 3.51], [5.61, 3.39, 4.93, 5.38, 4.14, 3.68, 3.83], [5.31, 3.76, 4.96, 5.30, 4.49, 3.63, 3.67], [5.40, 4.06, 5.40, 5.77, 4.49, 3.94, 3.79], [5.03, 3.87, 5.74, 5.75, 4.46, 4.40, 4.18], [5.38, 3.91, 5.53, 6.15, 4.13, 4.03, 4.02], [5.79, 4.13, 5.79, 6.04, 3.79, 3.93, 4.41], [6.27, 4.27, 5.68, 6.01, 4.23, 3.50, 4.65], [6.59, 4.57, 5.90, 5.71, 4.57, 3.39, 4.89], [6.91, 5.04, 5.75, 5.23, 4.92, 3.30, 4.41], [6.71, 5.31, 6.11, 5.47, 5.28, 3.25, 4.66], [6.33, 5.40, 5.77, 5.79, 5.67, 2.94, 4.37], [6.07, 5.21, 5.85, 5.82, 6.00, 2.71, 4.58], [5.98, 5.06, 5.61, 5.61, 5.89, 2.55, 4.76], [6.46, 4.69, 5.75, 5.31, 5.55, 2.21, 4.37], [6.95, 5.12, 5.50, 5.24, 5.39, 2.29, 4.16], [6.77, 5.27, 5.14, 5.41, 5.26, 2.21, 4.02], [6.70, 5.72, 5.31, 5.60, 5.31, 2.04, 3.77], [6.28, 6.10, 5.68, 5.28, 5.22, 2.39, 3.38], [6.61, 6.27, 5.73, 4.99, 4.90, 2.30, 3.07], [6.25, 6.49, 6.04, 5.09, 4.57, 2.41, 2.90], [6.47, 6.16, 6.27, 5.39, 4.96, 2.40, 2.50], [6.45, 6.26, 6.60, 5.58, 4.82, 2.79, 2.76], [6.88, 6.39, 6.10, 5.33, 4.39, 2.67, 2.29], [7.00, 6.58, 6.25, 5.48, 4.63, 2.27, 2.17], [6.59, 6.20, 6.73, 5.10, 5.05, 2.09, 1.84], [6.59, 5.70, 6.91, 5.39, 4.68, 2.55, 1.83], [6.64, 5.20, 7.01, 5.30, 5.02, 2.22, 2.21], [6.38, 5.37, 7.36, 5.04, 4.84, 2.59, 2.00], [6.10, 5.40, 7.72, 5.51, 4.60, 2.59, 1.76], [6.35, 5.22, 7.68, 5.43, 4.66, 2.95, 1.27], [6.52, 5.38, 7.62, 5.23, 4.41, 2.69, 1.40], [6.87, 5.53, 7.74, 4.99, 4.87, 2.20, 1.11], [6.84, 6.03, 7.53, 5.43, 4.42, 2.69, 1.60], [7.09, 5.77, 7.46, 5.40, 4.08, 2.65, 1.23], [6.88, 5.66, 7.84, 5.60, 4.16, 2.63, 1.59], [6.84, 6.08, 8.11, 5.66, 4.10, 2.14, 1.50], [6.98, 5.62, 8.04, 6.01, 4.43, 2.39, 1.80], [7.02, 5.63, 7.65, 5.64, 4.07, 1.95, 1.55], [7.13, 6.11, 7.52, 5.67, 3.97, 2.32, 1.35], [7.59, 6.03, 7.67, 5.30, 4.16, 2.69, 1.51], [7.61, 6.27, 7.47, 4.91, 4.12, 2.51, 1.08], [7.21, 6.28, 7.44, 5.37, 4.04, 2.62, 1.06], [7.48, 6.52, 7.59, 5.75, 3.84, 2.16, 1.43], [7.66, 7.00, 7.94, 6.08, 3.46, 2.35, 1.43], [7.51, 7.34, 8.25, 6.58, 3.18, 2.31, 1.74], [7.12, 7.34, 7.77, 6.78, 3.10, 1.96, 1.44], [6.97, 7.68, 8.03, 7.20, 3.55, 2.35, 1.83], [6.67, 8.09, 7.87, 7.65, 3.66, 2.58, 1.71], [6.20, 7.68, 7.58, 8.00, 3.66, 2.40, 2.12], [6.34, 7.58, 7.33, 7.92, 3.29, 2.20, 2.45], [6.22, 7.46, 7.22, 8.30, 2.80, 2.31, 2.85], [5.98, 7.59, 6.86, 8.46, 2.88, 2.16, 2.79], [6.37, 7.19, 7.18, 7.99, 3.04, 2.16, 2.91], [6.56, 7.40, 7.54, 8.19, 3.45, 2.20, 3.26], [6.26, 7.48, 7.24, 8.61, 3.88, 1.73, 3.14], [6.69, 7.93, 6.85, 8.66, 3.58, 1.93, 3.53], [7.13, 8.23, 6.60, 8.91, 3.60, 2.25, 3.65], [6.83, 8.35, 6.65, 9.08, 3.97, 2.69, 3.69], [7.31, 8.44, 6.74, 9.34, 4.05, 2.59, 3.50], [7.43, 8.35, 7.19, 8.96, 4.40, 2.14, 3.25], [7.54, 8.58, 7.14, 8.98, 4.06, 1.68, 3.64], [7.18, 8.82, 6.88, 8.50, 3.60, 1.98, 4.00], [7.21, 9.09, 7.14, 8.65, 3.61, 2.14, 3.63], [7.45, 9.02, 7.30, 8.94, 4.10, 1.89, 3.78], [7.37, 8.87, 6.95, 8.63, 3.74, 1.97, 3.42], [6.88, 9.22, 7.02, 8.65, 4.02, 1.99, 3.76], [7.08, 9.04, 7.38, 8.40, 3.95, 2.37, 3.62], [6.75, 8.60, 7.50, 8.38, 3.81, 2.14, 3.67], [6.60, 8.48, 7.60, 8.23, 3.71, 2.35, 3.61], [6.21, 8.71, 7.15, 8.04, 3.94, 1.86, 3.39], [6.36, 8.79, 7.30, 7.91, 4.43, 2.14, 3.43], [6.82, 8.93, 7.80, 7.57, 4.07, 2.39, 3.33], [6.45, 9.36, 8.15, 7.73, 4.04, 2.53, 3.03], [6.85, 9.68, 8.40, 7.74, 4.34, 2.47, 3.28], [6.48, 10.16, 8.87, 8.07, 4.80, 2.93, 3.46], [6.10, 10.56, 8.53, 7.99, 5.18, 3.09, 3.25], [5.64, 10.63, 8.94, 7.92, 4.90, 2.93, 2.95], [6.01, 10.55, 8.52, 8.40, 5.40, 3.22, 2.87], [6.21, 10.65, 8.80, 8.80, 5.73, 3.06, 2.63], [6.61, 10.55, 8.92, 8.47, 5.62, 2.90, 2.40], [7.02, 10.19, 9.20, 8.07, 5.20, 2.68, 2.53], [7.04, 10.48, 8.71, 7.87, 4.85, 2.46, 2.96], [6.77, 10.36, 8.25, 8.02, 5.18, 2.41, 3.26], [7.09, 10.03, 8.19, 8.39, 4.72, 2.74, 2.97], [6.65, 10.24, 7.80, 8.69, 4.62, 3.15, 3.16], [7.07, 10.01, 7.69, 8.81, 4.55, 3.40, 3.58], [6.80, 10.14, 7.23, 8.99, 4.37, 3.82, 3.23], [6.79, 10.31, 6.98, 9.10, 4.26, 4.02, 3.62], [6.48, 9.88, 7.07, 8.90, 4.25, 3.76, 3.13], [6.39, 10.05, 6.95, 8.87, 4.59, 4.10, 2.93]]) # 精心设计的模拟PT持股仓位目标信号: self.pt_signals = np.array([[0.000, 0.000, 0.000, 0.000, 0.250, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.250, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.250, 0.100, 0.150], [0.200, 0.200, 0.000, 0.000, 0.250, 0.100, 0.150], [0.200, 0.200, 0.100, 0.000, 0.250, 0.100, 0.150], [0.200, 0.200, 0.100, 0.000, 0.062, 0.100, 0.150], [0.200, 0.200, 0.100, 0.000, 0.062, 0.100, 0.150], [0.200, 0.200, 0.100, 0.000, 0.062, 0.100, 0.150], [0.200, 0.200, 0.100, 0.000, 0.062, 0.100, 0.150], [0.200, 0.200, 0.100, 0.000, 0.062, 0.100, 0.150], [0.200, 0.200, 0.100, 0.000, 0.062, 0.100, 0.150], [0.200, 0.200, 0.100, 0.000, 0.062, 0.100, 0.150], [0.200, 0.200, 0.100, 0.000, 0.062, 0.100, 0.150], [0.133, 0.200, 0.100, 0.000, 0.062, 0.100, 0.150], [0.133, 0.200, 0.100, 0.000, 0.062, 0.100, 0.150], [0.133, 0.200, 0.100, 0.000, 0.062, 0.100, 0.150], [0.133, 0.200, 0.100, 0.000, 0.062, 0.100, 0.150], [0.133, 0.200, 0.050, 0.000, 0.062, 0.100, 0.150], [0.133, 0.200, 0.050, 0.000, 0.062, 0.100, 0.150], [0.133, 0.200, 0.050, 0.000, 0.062, 0.100, 0.150], [0.133, 0.200, 0.050, 0.000, 0.062, 0.100, 0.150], [0.133, 0.200, 0.050, 0.000, 0.062, 0.100, 0.000], [0.133, 0.200, 0.050, 0.000, 0.262, 0.100, 0.000], [0.133, 0.200, 0.050, 0.000, 0.262, 0.100, 0.000], [0.133, 0.200, 0.050, 0.000, 0.262, 0.100, 0.000], [0.066, 0.200, 0.050, 0.150, 0.262, 0.100, 0.000], [0.066, 0.200, 0.050, 0.150, 0.262, 0.100, 0.000], [0.066, 0.200, 0.050, 0.150, 0.262, 0.100, 0.000], [0.066, 0.200, 0.050, 0.150, 0.262, 0.100, 0.000], [0.066, 0.200, 0.050, 0.150, 0.262, 0.100, 0.000], [0.066, 0.200, 0.250, 0.150, 0.000, 0.300, 0.000], [0.386, 0.136, 0.170, 0.102, 0.000, 0.204, 0.000], [0.386, 0.136, 0.170, 0.102, 0.000, 0.204, 0.000], [0.386, 0.136, 0.170, 0.102, 0.000, 0.204, 0.000], [0.386, 0.136, 0.170, 0.102, 0.000, 0.204, 0.000], [0.386, 0.136, 0.170, 0.102, 0.000, 0.204, 0.000], [0.386, 0.136, 0.170, 0.102, 0.000, 0.204, 0.000], [0.386, 0.136, 0.170, 0.102, 0.000, 0.204, 0.000], [0.386, 0.136, 0.170, 0.102, 0.000, 0.204, 0.000], [0.386, 0.136, 0.170, 0.102, 0.000, 0.204, 0.000], [0.386, 0.136, 0.170, 0.102, 0.000, 0.204, 0.000], [0.386, 0.136, 0.170, 0.102, 0.000, 0.204, 0.000], [0.460, 0.119, 0.149, 0.089, 0.000, 0.179, 0.000], [0.460, 0.119, 0.149, 0.089, 0.000, 0.179, 0.000], [0.460, 0.119, 0.149, 0.089, 0.000, 0.179, 0.000], [0.446, 0.116, 0.145, 0.087, 0.000, 0.087, 0.116], [0.446, 0.116, 0.145, 0.087, 0.000, 0.087, 0.116], [0.446, 0.116, 0.145, 0.087, 0.000, 0.087, 0.116], [0.446, 0.116, 0.145, 0.087, 0.000, 0.087, 0.116], [0.446, 0.116, 0.145, 0.087, 0.000, 0.087, 0.116], [0.400, 0.208, 0.130, 0.078, 0.000, 0.078, 0.104], [0.400, 0.208, 0.130, 0.078, 0.000, 0.078, 0.104], [0.400, 0.208, 0.130, 0.078, 0.000, 0.078, 0.104], [0.400, 0.208, 0.130, 0.078, 0.000, 0.078, 0.104], [0.400, 0.208, 0.130, 0.078, 0.000, 0.078, 0.104], [0.400, 0.208, 0.130, 0.078, 0.000, 0.078, 0.104], [0.400, 0.208, 0.130, 0.078, 0.000, 0.078, 0.104], [0.400, 0.208, 0.130, 0.078, 0.000, 0.078, 0.104], [0.400, 0.208, 0.130, 0.078, 0.000, 0.078, 0.104], [0.400, 0.208, 0.130, 0.078, 0.000, 0.078, 0.104], [0.370, 0.193, 0.120, 0.072, 0.072, 0.072, 0.096], [0.000, 0.222, 0.138, 0.222, 0.083, 0.222, 0.111], [0.000, 0.222, 0.138, 0.222, 0.083, 0.222, 0.111], [0.121, 0.195, 0.121, 0.195, 0.073, 0.195, 0.097], [0.121, 0.195, 0.121, 0.195, 0.073, 0.195, 0.097], [0.121, 0.195, 0.121, 0.195, 0.073, 0.195, 0.097], [0.121, 0.195, 0.121, 0.195, 0.073, 0.195, 0.097], [0.121, 0.195, 0.121, 0.195, 0.073, 0.195, 0.097], [0.121, 0.195, 0.121, 0.195, 0.073, 0.195, 0.097], [0.121, 0.195, 0.121, 0.195, 0.073, 0.195, 0.097], [0.121, 0.195, 0.121, 0.195, 0.073, 0.195, 0.097], [0.200, 0.320, 0.200, 0.000, 0.120, 0.000, 0.160], [0.200, 0.320, 0.200, 0.000, 0.120, 0.000, 0.160], [0.200, 0.320, 0.200, 0.000, 0.120, 0.000, 0.160], [0.200, 0.320, 0.200, 0.000, 0.120, 0.000, 0.160], [0.200, 0.320, 0.200, 0.000, 0.120, 0.000, 0.160], [0.200, 0.320, 0.200, 0.000, 0.120, 0.000, 0.160], [0.200, 0.320, 0.200, 0.000, 0.120, 0.000, 0.160], [0.200, 0.320, 0.200, 0.000, 0.120, 0.000, 0.160], [0.047, 0.380, 0.238, 0.000, 0.142, 0.000, 0.190], [0.047, 0.380, 0.238, 0.000, 0.142, 0.000, 0.190], [0.043, 0.434, 0.217, 0.000, 0.130, 0.000, 0.173], [0.043, 0.434, 0.217, 0.000, 0.130, 0.000, 0.173], [0.043, 0.434, 0.217, 0.000, 0.130, 0.000, 0.173], [0.043, 0.434, 0.217, 0.000, 0.130, 0.000, 0.173], [0.043, 0.434, 0.217, 0.000, 0.130, 0.000, 0.173], [0.043, 0.434, 0.217, 0.000, 0.130, 0.000, 0.173], [0.045, 0.454, 0.227, 0.000, 0.000, 0.000, 0.272], [0.045, 0.454, 0.227, 0.000, 0.000, 0.000, 0.272], [0.050, 0.000, 0.250, 0.000, 0.000, 0.000, 0.300], [0.050, 0.000, 0.250, 0.000, 0.000, 0.000, 0.300], [0.050, 0.000, 0.250, 0.000, 0.000, 0.000, 0.300], [0.050, 0.000, 0.250, 0.000, 0.000, 0.000, 0.300], [0.050, 0.000, 0.250, 0.000, 0.000, 0.000, 0.300], [0.050, 0.000, 0.250, 0.000, 0.000, 0.000, 0.300], [0.050, 0.000, 0.250, 0.000, 0.000, 0.000, 0.300], [0.050, 0.000, 0.250, 0.000, 0.000, 0.000, 0.300], [0.000, 0.000, 0.400, 0.000, 0.000, 0.000, 0.300], [0.000, 0.000, 0.400, 0.000, 0.000, 0.000, 0.300], [0.000, 0.000, 0.400, 0.000, 0.000, 0.000, 0.300]]) # 精心设计的模拟PS比例交易信号,与模拟PT信号高度相似 self.ps_signals = np.array([[0.000, 0.000, 0.000, 0.000, 0.250, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.100, 0.150], [0.200, 0.200, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.100, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, -0.750, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [-0.333, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, -0.500, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, -1.000], [0.000, 0.000, 0.000, 0.000, 0.200, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [-0.500, 0.000, 0.000, 0.150, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.200, 0.000, -1.000, 0.200, 0.000], [0.500, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.200, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, -0.500, 0.200], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.200, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.150, 0.000, 0.000], [-1.000, 0.000, 0.000, 0.250, 0.000, 0.250, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.250, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, -1.000, 0.000, -1.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [-0.800, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.100, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, -1.000, 0.000, 0.100], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, -1.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [-1.000, 0.000, 0.150, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000], [0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000]]) # 精心设计的模拟VS股票交易信号,与模拟PS信号类似 self.vs_signals = np.array([[000, 000, 000, 000, 500, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 300, 300], [400, 400, 000, 000, 000, 000, 000], [000, 000, 250, 000, 000, 000, 000], [000, 000, 000, 000, -400, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [-200, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, -200, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, -300], [000, 000, 000, 000, 500, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [-200, 000, 000, 300, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 400, 000, -300, 600, 000], [500, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [600, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, -400, 600], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 500, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 300, 000, 000], [-500, 000, 000, 500, 000, 200, 000], [000, 000, 000, 000, 000, 000, 000], [500, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, -700, 000, -600, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [-400, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 300, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, -600, 000, 300], [000, 000, 000, 000, 000, 000, 000], [000, -300, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [-200, 000, 700, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000], [000, 000, 000, 000, 000, 000, 000]]) # 精心设计的模拟多价格交易信号,模拟50个交易日对三只股票的操作 self.multi_shares = ['000010', '000030', '000039'] self.multi_dates = ['2016/07/01', '2016/07/04', '2016/07/05', '2016/07/06', '2016/07/07', '2016/07/08', '2016/07/11', '2016/07/12', '2016/07/13', '2016/07/14', '2016/07/15', '2016/07/18', '2016/07/19', '2016/07/20', '2016/07/21', '2016/07/22', '2016/07/25', '2016/07/26', '2016/07/27', '2016/07/28', '2016/07/29', '2016/08/01', '2016/08/02', '2016/08/03', '2016/08/04', '2016/08/05', '2016/08/08', '2016/08/09', '2016/08/10', '2016/08/11', '2016/08/12', '2016/08/15', '2016/08/16', '2016/08/17', '2016/08/18', '2016/08/19', '2016/08/22', '2016/08/23', '2016/08/24', '2016/08/25', '2016/08/26', '2016/08/29', '2016/08/30', '2016/08/31', '2016/09/01', '2016/09/02', '2016/09/05', '2016/09/06', '2016/09/07', '2016/09/08'] self.multi_dates = [pd.Timestamp(date_text) for date_text in self.multi_dates] # 操作的交易价格包括开盘价、最高价和收盘价 self.multi_prices_open = np.array([[10.02, 9.88, 7.26], [10.00, 9.88, 7.00], [9.98, 9.89, 6.88], [9.97, 9.75, 6.91], [9.99, 9.74, np.nan], [10.01, 9.80, 6.81], [10.04, 9.62, 6.63], [10.06, 9.65, 6.45], [10.06, 9.58, 6.16], [10.11, 9.67, 6.24], [10.11, 9.81, 5.96], [10.07, 9.80, 5.97], [10.06, 10.00, 5.96], [10.09, 9.95, 6.20], [10.03, 10.10, 6.35], [10.02, 10.06, 6.11], [10.06, 10.14, 6.37], [10.08, 9.90, 5.58], [9.99, 10.20, 5.65], [10.00, 10.29, 5.65], [10.03, 9.86, 5.19], [10.02, 9.48, 5.42], [10.06, 10.01, 6.30], [10.03, 10.24, 6.15], [9.97, 10.26, 6.05], [9.94, 10.24, 5.89], [9.83, 10.12, 5.22], [9.78, 10.65, 5.20], [9.77, 10.64, 5.07], [9.91, 10.56, 6.04], [9.92, 10.42, 6.12], [9.97, 10.43, 5.85], [9.91, 10.29, 5.67], [9.90, 10.30, 6.02], [9.88, 10.44, 6.04], [9.91, 10.60, 7.07], [9.63, 10.67, 7.64], [9.64, 10.46, 7.99], [9.57, 10.39, 7.59], [9.55, 10.90, 8.73], [9.58, 11.01, 8.72], [9.61, 11.01, 8.97], [9.62, np.nan, 8.58], [9.55, np.nan, 8.71], [9.57, 10.82, 8.77], [9.61, 11.02, 8.40], [9.63, 10.96, 7.95], [9.64, 11.55, 7.76], [9.61, 11.74, 8.25], [9.56, 11.80, 7.51]]) self.multi_prices_high = np.array([[10.07, 9.91, 7.41], [10.00, 10.04, 7.31], [10.00, 9.93, 7.14], [10.00, 10.04, 7.00], [10.03, 9.84, np.nan], [10.03, 9.88, 6.82], [10.04, 9.99, 6.96], [10.09, 9.70, 6.85], [10.10, 9.67, 6.50], [10.14, 9.71, 6.34], [10.11, 9.85, 6.04], [10.10, 9.90, 6.02], [10.09, 10.00, 6.12], [10.09, 10.20, 6.38], [10.10, 10.11, 6.43], [10.05, 10.18, 6.46], [10.07, 10.21, 6.43], [10.09, 10.26, 6.27], [10.10, 10.38, 5.77], [10.00, 10.47, 6.01], [10.04, 10.42, 5.67], [10.04, 10.07, 5.67], [10.06, 10.24, 6.35], [10.09, 10.27, 6.32], [10.05, 10.38, 6.43], [9.97, 10.43, 6.36], [9.96, 10.39, 5.79], [9.86, 10.65, 5.47], [9.77, 10.84, 5.65], [9.92, 10.65, 6.04], [9.94, 10.73, 6.14], [9.97, 10.63, 6.23], [9.97, 10.51, 5.83], [9.92, 10.35, 6.25], [9.92, 10.46, 6.27], [9.92, 10.63, 7.12], [9.93, 10.74, 7.82], [9.64, 10.76, 8.14], [9.58, 10.54, 8.27], [9.60, 11.02, 8.92], [9.58, 11.12, 8.76], [9.62, 11.17, 9.15], [9.62, np.nan, 8.90], [9.64, np.nan, 9.01], [9.59, 10.92, 9.16], [9.62, 11.15, 9.00], [9.63, 11.11, 8.27], [9.70, 11.55, 7.99], [9.66, 11.95, 8.33], [9.64, 11.93, 8.25]]) self.multi_prices_close = np.array([[10.04, 9.68, 6.64], [10.00, 9.87, 7.26], [10.00, 9.86, 7.03], [9.99, 9.87, 6.87], [9.97, 9.79, np.nan], [9.99, 9.82, 6.64], [10.03, 9.80, 6.85], [10.03, 9.66, 6.70], [10.06, 9.62, 6.39], [10.06, 9.58, 6.22], [10.11, 9.69, 5.92], [10.09, 9.78, 5.91], [10.07, 9.75, 6.11], [10.06, 9.96, 5.91], [10.09, 9.90, 6.23], [10.03, 10.04, 6.28], [10.03, 10.06, 6.28], [10.06, 10.08, 6.27], [10.08, 10.24, 5.70], [10.00, 10.24, 5.56], [9.99, 10.24, 5.67], [10.03, 9.86, 5.16], [10.03, 10.13, 5.69], [10.06, 10.12, 6.32], [10.03, 10.10, 6.14], [9.97, 10.25, 6.25], [9.94, 10.24, 5.79], [9.83, 10.22, 5.26], [9.77, 10.75, 5.05], [9.84, 10.64, 5.45], [9.91, 10.56, 6.06], [9.93, 10.60, 6.21], [9.96, 10.42, 5.69], [9.91, 10.25, 5.46], [9.91, 10.24, 6.02], [9.88, 10.49, 6.69], [9.91, 10.57, 7.43], [9.64, 10.63, 7.72], [9.56, 10.48, 8.16], [9.57, 10.37, 7.83], [9.55, 10.96, 8.70], [9.57, 11.02, 8.71], [9.61, np.nan, 8.88], [9.61, np.nan, 8.54], [9.55, 10.88, 8.87], [9.57, 10.87, 8.87], [9.63, 11.01, 8.18], [9.64, 11.01, 7.80], [9.65, 11.58, 7.97], [9.62, 11.80, 8.25]]) # 交易信号包括三组,分别作用与开盘价、最高价和收盘价 # 此时的关键是股票交割期的处理,交割期不为0时,以交易日为单位交割 self.multi_signals = [] # multisignal的第一组信号为开盘价信号 self.multi_signals.append( pd.DataFrame(np.array([[0.000, 0.000, 0.000], [0.000, -0.500, 0.000], [0.000, -0.500, 0.000], [0.000, 0.000, 0.000], [0.150, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.300, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.300], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.350, 0.250], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.100, 0.000, 0.350], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.200, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.050, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000]]), columns=self.multi_shares, index=self.multi_dates ) ) # 第二组信号为最高价信号 self.multi_signals.append( pd.DataFrame(np.array([[0.000, 0.150, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, -0.200, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.200], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000]]), columns=self.multi_shares, index=self.multi_dates ) ) # 第三组信号为收盘价信号 self.multi_signals.append( pd.DataFrame(np.array([[0.000, 0.200, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [-0.500, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, -0.800], [0.000, 0.000, 0.000], [0.000, -1.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [-0.750, 0.000, 0.000], [0.000, 0.000, -0.850], [0.000, 0.000, 0.000], [0.000, -0.700, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [0.000, 0.000, -1.000], [0.000, 0.000, 0.000], [0.000, 0.000, 0.000], [-1.000, 0.000, 0.000], [0.000, -1.000, 0.000], [0.000, 0.000, 0.000]]), columns=self.multi_shares, index=self.multi_dates ) ) # 交易回测所需的价格也有三组,分别是开盘价、最高价和收盘价 self.multi_histories = [] # multisignal的第一组信号为开盘价信号 self.multi_histories.append( pd.DataFrame(self.multi_prices_open, columns=self.multi_shares, index=self.multi_dates ) ) # 第二组信号为最高价信号 self.multi_histories.append( pd.DataFrame(self.multi_prices_high, columns=self.multi_shares, index=self.multi_dates ) ) # 第三组信号为收盘价信号 self.multi_histories.append( pd.DataFrame(self.multi_prices_close, columns=self.multi_shares, index=self.multi_dates ) ) # 设置回测参数 self.cash = qt.CashPlan(['2016/07/01', '2016/08/12', '2016/09/23'], [10000, 10000, 10000]) self.rate = qt.Cost(buy_fix=0, sell_fix=0, buy_rate=0, sell_rate=0, buy_min=0, sell_min=0, slipage=0) self.rate2 = qt.Cost(buy_fix=0, sell_fix=0, buy_rate=0, sell_rate=0, buy_min=10, sell_min=5, slipage=0) self.pt_signal_hp = dataframe_to_hp( pd.DataFrame(self.pt_signals, index=self.dates, columns=self.shares), htypes='close' ) self.ps_signal_hp = dataframe_to_hp( pd.DataFrame(self.ps_signals, index=self.dates, columns=self.shares), htypes='close' ) self.vs_signal_hp = dataframe_to_hp( pd.DataFrame(self.vs_signals, index=self.dates, columns=self.shares), htypes='close' ) self.multi_signal_hp = stack_dataframes( self.multi_signals, stack_along='htypes', htypes='open, high, close' ) self.history_list = dataframe_to_hp( pd.DataFrame(self.prices, index=self.dates, columns=self.shares), htypes='close' ) self.multi_history_list = stack_dataframes( self.multi_histories, stack_along='htypes', htypes='open, high, close' ) # 模拟PT信号回测结果 # PT信号,先卖后买,交割期为0 self.pt_res_sb00 = np.array( [[0.0000, 0.0000, 0.0000, 0.0000, 555.5556, 0.0000, 0.0000, 7500.0000, 0.0000, 10000.0000], [0.0000, 0.0000, 0.0000, 0.0000, 555.5556, 0.0000, 0.0000, 7500.0000, 0.0000, 9916.6667], [0.0000, 0.0000, 0.0000, 0.0000, 555.5556, 0.0000, 321.0892, 6035.8333, 0.0000, 9761.1111], [348.0151, 417.9188, 0.0000, 0.0000, 555.5556, 0.0000, 321.0892, 2165.9050, 0.0000, 9674.8209], [348.0151, 417.9188, 0.0000, 0.0000, 555.5556, 0.0000, 321.0892, 2165.9050, 0.0000, 9712.5872], [348.0151, 417.9188, 0.0000, 0.0000, 154.3882, 0.0000, 321.0892, 3762.5512, 0.0000, 9910.7240], [348.0151, 417.9188, 0.0000, 0.0000, 154.3882, 0.0000, 321.0892, 3762.5512, 0.0000, 9919.3782], [348.0151, 417.9188, 0.0000, 0.0000, 154.3882, 0.0000, 321.0892, 3762.5512, 0.0000, 9793.0692], [348.0151, 417.9188, 0.0000, 0.0000, 154.3882, 0.0000, 321.0892, 3762.5512, 0.0000, 9513.8217], [348.0151, 417.9188, 0.0000, 0.0000, 154.3882, 0.0000, 321.0892, 3762.5512, 0.0000, 9123.5935], [348.0151, 417.9188, 0.0000, 0.0000, 154.3882, 0.0000, 321.0892, 3762.5512, 0.0000, 9000.5995], [348.0151, 417.9188, 0.0000, 0.0000, 154.3882, 0.0000, 321.0892, 3762.5512, 0.0000, 9053.4865], [348.0151, 417.9188, 0.0000, 0.0000, 154.3882, 0.0000, 321.0892, 3762.5512, 0.0000, 9248.7142], [348.0151, 417.9188, 0.0000, 0.0000, 154.3882, 0.0000, 321.0892, 3762.5512, 0.0000, 9161.1372], [348.0151, 417.9188, 0.0000, 0.0000, 154.3882, 0.0000, 321.0892, 3762.5512, 0.0000, 9197.3369], [348.0151, 417.9188, 0.0000, 0.0000, 154.3882, 0.0000, 321.0892, 3762.5512, 0.0000, 9504.6981], [348.0151, 417.9188, 0.0000, 0.0000, 154.3882, 0.0000, 321.0892, 3762.5512, 0.0000, 9875.2461], [348.0151, 417.9188, 0.0000, 0.0000, 154.3882, 0.0000, 321.0892, 3762.5512, 0.0000, 10241.5400], [348.0151, 417.9188, 0.0000, 0.0000, 154.3882, 0.0000, 321.0892, 3762.5512, 0.0000, 10449.2398], [348.0151, 417.9188, 0.0000, 0.0000, 154.3882, 0.0000, 321.0892, 3762.5512, 0.0000, 10628.3269], [348.0151, 417.9188, 0.0000, 0.0000, 154.3882, 0.0000, 321.0892, 3762.5512, 0.0000, 10500.7893], [348.0151, 417.9188, 0.0000, 0.0000, 154.3882, 0.0000, 0.0000, 5233.1396, 0.0000, 10449.2776], [348.0151, 417.9188, 0.0000, 0.0000, 459.8694, 0.0000, 0.0000, 3433.8551, 0.0000, 10338.2857], [348.0151, 417.9188, 0.0000, 0.0000, 459.8694, 0.0000, 0.0000, 3433.8551, 0.0000, 10194.3474], [348.0151, 417.9188, 0.0000, 0.0000, 459.8694, 0.0000, 0.0000, 3433.8551, 0.0000, 10471.0008], [101.4983, 417.9188, 0.0000, 288.6672, 459.8694, 0.0000, 0.0000, 3541.0848, 0.0000, 10411.2629], [101.4983, 417.9188, 0.0000, 288.6672, 459.8694, 0.0000, 0.0000, 3541.0848, 0.0000, 10670.0618], [101.4983, 417.9188, 0.0000, 288.6672, 459.8694, 0.0000, 0.0000, 3541.0848, 0.0000, 10652.4799], [101.4983, 417.9188, 0.0000, 288.6672, 459.8694, 0.0000, 0.0000, 3541.0848, 0.0000, 10526.1488], [101.4983, 417.9188, 0.0000, 288.6672, 459.8694, 0.0000, 0.0000, 3541.0848, 0.0000, 10458.6614], [101.4983, 417.9188, 821.7315, 288.6672, 0.0000, 2576.1284, 0.0000, 4487.0722, 0.0000, 20609.0270], [1216.3282, 417.9188, 821.7315, 288.6672, 0.0000, 1607.1030, 0.0000, 0.0000, 0.0000, 21979.4972], [1216.3282, 417.9188, 821.7315, 288.6672, 0.0000, 1607.1030, 0.0000, 0.0000, 0.0000, 21880.9628], [1216.3282, 417.9188, 821.7315, 288.6672, 0.0000, 1607.1030, 0.0000, 0.0000, 0.0000, 21630.0454], [1216.3282, 417.9188, 821.7315, 288.6672, 0.0000, 1607.1030, 0.0000, 0.0000, 0.0000, 20968.0007], [1216.3282, 417.9188, 821.7315, 288.6672, 0.0000, 1607.1030, 0.0000, 0.0000, 0.0000, 21729.9339], [1216.3282, 417.9188, 511.8829, 288.6672, 0.0000, 1607.1030, 0.0000, 2172.0393, 0.0000, 21107.6400], [1216.3282, 417.9188, 511.8829, 288.6672, 0.0000, 1607.1030, 0.0000, 2172.0393, 0.0000, 21561.1745], [1216.3282, 417.9188, 511.8829, 288.6672, 0.0000, 1607.1030, 0.0000, 2172.0393, 0.0000, 21553.0916], [1216.3282, 417.9188, 511.8829, 288.6672, 0.0000, 1607.1030, 0.0000, 2172.0393, 0.0000, 22316.9366], [1216.3282, 417.9188, 511.8829, 288.6672, 0.0000, 1607.1030, 0.0000, 2172.0393, 0.0000, 22084.2862], [1216.3282, 417.9188, 511.8829, 288.6672, 0.0000, 1607.1030, 0.0000, 2172.0393, 0.0000, 21777.3543], [1216.3282, 417.9188, 511.8829, 288.6672, 0.0000, 1607.1030, 0.0000, 2172.0393, 0.0000, 22756.8225], [1216.3282, 417.9188, 511.8829, 288.6672, 0.0000, 1607.1030, 0.0000, 2172.0393, 0.0000, 22843.4697], [1216.3282, 417.9188, 511.8829, 288.6672, 0.0000, 1607.1030, 0.0000, 2172.0393, 0.0000, 22762.1766], [1216.3282, 417.9188, 511.8829, 288.6672, 0.0000, 1607.1030, 1448.0262, 0.0000, 0.0000, 22257.0973], [1216.3282, 417.9188, 511.8829, 288.6672, 0.0000, 1607.1030, 1448.0262, 0.0000, 0.0000, 23136.5259], [1216.3282, 417.9188, 511.8829, 288.6672, 0.0000, 1607.1030, 1448.0262, 0.0000, 0.0000, 21813.7852], [1216.3282, 417.9188, 511.8829, 288.6672, 0.0000, 1607.1030, 1448.0262, 0.0000, 0.0000, 22395.3204], [1216.3282, 417.9188, 511.8829, 288.6672, 0.0000, 1607.1030, 1448.0262, 0.0000, 0.0000, 23717.6858], [1216.3282, 417.9188, 511.8829, 288.6672, 0.0000, 1607.1030, 1448.0262, 0.0000, 0.0000, 22715.4263], [1216.3282, 417.9188, 511.8829, 288.6672, 0.0000, 669.7975, 1448.0262, 2455.7405, 0.0000, 22498.3254], [1216.3282, 417.9188, 511.8829, 288.6672, 0.0000, 669.7975, 1448.0262, 2455.7405, 0.0000, 23341.1733], [1216.3282, 417.9188, 511.8829, 288.6672, 0.0000, 669.7975, 1448.0262, 2455.7405, 0.0000, 24162.3941], [1216.3282, 417.9188, 511.8829, 288.6672, 0.0000, 669.7975, 1448.0262, 2455.7405, 0.0000, 24847.1508], [1216.3282, 417.9188, 511.8829, 288.6672, 0.0000, 669.7975, 1448.0262, 2455.7405, 0.0000, 23515.9755], [1216.3282, 417.9188, 511.8829, 288.6672, 0.0000, 669.7975, 1448.0262, 2455.7405, 0.0000, 24555.8997], [1216.3282, 417.9188, 511.8829, 288.6672, 0.0000, 669.7975, 1448.0262, 2455.7405, 0.0000, 24390.6372], [1216.3282, 417.9188, 511.8829, 288.6672, 0.0000, 669.7975, 1448.0262, 2455.7405, 0.0000, 24073.3309], [1216.3282, 417.9188, 511.8829, 288.6672, 0.0000, 669.7975, 1448.0262, 2455.7405, 0.0000, 24394.6500], [2076.3314, 903.0334, 511.8829, 288.6672, 0.0000, 669.7975, 1448.0262, 3487.5655, 0.0000, 34904.8150], [0.0000, 903.0334, 511.8829, 897.4061, 0.0000, 3514.8404, 1448.0262, 4608.8037, 0.0000, 34198.4475], [0.0000, 903.0334, 511.8829, 897.4061, 0.0000, 3514.8404, 1448.0262, 4608.8037, 0.0000, 33753.0190], [644.7274, 903.0334, 511.8829, 897.4061, 0.0000, 3514.8404, 1448.0262, 379.3918, 0.0000, 34953.8178], [644.7274, 903.0334, 511.8829, 897.4061, 0.0000, 3514.8404, 1448.0262, 379.3918, 0.0000, 33230.2498], [644.7274, 903.0334, 511.8829, 897.4061, 0.0000, 3514.8404, 1448.0262, 379.3918, 0.0000, 35026.7819], [644.7274, 903.0334, 511.8829, 897.4061, 0.0000, 3514.8404, 1448.0262, 379.3918, 0.0000, 36976.2649], [644.7274, 903.0334, 511.8829, 897.4061, 0.0000, 3514.8404, 1448.0262, 379.3918, 0.0000, 38673.8147], [644.7274, 903.0334, 511.8829, 897.4061, 0.0000, 3514.8404, 1448.0262, 379.3918, 0.0000, 38717.3429], [644.7274, 903.0334, 511.8829, 897.4061, 0.0000, 3514.8404, 1448.0262, 379.3918, 0.0000, 36659.0854], [644.7274, 903.0334, 511.8829, 897.4061, 0.0000, 3514.8404, 1448.0262, 379.3918, 0.0000, 35877.9607], [644.7274, 1337.8498, 1071.9327, 0.0000, 1229.1495, 0.0000, 1448.0262, 2853.5665, 0.0000, 36874.4840], [644.7274, 1337.8498, 1071.9327, 0.0000, 1229.1495, 0.0000, 1448.0262, 2853.5665, 0.0000, 37010.2695], [644.7274, 1337.8498, 1071.9327, 0.0000, 1229.1495, 0.0000, 1448.0262, 2853.5665, 0.0000, 38062.3510], [644.7274, 1337.8498, 1071.9327, 0.0000, 1229.1495, 0.0000, 1448.0262, 2853.5665, 0.0000, 36471.1357], [644.7274, 1337.8498, 1071.9327, 0.0000, 1229.1495, 0.0000, 1448.0262, 2853.5665, 0.0000, 37534.9927], [644.7274, 1337.8498, 1071.9327, 0.0000, 1229.1495, 0.0000, 1448.0262, 2853.5665, 0.0000, 37520.2569], [644.7274, 1337.8498, 1071.9327, 0.0000, 1229.1495, 0.0000, 1448.0262, 2853.5665, 0.0000, 36747.7952], [644.7274, 1337.8498, 1071.9327, 0.0000, 1229.1495, 0.0000, 1448.0262, 2853.5665, 0.0000, 36387.9409], [644.7274, 1337.8498, 1071.9327, 0.0000, 1229.1495, 0.0000, 1448.0262, 2853.5665, 0.0000, 35925.9715], [644.7274, 1337.8498, 1071.9327, 0.0000, 1229.1495, 0.0000, 1448.0262, 2853.5665, 0.0000, 36950.7028], [644.7274, 1657.3981, 1071.9327, 0.0000, 1229.1495, 0.0000, 1448.0262, 0.0000, 0.0000, 37383.2463], [644.7274, 1657.3981, 1071.9327, 0.0000, 1229.1495, 0.0000, 1448.0262, 0.0000, 0.0000, 37761.2724], [644.7274, 1657.3981, 1071.9327, 0.0000, 1229.1495, 0.0000, 1448.0262, 0.0000, 0.0000, 39548.2653], [644.7274, 1657.3981, 1071.9327, 0.0000, 1229.1495, 0.0000, 1448.0262, 0.0000, 0.0000, 41435.1291], [644.7274, 1657.3981, 1071.9327, 0.0000, 1229.1495, 0.0000, 1448.0262, 0.0000, 0.0000, 41651.6261], [644.7274, 1657.3981, 1071.9327, 0.0000, 1229.1495, 0.0000, 1448.0262, 0.0000, 0.0000, 41131.9920], [644.7274, 1657.3981, 1071.9327, 0.0000, 0.0000, 0.0000, 3760.7116, 0.0000, 0.0000, 41286.4702], [644.7274, 1657.3981, 1071.9327, 0.0000, 0.0000, 0.0000, 3760.7116, 0.0000, 0.0000, 40978.7259], [644.7274, 0.0000, 1071.9327, 0.0000, 0.0000, 0.0000, 3760.7116, 17485.5497, 0.0000, 40334.5453], [644.7274, 0.0000, 1071.9327, 0.0000, 0.0000, 0.0000, 3760.7116, 17485.5497, 0.0000, 41387.9172], [644.7274, 0.0000, 1071.9327, 0.0000, 0.0000, 0.0000, 3760.7116, 17485.5497, 0.0000, 42492.6707], [644.7274, 0.0000, 1071.9327, 0.0000, 0.0000, 0.0000, 3760.7116, 17485.5497, 0.0000, 42953.7188], [644.7274, 0.0000, 1071.9327, 0.0000, 0.0000, 0.0000, 3760.7116, 17485.5497, 0.0000, 42005.1092], [644.7274, 0.0000, 1071.9327, 0.0000, 0.0000, 0.0000, 3760.7116, 17485.5497, 0.0000, 42017.9106], [644.7274, 0.0000, 1071.9327, 0.0000, 0.0000, 0.0000, 3760.7116, 17485.5497, 0.0000, 43750.2824], [644.7274, 0.0000, 1071.9327, 0.0000, 0.0000, 0.0000, 3760.7116, 17485.5497, 0.0000, 41766.8679], [0.0000, 0.0000, 2461.8404, 0.0000, 0.0000, 0.0000, 3760.7116, 12161.6930, 0.0000, 42959.1150], [0.0000, 0.0000, 2461.8404, 0.0000, 0.0000, 0.0000, 3760.7116, 12161.6930, 0.0000, 41337.9320], [0.0000, 0.0000, 2461.8404, 0.0000, 0.0000, 0.0000, 3760.7116, 12161.6930, 0.0000, 40290.3688]]) # PT信号,先买后卖,交割期为0 self.pt_res_bs00 = np.array( [[0.0000, 0.0000, 0.0000, 0.0000, 555.5556, 0.0000, 0.0000, 7500.0000, 0.0000, 10000.0000], [0.0000, 0.0000, 0.0000, 0.0000, 555.5556, 0.0000, 0.0000, 7500.0000, 0.0000, 9916.6667], [0.0000, 0.0000, 0.0000, 0.0000, 555.5556, 0.0000, 321.0892, 6035.8333, 0.0000, 9761.1111], [348.0151, 417.9188, 0.0000, 0.0000, 555.5556, 0.0000, 321.0892, 2165.9050, 0.0000, 9674.8209], [348.0151, 417.9188, 0.0000, 0.0000, 555.5556, 0.0000, 321.0892, 2165.9050, 0.0000, 9712.5872], [348.0151, 417.9188, 0.0000, 0.0000, 154.3882, 0.0000, 321.0892, 3762.5512, 0.0000, 9910.7240], [348.0151, 417.9188, 0.0000, 0.0000, 154.3882, 0.0000, 321.0892, 3762.5512, 0.0000, 9919.3782], [348.0151, 417.9188, 0.0000, 0.0000, 154.3882, 0.0000, 321.0892, 3762.5512, 0.0000, 9793.0692], [348.0151, 417.9188, 0.0000, 0.0000, 154.3882, 0.0000, 321.0892, 3762.5512, 0.0000, 9513.8217], [348.0151, 417.9188, 0.0000, 0.0000, 154.3882, 0.0000, 321.0892, 3762.5512, 0.0000, 9123.5935], [348.0151, 417.9188, 0.0000, 0.0000, 154.3882, 0.0000, 321.0892, 3762.5512, 0.0000, 9000.5995], [348.0151, 417.9188, 0.0000, 0.0000, 154.3882, 0.0000, 321.0892, 3762.5512, 0.0000, 9053.4865], [348.0151, 417.9188, 0.0000, 0.0000, 154.3882, 0.0000, 321.0892, 3762.5512, 0.0000, 9248.7142], [348.0151, 417.9188, 0.0000, 0.0000, 154.3882, 0.0000, 321.0892, 3762.5512, 0.0000, 9161.1372], [348.0151, 417.9188, 0.0000, 0.0000, 154.3882, 0.0000, 321.0892, 3762.5512, 0.0000, 9197.3369], [348.0151, 417.9188, 0.0000, 0.0000, 154.3882, 0.0000, 321.0892, 3762.5512, 0.0000, 9504.6981], [348.0151, 417.9188, 0.0000, 0.0000, 154.3882, 0.0000, 321.0892, 3762.5512, 0.0000, 9875.2461], [348.0151, 417.9188, 0.0000, 0.0000, 154.3882, 0.0000, 321.0892, 3762.5512, 0.0000, 10241.5400], [348.0151, 417.9188, 0.0000, 0.0000, 154.3882, 0.0000, 321.0892, 3762.5512, 0.0000, 10449.2398], [348.0151, 417.9188, 0.0000, 0.0000, 154.3882, 0.0000, 321.0892, 3762.5512, 0.0000, 10628.3269], [348.0151, 417.9188, 0.0000, 0.0000, 154.3882, 0.0000, 321.0892, 3762.5512, 0.0000, 10500.7893], [348.0151, 417.9188, 0.0000, 0.0000, 154.3882, 0.0000, 0.0000, 5233.1396, 0.0000, 10449.2776], [348.0151, 417.9188, 0.0000, 0.0000, 459.8694, 0.0000, 0.0000, 3433.8551, 0.0000, 10338.2857], [348.0151, 417.9188, 0.0000, 0.0000, 459.8694, 0.0000, 0.0000, 3433.8551, 0.0000, 10194.3474], [348.0151, 417.9188, 0.0000, 0.0000, 459.8694, 0.0000, 0.0000, 3433.8551, 0.0000, 10471.0008], [101.4983, 417.9188, 0.0000, 288.6672, 459.8694, 0.0000, 0.0000, 3541.0848, 0.0000, 10411.2629], [101.4983, 417.9188, 0.0000, 288.6672, 459.8694, 0.0000, 0.0000, 3541.0848, 0.0000, 10670.0618], [101.4983, 417.9188, 0.0000, 288.6672, 459.8694, 0.0000, 0.0000, 3541.0848, 0.0000, 10652.4799], [101.4983, 417.9188, 0.0000, 288.6672, 459.8694, 0.0000, 0.0000, 3541.0848, 0.0000, 10526.1488], [101.4983, 417.9188, 0.0000, 288.6672, 459.8694, 0.0000, 0.0000, 3541.0848, 0.0000, 10458.6614], [101.4983, 417.9188, 821.7315, 288.6672, 0.0000, 2576.1284, 0.0000, 4487.0722, 0.0000, 20609.0270], [797.1684, 417.9188, 821.7315, 288.6672, 0.0000, 1607.1030, 0.0000, 2703.5808, 0.0000, 21979.4972], [1190.1307, 417.9188, 821.7315, 288.6672, 0.0000, 1607.1030, 0.0000, 0.0000, 0.0000, 21700.7241], [1190.1307, 417.9188, 821.7315, 288.6672, 0.0000, 1607.1030, 0.0000, 0.0000, 0.0000, 21446.6630], [1190.1307, 417.9188, 821.7315, 288.6672, 0.0000, 1607.1030, 0.0000, 0.0000, 0.0000, 20795.3593], [1190.1307, 417.9188, 821.7315, 288.6672, 0.0000, 1607.1030, 0.0000, 0.0000, 0.0000, 21557.2924], [1190.1307, 417.9188, 507.6643, 288.6672, 0.0000, 1607.1030, 0.0000, 2201.6110, 0.0000, 20933.6887], [1190.1307, 417.9188, 507.6643, 288.6672, 0.0000, 1607.1030, 0.0000, 2201.6110, 0.0000, 21392.5581], [1190.1307, 417.9188, 507.6643, 288.6672, 0.0000, 1607.1030, 0.0000, 2201.6110, 0.0000, 21390.2918], [1190.1307, 417.9188, 507.6643, 288.6672, 0.0000, 1607.1030, 0.0000, 2201.6110, 0.0000, 22147.7562], [1190.1307, 417.9188, 507.6643, 288.6672, 0.0000, 1607.1030, 0.0000, 2201.6110, 0.0000, 21910.9053], [1190.1307, 417.9188, 507.6643, 288.6672, 0.0000, 1607.1030, 0.0000, 2201.6110, 0.0000, 21594.2980], [1190.1307, 417.9188, 507.6643, 288.6672, 0.0000, 1607.1030, 0.0000, 2201.6110, 0.0000, 22575.4380], [1190.1307, 417.9188, 507.6643, 288.6672, 0.0000, 1607.1030, 0.0000, 2201.6110, 0.0000, 22655.8312], [1190.1307, 417.9188, 507.6643, 288.6672, 0.0000, 1607.1030, 0.0000, 2201.6110, 0.0000, 22578.4365], [1190.1307, 417.9188, 507.6643, 288.6672, 0.0000, 1607.1030, 1467.7407, 0.0000, 0.0000, 22073.2661], [1190.1307, 417.9188, 507.6643, 288.6672, 0.0000, 1607.1030, 1467.7407, 0.0000, 0.0000, 22955.2367], [1190.1307, 417.9188, 507.6643, 288.6672, 0.0000, 1607.1030, 1467.7407, 0.0000, 0.0000, 21628.1647], [1190.1307, 417.9188, 507.6643, 288.6672, 0.0000, 1607.1030, 1467.7407, 0.0000, 0.0000, 22203.4237], [1190.1307, 417.9188, 507.6643, 288.6672, 0.0000, 1607.1030, 1467.7407, 0.0000, 0.0000, 23516.2598], [1190.1307, 417.9188, 507.6643, 288.6672, 0.0000, 699.3848, 1467.7407, 2278.3728, 0.0000, 22505.8428], [1190.1307, 417.9188, 507.6643, 288.6672, 0.0000, 699.3848, 1467.7407, 2278.3728, 0.0000, 22199.1042], [1190.1307, 417.9188, 507.6643, 288.6672, 0.0000, 699.3848, 1467.7407, 2278.3728, 0.0000, 23027.9302], [1190.1307, 417.9188, 507.6643, 288.6672, 0.0000, 699.3848, 1467.7407, 2278.3728, 0.0000, 23848.5806], [1190.1307, 417.9188, 507.6643, 288.6672, 0.0000, 699.3848, 1467.7407, 2278.3728, 0.0000, 24540.8871], [1190.1307, 417.9188, 507.6643, 288.6672, 0.0000, 699.3848, 1467.7407, 2278.3728, 0.0000, 23205.6838], [1190.1307, 417.9188, 507.6643, 288.6672, 0.0000, 699.3848, 1467.7407, 2278.3728, 0.0000, 24267.6685], [1190.1307, 417.9188, 507.6643, 288.6672, 0.0000, 699.3848, 1467.7407, 2278.3728, 0.0000, 24115.3796], [1190.1307, 417.9188, 507.6643, 288.6672, 0.0000, 699.3848, 1467.7407, 2278.3728, 0.0000, 23814.3667], [1190.1307, 417.9188, 507.6643, 288.6672, 0.0000, 699.3848, 1467.7407, 2278.3728, 0.0000, 24133.6611], [2061.6837, 896.6628, 507.6643, 288.6672, 0.0000, 699.3848, 1467.7407, 3285.8830, 0.0000, 34658.5742], [0.0000, 896.6628, 507.6643, 466.6033, 0.0000, 1523.7106, 1467.7407, 12328.8684, 0.0000, 33950.7917], [0.0000, 896.6628, 507.6643, 936.6623, 0.0000, 3464.7832, 1467.7407, 4380.3797, 0.0000, 33711.4045], [644.1423, 896.6628, 507.6643, 936.6623, 0.0000, 3464.7832, 1467.7407, 154.8061, 0.0000, 34922.0959], [644.1423, 896.6628, 507.6643, 936.6623, 0.0000, 3464.7832, 1467.7407, 154.8061, 0.0000, 33237.1081], [644.1423, 896.6628, 507.6643, 936.6623, 0.0000, 3464.7832, 1467.7407, 154.8061, 0.0000, 35031.8071], [644.1423, 896.6628, 507.6643, 936.6623, 0.0000, 3464.7832, 1467.7407, 154.8061, 0.0000, 36976.3376], [644.1423, 896.6628, 507.6643, 936.6623, 0.0000, 3464.7832, 1467.7407, 154.8061, 0.0000, 38658.5245], [644.1423, 896.6628, 507.6643, 936.6623, 0.0000, 3464.7832, 1467.7407, 154.8061, 0.0000, 38712.2854], [644.1423, 896.6628, 507.6643, 936.6623, 0.0000, 3464.7832, 1467.7407, 154.8061, 0.0000, 36655.3125], [644.1423, 896.6628, 507.6643, 936.6623, 0.0000, 3464.7832, 1467.7407, 154.8061, 0.0000, 35904.3692], [644.1423, 902.2617, 514.8253, 0.0000, 15.5990, 0.0000, 1467.7407, 14821.9004, 0.0000, 36873.9080], [644.1423, 902.2617, 514.8253, 0.0000, 1220.8683, 0.0000, 1467.7407, 10470.8781, 0.0000, 36727.7895], [644.1423, 1338.1812, 1033.4242, 0.0000, 1220.8683, 0.0000, 1467.7407, 2753.1120, 0.0000, 37719.9840], [644.1423, 1338.1812, 1033.4242, 0.0000, 1220.8683, 0.0000, 1467.7407, 2753.1120, 0.0000, 36138.1277], [644.1423, 1338.1812, 1033.4242, 0.0000, 1220.8683, 0.0000, 1467.7407, 2753.1120, 0.0000, 37204.0760], [644.1423, 1338.1812, 1033.4242, 0.0000, 1220.8683, 0.0000, 1467.7407, 2753.1120, 0.0000, 37173.1201], [644.1423, 1338.1812, 1033.4242, 0.0000, 1220.8683, 0.0000, 1467.7407, 2753.1120, 0.0000, 36398.2298], [644.1423, 1338.1812, 1033.4242, 0.0000, 1220.8683, 0.0000, 1467.7407, 2753.1120, 0.0000, 36034.2178], [644.1423, 1338.1812, 1033.4242, 0.0000, 1220.8683, 0.0000, 1467.7407, 2753.1120, 0.0000, 35583.6399], [644.1423, 1338.1812, 1033.4242, 0.0000, 1220.8683, 0.0000, 1467.7407, 2753.1120, 0.0000, 36599.2645], [644.1423, 1646.4805, 1033.4242, 0.0000, 1220.8683, 0.0000, 1467.7407, 0.0000, 0.0000, 37013.3408], [644.1423, 1646.4805, 1033.4242, 0.0000, 1220.8683, 0.0000, 1467.7407, 0.0000, 0.0000, 37367.7449], [644.1423, 1646.4805, 1033.4242, 0.0000, 1220.8683, 0.0000, 1467.7407, 0.0000, 0.0000, 39143.8273], [644.1423, 1646.4805, 1033.4242, 0.0000, 1220.8683, 0.0000, 1467.7407, 0.0000, 0.0000, 41007.3074], [644.1423, 1646.4805, 1033.4242, 0.0000, 1220.8683, 0.0000, 1467.7407, 0.0000, 0.0000, 41225.4657], [644.1423, 1646.4805, 1033.4242, 0.0000, 1220.8683, 0.0000, 1467.7407, 0.0000, 0.0000, 40685.9525], [644.1423, 1646.4805, 1033.4242, 0.0000, 0.0000, 0.0000, 1467.7407, 6592.6891, 0.0000, 40851.5435], [644.1423, 1646.4805, 1033.4242, 0.0000, 0.0000, 0.0000, 3974.4666, 0.0000, 0.0000, 41082.1210], [644.1423, 0.0000, 1033.4242, 0.0000, 0.0000, 0.0000, 3974.4666, 17370.3689, 0.0000, 40385.0135], [644.1423, 0.0000, 1033.4242, 0.0000, 0.0000, 0.0000, 3974.4666, 17370.3689, 0.0000, 41455.1513], [644.1423, 0.0000, 1033.4242, 0.0000, 0.0000, 0.0000, 3974.4666, 17370.3689, 0.0000, 42670.6769], [644.1423, 0.0000, 1033.4242, 0.0000, 0.0000, 0.0000, 3974.4666, 17370.3689, 0.0000, 43213.7233], [644.1423, 0.0000, 1033.4242, 0.0000, 0.0000, 0.0000, 3974.4666, 17370.3689, 0.0000, 42205.2480], [644.1423, 0.0000, 1033.4242, 0.0000, 0.0000, 0.0000, 3974.4666, 17370.3689, 0.0000, 42273.9386], [644.1423, 0.0000, 1033.4242, 0.0000, 0.0000, 0.0000, 3974.4666, 17370.3689, 0.0000, 44100.0777], [644.1423, 0.0000, 1033.4242, 0.0000, 0.0000, 0.0000, 3974.4666, 17370.3689, 0.0000, 42059.7208], [0.0000, 0.0000, 2483.9522, 0.0000, 0.0000, 0.0000, 3974.4666, 11619.4102, 0.0000, 43344.9653], [0.0000, 0.0000, 2483.9522, 0.0000, 0.0000, 0.0000, 3974.4666, 11619.4102, 0.0000, 41621.0324], [0.0000, 0.0000, 2483.9522, 0.0000, 0.0000, 0.0000, 3974.4666, 11619.4102, 0.0000, 40528.0648]]) # PT信号,先卖后买,交割期为2天(股票)0天(现金)以便利用先卖的现金继续买入 self.pt_res_sb20 = np.array( [[0.000, 0.000, 0.000, 0.000, 555.556, 0.000, 0.000, 7500.000, 0.000, 10000.000], [0.000, 0.000, 0.000, 0.000, 555.556, 0.000, 0.000, 7500.000, 0.000, 9916.667], [0.000, 0.000, 0.000, 0.000, 555.556, 0.000, 321.089, 6035.833, 0.000, 9761.111], [348.015, 417.919, 0.000, 0.000, 555.556, 0.000, 321.089, 2165.905, 0.000, 9674.821], [348.015, 417.919, 0.000, 0.000, 555.556, 0.000, 321.089, 2165.905, 0.000, 9712.587], [348.015, 417.919, 0.000, 0.000, 154.388, 0.000, 321.089, 3762.551, 0.000, 9910.724], [348.015, 417.919, 0.000, 0.000, 154.388, 0.000, 321.089, 3762.551, 0.000, 9919.378], [348.015, 417.919, 0.000, 0.000, 154.388, 0.000, 321.089, 3762.551, 0.000, 9793.069], [348.015, 417.919, 0.000, 0.000, 154.388, 0.000, 321.089, 3762.551, 0.000, 9513.822], [348.015, 417.919, 0.000, 0.000, 154.388, 0.000, 321.089, 3762.551, 0.000, 9123.593], [348.015, 417.919, 0.000, 0.000, 154.388, 0.000, 321.089, 3762.551, 0.000, 9000.600], [348.015, 417.919, 0.000, 0.000, 154.388, 0.000, 321.089, 3762.551, 0.000, 9053.487], [348.015, 417.919, 0.000, 0.000, 154.388, 0.000, 321.089, 3762.551, 0.000, 9248.714], [348.015, 417.919, 0.000, 0.000, 154.388, 0.000, 321.089, 3762.551, 0.000, 9161.137], [348.015, 417.919, 0.000, 0.000, 154.388, 0.000, 321.089, 3762.551, 0.000, 9197.337], [348.015, 417.919, 0.000, 0.000, 154.388, 0.000, 321.089, 3762.551, 0.000, 9504.698], [348.015, 417.919, 0.000, 0.000, 154.388, 0.000, 321.089, 3762.551, 0.000, 9875.246], [348.015, 417.919, 0.000, 0.000, 154.388, 0.000, 321.089, 3762.551, 0.000, 10241.540], [348.015, 417.919, 0.000, 0.000, 154.388, 0.000, 321.089, 3762.551, 0.000, 10449.240], [348.015, 417.919, 0.000, 0.000, 154.388, 0.000, 321.089, 3762.551, 0.000, 10628.327], [348.015, 417.919, 0.000, 0.000, 154.388, 0.000, 321.089, 3762.551, 0.000, 10500.789], [348.015, 417.919, 0.000, 0.000, 154.388, 0.000, 0.000, 5233.140, 0.000, 10449.278], [348.015, 417.919, 0.000, 0.000, 459.869, 0.000, 0.000, 3433.855, 0.000, 10338.286], [348.015, 417.919, 0.000, 0.000, 459.869, 0.000, 0.000, 3433.855, 0.000, 10194.347], [348.015, 417.919, 0.000, 0.000, 459.869, 0.000, 0.000, 3433.855, 0.000, 10471.001], [101.498, 417.919, 0.000, 288.667, 459.869, 0.000, 0.000, 3541.085, 0.000, 10411.263], [101.498, 417.919, 0.000, 288.667, 459.869, 0.000, 0.000, 3541.085, 0.000, 10670.062], [101.498, 417.919, 0.000, 288.667, 459.869, 0.000, 0.000, 3541.085, 0.000, 10652.480], [101.498, 417.919, 0.000, 288.667, 459.869, 0.000, 0.000, 3541.085, 0.000, 10526.149], [101.498, 417.919, 0.000, 288.667, 459.869, 0.000, 0.000, 3541.085, 0.000, 10458.661], [101.498, 417.919, 821.732, 288.667, 0.000, 2576.128, 0.000, 4487.072, 0.000, 20609.027], [797.168, 417.919, 821.732, 288.667, 0.000, 2576.128, 0.000, 0.000, 0.000, 21979.497], [1156.912, 417.919, 821.732, 288.667, 0.000, 1649.148, 0.000, 0.000, 0.000, 21584.441], [1156.912, 417.919, 821.732, 288.667, 0.000, 1649.148, 0.000, 0.000, 0.000, 21309.576], [1156.912, 417.919, 821.732, 288.667, 0.000, 1649.148, 0.000, 0.000, 0.000, 20664.323], [1156.912, 417.919, 821.732, 288.667, 0.000, 1649.148, 0.000, 0.000, 0.000, 21445.597], [1156.912, 417.919, 504.579, 288.667, 0.000, 1649.148, 0.000, 2223.240, 0.000, 20806.458], [1156.912, 417.919, 504.579, 288.667, 0.000, 1649.148, 0.000, 2223.240, 0.000, 21288.441], [1156.912, 417.919, 504.579, 288.667, 0.000, 1649.148, 0.000, 2223.240, 0.000, 21294.365], [1156.912, 417.919, 504.579, 288.667, 0.000, 1649.148, 0.000, 2223.240, 0.000, 22058.784], [1156.912, 417.919, 504.579, 288.667, 0.000, 1649.148, 0.000, 2223.240, 0.000, 21805.540], [1156.912, 417.919, 504.579, 288.667, 0.000, 1649.148, 0.000, 2223.240, 0.000, 21456.333], [1481.947, 417.919, 504.579, 288.667, 0.000, 1649.148, 0.000, 0.000, 0.000, 22459.720], [1481.947, 417.919, 504.579, 288.667, 0.000, 1649.148, 0.000, 0.000, 0.000, 22611.602], [1481.947, 417.919, 504.579, 288.667, 0.000, 1649.148, 0.000, 0.000, 0.000, 22470.912], [1481.947, 417.919, 504.579, 288.667, 0.000, 1649.148, 0.000, 0.000, 0.000, 21932.634], [1481.947, 417.919, 504.579, 288.667, 0.000, 1649.148, 0.000, 0.000, 0.000, 22425.864], [1481.947, 417.919, 504.579, 288.667, 0.000, 1649.148, 0.000, 0.000, 0.000, 21460.103], [1481.947, 417.919, 504.579, 288.667, 0.000, 1649.148, 0.000, 0.000, 0.000, 22376.968], [1481.947, 417.919, 504.579, 288.667, 0.000, 763.410, 1577.904, 0.000, 0.000, 23604.295], [1481.947, 417.919, 504.579, 288.667, 0.000, 763.410, 1577.904, 0.000, 0.000, 22704.826], [1481.947, 417.919, 504.579, 288.667, 0.000, 763.410, 1577.904, 0.000, 0.000, 22286.293], [1481.947, 417.919, 504.579, 288.667, 0.000, 763.410, 1577.904, 0.000, 0.000, 23204.755], [1481.947, 417.919, 504.579, 288.667, 0.000, 763.410, 1577.904, 0.000, 0.000, 24089.017], [1481.947, 417.919, 504.579, 288.667, 0.000, 763.410, 1577.904, 0.000, 0.000, 24768.185], [1481.947, 417.919, 504.579, 288.667, 0.000, 763.410, 1577.904, 0.000, 0.000, 23265.196], [1481.947, 417.919, 504.579, 288.667, 0.000, 763.410, 1577.904, 0.000, 0.000, 24350.540], [1481.947, 417.919, 504.579, 288.667, 0.000, 763.410, 1577.904, 0.000, 0.000, 24112.706], [1481.947, 417.919, 504.579, 288.667, 0.000, 763.410, 1577.904, 0.000, 0.000, 23709.076], [1481.947, 417.919, 504.579, 288.667, 0.000, 763.410, 1577.904, 0.000, 0.000, 24093.545], [2060.275, 896.050, 504.579, 288.667, 0.000, 763.410, 1577.904, 2835.944, 0.000, 34634.888], [578.327, 896.050, 504.579, 889.896, 0.000, 3485.427, 1577.904, 732.036, 0.000, 33912.261], [0.000, 896.050, 504.579, 889.896, 0.000, 3485.427, 1577.904, 4415.981, 0.000, 33711.951], [644.683, 896.050, 504.579, 889.896, 0.000, 3485.427, 1577.904, 186.858, 0.000, 34951.433], [644.683, 896.050, 504.579, 889.896, 0.000, 3485.427, 1577.904, 186.858, 0.000, 33224.596], [644.683, 896.050, 504.579, 889.896, 0.000, 3485.427, 1577.904, 186.858, 0.000, 35065.209], [644.683, 896.050, 504.579, 889.896, 0.000, 3485.427, 1577.904, 186.858, 0.000, 37018.699], [644.683, 896.050, 504.579, 889.896, 0.000, 3485.427, 1577.904, 186.858, 0.000, 38706.035], [644.683, 896.050, 504.579, 889.896, 0.000, 3485.427, 1577.904, 186.858, 0.000, 38724.569], [644.683, 896.050, 504.579, 889.896, 0.000, 3485.427, 1577.904, 186.858, 0.000, 36647.268], [644.683, 896.050, 504.579, 889.896, 0.000, 3485.427, 1577.904, 186.858, 0.000, 35928.930], [644.683, 1341.215, 1074.629, 0.000, 1232.241, 0.000, 1577.904, 2367.759, 0.000, 36967.229], [644.683, 1341.215, 1074.629, 0.000, 1232.241, 0.000, 1577.904, 2367.759, 0.000, 37056.598], [644.683, 1341.215, 1074.629, 0.000, 1232.241, 0.000, 1577.904, 2367.759, 0.000, 38129.862], [644.683, 1341.215, 1074.629, 0.000, 1232.241, 0.000, 1577.904, 2367.759, 0.000, 36489.333], [644.683, 1341.215, 1074.629, 0.000, 1232.241, 0.000, 1577.904, 2367.759, 0.000, 37599.602], [644.683, 1341.215, 1074.629, 0.000, 1232.241, 0.000, 1577.904, 2367.759, 0.000, 37566.823], [644.683, 1341.215, 1074.629, 0.000, 1232.241, 0.000, 1577.904, 2367.759, 0.000, 36799.280], [644.683, 1341.215, 1074.629, 0.000, 1232.241, 0.000, 1577.904, 2367.759, 0.000, 36431.196], [644.683, 1341.215, 1074.629, 0.000, 1232.241, 0.000, 1577.904, 2367.759, 0.000, 35940.942], [644.683, 1341.215, 1074.629, 0.000, 1232.241, 0.000, 1577.904, 2367.759, 0.000, 36973.050], [644.683, 1606.361, 1074.629, 0.000, 1232.241, 0.000, 1577.904, 0.000, 0.000, 37393.292], [644.683, 1606.361, 1074.629, 0.000, 1232.241, 0.000, 1577.904, 0.000, 0.000, 37711.276], [644.683, 1606.361, 1074.629, 0.000, 1232.241, 0.000, 1577.904, 0.000, 0.000, 39515.991], [644.683, 1606.361, 1074.629, 0.000, 1232.241, 0.000, 1577.904, 0.000, 0.000, 41404.440], [644.683, 1606.361, 1074.629, 0.000, 1232.241, 0.000, 1577.904, 0.000, 0.000, 41573.523], [644.683, 1606.361, 1074.629, 0.000, 1232.241, 0.000, 1577.904, 0.000, 0.000, 41011.613], [644.683, 1606.361, 1074.629, 0.000, 0.000, 0.000, 3896.406, 0.000, 0.000, 41160.181], [644.683, 1606.361, 1074.629, 0.000, 0.000, 0.000, 3896.406, 0.000, 0.000, 40815.512], [644.683, 0.000, 1074.629, 0.000, 0.000, 0.000, 3896.406, 16947.110, 0.000, 40145.531], [644.683, 0.000, 1074.629, 0.000, 0.000, 0.000, 3896.406, 16947.110, 0.000, 41217.281], [644.683, 0.000, 1074.629, 0.000, 0.000, 0.000, 3896.406, 16947.110, 0.000, 42379.061], [644.683, 0.000, 1074.629, 0.000, 0.000, 0.000, 3896.406, 16947.110, 0.000, 42879.589], [644.683, 0.000, 1074.629, 0.000, 0.000, 0.000, 3896.406, 16947.110, 0.000, 41891.452], [644.683, 0.000, 1074.629, 0.000, 0.000, 0.000, 3896.406, 16947.110, 0.000, 41929.003], [644.683, 0.000, 1074.629, 0.000, 0.000, 0.000, 3896.406, 16947.110, 0.000, 43718.052], [644.683, 0.000, 1074.629, 0.000, 0.000, 0.000, 3896.406, 16947.110, 0.000, 41685.916], [0.000, 0.000, 2460.195, 0.000, 0.000, 0.000, 3896.406, 11653.255, 0.000, 42930.410], [0.000, 0.000, 2460.195, 0.000, 0.000, 0.000, 3896.406, 11653.255, 0.000, 41242.589], [0.000, 0.000, 2460.195, 0.000, 0.000, 0.000, 3896.406, 11653.255, 0.000, 40168.084]]) # PT信号,先买后卖,交割期为2天(股票)1天(现金) self.pt_res_bs21 = np.array([ [0.000, 0.000, 0.000, 0.000, 555.556, 0.000, 0.000, 7500.000, 0.000, 10000.000], [0.000, 0.000, 0.000, 0.000, 555.556, 0.000, 0.000, 7500.000, 0.000, 9916.667], [0.000, 0.000, 0.000, 0.000, 555.556, 0.000, 321.089, 6035.833, 0.000, 9761.111], [348.015, 417.919, 0.000, 0.000, 555.556, 0.000, 321.089, 2165.905, 0.000, 9674.821], [348.015, 417.919, 0.000, 0.000, 555.556, 0.000, 321.089, 2165.905, 0.000, 9712.587], [348.015, 417.919, 0.000, 0.000, 154.388, 0.000, 321.089, 3762.551, 0.000, 9910.724], [348.015, 417.919, 0.000, 0.000, 154.388, 0.000, 321.089, 3762.551, 0.000, 9919.378], [348.015, 417.919, 0.000, 0.000, 154.388, 0.000, 321.089, 3762.551, 0.000, 9793.069], [348.015, 417.919, 0.000, 0.000, 154.388, 0.000, 321.089, 3762.551, 0.000, 9513.822], [348.015, 417.919, 0.000, 0.000, 154.388, 0.000, 321.089, 3762.551, 0.000, 9123.593], [348.015, 417.919, 0.000, 0.000, 154.388, 0.000, 321.089, 3762.551, 0.000, 9000.600], [348.015, 417.919, 0.000, 0.000, 154.388, 0.000, 321.089, 3762.551, 0.000, 9053.487], [348.015, 417.919, 0.000, 0.000, 154.388, 0.000, 321.089, 3762.551, 0.000, 9248.714], [348.015, 417.919, 0.000, 0.000, 154.388, 0.000, 321.089, 3762.551, 0.000, 9161.137], [348.015, 417.919, 0.000, 0.000, 154.388, 0.000, 321.089, 3762.551, 0.000, 9197.337], [348.015, 417.919, 0.000, 0.000, 154.388, 0.000, 321.089, 3762.551, 0.000, 9504.698], [348.015, 417.919, 0.000, 0.000, 154.388, 0.000, 321.089, 3762.551, 0.000, 9875.246], [348.015, 417.919, 0.000, 0.000, 154.388, 0.000, 321.089, 3762.551, 0.000, 10241.540], [348.015, 417.919, 0.000, 0.000, 154.388, 0.000, 321.089, 3762.551, 0.000, 10449.240], [348.015, 417.919, 0.000, 0.000, 154.388, 0.000, 321.089, 3762.551, 0.000, 10628.327], [348.015, 417.919, 0.000, 0.000, 154.388, 0.000, 321.089, 3762.551, 0.000, 10500.789], [348.015, 417.919, 0.000, 0.000, 154.388, 0.000, 0.000, 5233.140, 0.000, 10449.278], [348.015, 417.919, 0.000, 0.000, 459.869, 0.000, 0.000, 3433.855, 0.000, 10338.286], [348.015, 417.919, 0.000, 0.000, 459.869, 0.000, 0.000, 3433.855, 0.000, 10194.347], [348.015, 417.919, 0.000, 0.000, 459.869, 0.000, 0.000, 3433.855, 0.000, 10471.001], [101.498, 417.919, 0.000, 288.667, 459.869, 0.000, 0.000, 3541.085, 0.000, 10411.263], [101.498, 417.919, 0.000, 288.667, 459.869, 0.000, 0.000, 3541.085, 0.000, 10670.062], [101.498, 417.919, 0.000, 288.667, 459.869, 0.000, 0.000, 3541.085, 0.000, 10652.480], [101.498, 417.919, 0.000, 288.667, 459.869, 0.000, 0.000, 3541.085, 0.000, 10526.149], [101.498, 417.919, 0.000, 288.667, 459.869, 0.000, 0.000, 3541.085, 0.000, 10458.661], [101.498, 417.919, 821.732, 288.667, 0.000, 2576.128, 0.000, 4487.072, 0.000, 20609.027], [797.168, 417.919, 821.732, 288.667, 0.000, 2576.128, 0.000, 0.000, 0.000, 21979.497], [797.168, 417.919, 821.732, 288.667, 0.000, 1649.148, 0.000, 2475.037, 0.000, 21584.441], [1150.745, 417.919, 821.732, 288.667, 0.000, 1649.148, 0.000, 0.000, 0.000, 21266.406], [1150.745, 417.919, 821.732, 288.667, 0.000, 1649.148, 0.000, 0.000, 0.000, 20623.683], [1150.745, 417.919, 821.732, 288.667, 0.000, 1649.148, 0.000, 0.000, 0.000, 21404.957], [1150.745, 417.919, 503.586, 288.667, 0.000, 1649.148, 0.000, 2230.202, 0.000, 20765.509], [1150.745, 417.919, 503.586, 288.667, 0.000, 1649.148, 0.000, 2230.202, 0.000, 21248.748], [1150.745, 417.919, 503.586, 288.667, 0.000, 1649.148, 0.000, 2230.202, 0.000, 21256.041], [1150.745, 417.919, 503.586, 288.667, 0.000, 1649.148, 0.000, 2230.202, 0.000, 22018.958], [1150.745, 417.919, 503.586, 288.667, 0.000, 1649.148, 0.000, 2230.202, 0.000, 21764.725], [1150.745, 417.919, 503.586, 288.667, 0.000, 1649.148, 0.000, 2230.202, 0.000, 21413.241], [1476.798, 417.919, 503.586, 288.667, 0.000, 1649.148, 0.000, 0.000, 0.000, 22417.021], [1476.798, 417.919, 503.586, 288.667, 0.000, 1649.148, 0.000, 0.000, 0.000, 22567.685], [1476.798, 417.919, 503.586, 288.667, 0.000, 1649.148, 0.000, 0.000, 0.000, 22427.699], [1476.798, 417.919, 503.586, 288.667, 0.000, 1649.148, 0.000, 0.000, 0.000, 21889.359], [1476.798, 417.919, 503.586, 288.667, 0.000, 1649.148, 0.000, 0.000, 0.000, 22381.938], [1476.798, 417.919, 503.586, 288.667, 0.000, 1649.148, 0.000, 0.000, 0.000, 21416.358], [1476.798, 417.919, 503.586, 288.667, 0.000, 1649.148, 0.000, 0.000, 0.000, 22332.786], [1476.798, 417.919, 503.586, 288.667, 0.000, 761.900, 0.000, 2386.698, 0.000, 23557.595], [1476.798, 417.919, 503.586, 288.667, 0.000, 761.900, 2209.906, 0.000, 0.000, 23336.992], [1476.798, 417.919, 503.586, 288.667, 0.000, 761.900, 2209.906, 0.000, 0.000, 22907.742], [1476.798, 417.919, 503.586, 288.667, 0.000, 761.900, 2209.906, 0.000, 0.000, 24059.201], [1476.798, 417.919, 503.586, 288.667, 0.000, 761.900, 2209.906, 0.000, 0.000, 24941.902], [1476.798, 417.919, 503.586, 288.667, 0.000, 761.900, 2209.906, 0.000, 0.000, 25817.514], [1476.798, 417.919, 503.586, 288.667, 0.000, 761.900, 2209.906, 0.000, 0.000, 24127.939], [1476.798, 417.919, 503.586, 288.667, 0.000, 761.900, 2209.906, 0.000, 0.000, 25459.688], [1476.798, 417.919, 503.586, 288.667, 0.000, 761.900, 2209.906, 0.000, 0.000, 25147.370], [1476.798, 417.919, 503.586, 288.667, 0.000, 761.900, 2209.906, 0.000, 0.000, 25005.842], [1476.798, 417.919, 503.586, 288.667, 0.000, 761.900, 1086.639, 2752.004, 0.000, 25598.700], [2138.154, 929.921, 503.586, 288.667, 0.000, 761.900, 1086.639, 4818.835, 0.000, 35944.098], [661.356, 929.921, 503.586, 553.843, 0.000, 1954.237, 1086.639, 8831.252, 0.000, 35237.243], [0.000, 929.921, 503.586, 553.843, 0.000, 3613.095, 1086.639, 9460.955, 0.000, 35154.442], [667.098, 929.921, 503.586, 553.843, 0.000, 3613.095, 1086.639, 5084.792, 0.000, 36166.632], [667.098, 929.921, 503.586, 553.843, 0.000, 3613.095, 1086.639, 5084.792, 0.000, 34293.883], [667.098, 929.921, 503.586, 553.843, 0.000, 3613.095, 1086.639, 5084.792, 0.000, 35976.901], [667.098, 929.921, 503.586, 553.843, 0.000, 3613.095, 1086.639, 5084.792, 0.000, 37848.552], [667.098, 929.921, 503.586, 553.843, 0.000, 3613.095, 1086.639, 5084.792, 0.000, 39512.574], [667.098, 929.921, 503.586, 553.843, 0.000, 3613.095, 1086.639, 5084.792, 0.000, 39538.024], [667.098, 929.921, 503.586, 553.843, 0.000, 3613.095, 1086.639, 5084.792, 0.000, 37652.984], [667.098, 929.921, 503.586, 553.843, 0.000, 3613.095, 1086.639, 5084.792, 0.000, 36687.909], [667.098, 1108.871, 745.260, 0.000, 512.148, 0.000, 1086.639, 11861.593, 0.000, 37749.277], [667.098, 1108.871, 745.260, 0.000, 512.148, 0.000, 1086.639, 11861.593, 0.000, 37865.518], [667.098, 1108.871, 745.260, 0.000, 512.148, 0.000, 1086.639, 11861.593, 0.000, 38481.190], [667.098, 1108.871, 745.260, 0.000, 512.148, 0.000, 1086.639, 11861.593, 0.000, 37425.087], [667.098, 1108.871, 745.260, 0.000, 512.148, 0.000, 1086.639, 11861.593, 0.000, 38051.341], [667.098, 1108.871, 745.260, 0.000, 512.148, 0.000, 1086.639, 11861.593, 0.000, 38065.478], [667.098, 1108.871, 745.260, 0.000, 512.148, 0.000, 1086.639, 11861.593, 0.000, 37429.495], [667.098, 1108.871, 745.260, 0.000, 512.148, 0.000, 1086.639, 11861.593, 0.000, 37154.479], [667.098, 1600.830, 745.260, 0.000, 512.148, 0.000, 1086.639, 7576.628, 0.000, 36692.717], [667.098, 1600.830, 745.260, 0.000, 512.148, 0.000, 1086.639, 7576.628, 0.000, 37327.055], [667.098, 1600.830, 745.260, 0.000, 512.148, 0.000, 1086.639, 7576.628, 0.000, 37937.630], [667.098, 1600.830, 745.260, 0.000, 512.148, 0.000, 1086.639, 7576.628, 0.000, 38298.645], [667.098, 1600.830, 745.260, 0.000, 512.148, 0.000, 1086.639, 7576.628, 0.000, 39689.369], [667.098, 1600.830, 745.260, 0.000, 512.148, 0.000, 1086.639, 7576.628, 0.000, 40992.397], [667.098, 1600.830, 745.260, 0.000, 512.148, 0.000, 1086.639, 7576.628, 0.000, 41092.265], [667.098, 1600.830, 745.260, 0.000, 512.148, 0.000, 1086.639, 7576.628, 0.000, 40733.622], [667.098, 1600.830, 745.260, 0.000, 512.148, 0.000, 3726.579, 0.000, 0.000, 40708.515], [667.098, 1600.830, 745.260, 0.000, 512.148, 0.000, 3726.579, 0.000, 0.000, 40485.321], [667.098, 0.000, 745.260, 0.000, 512.148, 0.000, 3726.579, 16888.760, 0.000, 39768.059], [667.098, 0.000, 745.260, 0.000, 512.148, 0.000, 3726.579, 16888.760, 0.000, 40519.595], [667.098, 0.000, 745.260, 0.000, 512.148, 0.000, 3726.579, 16888.760, 0.000, 41590.937], [667.098, 0.000, 1283.484, 0.000, 512.148, 0.000, 3726.579, 12448.413, 0.000, 42354.983], [667.098, 0.000, 1283.484, 0.000, 512.148, 0.000, 3726.579, 12448.413, 0.000, 41175.149], [667.098, 0.000, 1283.484, 0.000, 512.148, 0.000, 3726.579, 12448.413, 0.000, 41037.902], [667.098, 0.000, 1283.484, 0.000, 512.148, 0.000, 3726.579, 12448.413, 0.000, 42706.213], [667.098, 0.000, 1283.484, 0.000, 512.148, 0.000, 3726.579, 12448.413, 0.000, 40539.205], [0.000, 0.000, 2384.452, 0.000, 512.148, 0.000, 3726.579, 9293.252, 0.000, 41608.692], [0.000, 0.000, 2384.452, 0.000, 512.148, 0.000, 3726.579, 9293.252, 0.000, 39992.148], [0.000, 0.000, 2384.452, 0.000, 512.148, 0.000, 3726.579, 9293.252, 0.000, 39134.828]]) # 模拟PS信号回测结果 # PS信号,先卖后买,交割期为0 self.ps_res_sb00 = np.array( [[0.0000, 0.0000, 0.0000, 0.0000, 555.5556, 0.0000, 0.0000, 7500.0000, 0.0000, 10000.0000], [0.0000, 0.0000, 0.0000, 0.0000, 555.5556, 0.0000, 0.0000, 7500.0000, 0.0000, 9916.6667], [0.0000, 0.0000, 0.0000, 0.0000, 555.5556, 205.0654, 321.0892, 5059.7222, 0.0000, 9761.1111], [346.9824, 416.6787, 0.0000, 0.0000, 555.5556, 205.0654, 321.0892, 1201.2775, 0.0000, 9646.1118], [346.9824, 416.6787, 191.0372, 0.0000, 555.5556, 205.0654, 321.0892, 232.7189, 0.0000, 9685.5858], [346.9824, 416.6787, 191.0372, 0.0000, 138.8889, 205.0654, 321.0892, 1891.0523, 0.0000, 9813.2184], [346.9824, 416.6787, 191.0372, 0.0000, 138.8889, 205.0654, 321.0892, 1891.0523, 0.0000, 9803.1288], [346.9824, 416.6787, 191.0372, 0.0000, 138.8889, 205.0654, 321.0892, 1891.0523, 0.0000, 9608.0198], [346.9824, 416.6787, 191.0372, 0.0000, 138.8889, 205.0654, 321.0892, 1891.0523, 0.0000, 9311.5727], [346.9824, 416.6787, 191.0372, 0.0000, 138.8889, 205.0654, 321.0892, 1891.0523, 0.0000, 8883.6246], [346.9824, 416.6787, 191.0372, 0.0000, 138.8889, 205.0654, 321.0892, 1891.0523, 0.0000, 8751.3900], [346.9824, 416.6787, 191.0372, 0.0000, 138.8889, 205.0654, 321.0892, 1891.0523, 0.0000, 8794.1811], [346.9824, 416.6787, 191.0372, 0.0000, 138.8889, 205.0654, 321.0892, 1891.0523, 0.0000, 9136.5704], [231.4373, 416.6787, 191.0372, 0.0000, 138.8889, 205.0654, 321.0892, 2472.2444, 0.0000, 9209.3588], [231.4373, 416.6787, 191.0372, 0.0000, 138.8889, 205.0654, 321.0892, 2472.2444, 0.0000, 9093.8294], [231.4373, 416.6787, 191.0372, 0.0000, 138.8889, 205.0654, 321.0892, 2472.2444, 0.0000, 9387.5537], [231.4373, 416.6787, 191.0372, 0.0000, 138.8889, 205.0654, 321.0892, 2472.2444, 0.0000, 9585.9589], [231.4373, 416.6787, 95.5186, 0.0000, 138.8889, 205.0654, 321.0892, 3035.8041, 0.0000, 9928.7771], [231.4373, 416.6787, 95.5186, 0.0000, 138.8889, 205.0654, 321.0892, 3035.8041, 0.0000, 10060.3806], [231.4373, 416.6787, 95.5186, 0.0000, 138.8889, 205.0654, 321.0892, 3035.8041, 0.0000, 10281.0021], [231.4373, 416.6787, 95.5186, 0.0000, 138.8889, 205.0654, 321.0892, 3035.8041, 0.0000, 10095.5613], [231.4373, 416.6787, 95.5186, 0.0000, 138.8889, 205.0654, 0.0000, 4506.3926, 0.0000, 10029.9571], [231.4373, 416.6787, 95.5186, 0.0000, 474.2238, 205.0654, 0.0000, 2531.2699, 0.0000, 9875.6133], [231.4373, 416.6787, 95.5186, 0.0000, 474.2238, 205.0654, 0.0000, 2531.2699, 0.0000, 9614.9463], [231.4373, 416.6787, 95.5186, 0.0000, 474.2238, 205.0654, 0.0000, 2531.2699, 0.0000, 9824.1722], [115.7186, 416.6787, 95.5186, 269.8496, 474.2238, 205.0654, 0.0000, 1854.7990, 0.0000, 9732.5743], [115.7186, 416.6787, 95.5186, 269.8496, 474.2238, 205.0654, 0.0000, 1854.7990, 0.0000, 9968.3391], [115.7186, 416.6787, 95.5186, 269.8496, 474.2238, 205.0654, 0.0000, 1854.7990, 0.0000, 10056.1579], [115.7186, 416.6787, 95.5186, 269.8496, 474.2238, 205.0654, 0.0000, 1854.7990, 0.0000, 9921.4925], [115.7186, 416.6787, 95.5186, 269.8496, 474.2238, 205.0654, 0.0000, 1854.7990, 0.0000, 9894.1621], [115.7186, 416.6787, 735.6442, 269.8496, 0.0000, 1877.3934, 0.0000, 6179.7742, 0.0000, 20067.9370], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 1877.3934, 0.0000, 0.0000, 0.0000, 21133.5080], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 1877.3934, 0.0000, 0.0000, 0.0000, 20988.8485], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 1877.3934, 0.0000, 0.0000, 0.0000, 20596.7429], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 1877.3934, 0.0000, 0.0000, 0.0000, 19910.7730], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 1877.3934, 0.0000, 0.0000, 0.0000, 20776.7070], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 1877.3934, 0.0000, 0.0000, 0.0000, 20051.7969], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 1877.3934, 0.0000, 0.0000, 0.0000, 20725.3884], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 1877.3934, 0.0000, 0.0000, 0.0000, 20828.8795], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 1877.3934, 0.0000, 0.0000, 0.0000, 21647.1811], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 1877.3934, 0.0000, 0.0000, 0.0000, 21310.1687], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 1877.3934, 0.0000, 0.0000, 0.0000, 20852.0993], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 1877.3934, 0.0000, 0.0000, 0.0000, 21912.3952], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 1877.3934, 0.0000, 0.0000, 0.0000, 21937.8282], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 1877.3934, 0.0000, 0.0000, 0.0000, 21962.4576], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 938.6967, 1339.2073, 0.0000, 0.0000, 21389.4018], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 938.6967, 1339.2073, 0.0000, 0.0000, 22027.4535], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 938.6967, 1339.2073, 0.0000, 0.0000, 20939.9992], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 938.6967, 1339.2073, 0.0000, 0.0000, 21250.0636], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 938.6967, 1339.2073, 0.0000, 0.0000, 22282.7812], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 938.6967, 1339.2073, 0.0000, 0.0000, 21407.0658], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 938.6967, 1339.2073, 0.0000, 0.0000, 21160.2373], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 938.6967, 1339.2073, 0.0000, 0.0000, 21826.7682], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 938.6967, 1339.2073, 0.0000, 0.0000, 22744.9403], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 938.6967, 1339.2073, 0.0000, 0.0000, 23466.1185], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 938.6967, 1339.2073, 0.0000, 0.0000, 22017.8821], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 938.6967, 1339.2073, 0.0000, 0.0000, 23191.4662], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 938.6967, 1339.2073, 0.0000, 0.0000, 23099.0822], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 938.6967, 1339.2073, 0.0000, 0.0000, 22684.7671], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 938.6967, 1339.2073, 0.0000, 0.0000, 22842.1346], [1073.8232, 416.6787, 735.6442, 269.8496, 1785.2055, 938.6967, 1339.2073, 5001.4246, 0.0000, 33323.8359], [0.0000, 416.6787, 735.6442, 944.9611, 1785.2055, 3582.8836, 1339.2073, 0.0000, 0.0000, 32820.2901], [0.0000, 416.6787, 735.6442, 944.9611, 1785.2055, 3582.8836, 1339.2073, 0.0000, 0.0000, 32891.2308], [0.0000, 416.6787, 735.6442, 944.9611, 1785.2055, 3582.8836, 1339.2073, 0.0000, 0.0000, 34776.5296], [0.0000, 416.6787, 735.6442, 944.9611, 1785.2055, 3582.8836, 1339.2073, 0.0000, 0.0000, 33909.0325], [0.0000, 416.6787, 735.6442, 944.9611, 1785.2055, 3582.8836, 1339.2073, 0.0000, 0.0000, 34560.1906], [0.0000, 416.6787, 735.6442, 944.9611, 1785.2055, 3582.8836, 1339.2073, 0.0000, 0.0000, 36080.4552], [0.0000, 416.6787, 735.6442, 944.9611, 1785.2055, 3582.8836, 1339.2073, 0.0000, 0.0000, 38618.4454], [0.0000, 416.6787, 735.6442, 944.9611, 1785.2055, 3582.8836, 1339.2073, 0.0000, 0.0000, 38497.9230], [0.0000, 416.6787, 735.6442, 944.9611, 1785.2055, 3582.8836, 1339.2073, 0.0000, 0.0000, 37110.0991], [0.0000, 416.6787, 735.6442, 944.9611, 1785.2055, 3582.8836, 1339.2073, 0.0000, 0.0000, 35455.2467], [0.0000, 416.6787, 735.6442, 0.0000, 1785.2055, 0.0000, 1339.2073, 15126.2788, 0.0000, 35646.1860], [0.0000, 416.6787, 735.6442, 0.0000, 1785.2055, 0.0000, 1339.2073, 15126.2788, 0.0000, 35472.3020], [0.0000, 416.6787, 735.6442, 0.0000, 1785.2055, 0.0000, 1339.2073, 15126.2788, 0.0000, 36636.4694], [0.0000, 416.6787, 735.6442, 0.0000, 1785.2055, 0.0000, 1339.2073, 15126.2788, 0.0000, 35191.7035], [0.0000, 416.6787, 735.6442, 0.0000, 1785.2055, 0.0000, 1339.2073, 15126.2788, 0.0000, 36344.2242], [0.0000, 416.6787, 735.6442, 0.0000, 1785.2055, 0.0000, 1339.2073, 15126.2788, 0.0000, 36221.6005], [0.0000, 416.6787, 735.6442, 0.0000, 1785.2055, 0.0000, 1339.2073, 15126.2788, 0.0000, 35943.5708], [0.0000, 416.6787, 735.6442, 0.0000, 1785.2055, 0.0000, 1339.2073, 15126.2788, 0.0000, 35708.2608], [0.0000, 416.6787, 735.6442, 0.0000, 1785.2055, 0.0000, 1339.2073, 15126.2788, 0.0000, 35589.0286], [0.0000, 416.6787, 735.6442, 0.0000, 1785.2055, 0.0000, 1339.2073, 15126.2788, 0.0000, 36661.0285], [0.0000, 823.2923, 735.6442, 0.0000, 1785.2055, 0.0000, 1339.2073, 11495.2197, 0.0000, 36310.5909], [0.0000, 823.2923, 735.6442, 0.0000, 1785.2055, 0.0000, 1339.2073, 11495.2197, 0.0000, 36466.7637], [0.0000, 823.2923, 735.6442, 0.0000, 1785.2055, 0.0000, 1339.2073, 11495.2197, 0.0000, 37784.4918], [0.0000, 823.2923, 735.6442, 0.0000, 1785.2055, 0.0000, 1339.2073, 11495.2197, 0.0000, 39587.6766], [0.0000, 823.2923, 735.6442, 0.0000, 1785.2055, 0.0000, 1339.2073, 11495.2197, 0.0000, 40064.0191], [0.0000, 823.2923, 735.6442, 0.0000, 1785.2055, 0.0000, 1339.2073, 11495.2197, 0.0000, 39521.6439], [0.0000, 823.2923, 735.6442, 0.0000, 0.0000, 0.0000, 2730.5758, 17142.1018, 0.0000, 39932.2761], [0.0000, 823.2923, 735.6442, 0.0000, 0.0000, 0.0000, 2730.5758, 17142.1018, 0.0000, 39565.2475], [0.0000, 0.0000, 735.6442, 0.0000, 0.0000, 0.0000, 2730.5758, 25827.8351, 0.0000, 38943.1632], [0.0000, 0.0000, 735.6442, 0.0000, 0.0000, 0.0000, 2730.5758, 25827.8351, 0.0000, 39504.1184], [0.0000, 0.0000, 735.6442, 0.0000, 0.0000, 0.0000, 2730.5758, 25827.8351, 0.0000, 40317.8004], [0.0000, 0.0000, 735.6442, 0.0000, 0.0000, 0.0000, 2730.5758, 25827.8351, 0.0000, 40798.5768], [0.0000, 0.0000, 735.6442, 0.0000, 0.0000, 0.0000, 2730.5758, 25827.8351, 0.0000, 39962.5711], [0.0000, 0.0000, 735.6442, 0.0000, 0.0000, 0.0000, 2730.5758, 25827.8351, 0.0000, 40194.4793], [0.0000, 0.0000, 735.6442, 0.0000, 0.0000, 0.0000, 2730.5758, 25827.8351, 0.0000, 41260.4003], [0.0000, 0.0000, 735.6442, 0.0000, 0.0000, 0.0000, 2730.5758, 25827.8351, 0.0000, 39966.3024], [0.0000, 0.0000, 1613.4518, 0.0000, 0.0000, 0.0000, 2730.5758, 19700.7377, 0.0000, 40847.3160], [0.0000, 0.0000, 1613.4518, 0.0000, 0.0000, 0.0000, 2730.5758, 19700.7377, 0.0000, 39654.5445], [0.0000, 0.0000, 1613.4518, 0.0000, 0.0000, 0.0000, 2730.5758, 19700.7377, 0.0000, 38914.8151]]) # PS信号,先买后卖,交割期为0 self.ps_res_bs00 = np.array( [[0.0000, 0.0000, 0.0000, 0.0000, 555.5556, 0.0000, 0.0000, 7500.0000, 0.0000, 10000.0000], [0.0000, 0.0000, 0.0000, 0.0000, 555.5556, 0.0000, 0.0000, 7500.0000, 0.0000, 9916.6667], [0.0000, 0.0000, 0.0000, 0.0000, 555.5556, 205.0654, 321.0892, 5059.7222, 0.0000, 9761.1111], [346.9824, 416.6787, 0.0000, 0.0000, 555.5556, 205.0654, 321.0892, 1201.2775, 0.0000, 9646.1118], [346.9824, 416.6787, 191.0372, 0.0000, 555.5556, 205.0654, 321.0892, 232.7189, 0.0000, 9685.5858], [346.9824, 416.6787, 191.0372, 0.0000, 138.8889, 205.0654, 321.0892, 1891.0523, 0.0000, 9813.2184], [346.9824, 416.6787, 191.0372, 0.0000, 138.8889, 205.0654, 321.0892, 1891.0523, 0.0000, 9803.1288], [346.9824, 416.6787, 191.0372, 0.0000, 138.8889, 205.0654, 321.0892, 1891.0523, 0.0000, 9608.0198], [346.9824, 416.6787, 191.0372, 0.0000, 138.8889, 205.0654, 321.0892, 1891.0523, 0.0000, 9311.5727], [346.9824, 416.6787, 191.0372, 0.0000, 138.8889, 205.0654, 321.0892, 1891.0523, 0.0000, 8883.6246], [346.9824, 416.6787, 191.0372, 0.0000, 138.8889, 205.0654, 321.0892, 1891.0523, 0.0000, 8751.3900], [346.9824, 416.6787, 191.0372, 0.0000, 138.8889, 205.0654, 321.0892, 1891.0523, 0.0000, 8794.1811], [346.9824, 416.6787, 191.0372, 0.0000, 138.8889, 205.0654, 321.0892, 1891.0523, 0.0000, 9136.5704], [231.4373, 416.6787, 191.0372, 0.0000, 138.8889, 205.0654, 321.0892, 2472.2444, 0.0000, 9209.3588], [231.4373, 416.6787, 191.0372, 0.0000, 138.8889, 205.0654, 321.0892, 2472.2444, 0.0000, 9093.8294], [231.4373, 416.6787, 191.0372, 0.0000, 138.8889, 205.0654, 321.0892, 2472.2444, 0.0000, 9387.5537], [231.4373, 416.6787, 191.0372, 0.0000, 138.8889, 205.0654, 321.0892, 2472.2444, 0.0000, 9585.9589], [231.4373, 416.6787, 95.5186, 0.0000, 138.8889, 205.0654, 321.0892, 3035.8041, 0.0000, 9928.7771], [231.4373, 416.6787, 95.5186, 0.0000, 138.8889, 205.0654, 321.0892, 3035.8041, 0.0000, 10060.3806], [231.4373, 416.6787, 95.5186, 0.0000, 138.8889, 205.0654, 321.0892, 3035.8041, 0.0000, 10281.0021], [231.4373, 416.6787, 95.5186, 0.0000, 138.8889, 205.0654, 321.0892, 3035.8041, 0.0000, 10095.5613], [231.4373, 416.6787, 95.5186, 0.0000, 138.8889, 205.0654, 0.0000, 4506.3926, 0.0000, 10029.9571], [231.4373, 416.6787, 95.5186, 0.0000, 474.2238, 205.0654, 0.0000, 2531.2699, 0.0000, 9875.6133], [231.4373, 416.6787, 95.5186, 0.0000, 474.2238, 205.0654, 0.0000, 2531.2699, 0.0000, 9614.9463], [231.4373, 416.6787, 95.5186, 0.0000, 474.2238, 205.0654, 0.0000, 2531.2699, 0.0000, 9824.1722], [115.7186, 416.6787, 95.5186, 269.8496, 474.2238, 205.0654, 0.0000, 1854.7990, 0.0000, 9732.5743], [115.7186, 416.6787, 95.5186, 269.8496, 474.2238, 205.0654, 0.0000, 1854.7990, 0.0000, 9968.3391], [115.7186, 416.6787, 95.5186, 269.8496, 474.2238, 205.0654, 0.0000, 1854.7990, 0.0000, 10056.1579], [115.7186, 416.6787, 95.5186, 269.8496, 474.2238, 205.0654, 0.0000, 1854.7990, 0.0000, 9921.4925], [115.7186, 416.6787, 95.5186, 269.8496, 474.2238, 205.0654, 0.0000, 1854.7990, 0.0000, 9894.1621], [115.7186, 416.6787, 735.6442, 269.8496, 0.0000, 1877.3934, 0.0000, 6179.7742, 0.0000, 20067.9370], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 1877.3934, 0.0000, 0.0000, 0.0000, 21133.5080], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 1877.3934, 0.0000, 0.0000, 0.0000, 20988.8485], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 1877.3934, 0.0000, 0.0000, 0.0000, 20596.7429], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 1877.3934, 0.0000, 0.0000, 0.0000, 19910.7730], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 1877.3934, 0.0000, 0.0000, 0.0000, 20776.7070], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 1877.3934, 0.0000, 0.0000, 0.0000, 20051.7969], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 1877.3934, 0.0000, 0.0000, 0.0000, 20725.3884], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 1877.3934, 0.0000, 0.0000, 0.0000, 20828.8795], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 1877.3934, 0.0000, 0.0000, 0.0000, 21647.1811], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 1877.3934, 0.0000, 0.0000, 0.0000, 21310.1687], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 1877.3934, 0.0000, 0.0000, 0.0000, 20852.0993], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 1877.3934, 0.0000, 0.0000, 0.0000, 21912.3952], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 1877.3934, 0.0000, 0.0000, 0.0000, 21937.8282], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 1877.3934, 0.0000, 0.0000, 0.0000, 21962.4576], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 938.6967, 0.0000, 2008.8110, 0.0000, 21389.4018], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 938.6967, 0.0000, 2008.8110, 0.0000, 21625.6913], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 938.6967, 0.0000, 2008.8110, 0.0000, 20873.0389], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 938.6967, 0.0000, 2008.8110, 0.0000, 21450.9447], [1073.8232, 416.6787, 735.6442, 269.8496, 0.0000, 938.6967, 0.0000, 2008.8110, 0.0000, 22269.3892], [1073.8232, 737.0632, 735.6442, 269.8496, 0.0000, 938.6967, 0.0000, 0.0000, 0.0000, 21969.5329], [1073.8232, 737.0632, 735.6442, 269.8496, 0.0000, 938.6967, 0.0000, 0.0000, 0.0000, 21752.6924], [1073.8232, 737.0632, 735.6442, 269.8496, 0.0000, 938.6967, 0.0000, 0.0000, 0.0000, 22000.6088], [1073.8232, 737.0632, 735.6442, 269.8496, 0.0000, 938.6967, 0.0000, 0.0000, 0.0000, 23072.5655], [1073.8232, 737.0632, 735.6442, 269.8496, 0.0000, 938.6967, 0.0000, 0.0000, 0.0000, 23487.5201], [1073.8232, 737.0632, 735.6442, 269.8496, 0.0000, 938.6967, 0.0000, 0.0000, 0.0000, 22441.0460], [1073.8232, 737.0632, 735.6442, 269.8496, 0.0000, 938.6967, 0.0000, 0.0000, 0.0000, 23201.2700], [1073.8232, 737.0632, 735.6442, 269.8496, 0.0000, 938.6967, 0.0000, 0.0000, 0.0000, 23400.9485], [1073.8232, 737.0632, 735.6442, 269.8496, 0.0000, 938.6967, 0.0000, 0.0000, 0.0000, 22306.2008], [1073.8232, 737.0632, 735.6442, 269.8496, 0.0000, 938.6967, 0.0000, 0.0000, 0.0000, 21989.5913], [1073.8232, 737.0632, 735.6442, 269.8496, 1708.7766, 938.6967, 0.0000, 5215.4255, 0.0000, 31897.1636], [0.0000, 737.0632, 735.6442, 578.0898, 1708.7766, 2145.9711, 0.0000, 6421.4626, 0.0000, 31509.5059], [0.0000, 737.0632, 735.6442, 578.0898, 1708.7766, 2145.9711, 0.0000, 6421.4626, 0.0000, 31451.7888], [978.8815, 737.0632, 735.6442, 578.0898, 1708.7766, 2145.9711, 0.0000, 0.0000, 0.0000, 32773.4592], [978.8815, 737.0632, 735.6442, 578.0898, 1708.7766, 2145.9711, 0.0000, 0.0000, 0.0000, 32287.0318], [978.8815, 737.0632, 735.6442, 578.0898, 1708.7766, 2145.9711, 0.0000, 0.0000, 0.0000, 32698.1938], [978.8815, 737.0632, 735.6442, 578.0898, 1708.7766, 2145.9711, 0.0000, 0.0000, 0.0000, 34031.5183], [978.8815, 737.0632, 735.6442, 578.0898, 1708.7766, 2145.9711, 0.0000, 0.0000, 0.0000, 35537.8336], [978.8815, 737.0632, 735.6442, 578.0898, 1708.7766, 2145.9711, 0.0000, 0.0000, 0.0000, 36212.6487], [978.8815, 737.0632, 735.6442, 578.0898, 1708.7766, 2145.9711, 0.0000, 0.0000, 0.0000, 36007.5294], [978.8815, 737.0632, 735.6442, 578.0898, 1708.7766, 2145.9711, 0.0000, 0.0000, 0.0000, 34691.3797], [978.8815, 737.0632, 735.6442, 0.0000, 1708.7766, 0.0000, 0.0000, 9162.7865, 0.0000, 33904.8810], [978.8815, 737.0632, 735.6442, 0.0000, 1708.7766, 0.0000, 0.0000, 9162.7865, 0.0000, 34341.6098], [978.8815, 737.0632, 735.6442, 0.0000, 1708.7766, 0.0000, 0.0000, 9162.7865, 0.0000, 35479.9505], [978.8815, 737.0632, 735.6442, 0.0000, 1708.7766, 0.0000, 0.0000, 9162.7865, 0.0000, 34418.4455], [978.8815, 737.0632, 735.6442, 0.0000, 1708.7766, 0.0000, 0.0000, 9162.7865, 0.0000, 34726.7182], [978.8815, 737.0632, 735.6442, 0.0000, 1708.7766, 0.0000, 0.0000, 9162.7865, 0.0000, 34935.0407], [978.8815, 737.0632, 735.6442, 0.0000, 1708.7766, 0.0000, 0.0000, 9162.7865, 0.0000, 34136.7505], [978.8815, 737.0632, 735.6442, 0.0000, 1708.7766, 0.0000, 0.0000, 9162.7865, 0.0000, 33804.1575], [195.7763, 737.0632, 735.6442, 0.0000, 1708.7766, 0.0000, 0.0000, 14025.8697, 0.0000, 33653.8970], [195.7763, 737.0632, 735.6442, 0.0000, 1708.7766, 0.0000, 0.0000, 14025.8697, 0.0000, 34689.8757], [195.7763, 1124.9219, 735.6442, 0.0000, 1708.7766, 0.0000, 0.0000, 10562.2913, 0.0000, 34635.7841], [195.7763, 1124.9219, 735.6442, 0.0000, 1708.7766, 0.0000, 0.0000, 10562.2913, 0.0000, 35253.2755], [195.7763, 1124.9219, 735.6442, 0.0000, 1708.7766, 0.0000, 0.0000, 10562.2913, 0.0000, 36388.1051], [195.7763, 1124.9219, 735.6442, 0.0000, 1708.7766, 0.0000, 0.0000, 10562.2913, 0.0000, 37987.4204], [195.7763, 1124.9219, 735.6442, 0.0000, 1708.7766, 0.0000, 0.0000, 10562.2913, 0.0000, 38762.2103], [195.7763, 1124.9219, 735.6442, 0.0000, 1708.7766, 0.0000, 0.0000, 10562.2913, 0.0000, 38574.0544], [195.7763, 1124.9219, 735.6442, 0.0000, 0.0000, 0.0000, 1362.4361, 15879.4935, 0.0000, 39101.9156], [195.7763, 1124.9219, 735.6442, 0.0000, 0.0000, 0.0000, 1362.4361, 15879.4935, 0.0000, 39132.5587], [195.7763, 0.0000, 735.6442, 0.0000, 0.0000, 0.0000, 1362.4361, 27747.4200, 0.0000, 38873.2941], [195.7763, 0.0000, 735.6442, 0.0000, 0.0000, 0.0000, 1362.4361, 27747.4200, 0.0000, 39336.6594], [195.7763, 0.0000, 735.6442, 0.0000, 0.0000, 0.0000, 1362.4361, 27747.4200, 0.0000, 39565.9568], [195.7763, 0.0000, 735.6442, 0.0000, 0.0000, 0.0000, 1362.4361, 27747.4200, 0.0000, 39583.4317], [195.7763, 0.0000, 735.6442, 0.0000, 0.0000, 0.0000, 1362.4361, 27747.4200, 0.0000, 39206.8350], [195.7763, 0.0000, 735.6442, 0.0000, 0.0000, 0.0000, 1362.4361, 27747.4200, 0.0000, 39092.6551], [195.7763, 0.0000, 735.6442, 0.0000, 0.0000, 0.0000, 1362.4361, 27747.4200, 0.0000, 39666.1834], [195.7763, 0.0000, 735.6442, 0.0000, 0.0000, 0.0000, 1362.4361, 27747.4200, 0.0000, 38798.0749], [0.0000, 0.0000, 1576.8381, 0.0000, 0.0000, 0.0000, 1362.4361, 23205.2077, 0.0000, 39143.5561], [0.0000, 0.0000, 1576.8381, 0.0000, 0.0000, 0.0000, 1362.4361, 23205.2077, 0.0000, 38617.8779], [0.0000, 0.0000, 1576.8381, 0.0000, 0.0000, 0.0000, 1362.4361, 23205.2077, 0.0000, 38156.1701]]) # PS信号,先卖后买,交割期为2天(股票)1天(现金) self.ps_res_sb20 = np.array( [[0.000, 0.000, 0.000, 0.000, 555.556, 0.000, 0.000, 7500.000, 0.000, 10000.000], [0.000, 0.000, 0.000, 0.000, 555.556, 0.000, 0.000, 7500.000, 0.000, 9916.667], [0.000, 0.000, 0.000, 0.000, 555.556, 205.065, 321.089, 5059.722, 0.000, 9761.111], [346.982, 416.679, 0.000, 0.000, 555.556, 205.065, 321.089, 1201.278, 0.000, 9646.112], [346.982, 416.679, 191.037, 0.000, 555.556, 205.065, 321.089, 232.719, 0.000, 9685.586], [346.982, 416.679, 191.037, 0.000, 138.889, 205.065, 321.089, 1891.052, 0.000, 9813.218], [346.982, 416.679, 191.037, 0.000, 138.889, 205.065, 321.089, 1891.052, 0.000, 9803.129], [346.982, 416.679, 191.037, 0.000, 138.889, 205.065, 321.089, 1891.052, 0.000, 9608.020], [346.982, 416.679, 191.037, 0.000, 138.889, 205.065, 321.089, 1891.052, 0.000, 9311.573], [346.982, 416.679, 191.037, 0.000, 138.889, 205.065, 321.089, 1891.052, 0.000, 8883.625], [346.982, 416.679, 191.037, 0.000, 138.889, 205.065, 321.089, 1891.052, 0.000, 8751.390], [346.982, 416.679, 191.037, 0.000, 138.889, 205.065, 321.089, 1891.052, 0.000, 8794.181], [346.982, 416.679, 191.037, 0.000, 138.889, 205.065, 321.089, 1891.052, 0.000, 9136.570], [231.437, 416.679, 191.037, 0.000, 138.889, 205.065, 321.089, 2472.244, 0.000, 9209.359], [231.437, 416.679, 191.037, 0.000, 138.889, 205.065, 321.089, 2472.244, 0.000, 9093.829], [231.437, 416.679, 191.037, 0.000, 138.889, 205.065, 321.089, 2472.244, 0.000, 9387.554], [231.437, 416.679, 191.037, 0.000, 138.889, 205.065, 321.089, 2472.244, 0.000, 9585.959], [231.437, 416.679, 95.519, 0.000, 138.889, 205.065, 321.089, 3035.804, 0.000, 9928.777], [231.437, 416.679, 95.519, 0.000, 138.889, 205.065, 321.089, 3035.804, 0.000, 10060.381], [231.437, 416.679, 95.519, 0.000, 138.889, 205.065, 321.089, 3035.804, 0.000, 10281.002], [231.437, 416.679, 95.519, 0.000, 138.889, 205.065, 321.089, 3035.804, 0.000, 10095.561], [231.437, 416.679, 95.519, 0.000, 138.889, 205.065, 0.000, 4506.393, 0.000, 10029.957], [231.437, 416.679, 95.519, 0.000, 474.224, 205.065, 0.000, 2531.270, 0.000, 9875.613], [231.437, 416.679, 95.519, 0.000, 474.224, 205.065, 0.000, 2531.270, 0.000, 9614.946], [231.437, 416.679, 95.519, 0.000, 474.224, 205.065, 0.000, 2531.270, 0.000, 9824.172], [115.719, 416.679, 95.519, 269.850, 474.224, 205.065, 0.000, 1854.799, 0.000, 9732.574], [115.719, 416.679, 95.519, 269.850, 474.224, 205.065, 0.000, 1854.799, 0.000, 9968.339], [115.719, 416.679, 95.519, 269.850, 474.224, 205.065, 0.000, 1854.799, 0.000, 10056.158], [115.719, 416.679, 95.519, 269.850, 474.224, 205.065, 0.000, 1854.799, 0.000, 9921.492], [115.719, 416.679, 95.519, 269.850, 474.224, 205.065, 0.000, 1854.799, 0.000, 9894.162], [115.719, 416.679, 735.644, 269.850, 0.000, 1877.393, 0.000, 6179.774, 0.000, 20067.937], [1073.823, 416.679, 735.644, 269.850, 0.000, 1877.393, 0.000, 0.000, 0.000, 21133.508], [1073.823, 416.679, 735.644, 269.850, 0.000, 1877.393, 0.000, 0.000, 0.000, 20988.848], [1073.823, 416.679, 735.644, 269.850, 0.000, 1877.393, 0.000, 0.000, 0.000, 20596.743], [1073.823, 416.679, 735.644, 269.850, 0.000, 1877.393, 0.000, 0.000, 0.000, 19910.773], [1073.823, 416.679, 735.644, 269.850, 0.000, 1877.393, 0.000, 0.000, 0.000, 20776.707], [1073.823, 416.679, 735.644, 269.850, 0.000, 1877.393, 0.000, 0.000, 0.000, 20051.797], [1073.823, 416.679, 735.644, 269.850, 0.000, 1877.393, 0.000, 0.000, 0.000, 20725.388], [1073.823, 416.679, 735.644, 269.850, 0.000, 1877.393, 0.000, 0.000, 0.000, 20828.880], [1073.823, 416.679, 735.644, 269.850, 0.000, 1877.393, 0.000, 0.000, 0.000, 21647.181], [1073.823, 416.679, 735.644, 269.850, 0.000, 1877.393, 0.000, 0.000, 0.000, 21310.169], [1073.823, 416.679, 735.644, 269.850, 0.000, 1877.393, 0.000, 0.000, 0.000, 20852.099], [1073.823, 416.679, 735.644, 269.850, 0.000, 1877.393, 0.000, 0.000, 0.000, 21912.395], [1073.823, 416.679, 735.644, 269.850, 0.000, 1877.393, 0.000, 0.000, 0.000, 21937.828], [1073.823, 416.679, 735.644, 269.850, 0.000, 1877.393, 0.000, 0.000, 0.000, 21962.458], [1073.823, 416.679, 735.644, 269.850, 0.000, 938.697, 1339.207, 0.000, 0.000, 21389.402], [1073.823, 416.679, 735.644, 269.850, 0.000, 938.697, 1339.207, 0.000, 0.000, 22027.453], [1073.823, 416.679, 735.644, 269.850, 0.000, 938.697, 1339.207, 0.000, 0.000, 20939.999], [1073.823, 416.679, 735.644, 269.850, 0.000, 938.697, 1339.207, 0.000, 0.000, 21250.064], [1073.823, 416.679, 735.644, 269.850, 0.000, 938.697, 1339.207, 0.000, 0.000, 22282.781], [1073.823, 416.679, 735.644, 269.850, 0.000, 938.697, 1339.207, 0.000, 0.000, 21407.066], [1073.823, 416.679, 735.644, 269.850, 0.000, 938.697, 1339.207, 0.000, 0.000, 21160.237], [1073.823, 416.679, 735.644, 269.850, 0.000, 938.697, 1339.207, 0.000, 0.000, 21826.768], [1073.823, 416.679, 735.644, 269.850, 0.000, 938.697, 1339.207, 0.000, 0.000, 22744.940], [1073.823, 416.679, 735.644, 269.850, 0.000, 938.697, 1339.207, 0.000, 0.000, 23466.118], [1073.823, 416.679, 735.644, 269.850, 0.000, 938.697, 1339.207, 0.000, 0.000, 22017.882], [1073.823, 416.679, 735.644, 269.850, 0.000, 938.697, 1339.207, 0.000, 0.000, 23191.466], [1073.823, 416.679, 735.644, 269.850, 0.000, 938.697, 1339.207, 0.000, 0.000, 23099.082], [1073.823, 416.679, 735.644, 269.850, 0.000, 938.697, 1339.207, 0.000, 0.000, 22684.767], [1073.823, 416.679, 735.644, 269.850, 0.000, 938.697, 1339.207, 0.000, 0.000, 22842.135], [1073.823, 416.679, 735.644, 269.850, 1785.205, 938.697, 1339.207, 5001.425, 0.000, 33323.836], [0.000, 416.679, 735.644, 944.961, 1785.205, 3582.884, 1339.207, 0.000, 0.000, 32820.290], [0.000, 416.679, 735.644, 944.961, 1785.205, 3582.884, 1339.207, 0.000, 0.000, 32891.231], [0.000, 416.679, 735.644, 944.961, 1785.205, 3582.884, 1339.207, 0.000, 0.000, 34776.530], [0.000, 416.679, 735.644, 944.961, 1785.205, 3582.884, 1339.207, 0.000, 0.000, 33909.032], [0.000, 416.679, 735.644, 944.961, 1785.205, 3582.884, 1339.207, 0.000, 0.000, 34560.191], [0.000, 416.679, 735.644, 944.961, 1785.205, 3582.884, 1339.207, 0.000, 0.000, 36080.455], [0.000, 416.679, 735.644, 944.961, 1785.205, 3582.884, 1339.207, 0.000, 0.000, 38618.445], [0.000, 416.679, 735.644, 944.961, 1785.205, 3582.884, 1339.207, 0.000, 0.000, 38497.923], [0.000, 416.679, 735.644, 944.961, 1785.205, 3582.884, 1339.207, 0.000, 0.000, 37110.099], [0.000, 416.679, 735.644, 944.961, 1785.205, 3582.884, 1339.207, 0.000, 0.000, 35455.247], [0.000, 416.679, 735.644, 0.000, 1785.205, 0.000, 1339.207, 15126.279, 0.000, 35646.186], [0.000, 416.679, 735.644, 0.000, 1785.205, 0.000, 1339.207, 15126.279, 0.000, 35472.302], [0.000, 416.679, 735.644, 0.000, 1785.205, 0.000, 1339.207, 15126.279, 0.000, 36636.469], [0.000, 416.679, 735.644, 0.000, 1785.205, 0.000, 1339.207, 15126.279, 0.000, 35191.704], [0.000, 416.679, 735.644, 0.000, 1785.205, 0.000, 1339.207, 15126.279, 0.000, 36344.224], [0.000, 416.679, 735.644, 0.000, 1785.205, 0.000, 1339.207, 15126.279, 0.000, 36221.601], [0.000, 416.679, 735.644, 0.000, 1785.205, 0.000, 1339.207, 15126.279, 0.000, 35943.571], [0.000, 416.679, 735.644, 0.000, 1785.205, 0.000, 1339.207, 15126.279, 0.000, 35708.261], [0.000, 416.679, 735.644, 0.000, 1785.205, 0.000, 1339.207, 15126.279, 0.000, 35589.029], [0.000, 416.679, 735.644, 0.000, 1785.205, 0.000, 1339.207, 15126.279, 0.000, 36661.029], [0.000, 823.292, 735.644, 0.000, 1785.205, 0.000, 1339.207, 11495.220, 0.000, 36310.591], [0.000, 823.292, 735.644, 0.000, 1785.205, 0.000, 1339.207, 11495.220, 0.000, 36466.764], [0.000, 823.292, 735.644, 0.000, 1785.205, 0.000, 1339.207, 11495.220, 0.000, 37784.492], [0.000, 823.292, 735.644, 0.000, 1785.205, 0.000, 1339.207, 11495.220, 0.000, 39587.677], [0.000, 823.292, 735.644, 0.000, 1785.205, 0.000, 1339.207, 11495.220, 0.000, 40064.019], [0.000, 823.292, 735.644, 0.000, 1785.205, 0.000, 1339.207, 11495.220, 0.000, 39521.644], [0.000, 823.292, 735.644, 0.000, 0.000, 0.000, 2730.576, 17142.102, 0.000, 39932.276], [0.000, 823.292, 735.644, 0.000, 0.000, 0.000, 2730.576, 17142.102, 0.000, 39565.248], [0.000, 0.000, 735.644, 0.000, 0.000, 0.000, 2730.576, 25827.835, 0.000, 38943.163], [0.000, 0.000, 735.644, 0.000, 0.000, 0.000, 2730.576, 25827.835, 0.000, 39504.118], [0.000, 0.000, 735.644, 0.000, 0.000, 0.000, 2730.576, 25827.835, 0.000, 40317.800], [0.000, 0.000, 735.644, 0.000, 0.000, 0.000, 2730.576, 25827.835, 0.000, 40798.577], [0.000, 0.000, 735.644, 0.000, 0.000, 0.000, 2730.576, 25827.835, 0.000, 39962.571], [0.000, 0.000, 735.644, 0.000, 0.000, 0.000, 2730.576, 25827.835, 0.000, 40194.479], [0.000, 0.000, 735.644, 0.000, 0.000, 0.000, 2730.576, 25827.835, 0.000, 41260.400], [0.000, 0.000, 735.644, 0.000, 0.000, 0.000, 2730.576, 25827.835, 0.000, 39966.302], [0.000, 0.000, 1613.452, 0.000, 0.000, 0.000, 2730.576, 19700.738, 0.000, 40847.316], [0.000, 0.000, 1613.452, 0.000, 0.000, 0.000, 2730.576, 19700.738, 0.000, 39654.544], [0.000, 0.000, 1613.452, 0.000, 0.000, 0.000, 2730.576, 19700.738, 0.000, 38914.815]]) # PS信号,先买后卖,交割期为2天(股票)1天(现金) self.ps_res_bs21 = np.array( [[0.000, 0.000, 0.000, 0.000, 555.556, 0.000, 0.000, 7500.000, 0.000, 10000.000], [0.000, 0.000, 0.000, 0.000, 555.556, 0.000, 0.000, 7500.000, 0.000, 9916.667], [0.000, 0.000, 0.000, 0.000, 555.556, 208.333, 326.206, 5020.833, 0.000, 9761.111], [351.119, 421.646, 0.000, 0.000, 555.556, 208.333, 326.206, 1116.389, 0.000, 9645.961], [351.119, 421.646, 190.256, 0.000, 555.556, 208.333, 326.206, 151.793, 0.000, 9686.841], [351.119, 421.646, 190.256, 0.000, 138.889, 208.333, 326.206, 1810.126, 0.000, 9813.932], [351.119, 421.646, 190.256, 0.000, 138.889, 208.333, 326.206, 1810.126, 0.000, 9803.000], [351.119, 421.646, 190.256, 0.000, 138.889, 208.333, 326.206, 1810.126, 0.000, 9605.334], [351.119, 421.646, 190.256, 0.000, 138.889, 208.333, 326.206, 1810.126, 0.000, 9304.001], [351.119, 421.646, 190.256, 0.000, 138.889, 208.333, 326.206, 1810.126, 0.000, 8870.741], [351.119, 421.646, 190.256, 0.000, 138.889, 208.333, 326.206, 1810.126, 0.000, 8738.282], [351.119, 421.646, 190.256, 0.000, 138.889, 208.333, 326.206, 1810.126, 0.000, 8780.664], [351.119, 421.646, 190.256, 0.000, 138.889, 208.333, 326.206, 1810.126, 0.000, 9126.199], [234.196, 421.646, 190.256, 0.000, 138.889, 208.333, 326.206, 2398.247, 0.000, 9199.746], [234.196, 421.646, 190.256, 0.000, 138.889, 208.333, 326.206, 2398.247, 0.000, 9083.518], [234.196, 421.646, 190.256, 0.000, 138.889, 208.333, 326.206, 2398.247, 0.000, 9380.932], [234.196, 421.646, 190.256, 0.000, 138.889, 208.333, 326.206, 2398.247, 0.000, 9581.266], [234.196, 421.646, 95.128, 0.000, 138.889, 208.333, 326.206, 2959.501, 0.000, 9927.154], [234.196, 421.646, 95.128, 0.000, 138.889, 208.333, 326.206, 2959.501, 0.000, 10059.283], [234.196, 421.646, 95.128, 0.000, 138.889, 208.333, 326.206, 2959.501, 0.000, 10281.669], [234.196, 421.646, 95.128, 0.000, 138.889, 208.333, 326.206, 2959.501, 0.000, 10093.263], [234.196, 421.646, 95.128, 0.000, 138.889, 208.333, 0.000, 4453.525, 0.000, 10026.289], [234.196, 421.646, 95.128, 0.000, 479.340, 208.333, 0.000, 2448.268, 0.000, 9870.523], [234.196, 421.646, 95.128, 0.000, 479.340, 208.333, 0.000, 2448.268, 0.000, 9606.437], [234.196, 421.646, 95.128, 0.000, 479.340, 208.333, 0.000, 2448.268, 0.000, 9818.691], [117.098, 421.646, 95.128, 272.237, 479.340, 208.333, 0.000, 1768.219, 0.000, 9726.556], [117.098, 421.646, 95.128, 272.237, 479.340, 208.333, 0.000, 1768.219, 0.000, 9964.547], [117.098, 421.646, 95.128, 272.237, 479.340, 208.333, 0.000, 1768.219, 0.000, 10053.449], [117.098, 421.646, 95.128, 272.237, 479.340, 208.333, 0.000, 1768.219, 0.000, 9917.440], [117.098, 421.646, 95.128, 272.237, 479.340, 208.333, 0.000, 1768.219, 0.000, 9889.495], [117.098, 421.646, 729.561, 272.237, 0.000, 1865.791, 0.000, 6189.948, 0.000, 20064.523], [708.171, 421.646, 729.561, 272.237, 0.000, 1865.791, 0.000, 2377.527, 0.000, 21124.484], [708.171, 421.646, 729.561, 272.237, 0.000, 1865.791, 0.000, 2377.527, 0.000, 20827.077], [708.171, 421.646, 729.561, 272.237, 0.000, 1865.791, 0.000, 2377.527, 0.000, 20396.124], [708.171, 421.646, 729.561, 272.237, 0.000, 1865.791, 0.000, 2377.527, 0.000, 19856.445], [708.171, 421.646, 729.561, 272.237, 0.000, 1865.791, 0.000, 2377.527, 0.000, 20714.156], [708.171, 421.646, 729.561, 272.237, 0.000, 1865.791, 0.000, 2377.527, 0.000, 19971.485], [708.171, 421.646, 729.561, 272.237, 0.000, 1865.791, 0.000, 2377.527, 0.000, 20733.948], [708.171, 421.646, 729.561, 272.237, 0.000, 1865.791, 0.000, 2377.527, 0.000, 20938.903], [708.171, 421.646, 729.561, 272.237, 0.000, 1865.791, 0.000, 2377.527, 0.000, 21660.772], [708.171, 421.646, 729.561, 272.237, 0.000, 1865.791, 0.000, 2377.527, 0.000, 21265.298], [708.171, 421.646, 729.561, 272.237, 0.000, 1865.791, 0.000, 2377.527, 0.000, 20684.378], [1055.763, 421.646, 729.561, 272.237, 0.000, 1865.791, 0.000, 0.000, 0.000, 21754.770], [1055.763, 421.646, 729.561, 272.237, 0.000, 1865.791, 0.000, 0.000, 0.000, 21775.215], [1055.763, 421.646, 729.561, 272.237, 0.000, 1865.791, 0.000, 0.000, 0.000, 21801.488], [1055.763, 421.646, 729.561, 272.237, 0.000, 932.896, 0.000, 1996.397, 0.000, 21235.427], [1055.763, 421.646, 729.561, 272.237, 0.000, 932.896, 0.000, 1996.397, 0.000, 21466.714], [1055.763, 421.646, 729.561, 272.237, 0.000, 932.896, 0.000, 1996.397, 0.000, 20717.431], [1055.763, 421.646, 729.561, 272.237, 0.000, 932.896, 0.000, 1996.397, 0.000, 21294.450], [1055.763, 421.646, 729.561, 272.237, 0.000, 932.896, 0.000, 1996.397, 0.000, 22100.247], [1055.763, 740.051, 729.561, 272.237, 0.000, 932.896, 0.000, 0.000, 0.000, 21802.552], [1055.763, 740.051, 729.561, 272.237, 0.000, 932.896, 0.000, 0.000, 0.000, 21593.608], [1055.763, 740.051, 729.561, 272.237, 0.000, 932.896, 0.000, 0.000, 0.000, 21840.028], [1055.763, 740.051, 729.561, 272.237, 0.000, 932.896, 0.000, 0.000, 0.000, 22907.725], [1055.763, 740.051, 729.561, 272.237, 0.000, 932.896, 0.000, 0.000, 0.000, 23325.945], [1055.763, 740.051, 729.561, 272.237, 0.000, 932.896, 0.000, 0.000, 0.000, 22291.942], [1055.763, 740.051, 729.561, 272.237, 0.000, 932.896, 0.000, 0.000, 0.000, 23053.050], [1055.763, 740.051, 729.561, 272.237, 0.000, 932.896, 0.000, 0.000, 0.000, 23260.084], [1055.763, 740.051, 729.561, 272.237, 0.000, 932.896, 0.000, 0.000, 0.000, 22176.244], [1055.763, 740.051, 729.561, 272.237, 0.000, 932.896, 0.000, 0.000, 0.000, 21859.297], [1055.763, 740.051, 729.561, 272.237, 1706.748, 932.896, 0.000, 5221.105, 0.000, 31769.617], [0.000, 740.051, 729.561, 580.813, 1706.748, 2141.485, 0.000, 6313.462, 0.000, 31389.961], [0.000, 740.051, 729.561, 580.813, 1706.748, 2141.485, 0.000, 6313.462, 0.000, 31327.498], [962.418, 740.051, 729.561, 580.813, 1706.748, 2141.485, 0.000, 0.000, 0.000, 32647.140], [962.418, 740.051, 729.561, 580.813, 1706.748, 2141.485, 0.000, 0.000, 0.000, 32170.095], [962.418, 740.051, 729.561, 580.813, 1706.748, 2141.485, 0.000, 0.000, 0.000, 32577.742], [962.418, 740.051, 729.561, 580.813, 1706.748, 2141.485, 0.000, 0.000, 0.000, 33905.444], [962.418, 740.051, 729.561, 580.813, 1706.748, 2141.485, 0.000, 0.000, 0.000, 35414.492], [962.418, 740.051, 729.561, 580.813, 1706.748, 2141.485, 0.000, 0.000, 0.000, 36082.120], [962.418, 740.051, 729.561, 580.813, 1706.748, 2141.485, 0.000, 0.000, 0.000, 35872.293], [962.418, 740.051, 729.561, 580.813, 1706.748, 2141.485, 0.000, 0.000, 0.000, 34558.132], [962.418, 740.051, 729.561, 0.000, 1706.748, 0.000, 0.000, 9177.053, 0.000, 33778.138], [962.418, 740.051, 729.561, 0.000, 1706.748, 0.000, 0.000, 9177.053, 0.000, 34213.578], [962.418, 740.051, 729.561, 0.000, 1706.748, 0.000, 0.000, 9177.053, 0.000, 35345.791], [962.418, 740.051, 729.561, 0.000, 1706.748, 0.000, 0.000, 9177.053, 0.000, 34288.014], [962.418, 740.051, 729.561, 0.000, 1706.748, 0.000, 0.000, 9177.053, 0.000, 34604.406], [962.418, 740.051, 729.561, 0.000, 1706.748, 0.000, 0.000, 9177.053, 0.000, 34806.850], [962.418, 740.051, 729.561, 0.000, 1706.748, 0.000, 0.000, 9177.053, 0.000, 34012.232], [962.418, 740.051, 729.561, 0.000, 1706.748, 0.000, 0.000, 9177.053, 0.000, 33681.345], [192.484, 740.051, 729.561, 0.000, 1706.748, 0.000, 0.000, 13958.345, 0.000, 33540.463], [192.484, 740.051, 729.561, 0.000, 1706.748, 0.000, 0.000, 13958.345, 0.000, 34574.280], [192.484, 1127.221, 729.561, 0.000, 1706.748, 0.000, 0.000, 10500.917, 0.000, 34516.781], [192.484, 1127.221, 729.561, 0.000, 1706.748, 0.000, 0.000, 10500.917, 0.000, 35134.412], [192.484, 1127.221, 729.561, 0.000, 1706.748, 0.000, 0.000, 10500.917, 0.000, 36266.530], [192.484, 1127.221, 729.561, 0.000, 1706.748, 0.000, 0.000, 10500.917, 0.000, 37864.376], [192.484, 1127.221, 729.561, 0.000, 1706.748, 0.000, 0.000, 10500.917, 0.000, 38642.633], [192.484, 1127.221, 729.561, 0.000, 1706.748, 0.000, 0.000, 10500.917, 0.000, 38454.227], [192.484, 1127.221, 729.561, 0.000, 0.000, 0.000, 1339.869, 15871.934, 0.000, 38982.227], [192.484, 1127.221, 729.561, 0.000, 0.000, 0.000, 1339.869, 15871.934, 0.000, 39016.154], [192.484, 0.000, 729.561, 0.000, 0.000, 0.000, 1339.869, 27764.114, 0.000, 38759.803], [192.484, 0.000, 729.561, 0.000, 0.000, 0.000, 1339.869, 27764.114, 0.000, 39217.182], [192.484, 0.000, 729.561, 0.000, 0.000, 0.000, 1339.869, 27764.114, 0.000, 39439.690], [192.484, 0.000, 729.561, 0.000, 0.000, 0.000, 1339.869, 27764.114, 0.000, 39454.081], [192.484, 0.000, 729.561, 0.000, 0.000, 0.000, 1339.869, 27764.114, 0.000, 39083.341], [192.484, 0.000, 729.561, 0.000, 0.000, 0.000, 1339.869, 27764.114, 0.000, 38968.694], [192.484, 0.000, 729.561, 0.000, 0.000, 0.000, 1339.869, 27764.114, 0.000, 39532.030], [192.484, 0.000, 729.561, 0.000, 0.000, 0.000, 1339.869, 27764.114, 0.000, 38675.507], [0.000, 0.000, 1560.697, 0.000, 0.000, 0.000, 1339.869, 23269.751, 0.000, 39013.741], [0.000, 0.000, 1560.697, 0.000, 0.000, 0.000, 1339.869, 23269.751, 0.000, 38497.668], [0.000, 0.000, 1560.697, 0.000, 0.000, 0.000, 1339.869, 23269.751, 0.000, 38042.410]]) # 模拟VS信号回测结果 # VS信号,先卖后买,交割期为0 self.vs_res_sb00 = np.array( [[0.0000, 0.0000, 0.0000, 0.0000, 500.0000, 0.0000, 0.0000, 7750.0000, 0.0000, 10000.0000], [0.0000, 0.0000, 0.0000, 0.0000, 500.0000, 0.0000, 0.0000, 7750.0000, 0.0000, 9925.0000], [0.0000, 0.0000, 0.0000, 0.0000, 500.0000, 300.0000, 300.0000, 4954.0000, 0.0000, 9785.0000], [400.0000, 400.0000, 0.0000, 0.0000, 500.0000, 300.0000, 300.0000, 878.0000, 0.0000, 9666.0000], [400.0000, 400.0000, 173.1755, 0.0000, 500.0000, 300.0000, 300.0000, 0.0000, 0.0000, 9731.0000], [400.0000, 400.0000, 173.1755, 0.0000, 100.0000, 300.0000, 300.0000, 1592.0000, 0.0000, 9830.9270], [400.0000, 400.0000, 173.1755, 0.0000, 100.0000, 300.0000, 300.0000, 1592.0000, 0.0000, 9785.8540], [400.0000, 400.0000, 173.1755, 0.0000, 100.0000, 300.0000, 300.0000, 1592.0000, 0.0000, 9614.3412], [400.0000, 400.0000, 173.1755, 0.0000, 100.0000, 300.0000, 300.0000, 1592.0000, 0.0000, 9303.1953], [400.0000, 400.0000, 173.1755, 0.0000, 100.0000, 300.0000, 300.0000, 1592.0000, 0.0000, 8834.4398], [400.0000, 400.0000, 173.1755, 0.0000, 100.0000, 300.0000, 300.0000, 1592.0000, 0.0000, 8712.7554], [400.0000, 400.0000, 173.1755, 0.0000, 100.0000, 300.0000, 300.0000, 1592.0000, 0.0000, 8717.9507], [400.0000, 400.0000, 173.1755, 0.0000, 100.0000, 300.0000, 300.0000, 1592.0000, 0.0000, 9079.1479], [200.0000, 400.0000, 173.1755, 0.0000, 100.0000, 300.0000, 300.0000, 2598.0000, 0.0000, 9166.0276], [200.0000, 400.0000, 173.1755, 0.0000, 100.0000, 300.0000, 300.0000, 2598.0000, 0.0000, 9023.6607], [200.0000, 400.0000, 173.1755, 0.0000, 100.0000, 300.0000, 300.0000, 2598.0000, 0.0000, 9291.6864], [200.0000, 400.0000, 173.1755, 0.0000, 100.0000, 300.0000, 300.0000, 2598.0000, 0.0000, 9411.6371], [200.0000, 400.0000, 0.0000, 0.0000, 100.0000, 300.0000, 300.0000, 3619.7357, 0.0000, 9706.7357], [200.0000, 400.0000, 0.0000, 0.0000, 100.0000, 300.0000, 300.0000, 3619.7357, 0.0000, 9822.7357], [200.0000, 400.0000, 0.0000, 0.0000, 100.0000, 300.0000, 300.0000, 3619.7357, 0.0000, 9986.7357], [200.0000, 400.0000, 0.0000, 0.0000, 100.0000, 300.0000, 300.0000, 3619.7357, 0.0000, 9805.7357], [200.0000, 400.0000, 0.0000, 0.0000, 100.0000, 300.0000, 0.0000, 4993.7357, 0.0000, 9704.7357], [200.0000, 400.0000, 0.0000, 0.0000, 600.0000, 300.0000, 0.0000, 2048.7357, 0.0000, 9567.7357], [200.0000, 400.0000, 0.0000, 0.0000, 600.0000, 300.0000, 0.0000, 2048.7357, 0.0000, 9209.7357], [200.0000, 400.0000, 0.0000, 0.0000, 600.0000, 300.0000, 0.0000, 2048.7357, 0.0000, 9407.7357], [0.0000, 400.0000, 0.0000, 300.0000, 600.0000, 300.0000, 0.0000, 1779.7357, 0.0000, 9329.7357], [0.0000, 400.0000, 0.0000, 300.0000, 600.0000, 300.0000, 0.0000, 1779.7357, 0.0000, 9545.7357], [0.0000, 400.0000, 0.0000, 300.0000, 600.0000, 300.0000, 0.0000, 1779.7357, 0.0000, 9652.7357], [0.0000, 400.0000, 0.0000, 300.0000, 600.0000, 300.0000, 0.0000, 1779.7357, 0.0000, 9414.7357], [0.0000, 400.0000, 0.0000, 300.0000, 600.0000, 300.0000, 0.0000, 1779.7357, 0.0000, 9367.7357], [0.0000, 400.0000, 400.0000, 300.0000, 300.0000, 900.0000, 0.0000, 9319.7357, 0.0000, 19556.7357], [500.0000, 400.0000, 400.0000, 300.0000, 300.0000, 900.0000, 0.0000, 6094.7357, 0.0000, 20094.7357], [500.0000, 400.0000, 400.0000, 300.0000, 300.0000, 900.0000, 0.0000, 6094.7357, 0.0000, 19849.7357], [500.0000, 400.0000, 400.0000, 300.0000, 300.0000, 900.0000, 0.0000, 6094.7357, 0.0000, 19802.7357], [500.0000, 400.0000, 400.0000, 300.0000, 300.0000, 900.0000, 0.0000, 6094.7357, 0.0000, 19487.7357], [500.0000, 400.0000, 400.0000, 300.0000, 300.0000, 900.0000, 0.0000, 6094.7357, 0.0000, 19749.7357], [500.0000, 400.0000, 400.0000, 300.0000, 300.0000, 900.0000, 0.0000, 6094.7357, 0.0000, 19392.7357], [500.0000, 400.0000, 400.0000, 300.0000, 300.0000, 900.0000, 0.0000, 6094.7357, 0.0000, 19671.7357], [500.0000, 400.0000, 400.0000, 300.0000, 300.0000, 900.0000, 0.0000, 6094.7357, 0.0000, 19756.7357], [500.0000, 400.0000, 400.0000, 300.0000, 300.0000, 900.0000, 0.0000, 6094.7357, 0.0000, 20111.7357], [500.0000, 400.0000, 400.0000, 300.0000, 300.0000, 900.0000, 0.0000, 6094.7357, 0.0000, 19867.7357], [500.0000, 400.0000, 400.0000, 300.0000, 300.0000, 900.0000, 0.0000, 6094.7357, 0.0000, 19775.7357], [1100.0000, 400.0000, 400.0000, 300.0000, 300.0000, 900.0000, 0.0000, 1990.7357, 0.0000, 20314.7357], [1100.0000, 400.0000, 400.0000, 300.0000, 300.0000, 900.0000, 0.0000, 1990.7357, 0.0000, 20310.7357], [1100.0000, 400.0000, 400.0000, 300.0000, 300.0000, 900.0000, 0.0000, 1990.7357, 0.0000, 20253.7357], [1100.0000, 400.0000, 400.0000, 300.0000, 300.0000, 500.0000, 600.0000, 1946.7357, 0.0000, 20044.7357], [1100.0000, 400.0000, 400.0000, 300.0000, 300.0000, 500.0000, 600.0000, 1946.7357, 0.0000, 20495.7357], [1100.0000, 400.0000, 400.0000, 300.0000, 300.0000, 500.0000, 600.0000, 1946.7357, 0.0000, 19798.7357], [1100.0000, 400.0000, 400.0000, 300.0000, 300.0000, 500.0000, 600.0000, 1946.7357, 0.0000, 20103.7357], [1100.0000, 400.0000, 400.0000, 300.0000, 300.0000, 500.0000, 600.0000, 1946.7357, 0.0000, 20864.7357], [1100.0000, 710.4842, 400.0000, 300.0000, 300.0000, 500.0000, 600.0000, 0.0000, 0.0000, 20425.7357], [1100.0000, 710.4842, 400.0000, 300.0000, 300.0000, 500.0000, 600.0000, 0.0000, 0.0000, 20137.8405], [1100.0000, 710.4842, 400.0000, 300.0000, 300.0000, 500.0000, 600.0000, 0.0000, 0.0000, 20711.3567], [1100.0000, 710.4842, 400.0000, 300.0000, 300.0000, 500.0000, 600.0000, 0.0000, 0.0000, 21470.3891], [1100.0000, 710.4842, 400.0000, 300.0000, 300.0000, 500.0000, 600.0000, 0.0000, 0.0000, 21902.9538], [1100.0000, 710.4842, 400.0000, 300.0000, 300.0000, 500.0000, 600.0000, 0.0000, 0.0000, 20962.9538], [1100.0000, 710.4842, 400.0000, 300.0000, 300.0000, 500.0000, 600.0000, 0.0000, 0.0000, 21833.5184], [1100.0000, 710.4842, 400.0000, 300.0000, 300.0000, 500.0000, 600.0000, 0.0000, 0.0000, 21941.8169], [1100.0000, 710.4842, 400.0000, 300.0000, 300.0000, 500.0000, 600.0000, 0.0000, 0.0000, 21278.5184], [1100.0000, 710.4842, 400.0000, 300.0000, 300.0000, 500.0000, 600.0000, 0.0000, 0.0000, 21224.4700], [1100.0000, 710.4842, 400.0000, 300.0000, 600.0000, 500.0000, 600.0000, 9160.0000, 0.0000, 31225.2119], [600.0000, 710.4842, 400.0000, 800.0000, 600.0000, 700.0000, 600.0000, 7488.0000, 0.0000, 30894.5748], [600.0000, 710.4842, 400.0000, 800.0000, 600.0000, 700.0000, 600.0000, 7488.0000, 0.0000, 30764.3811], [1100.0000, 710.4842, 400.0000, 800.0000, 600.0000, 700.0000, 600.0000, 4208.0000, 0.0000, 31815.5828], [1100.0000, 710.4842, 400.0000, 800.0000, 600.0000, 700.0000, 600.0000, 4208.0000, 0.0000, 31615.4215], [1100.0000, 710.4842, 400.0000, 800.0000, 600.0000, 700.0000, 600.0000, 4208.0000, 0.0000, 32486.1394], [1100.0000, 710.4842, 400.0000, 800.0000, 600.0000, 700.0000, 600.0000, 4208.0000, 0.0000, 33591.2847], [1100.0000, 710.4842, 400.0000, 800.0000, 600.0000, 700.0000, 600.0000, 4208.0000, 0.0000, 34056.5428], [1100.0000, 710.4842, 400.0000, 800.0000, 600.0000, 700.0000, 600.0000, 4208.0000, 0.0000, 34756.4863], [1100.0000, 710.4842, 400.0000, 800.0000, 600.0000, 700.0000, 600.0000, 4208.0000, 0.0000, 34445.5428], [1100.0000, 710.4842, 400.0000, 800.0000, 600.0000, 700.0000, 600.0000, 4208.0000, 0.0000, 34433.9541], [1100.0000, 710.4842, 400.0000, 100.0000, 600.0000, 100.0000, 600.0000, 11346.0000, 0.0000, 33870.4703], [1100.0000, 710.4842, 400.0000, 100.0000, 600.0000, 100.0000, 600.0000, 11346.0000, 0.0000, 34014.3010], [1100.0000, 710.4842, 400.0000, 100.0000, 600.0000, 100.0000, 600.0000, 11346.0000, 0.0000, 34680.5671], [1100.0000, 710.4842, 400.0000, 100.0000, 600.0000, 100.0000, 600.0000, 11346.0000, 0.0000, 33890.9945], [1100.0000, 710.4842, 400.0000, 100.0000, 600.0000, 100.0000, 600.0000, 11346.0000, 0.0000, 34004.6640], [1100.0000, 710.4842, 400.0000, 100.0000, 600.0000, 100.0000, 600.0000, 11346.0000, 0.0000, 34127.7768], [1100.0000, 710.4842, 400.0000, 100.0000, 600.0000, 100.0000, 600.0000, 11346.0000, 0.0000, 33421.1638], [1100.0000, 710.4842, 400.0000, 100.0000, 600.0000, 100.0000, 600.0000, 11346.0000, 0.0000, 33120.9057], [700.0000, 710.4842, 400.0000, 100.0000, 600.0000, 100.0000, 600.0000, 13830.0000, 0.0000, 32613.3171], [700.0000, 710.4842, 400.0000, 100.0000, 600.0000, 100.0000, 600.0000, 13830.0000, 0.0000, 33168.1558], [700.0000, 1010.4842, 400.0000, 100.0000, 600.0000, 100.0000, 600.0000, 11151.0000, 0.0000, 33504.6236], [700.0000, 1010.4842, 400.0000, 100.0000, 600.0000, 100.0000, 600.0000, 11151.0000, 0.0000, 33652.1318], [700.0000, 1010.4842, 400.0000, 100.0000, 600.0000, 100.0000, 600.0000, 11151.0000, 0.0000, 34680.4867], [700.0000, 1010.4842, 400.0000, 100.0000, 600.0000, 100.0000, 600.0000, 11151.0000, 0.0000, 35557.5191], [700.0000, 1010.4842, 400.0000, 100.0000, 600.0000, 100.0000, 600.0000, 11151.0000, 0.0000, 35669.7128], [700.0000, 1010.4842, 400.0000, 100.0000, 600.0000, 100.0000, 600.0000, 11151.0000, 0.0000, 35211.4466], [700.0000, 1010.4842, 400.0000, 100.0000, 0.0000, 100.0000, 900.0000, 13530.0000, 0.0000, 35550.6079], [700.0000, 1010.4842, 400.0000, 100.0000, 0.0000, 100.0000, 900.0000, 13530.0000, 0.0000, 35711.6563], [700.0000, 710.4842, 400.0000, 100.0000, 0.0000, 100.0000, 900.0000, 16695.0000, 0.0000, 35682.6079], [700.0000, 710.4842, 400.0000, 100.0000, 0.0000, 100.0000, 900.0000, 16695.0000, 0.0000, 35880.8336], [700.0000, 710.4842, 400.0000, 100.0000, 0.0000, 100.0000, 900.0000, 16695.0000, 0.0000, 36249.8740], [700.0000, 710.4842, 400.0000, 100.0000, 0.0000, 100.0000, 900.0000, 16695.0000, 0.0000, 36071.6159], [700.0000, 710.4842, 400.0000, 100.0000, 0.0000, 100.0000, 900.0000, 16695.0000, 0.0000, 35846.1562], [700.0000, 710.4842, 400.0000, 100.0000, 0.0000, 100.0000, 900.0000, 16695.0000, 0.0000, 35773.3578], [700.0000, 710.4842, 400.0000, 100.0000, 0.0000, 100.0000, 900.0000, 16695.0000, 0.0000, 36274.9465], [700.0000, 710.4842, 400.0000, 100.0000, 0.0000, 100.0000, 900.0000, 16695.0000, 0.0000, 35739.3094], [500.0000, 710.4842, 1100.0000, 100.0000, 0.0000, 100.0000, 900.0000, 13167.0000, 0.0000, 36135.0917], [500.0000, 710.4842, 1100.0000, 100.0000, 0.0000, 100.0000, 900.0000, 13167.0000, 0.0000, 35286.5835], [500.0000, 710.4842, 1100.0000, 100.0000, 0.0000, 100.0000, 900.0000, 13167.0000, 0.0000, 35081.3658]]) # VS信号,先买后卖,交割期为0 self.vs_res_bs00 = np.array( [[0.0000, 0.0000, 0.0000, 0.0000, 500.0000, 0.0000, 0.0000, 7750, 0.0000, 10000], [0.0000, 0.0000, 0.0000, 0.0000, 500.0000, 0.0000, 0.0000, 7750, 0.0000, 9925], [0.0000, 0.0000, 0.0000, 0.0000, 500.0000, 300.0000, 300.0000, 4954, 0.0000, 9785], [400.0000, 400.0000, 0.0000, 0.0000, 500.0000, 300.0000, 300.0000, 878, 0.0000, 9666], [400.0000, 400.0000, 173.1755, 0.0000, 500.0000, 300.0000, 300.0000, 0, 0.0000, 9731], [400.0000, 400.0000, 173.1755, 0.0000, 100.0000, 300.0000, 300.0000, 1592, 0.0000, 9830.927022], [400.0000, 400.0000, 173.1755, 0.0000, 100.0000, 300.0000, 300.0000, 1592, 0.0000, 9785.854043], [400.0000, 400.0000, 173.1755, 0.0000, 100.0000, 300.0000, 300.0000, 1592, 0.0000, 9614.341223], [400.0000, 400.0000, 173.1755, 0.0000, 100.0000, 300.0000, 300.0000, 1592, 0.0000, 9303.195266], [400.0000, 400.0000, 173.1755, 0.0000, 100.0000, 300.0000, 300.0000, 1592, 0.0000, 8834.439842], [400.0000, 400.0000, 173.1755, 0.0000, 100.0000, 300.0000, 300.0000, 1592, 0.0000, 8712.755424], [400.0000, 400.0000, 173.1755, 0.0000, 100.0000, 300.0000, 300.0000, 1592, 0.0000, 8717.95069], [400.0000, 400.0000, 173.1755, 0.0000, 100.0000, 300.0000, 300.0000, 1592, 0.0000, 9079.147929], [200.0000, 400.0000, 173.1755, 0.0000, 100.0000, 300.0000, 300.0000, 2598, 0.0000, 9166.027613], [200.0000, 400.0000, 173.1755, 0.0000, 100.0000, 300.0000, 300.0000, 2598, 0.0000, 9023.66075], [200.0000, 400.0000, 173.1755, 0.0000, 100.0000, 300.0000, 300.0000, 2598, 0.0000, 9291.686391], [200.0000, 400.0000, 173.1755, 0.0000, 100.0000, 300.0000, 300.0000, 2598, 0.0000, 9411.637081], [200.0000, 400.0000, 0.0000, 0.0000, 100.0000, 300.0000, 300.0000, 3619.7357, 0.0000, 9706.7357], [200.0000, 400.0000, 0.0000, 0.0000, 100.0000, 300.0000, 300.0000, 3619.7357, 0.0000, 9822.7357], [200.0000, 400.0000, 0.0000, 0.0000, 100.0000, 300.0000, 300.0000, 3619.7357, 0.0000, 9986.7357], [200.0000, 400.0000, 0.0000, 0.0000, 100.0000, 300.0000, 300.0000, 3619.7357, 0.0000, 9805.7357], [200.0000, 400.0000, 0.0000, 0.0000, 100.0000, 300.0000, 0.0000, 4993.7357, 0.0000, 9704.7357], [200.0000, 400.0000, 0.0000, 0.0000, 600.0000, 300.0000, 0.0000, 2048.7357, 0.0000, 9567.7357], [200.0000, 400.0000, 0.0000, 0.0000, 600.0000, 300.0000, 0.0000, 2048.7357, 0.0000, 9209.7357], [200.0000, 400.0000, 0.0000, 0.0000, 600.0000, 300.0000, 0.0000, 2048.7357, 0.0000, 9407.7357], [0.0000, 400.0000, 0.0000, 300.0000, 600.0000, 300.0000, 0.0000, 1779.7357, 0.0000, 9329.7357], [0.0000, 400.0000, 0.0000, 300.0000, 600.0000, 300.0000, 0.0000, 1779.7357, 0.0000, 9545.7357], [0.0000, 400.0000, 0.0000, 300.0000, 600.0000, 300.0000, 0.0000, 1779.7357, 0.0000, 9652.7357], [0.0000, 400.0000, 0.0000, 300.0000, 600.0000, 300.0000, 0.0000, 1779.7357, 0.0000, 9414.7357], [0.0000, 400.0000, 0.0000, 300.0000, 600.0000, 300.0000, 0.0000, 1779.7357, 0.0000, 9367.7357], [0.0000, 400.0000, 400.0000, 300.0000, 300.0000, 900.0000, 0.0000, 9319.7357, 0.0000, 19556.7357], [500.0000, 400.0000, 400.0000, 300.0000, 300.0000, 900.0000, 0.0000, 6094.7357, 0.0000, 20094.7357], [500.0000, 400.0000, 400.0000, 300.0000, 300.0000, 900.0000, 0.0000, 6094.7357, 0.0000, 19849.7357], [500.0000, 400.0000, 400.0000, 300.0000, 300.0000, 900.0000, 0.0000, 6094.7357, 0.0000, 19802.7357], [500.0000, 400.0000, 400.0000, 300.0000, 300.0000, 900.0000, 0.0000, 6094.7357, 0.0000, 19487.7357], [500.0000, 400.0000, 400.0000, 300.0000, 300.0000, 900.0000, 0.0000, 6094.7357, 0.0000, 19749.7357], [500.0000, 400.0000, 400.0000, 300.0000, 300.0000, 900.0000, 0.0000, 6094.7357, 0.0000, 19392.7357], [500.0000, 400.0000, 400.0000, 300.0000, 300.0000, 900.0000, 0.0000, 6094.7357, 0.0000, 19671.7357], [500.0000, 400.0000, 400.0000, 300.0000, 300.0000, 900.0000, 0.0000, 6094.7357, 0.0000, 19756.7357], [500.0000, 400.0000, 400.0000, 300.0000, 300.0000, 900.0000, 0.0000, 6094.7357, 0.0000, 20111.7357], [500.0000, 400.0000, 400.0000, 300.0000, 300.0000, 900.0000, 0.0000, 6094.7357, 0.0000, 19867.7357], [500.0000, 400.0000, 400.0000, 300.0000, 300.0000, 900.0000, 0.0000, 6094.7357, 0.0000, 19775.7357], [1100.0000, 400.0000, 400.0000, 300.0000, 300.0000, 900.0000, 0.0000, 1990.7357, 0.0000, 20314.7357], [1100.0000, 400.0000, 400.0000, 300.0000, 300.0000, 900.0000, 0.0000, 1990.7357, 0.0000, 20310.7357], [1100.0000, 400.0000, 400.0000, 300.0000, 300.0000, 900.0000, 0.0000, 1990.7357, 0.0000, 20253.7357], [1100.0000, 400.0000, 400.0000, 300.0000, 300.0000, 500.0000, 600.0000, 1946.7357, 0.0000, 20044.7357], [1100.0000, 400.0000, 400.0000, 300.0000, 300.0000, 500.0000, 600.0000, 1946.7357, 0.0000, 20495.7357], [1100.0000, 400.0000, 400.0000, 300.0000, 300.0000, 500.0000, 600.0000, 1946.7357, 0.0000, 19798.7357], [1100.0000, 400.0000, 400.0000, 300.0000, 300.0000, 500.0000, 600.0000, 1946.7357, 0.0000, 20103.7357], [1100.0000, 400.0000, 400.0000, 300.0000, 300.0000, 500.0000, 600.0000, 1946.7357, 0.0000, 20864.7357], [1100.0000, 710.4842, 400.0000, 300.0000, 300.0000, 500.0000, 600.0000, 0, 0.0000, 20425.7357], [1100.0000, 710.4842, 400.0000, 300.0000, 300.0000, 500.0000, 600.0000, 0, 0.0000, 20137.84054], [1100.0000, 710.4842, 400.0000, 300.0000, 300.0000, 500.0000, 600.0000, 0, 0.0000, 20711.35674], [1100.0000, 710.4842, 400.0000, 300.0000, 300.0000, 500.0000, 600.0000, 0, 0.0000, 21470.38914], [1100.0000, 710.4842, 400.0000, 300.0000, 300.0000, 500.0000, 600.0000, 0, 0.0000, 21902.95375], [1100.0000, 710.4842, 400.0000, 300.0000, 300.0000, 500.0000, 600.0000, 0, 0.0000, 20962.95375], [1100.0000, 710.4842, 400.0000, 300.0000, 300.0000, 500.0000, 600.0000, 0, 0.0000, 21833.51837], [1100.0000, 710.4842, 400.0000, 300.0000, 300.0000, 500.0000, 600.0000, 0, 0.0000, 21941.81688], [1100.0000, 710.4842, 400.0000, 300.0000, 300.0000, 500.0000, 600.0000, 0, 0.0000, 21278.51837], [1100.0000, 710.4842, 400.0000, 300.0000, 300.0000, 500.0000, 600.0000, 0, 0.0000, 21224.46995], [1100.0000, 710.4842, 400.0000, 300.0000, 600.0000, 500.0000, 600.0000, 9160, 0.0000, 31225.21185], [600.0000, 710.4842, 400.0000, 800.0000, 600.0000, 700.0000, 600.0000, 7488, 0.0000, 30894.57479], [600.0000, 710.4842, 400.0000, 800.0000, 600.0000, 700.0000, 600.0000, 7488, 0.0000, 30764.38113], [1100.0000, 710.4842, 400.0000, 800.0000, 600.0000, 700.0000, 600.0000, 4208, 0.0000, 31815.5828], [1100.0000, 710.4842, 400.0000, 800.0000, 600.0000, 700.0000, 600.0000, 4208, 0.0000, 31615.42154], [1100.0000, 710.4842, 400.0000, 800.0000, 600.0000, 700.0000, 600.0000, 4208, 0.0000, 32486.13941], [1100.0000, 710.4842, 400.0000, 800.0000, 600.0000, 700.0000, 600.0000, 4208, 0.0000, 33591.28466], [1100.0000, 710.4842, 400.0000, 800.0000, 600.0000, 700.0000, 600.0000, 4208, 0.0000, 34056.54276], [1100.0000, 710.4842, 400.0000, 800.0000, 600.0000, 700.0000, 600.0000, 4208, 0.0000, 34756.48633], [1100.0000, 710.4842, 400.0000, 800.0000, 600.0000, 700.0000, 600.0000, 4208, 0.0000, 34445.54276], [1100.0000, 710.4842, 400.0000, 800.0000, 600.0000, 700.0000, 600.0000, 4208, 0.0000, 34433.95412], [1100.0000, 710.4842, 400.0000, 100.0000, 600.0000, 100.0000, 600.0000, 11346, 0.0000, 33870.47032], [1100.0000, 710.4842, 400.0000, 100.0000, 600.0000, 100.0000, 600.0000, 11346, 0.0000, 34014.30104], [1100.0000, 710.4842, 400.0000, 100.0000, 600.0000, 100.0000, 600.0000, 11346, 0.0000, 34680.56715], [1100.0000, 710.4842, 400.0000, 100.0000, 600.0000, 100.0000, 600.0000, 11346, 0.0000, 33890.99452], [1100.0000, 710.4842, 400.0000, 100.0000, 600.0000, 100.0000, 600.0000, 11346, 0.0000, 34004.66398], [1100.0000, 710.4842, 400.0000, 100.0000, 600.0000, 100.0000, 600.0000, 11346, 0.0000, 34127.77683], [1100.0000, 710.4842, 400.0000, 100.0000, 600.0000, 100.0000, 600.0000, 11346, 0.0000, 33421.1638], [1100.0000, 710.4842, 400.0000, 100.0000, 600.0000, 100.0000, 600.0000, 11346, 0.0000, 33120.9057], [700.0000, 710.4842, 400.0000, 100.0000, 600.0000, 100.0000, 600.0000, 13830, 0.0000, 32613.31706], [700.0000, 710.4842, 400.0000, 100.0000, 600.0000, 100.0000, 600.0000, 13830, 0.0000, 33168.15579], [700.0000, 1010.4842, 400.0000, 100.0000, 600.0000, 100.0000, 600.0000, 11151, 0.0000, 33504.62357], [700.0000, 1010.4842, 400.0000, 100.0000, 600.0000, 100.0000, 600.0000, 11151, 0.0000, 33652.13176], [700.0000, 1010.4842, 400.0000, 100.0000, 600.0000, 100.0000, 600.0000, 11151, 0.0000, 34680.4867], [700.0000, 1010.4842, 400.0000, 100.0000, 600.0000, 100.0000, 600.0000, 11151, 0.0000, 35557.51909], [700.0000, 1010.4842, 400.0000, 100.0000, 600.0000, 100.0000, 600.0000, 11151, 0.0000, 35669.71276], [700.0000, 1010.4842, 400.0000, 100.0000, 600.0000, 100.0000, 600.0000, 11151, 0.0000, 35211.44665], [700.0000, 1010.4842, 400.0000, 100.0000, 0.0000, 100.0000, 900.0000, 13530, 0.0000, 35550.60792], [700.0000, 1010.4842, 400.0000, 100.0000, 0.0000, 100.0000, 900.0000, 13530, 0.0000, 35711.65633], [700.0000, 710.4842, 400.0000, 100.0000, 0.0000, 100.0000, 900.0000, 16695, 0.0000, 35682.60792], [700.0000, 710.4842, 400.0000, 100.0000, 0.0000, 100.0000, 900.0000, 16695, 0.0000, 35880.83362], [700.0000, 710.4842, 400.0000, 100.0000, 0.0000, 100.0000, 900.0000, 16695, 0.0000, 36249.87403], [700.0000, 710.4842, 400.0000, 100.0000, 0.0000, 100.0000, 900.0000, 16695, 0.0000, 36071.61593], [700.0000, 710.4842, 400.0000, 100.0000, 0.0000, 100.0000, 900.0000, 16695, 0.0000, 35846.15615], [700.0000, 710.4842, 400.0000, 100.0000, 0.0000, 100.0000, 900.0000, 16695, 0.0000, 35773.35783], [700.0000, 710.4842, 400.0000, 100.0000, 0.0000, 100.0000, 900.0000, 16695, 0.0000, 36274.94647], [700.0000, 710.4842, 400.0000, 100.0000, 0.0000, 100.0000, 900.0000, 16695, 0.0000, 35739.30941], [500.0000, 710.4842, 1100.0000, 100.0000, 0.0000, 100.0000, 900.0000, 13167, 0.0000, 36135.09172], [500.0000, 710.4842, 1100.0000, 100.0000, 0.0000, 100.0000, 900.0000, 13167, 0.0000, 35286.58353], [500.0000, 710.4842, 1100.0000, 100.0000, 0.0000, 100.0000, 900.0000, 13167, 0.0000, 35081.36584]]) # VS信号,先卖后买,交割期为2天(股票)1天(现金) self.vs_res_sb20 = np.array( [[0.000, 0.000, 0.000, 0.000, 500.000, 0.000, 0.000, 7750.000, 0.000, 10000.000], [0.000, 0.000, 0.000, 0.000, 500.000, 0.000, 0.000, 7750.000, 0.000, 9925.000], [0.000, 0.000, 0.000, 0.000, 500.000, 300.000, 300.000, 4954.000, 0.000, 9785.000], [400.000, 400.000, 0.000, 0.000, 500.000, 300.000, 300.000, 878.000, 0.000, 9666.000], [400.000, 400.000, 173.176, 0.000, 500.000, 300.000, 300.000, 0.000, 0.000, 9731.000], [400.000, 400.000, 173.176, 0.000, 100.000, 300.000, 300.000, 1592.000, 0.000, 9830.927], [400.000, 400.000, 173.176, 0.000, 100.000, 300.000, 300.000, 1592.000, 0.000, 9785.854], [400.000, 400.000, 173.176, 0.000, 100.000, 300.000, 300.000, 1592.000, 0.000, 9614.341], [400.000, 400.000, 173.176, 0.000, 100.000, 300.000, 300.000, 1592.000, 0.000, 9303.195], [400.000, 400.000, 173.176, 0.000, 100.000, 300.000, 300.000, 1592.000, 0.000, 8834.440], [400.000, 400.000, 173.176, 0.000, 100.000, 300.000, 300.000, 1592.000, 0.000, 8712.755], [400.000, 400.000, 173.176, 0.000, 100.000, 300.000, 300.000, 1592.000, 0.000, 8717.951], [400.000, 400.000, 173.176, 0.000, 100.000, 300.000, 300.000, 1592.000, 0.000, 9079.148], [200.000, 400.000, 173.176, 0.000, 100.000, 300.000, 300.000, 2598.000, 0.000, 9166.028], [200.000, 400.000, 173.176, 0.000, 100.000, 300.000, 300.000, 2598.000, 0.000, 9023.661], [200.000, 400.000, 173.176, 0.000, 100.000, 300.000, 300.000, 2598.000, 0.000, 9291.686], [200.000, 400.000, 173.176, 0.000, 100.000, 300.000, 300.000, 2598.000, 0.000, 9411.637], [200.000, 400.000, 0.000, 0.000, 100.000, 300.000, 300.000, 3619.736, 0.000, 9706.736], [200.000, 400.000, 0.000, 0.000, 100.000, 300.000, 300.000, 3619.736, 0.000, 9822.736], [200.000, 400.000, 0.000, 0.000, 100.000, 300.000, 300.000, 3619.736, 0.000, 9986.736], [200.000, 400.000, 0.000, 0.000, 100.000, 300.000, 300.000, 3619.736, 0.000, 9805.736], [200.000, 400.000, 0.000, 0.000, 100.000, 300.000, 0.000, 4993.736, 0.000, 9704.736], [200.000, 400.000, 0.000, 0.000, 600.000, 300.000, 0.000, 2048.736, 0.000, 9567.736], [200.000, 400.000, 0.000, 0.000, 600.000, 300.000, 0.000, 2048.736, 0.000, 9209.736], [200.000, 400.000, 0.000, 0.000, 600.000, 300.000, 0.000, 2048.736, 0.000, 9407.736], [0.000, 400.000, 0.000, 300.000, 600.000, 300.000, 0.000, 1779.736, 0.000, 9329.736], [0.000, 400.000, 0.000, 300.000, 600.000, 300.000, 0.000, 1779.736, 0.000, 9545.736], [0.000, 400.000, 0.000, 300.000, 600.000, 300.000, 0.000, 1779.736, 0.000, 9652.736], [0.000, 400.000, 0.000, 300.000, 600.000, 300.000, 0.000, 1779.736, 0.000, 9414.736], [0.000, 400.000, 0.000, 300.000, 600.000, 300.000, 0.000, 1779.736, 0.000, 9367.736], [0.000, 400.000, 400.000, 300.000, 300.000, 900.000, 0.000, 9319.736, 0.000, 19556.736], [500.000, 400.000, 400.000, 300.000, 300.000, 900.000, 0.000, 6094.736, 0.000, 20094.736], [500.000, 400.000, 400.000, 300.000, 300.000, 900.000, 0.000, 6094.736, 0.000, 19849.736], [500.000, 400.000, 400.000, 300.000, 300.000, 900.000, 0.000, 6094.736, 0.000, 19802.736], [500.000, 400.000, 400.000, 300.000, 300.000, 900.000, 0.000, 6094.736, 0.000, 19487.736], [500.000, 400.000, 400.000, 300.000, 300.000, 900.000, 0.000, 6094.736, 0.000, 19749.736], [500.000, 400.000, 400.000, 300.000, 300.000, 900.000, 0.000, 6094.736, 0.000, 19392.736], [500.000, 400.000, 400.000, 300.000, 300.000, 900.000, 0.000, 6094.736, 0.000, 19671.736], [500.000, 400.000, 400.000, 300.000, 300.000, 900.000, 0.000, 6094.736, 0.000, 19756.736], [500.000, 400.000, 400.000, 300.000, 300.000, 900.000, 0.000, 6094.736, 0.000, 20111.736], [500.000, 400.000, 400.000, 300.000, 300.000, 900.000, 0.000, 6094.736, 0.000, 19867.736], [500.000, 400.000, 400.000, 300.000, 300.000, 900.000, 0.000, 6094.736, 0.000, 19775.736], [1100.000, 400.000, 400.000, 300.000, 300.000, 900.000, 0.000, 1990.736, 0.000, 20314.736], [1100.000, 400.000, 400.000, 300.000, 300.000, 900.000, 0.000, 1990.736, 0.000, 20310.736], [1100.000, 400.000, 400.000, 300.000, 300.000, 900.000, 0.000, 1990.736, 0.000, 20253.736], [1100.000, 400.000, 400.000, 300.000, 300.000, 500.000, 600.000, 1946.736, 0.000, 20044.736], [1100.000, 400.000, 400.000, 300.000, 300.000, 500.000, 600.000, 1946.736, 0.000, 20495.736], [1100.000, 400.000, 400.000, 300.000, 300.000, 500.000, 600.000, 1946.736, 0.000, 19798.736], [1100.000, 400.000, 400.000, 300.000, 300.000, 500.000, 600.000, 1946.736, 0.000, 20103.736], [1100.000, 400.000, 400.000, 300.000, 300.000, 500.000, 600.000, 1946.736, 0.000, 20864.736], [1100.000, 710.484, 400.000, 300.000, 300.000, 500.000, 600.000, 0.000, 0.000, 20425.736], [1100.000, 710.484, 400.000, 300.000, 300.000, 500.000, 600.000, 0.000, 0.000, 20137.841], [1100.000, 710.484, 400.000, 300.000, 300.000, 500.000, 600.000, 0.000, 0.000, 20711.357], [1100.000, 710.484, 400.000, 300.000, 300.000, 500.000, 600.000, 0.000, 0.000, 21470.389], [1100.000, 710.484, 400.000, 300.000, 300.000, 500.000, 600.000, 0.000, 0.000, 21902.954], [1100.000, 710.484, 400.000, 300.000, 300.000, 500.000, 600.000, 0.000, 0.000, 20962.954], [1100.000, 710.484, 400.000, 300.000, 300.000, 500.000, 600.000, 0.000, 0.000, 21833.518], [1100.000, 710.484, 400.000, 300.000, 300.000, 500.000, 600.000, 0.000, 0.000, 21941.817], [1100.000, 710.484, 400.000, 300.000, 300.000, 500.000, 600.000, 0.000, 0.000, 21278.518], [1100.000, 710.484, 400.000, 300.000, 300.000, 500.000, 600.000, 0.000, 0.000, 21224.470], [1100.000, 710.484, 400.000, 300.000, 600.000, 500.000, 600.000, 9160.000, 0.000, 31225.212], [600.000, 710.484, 400.000, 800.000, 600.000, 700.000, 600.000, 7488.000, 0.000, 30894.575], [600.000, 710.484, 400.000, 800.000, 600.000, 700.000, 600.000, 7488.000, 0.000, 30764.381], [1100.000, 710.484, 400.000, 800.000, 600.000, 700.000, 600.000, 4208.000, 0.000, 31815.583], [1100.000, 710.484, 400.000, 800.000, 600.000, 700.000, 600.000, 4208.000, 0.000, 31615.422], [1100.000, 710.484, 400.000, 800.000, 600.000, 700.000, 600.000, 4208.000, 0.000, 32486.139], [1100.000, 710.484, 400.000, 800.000, 600.000, 700.000, 600.000, 4208.000, 0.000, 33591.285], [1100.000, 710.484, 400.000, 800.000, 600.000, 700.000, 600.000, 4208.000, 0.000, 34056.543], [1100.000, 710.484, 400.000, 800.000, 600.000, 700.000, 600.000, 4208.000, 0.000, 34756.486], [1100.000, 710.484, 400.000, 800.000, 600.000, 700.000, 600.000, 4208.000, 0.000, 34445.543], [1100.000, 710.484, 400.000, 800.000, 600.000, 700.000, 600.000, 4208.000, 0.000, 34433.954], [1100.000, 710.484, 400.000, 100.000, 600.000, 100.000, 600.000, 11346.000, 0.000, 33870.470], [1100.000, 710.484, 400.000, 100.000, 600.000, 100.000, 600.000, 11346.000, 0.000, 34014.301], [1100.000, 710.484, 400.000, 100.000, 600.000, 100.000, 600.000, 11346.000, 0.000, 34680.567], [1100.000, 710.484, 400.000, 100.000, 600.000, 100.000, 600.000, 11346.000, 0.000, 33890.995], [1100.000, 710.484, 400.000, 100.000, 600.000, 100.000, 600.000, 11346.000, 0.000, 34004.664], [1100.000, 710.484, 400.000, 100.000, 600.000, 100.000, 600.000, 11346.000, 0.000, 34127.777], [1100.000, 710.484, 400.000, 100.000, 600.000, 100.000, 600.000, 11346.000, 0.000, 33421.164], [1100.000, 710.484, 400.000, 100.000, 600.000, 100.000, 600.000, 11346.000, 0.000, 33120.906], [700.000, 710.484, 400.000, 100.000, 600.000, 100.000, 600.000, 13830.000, 0.000, 32613.317], [700.000, 710.484, 400.000, 100.000, 600.000, 100.000, 600.000, 13830.000, 0.000, 33168.156], [700.000, 1010.484, 400.000, 100.000, 600.000, 100.000, 600.000, 11151.000, 0.000, 33504.624], [700.000, 1010.484, 400.000, 100.000, 600.000, 100.000, 600.000, 11151.000, 0.000, 33652.132], [700.000, 1010.484, 400.000, 100.000, 600.000, 100.000, 600.000, 11151.000, 0.000, 34680.487], [700.000, 1010.484, 400.000, 100.000, 600.000, 100.000, 600.000, 11151.000, 0.000, 35557.519], [700.000, 1010.484, 400.000, 100.000, 600.000, 100.000, 600.000, 11151.000, 0.000, 35669.713], [700.000, 1010.484, 400.000, 100.000, 600.000, 100.000, 600.000, 11151.000, 0.000, 35211.447], [700.000, 1010.484, 400.000, 100.000, 0.000, 100.000, 900.000, 13530.000, 0.000, 35550.608], [700.000, 1010.484, 400.000, 100.000, 0.000, 100.000, 900.000, 13530.000, 0.000, 35711.656], [700.000, 710.484, 400.000, 100.000, 0.000, 100.000, 900.000, 16695.000, 0.000, 35682.608], [700.000, 710.484, 400.000, 100.000, 0.000, 100.000, 900.000, 16695.000, 0.000, 35880.834], [700.000, 710.484, 400.000, 100.000, 0.000, 100.000, 900.000, 16695.000, 0.000, 36249.874], [700.000, 710.484, 400.000, 100.000, 0.000, 100.000, 900.000, 16695.000, 0.000, 36071.616], [700.000, 710.484, 400.000, 100.000, 0.000, 100.000, 900.000, 16695.000, 0.000, 35846.156], [700.000, 710.484, 400.000, 100.000, 0.000, 100.000, 900.000, 16695.000, 0.000, 35773.358], [700.000, 710.484, 400.000, 100.000, 0.000, 100.000, 900.000, 16695.000, 0.000, 36274.946], [700.000, 710.484, 400.000, 100.000, 0.000, 100.000, 900.000, 16695.000, 0.000, 35739.309], [500.000, 710.484, 1100.000, 100.000, 0.000, 100.000, 900.000, 13167.000, 0.000, 36135.092], [500.000, 710.484, 1100.000, 100.000, 0.000, 100.000, 900.000, 13167.000, 0.000, 35286.584], [500.000, 710.484, 1100.000, 100.000, 0.000, 100.000, 900.000, 13167.000, 0.000, 35081.366]]) # VS信号,先买后卖,交割期为2天(股票)1天(现金) self.vs_res_bs21 = np.array( [[0.000, 0.000, 0.000, 0.000, 500.000, 0.000, 0.000, 7750.000, 0.000, 10000.000], [0.000, 0.000, 0.000, 0.000, 500.000, 0.000, 0.000, 7750.000, 0.000, 9925.000], [0.000, 0.000, 0.000, 0.000, 500.000, 300.000, 300.000, 4954.000, 0.000, 9785.000], [400.000, 400.000, 0.000, 0.000, 500.000, 300.000, 300.000, 878.000, 0.000, 9666.000], [400.000, 400.000, 173.176, 0.000, 500.000, 300.000, 300.000, 0.000, 0.000, 9731.000], [400.000, 400.000, 173.176, 0.000, 100.000, 300.000, 300.000, 1592.000, 0.000, 9830.927], [400.000, 400.000, 173.176, 0.000, 100.000, 300.000, 300.000, 1592.000, 0.000, 9785.854], [400.000, 400.000, 173.176, 0.000, 100.000, 300.000, 300.000, 1592.000, 0.000, 9614.341], [400.000, 400.000, 173.176, 0.000, 100.000, 300.000, 300.000, 1592.000, 0.000, 9303.195], [400.000, 400.000, 173.176, 0.000, 100.000, 300.000, 300.000, 1592.000, 0.000, 8834.440], [400.000, 400.000, 173.176, 0.000, 100.000, 300.000, 300.000, 1592.000, 0.000, 8712.755], [400.000, 400.000, 173.176, 0.000, 100.000, 300.000, 300.000, 1592.000, 0.000, 8717.951], [400.000, 400.000, 173.176, 0.000, 100.000, 300.000, 300.000, 1592.000, 0.000, 9079.148], [200.000, 400.000, 173.176, 0.000, 100.000, 300.000, 300.000, 2598.000, 0.000, 9166.028], [200.000, 400.000, 173.176, 0.000, 100.000, 300.000, 300.000, 2598.000, 0.000, 9023.661], [200.000, 400.000, 173.176, 0.000, 100.000, 300.000, 300.000, 2598.000, 0.000, 9291.686], [200.000, 400.000, 173.176, 0.000, 100.000, 300.000, 300.000, 2598.000, 0.000, 9411.637], [200.000, 400.000, 0.000, 0.000, 100.000, 300.000, 300.000, 3619.736, 0.000, 9706.736], [200.000, 400.000, 0.000, 0.000, 100.000, 300.000, 300.000, 3619.736, 0.000, 9822.736], [200.000, 400.000, 0.000, 0.000, 100.000, 300.000, 300.000, 3619.736, 0.000, 9986.736], [200.000, 400.000, 0.000, 0.000, 100.000, 300.000, 300.000, 3619.736, 0.000, 9805.736], [200.000, 400.000, 0.000, 0.000, 100.000, 300.000, 0.000, 4993.736, 0.000, 9704.736], [200.000, 400.000, 0.000, 0.000, 600.000, 300.000, 0.000, 2048.736, 0.000, 9567.736], [200.000, 400.000, 0.000, 0.000, 600.000, 300.000, 0.000, 2048.736, 0.000, 9209.736], [200.000, 400.000, 0.000, 0.000, 600.000, 300.000, 0.000, 2048.736, 0.000, 9407.736], [0.000, 400.000, 0.000, 300.000, 600.000, 300.000, 0.000, 1779.736, 0.000, 9329.736], [0.000, 400.000, 0.000, 300.000, 600.000, 300.000, 0.000, 1779.736, 0.000, 9545.736], [0.000, 400.000, 0.000, 300.000, 600.000, 300.000, 0.000, 1779.736, 0.000, 9652.736], [0.000, 400.000, 0.000, 300.000, 600.000, 300.000, 0.000, 1779.736, 0.000, 9414.736], [0.000, 400.000, 0.000, 300.000, 600.000, 300.000, 0.000, 1779.736, 0.000, 9367.736], [0.000, 400.000, 400.000, 300.000, 300.000, 900.000, 0.000, 9319.736, 0.000, 19556.736], [500.000, 400.000, 400.000, 300.000, 300.000, 900.000, 0.000, 6094.736, 0.000, 20094.736], [500.000, 400.000, 400.000, 300.000, 300.000, 900.000, 0.000, 6094.736, 0.000, 19849.736], [500.000, 400.000, 400.000, 300.000, 300.000, 900.000, 0.000, 6094.736, 0.000, 19802.736], [500.000, 400.000, 400.000, 300.000, 300.000, 900.000, 0.000, 6094.736, 0.000, 19487.736], [500.000, 400.000, 400.000, 300.000, 300.000, 900.000, 0.000, 6094.736, 0.000, 19749.736], [500.000, 400.000, 400.000, 300.000, 300.000, 900.000, 0.000, 6094.736, 0.000, 19392.736], [500.000, 400.000, 400.000, 300.000, 300.000, 900.000, 0.000, 6094.736, 0.000, 19671.736], [500.000, 400.000, 400.000, 300.000, 300.000, 900.000, 0.000, 6094.736, 0.000, 19756.736], [500.000, 400.000, 400.000, 300.000, 300.000, 900.000, 0.000, 6094.736, 0.000, 20111.736], [500.000, 400.000, 400.000, 300.000, 300.000, 900.000, 0.000, 6094.736, 0.000, 19867.736], [500.000, 400.000, 400.000, 300.000, 300.000, 900.000, 0.000, 6094.736, 0.000, 19775.736], [1100.000, 400.000, 400.000, 300.000, 300.000, 900.000, 0.000, 1990.736, 0.000, 20314.736], [1100.000, 400.000, 400.000, 300.000, 300.000, 900.000, 0.000, 1990.736, 0.000, 20310.736], [1100.000, 400.000, 400.000, 300.000, 300.000, 900.000, 0.000, 1990.736, 0.000, 20253.736], [1100.000, 400.000, 400.000, 300.000, 300.000, 500.000, 600.000, 1946.736, 0.000, 20044.736], [1100.000, 400.000, 400.000, 300.000, 300.000, 500.000, 600.000, 1946.736, 0.000, 20495.736], [1100.000, 400.000, 400.000, 300.000, 300.000, 500.000, 600.000, 1946.736, 0.000, 19798.736], [1100.000, 400.000, 400.000, 300.000, 300.000, 500.000, 600.000, 1946.736, 0.000, 20103.736], [1100.000, 400.000, 400.000, 300.000, 300.000, 500.000, 600.000, 1946.736, 0.000, 20864.736], [1100.000, 710.484, 400.000, 300.000, 300.000, 500.000, 600.000, 0.000, 0.000, 20425.736], [1100.000, 710.484, 400.000, 300.000, 300.000, 500.000, 600.000, 0.000, 0.000, 20137.841], [1100.000, 710.484, 400.000, 300.000, 300.000, 500.000, 600.000, 0.000, 0.000, 20711.357], [1100.000, 710.484, 400.000, 300.000, 300.000, 500.000, 600.000, 0.000, 0.000, 21470.389], [1100.000, 710.484, 400.000, 300.000, 300.000, 500.000, 600.000, 0.000, 0.000, 21902.954], [1100.000, 710.484, 400.000, 300.000, 300.000, 500.000, 600.000, 0.000, 0.000, 20962.954], [1100.000, 710.484, 400.000, 300.000, 300.000, 500.000, 600.000, 0.000, 0.000, 21833.518], [1100.000, 710.484, 400.000, 300.000, 300.000, 500.000, 600.000, 0.000, 0.000, 21941.817], [1100.000, 710.484, 400.000, 300.000, 300.000, 500.000, 600.000, 0.000, 0.000, 21278.518], [1100.000, 710.484, 400.000, 300.000, 300.000, 500.000, 600.000, 0.000, 0.000, 21224.470], [1100.000, 710.484, 400.000, 300.000, 600.000, 500.000, 600.000, 9160.000, 0.000, 31225.212], [600.000, 710.484, 400.000, 800.000, 600.000, 700.000, 600.000, 7488.000, 0.000, 30894.575], [600.000, 710.484, 400.000, 800.000, 600.000, 700.000, 600.000, 7488.000, 0.000, 30764.381], [1100.000, 710.484, 400.000, 800.000, 600.000, 700.000, 600.000, 4208.000, 0.000, 31815.583], [1100.000, 710.484, 400.000, 800.000, 600.000, 700.000, 600.000, 4208.000, 0.000, 31615.422], [1100.000, 710.484, 400.000, 800.000, 600.000, 700.000, 600.000, 4208.000, 0.000, 32486.139], [1100.000, 710.484, 400.000, 800.000, 600.000, 700.000, 600.000, 4208.000, 0.000, 33591.285], [1100.000, 710.484, 400.000, 800.000, 600.000, 700.000, 600.000, 4208.000, 0.000, 34056.543], [1100.000, 710.484, 400.000, 800.000, 600.000, 700.000, 600.000, 4208.000, 0.000, 34756.486], [1100.000, 710.484, 400.000, 800.000, 600.000, 700.000, 600.000, 4208.000, 0.000, 34445.543], [1100.000, 710.484, 400.000, 800.000, 600.000, 700.000, 600.000, 4208.000, 0.000, 34433.954], [1100.000, 710.484, 400.000, 100.000, 600.000, 100.000, 600.000, 11346.000, 0.000, 33870.470], [1100.000, 710.484, 400.000, 100.000, 600.000, 100.000, 600.000, 11346.000, 0.000, 34014.301], [1100.000, 710.484, 400.000, 100.000, 600.000, 100.000, 600.000, 11346.000, 0.000, 34680.567], [1100.000, 710.484, 400.000, 100.000, 600.000, 100.000, 600.000, 11346.000, 0.000, 33890.995], [1100.000, 710.484, 400.000, 100.000, 600.000, 100.000, 600.000, 11346.000, 0.000, 34004.664], [1100.000, 710.484, 400.000, 100.000, 600.000, 100.000, 600.000, 11346.000, 0.000, 34127.777], [1100.000, 710.484, 400.000, 100.000, 600.000, 100.000, 600.000, 11346.000, 0.000, 33421.164], [1100.000, 710.484, 400.000, 100.000, 600.000, 100.000, 600.000, 11346.000, 0.000, 33120.906], [700.000, 710.484, 400.000, 100.000, 600.000, 100.000, 600.000, 13830.000, 0.000, 32613.317], [700.000, 710.484, 400.000, 100.000, 600.000, 100.000, 600.000, 13830.000, 0.000, 33168.156], [700.000, 1010.484, 400.000, 100.000, 600.000, 100.000, 600.000, 11151.000, 0.000, 33504.624], [700.000, 1010.484, 400.000, 100.000, 600.000, 100.000, 600.000, 11151.000, 0.000, 33652.132], [700.000, 1010.484, 400.000, 100.000, 600.000, 100.000, 600.000, 11151.000, 0.000, 34680.487], [700.000, 1010.484, 400.000, 100.000, 600.000, 100.000, 600.000, 11151.000, 0.000, 35557.519], [700.000, 1010.484, 400.000, 100.000, 600.000, 100.000, 600.000, 11151.000, 0.000, 35669.713], [700.000, 1010.484, 400.000, 100.000, 600.000, 100.000, 600.000, 11151.000, 0.000, 35211.447], [700.000, 1010.484, 400.000, 100.000, 0.000, 100.000, 900.000, 13530.000, 0.000, 35550.608], [700.000, 1010.484, 400.000, 100.000, 0.000, 100.000, 900.000, 13530.000, 0.000, 35711.656], [700.000, 710.484, 400.000, 100.000, 0.000, 100.000, 900.000, 16695.000, 0.000, 35682.608], [700.000, 710.484, 400.000, 100.000, 0.000, 100.000, 900.000, 16695.000, 0.000, 35880.834], [700.000, 710.484, 400.000, 100.000, 0.000, 100.000, 900.000, 16695.000, 0.000, 36249.874], [700.000, 710.484, 400.000, 100.000, 0.000, 100.000, 900.000, 16695.000, 0.000, 36071.616], [700.000, 710.484, 400.000, 100.000, 0.000, 100.000, 900.000, 16695.000, 0.000, 35846.156], [700.000, 710.484, 400.000, 100.000, 0.000, 100.000, 900.000, 16695.000, 0.000, 35773.358], [700.000, 710.484, 400.000, 100.000, 0.000, 100.000, 900.000, 16695.000, 0.000, 36274.946], [700.000, 710.484, 400.000, 100.000, 0.000, 100.000, 900.000, 16695.000, 0.000, 35739.309], [500.000, 710.484, 1100.000, 100.000, 0.000, 100.000, 900.000, 13167.000, 0.000, 36135.092], [500.000, 710.484, 1100.000, 100.000, 0.000, 100.000, 900.000, 13167.000, 0.000, 35286.584], [500.000, 710.484, 1100.000, 100.000, 0.000, 100.000, 900.000, 13167.000, 0.000, 35081.366]]) # Multi信号处理结果,先卖后买,使用卖出的现金买进,交割期为2天(股票)0天(现金) self.multi_res = np.array( [[0.0000, 357.2545, 0.0000, 6506.9627, 0.0000, 9965.1867], [0.0000, 357.2545, 0.0000, 6506.9627, 0.0000, 10033.0650], [0.0000, 178.6273, 0.0000, 8273.5864, 0.0000, 10034.8513], [0.0000, 178.6273, 0.0000, 8273.5864, 0.0000, 10036.6376], [150.3516, 178.6273, 0.0000, 6771.5740, 0.0000, 10019.3404], [150.3516, 178.6273, 0.0000, 6771.5740, 0.0000, 10027.7062], [150.3516, 178.6273, 0.0000, 6771.5740, 0.0000, 10030.1477], [150.3516, 178.6273, 0.0000, 6771.5740, 0.0000, 10005.1399], [150.3516, 178.6273, 0.0000, 6771.5740, 0.0000, 10002.5054], [150.3516, 489.4532, 0.0000, 3765.8877, 0.0000, 9967.3860], [75.1758, 391.5625, 0.0000, 5490.1377, 0.0000, 10044.4059], [75.1758, 391.5625, 0.0000, 5490.1377, 0.0000, 10078.1430], [75.1758, 391.5625, 846.3525, 392.3025, 0.0000, 10138.2709], [75.1758, 391.5625, 846.3525, 392.3025, 0.0000, 10050.4768], [75.1758, 391.5625, 846.3525, 392.3025, 0.0000, 10300.0711], [75.1758, 391.5625, 846.3525, 392.3025, 0.0000, 10392.6970], [75.1758, 391.5625, 169.2705, 4644.3773, 0.0000, 10400.5282], [75.1758, 391.5625, 169.2705, 4644.3773, 0.0000, 10408.9220], [75.1758, 0.0000, 169.2705, 8653.9776, 0.0000, 10376.5914], [75.1758, 0.0000, 169.2705, 8653.9776, 0.0000, 10346.8794], [75.1758, 0.0000, 169.2705, 8653.9776, 0.0000, 10364.7474], [75.1758, 381.1856, 645.5014, 2459.1665, 0.0000, 10302.4570], [18.7939, 381.1856, 645.5014, 3024.6764, 0.0000, 10747.4929], [18.7939, 381.1856, 96.8252, 6492.3097, 0.0000, 11150.9107], [18.7939, 381.1856, 96.8252, 6492.3097, 0.0000, 11125.2946], [18.7939, 114.3557, 96.8252, 9227.3166, 0.0000, 11191.9956], [18.7939, 114.3557, 96.8252, 9227.3166, 0.0000, 11145.7486], [18.7939, 114.3557, 96.8252, 9227.3166, 0.0000, 11090.0768], [132.5972, 114.3557, 864.3802, 4223.9548, 0.0000, 11113.8733], [132.5972, 114.3557, 864.3802, 4223.9548, 0.0000, 11456.3281], [132.5972, 114.3557, 864.3802, 14223.9548, 0.0000, 21983.7333], [132.5972, 114.3557, 864.3802, 14223.9548, 0.0000, 22120.6165], [132.5972, 114.3557, 864.3802, 14223.9548, 0.0000, 21654.5327], [132.5972, 114.3557, 864.3802, 14223.9548, 0.0000, 21429.6550], [132.5972, 114.3557, 864.3802, 14223.9548, 0.0000, 21912.5643], [132.5972, 114.3557, 864.3802, 14223.9548, 0.0000, 22516.3100], [132.5972, 114.3557, 864.3802, 14223.9548, 0.0000, 23169.0777], [132.5972, 114.3557, 864.3802, 14223.9548, 0.0000, 23390.8080], [132.5972, 114.3557, 864.3802, 14223.9548, 0.0000, 23743.3742], [132.5972, 559.9112, 864.3802, 9367.3999, 0.0000, 23210.7311], [132.5972, 559.9112, 864.3802, 9367.3999, 0.0000, 24290.4375], [132.5972, 559.9112, 864.3802, 9367.3999, 0.0000, 24335.3279], [132.5972, 559.9112, 864.3802, 9367.3999, 0.0000, 18317.3553], [132.5972, 559.9112, 864.3802, 9367.3999, 0.0000, 18023.4660], [259.4270, 559.9112, 0.0000, 15820.6915, 0.0000, 24390.0527], [259.4270, 559.9112, 0.0000, 15820.6915, 0.0000, 24389.6421], [259.4270, 559.9112, 0.0000, 15820.6915, 0.0000, 24483.5953], [0.0000, 559.9112, 0.0000, 18321.5674, 0.0000, 24486.1895], [0.0000, 0.0000, 0.0000, 24805.3389, 0.0000, 24805.3389], [0.0000, 0.0000, 0.0000, 24805.3389, 0.0000, 24805.3389]]) def test_loop_step_pt_sb00(self): """ test loop step PT-signal, sell first""" c_g, c_s, a_p, a_s, fee = qt.core._loop_step(signal_type=0, own_cash=10000, own_amounts=np.zeros(7, dtype='float'), available_cash=10000, available_amounts=np.zeros(7, dtype='float'), op=self.pt_signals[0], prices=self.prices[0], rate=self.rate, pt_buy_threshold=0.1, pt_sell_threshold=0.1, maximize_cash_usage=True, allow_sell_short=False, moq_buy=0, moq_sell=0, print_log=True) print(f'day 1 result in complete looping: \n' f'cash_change: +{c_g:.2f} / {c_s:.2f}\n' f'amount_changed: \npurchased: {np.round(a_p, 2)}\nsold:{np.round(a_s, 2)}\n' f'----------------------------------\n') cash = 10000 + c_g + c_s amounts = np.zeros(7, dtype='float') + a_p + a_s self.assertAlmostEqual(cash, 7500) self.assertTrue(np.allclose(amounts, np.array([0, 0, 0, 0, 555.5555556, 0, 0]))) c_g, c_s, a_p, a_s, fee = qt.core._loop_step(signal_type=0, own_cash=self.pt_res_sb00[2][7], own_amounts=self.pt_res_sb00[2][0:7], available_cash=self.pt_res_sb00[2][7], available_amounts=self.pt_res_sb00[2][0:7], op=self.pt_signals[3], prices=self.prices[3], rate=self.rate, pt_buy_threshold=0.1, pt_sell_threshold=0.1, maximize_cash_usage=True, allow_sell_short=False, moq_buy=0, moq_sell=0, print_log=True) print(f'day 4 result in complete looping: \n' f'cash_change: + {c_g:.2f} / {c_s:.2f}\n' f'amount_changed: \npurchased: {np.round(a_p, 2)}\nsold:{np.round(a_s, 2)}\n' f'----------------------------------\n') cash = self.pt_res_sb00[2][7] + c_g + c_s amounts = self.pt_res_sb00[2][0:7] + a_p + a_s self.assertAlmostEqual(cash, self.pt_res_sb00[3][7], 2) self.assertTrue(np.allclose(amounts, self.pt_res_sb00[3][0:7])) c_g, c_s, a_p, a_s, fee = qt.core._loop_step(signal_type=0, own_cash=self.pt_res_sb00[30][7], own_amounts=self.pt_res_sb00[30][0:7], available_cash=self.pt_res_sb00[30][7], available_amounts=self.pt_res_sb00[30][0:7], op=self.pt_signals[31], prices=self.prices[31], rate=self.rate, pt_buy_threshold=0.1, pt_sell_threshold=0.1, maximize_cash_usage=True, allow_sell_short=False, moq_buy=0, moq_sell=0, print_log=True) print(f'day 32 result in complete looping: \n' f'cash_change: + {c_g:.2f} / {c_s:.2f}\n' f'amount_changed: \npurchased: {np.round(a_p, 2)}\nsold:{np.round(a_s, 2)}\n' f'----------------------------------\n') cash = self.pt_res_sb00[30][7] + c_g + c_s amounts = self.pt_res_sb00[30][0:7] + a_p + a_s self.assertAlmostEqual(cash, self.pt_res_sb00[31][7], 2) self.assertTrue(np.allclose(amounts, self.pt_res_sb00[31][0:7])) c_g, c_s, a_p, a_s, fee = qt.core._loop_step(signal_type=0, own_cash=self.pt_res_sb00[59][7] + 10000, own_amounts=self.pt_res_sb00[59][0:7], available_cash=self.pt_res_sb00[59][7] + 10000, available_amounts=self.pt_res_sb00[59][0:7], op=self.pt_signals[60], prices=self.prices[60], rate=self.rate, pt_buy_threshold=0.1, pt_sell_threshold=0.1, maximize_cash_usage=True, allow_sell_short=False, moq_buy=0, moq_sell=0, print_log=True) print(f'day 61 result in complete looping: \n' f'cash_change: + {c_g:.2f} / {c_s:.2f}\n' f'amount_changed: \npurchased: {np.round(a_p, 2)}\nsold:{np.round(a_s, 2)}\n' f'----------------------------------\n') cash = self.pt_res_sb00[59][7] + c_g + c_s + 10000 amounts = self.pt_res_sb00[59][0:7] + a_p + a_s self.assertAlmostEqual(cash, self.pt_res_sb00[60][7], 2) self.assertTrue(np.allclose(amounts, self.pt_res_sb00[60][0:7])) c_g, c_s, a_p, a_s, fee = qt.core._loop_step(signal_type=0, own_cash=cash, own_amounts=amounts, available_cash=cash, available_amounts=amounts, op=self.pt_signals[61], prices=self.prices[61], rate=self.rate, pt_buy_threshold=0.1, pt_sell_threshold=0.1, maximize_cash_usage=True, allow_sell_short=False, moq_buy=0, moq_sell=0, print_log=True) print(f'day 62 result in complete looping: \n' f'cash_change: + {c_g:.2f} / {c_s:.2f}\n' f'amount_changed: \npurchased: {np.round(a_p, 2)}\nsold:{np.round(a_s, 2)}\n' f'----------------------------------\n') cash = cash + c_g + c_s amounts = amounts + a_p + a_s self.assertAlmostEqual(cash, self.pt_res_sb00[61][7], 2) self.assertTrue(np.allclose(amounts, self.pt_res_sb00[61][0:7])) c_g, c_s, a_p, a_s, fee = qt.core._loop_step(signal_type=0, own_cash=self.pt_res_sb00[95][7], own_amounts=self.pt_res_sb00[95][0:7], available_cash=self.pt_res_sb00[95][7], available_amounts=self.pt_res_sb00[95][0:7], op=self.pt_signals[96], prices=self.prices[96], rate=self.rate, pt_buy_threshold=0.1, pt_sell_threshold=0.1, maximize_cash_usage=True, allow_sell_short=False, moq_buy=0, moq_sell=0, print_log=True) print(f'day 97 result in complete looping: \n' f'cash_change: + {c_g:.2f} / {c_s:.2f}\n' f'amount_changed: \npurchased: {np.round(a_p, 2)}\nsold:{np.round(a_s, 2)}\n' f'----------------------------------\n') cash = self.pt_res_sb00[96][7] + c_g + c_s amounts = self.pt_res_sb00[96][0:7] + a_p + a_s self.assertAlmostEqual(cash, self.pt_res_sb00[96][7], 2) self.assertTrue(np.allclose(amounts, self.pt_res_sb00[96][0:7])) c_g, c_s, a_p, a_s, fee = qt.core._loop_step(signal_type=0, own_cash=cash, own_amounts=amounts, available_cash=cash, available_amounts=amounts, op=self.pt_signals[97], prices=self.prices[97], rate=self.rate, pt_buy_threshold=0.1, pt_sell_threshold=0.1, maximize_cash_usage=True, allow_sell_short=False, moq_buy=0, moq_sell=0, print_log=True) print(f'day 98 result in complete looping: \n' f'cash_change: + {c_g:.2f} / {c_s:.2f}\n' f'amount_changed: \npurchased: {np.round(a_p, 2)}\nsold:{np.round(a_s, 2)}\n' f'----------------------------------\n') cash = cash + c_g + c_s amounts = amounts + a_p + a_s self.assertAlmostEqual(cash, self.pt_res_sb00[97][7], 2) self.assertTrue(np.allclose(amounts, self.pt_res_sb00[97][0:7])) def test_loop_step_pt_bs00(self): """ test loop step PT-signal, buy first""" c_g, c_s, a_p, a_s, fee = qt.core._loop_step(signal_type=0, own_cash=10000, own_amounts=np.zeros(7, dtype='float'), available_cash=10000, available_amounts=np.zeros(7, dtype='float'), op=self.pt_signals[0], prices=self.prices[0], rate=self.rate, pt_buy_threshold=0.1, pt_sell_threshold=0.1, maximize_cash_usage=False, allow_sell_short=False, moq_buy=0, moq_sell=0, print_log=True) print(f'day 1 result in complete looping: \n' f'cash_change: +{c_g:.2f} / {c_s:.2f}\n' f'amount_changed: \npurchased: {np.round(a_p, 2)}\nsold:{np.round(a_s, 2)}\n' f'----------------------------------\n') cash = 10000 + c_g + c_s amounts = np.zeros(7, dtype='float') + a_p + a_s self.assertAlmostEqual(cash, 7500) self.assertTrue(np.allclose(amounts, np.array([0, 0, 0, 0, 555.5555556, 0, 0]))) c_g, c_s, a_p, a_s, fee = qt.core._loop_step(signal_type=0, own_cash=self.pt_res_bs00[2][7], own_amounts=self.pt_res_bs00[2][0:7], available_cash=self.pt_res_bs00[2][7], available_amounts=self.pt_res_bs00[2][0:7], op=self.pt_signals[3], prices=self.prices[3], rate=self.rate, pt_buy_threshold=0.1, pt_sell_threshold=0.1, maximize_cash_usage=False, allow_sell_short=False, moq_buy=0, moq_sell=0, print_log=True) print(f'day 4 result in complete looping: \n' f'cash_change: + {c_g:.2f} / {c_s:.2f}\n' f'amount_changed: \npurchased: {np.round(a_p, 2)}\nsold:{np.round(a_s, 2)}\n' f'----------------------------------\n') cash = self.pt_res_bs00[2][7] + c_g + c_s amounts = self.pt_res_bs00[2][0:7] + a_p + a_s self.assertAlmostEqual(cash, self.pt_res_bs00[3][7], 2) self.assertTrue(np.allclose(amounts, self.pt_res_bs00[3][0:7])) c_g, c_s, a_p, a_s, fee = qt.core._loop_step(signal_type=0, own_cash=self.pt_res_bs00[30][7], own_amounts=self.pt_res_bs00[30][0:7], available_cash=self.pt_res_bs00[30][7], available_amounts=self.pt_res_bs00[30][0:7], op=self.pt_signals[31], prices=self.prices[31], rate=self.rate, pt_buy_threshold=0.1, pt_sell_threshold=0.1, maximize_cash_usage=False, allow_sell_short=False, moq_buy=0, moq_sell=0, print_log=True) print(f'day 32 result in complete looping: \n' f'cash_change: + {c_g:.2f} / {c_s:.2f}\n' f'amount_changed: \npurchased: {np.round(a_p, 2)}\nsold:{np.round(a_s, 2)}\n' f'----------------------------------\n') cash = self.pt_res_bs00[30][7] + c_g + c_s amounts = self.pt_res_bs00[30][0:7] + a_p + a_s self.assertAlmostEqual(cash, self.pt_res_bs00[31][7], 2) self.assertTrue(np.allclose(amounts, self.pt_res_bs00[31][0:7])) c_g, c_s, a_p, a_s, fee = qt.core._loop_step(signal_type=0, own_cash=self.pt_res_bs00[59][7] + 10000, own_amounts=self.pt_res_bs00[59][0:7], available_cash=self.pt_res_bs00[59][7] + 10000, available_amounts=self.pt_res_bs00[59][0:7], op=self.pt_signals[60], prices=self.prices[60], rate=self.rate, pt_buy_threshold=0.1, pt_sell_threshold=0.1, maximize_cash_usage=False, allow_sell_short=False, moq_buy=0, moq_sell=0, print_log=True) print(f'day 61 result in complete looping: \n' f'cash_change: + {c_g:.2f} / {c_s:.2f}\n' f'amount_changed: \npurchased: {np.round(a_p, 2)}\nsold:{np.round(a_s, 2)}\n' f'----------------------------------\n') cash = self.pt_res_bs00[59][7] + c_g + c_s + 10000 amounts = self.pt_res_bs00[59][0:7] + a_p + a_s self.assertAlmostEqual(cash, self.pt_res_bs00[60][7], 2) self.assertTrue(np.allclose(amounts, self.pt_res_bs00[60][0:7])) c_g, c_s, a_p, a_s, fee = qt.core._loop_step(signal_type=0, own_cash=cash, own_amounts=amounts, available_cash=cash, available_amounts=amounts, op=self.pt_signals[61], prices=self.prices[61], rate=self.rate, pt_buy_threshold=0.1, pt_sell_threshold=0.1, maximize_cash_usage=False, allow_sell_short=False, moq_buy=0, moq_sell=0, print_log=True) print(f'day 62 result in complete looping: \n' f'cash_change: + {c_g:.2f} / {c_s:.2f}\n' f'amount_changed: \npurchased: {np.round(a_p, 2)}\nsold:{np.round(a_s, 2)}\n' f'----------------------------------\n') cash = cash + c_g + c_s amounts = amounts + a_p + a_s self.assertAlmostEqual(cash, self.pt_res_bs00[61][7], 2) self.assertTrue(np.allclose(amounts, self.pt_res_bs00[61][0:7])) c_g, c_s, a_p, a_s, fee = qt.core._loop_step(signal_type=0, own_cash=self.pt_res_bs00[95][7], own_amounts=self.pt_res_bs00[95][0:7], available_cash=self.pt_res_bs00[95][7], available_amounts=self.pt_res_bs00[95][0:7], op=self.pt_signals[96], prices=self.prices[96], rate=self.rate, pt_buy_threshold=0.1, pt_sell_threshold=0.1, maximize_cash_usage=False, allow_sell_short=False, moq_buy=0, moq_sell=0, print_log=True) print(f'day 97 result in complete looping: \n' f'cash_change: + {c_g:.2f} / {c_s:.2f}\n' f'amount_changed: \npurchased: {np.round(a_p, 2)}\nsold:{np.round(a_s, 2)}\n' f'----------------------------------\n') cash = self.pt_res_bs00[96][7] + c_g + c_s amounts = self.pt_res_bs00[96][0:7] + a_p + a_s self.assertAlmostEqual(cash, self.pt_res_bs00[96][7], 2) self.assertTrue(np.allclose(amounts, self.pt_res_bs00[96][0:7])) c_g, c_s, a_p, a_s, fee = qt.core._loop_step(signal_type=0, own_cash=cash, own_amounts=amounts, available_cash=cash, available_amounts=amounts, op=self.pt_signals[97], prices=self.prices[97], rate=self.rate, pt_buy_threshold=0.1, pt_sell_threshold=0.1, maximize_cash_usage=False, allow_sell_short=False, moq_buy=0, moq_sell=0, print_log=True) print(f'day 98 result in complete looping: \n' f'cash_change: + {c_g:.2f} / {c_s:.2f}\n' f'amount_changed: \npurchased: {np.round(a_p, 2)}\nsold:{np.round(a_s, 2)}\n' f'----------------------------------\n') cash = cash + c_g + c_s amounts = amounts + a_p + a_s self.assertAlmostEqual(cash, self.pt_res_bs00[97][7], 2) self.assertTrue(np.allclose(amounts, self.pt_res_bs00[97][0:7])) def test_loop_step_ps_sb00(self): """ test loop step PS-signal, sell first""" c_g, c_s, a_p, a_s, fee = qt.core._loop_step(signal_type=1, own_cash=10000, own_amounts=np.zeros(7, dtype='float'), available_cash=10000, available_amounts=np.zeros(7, dtype='float'), op=self.ps_signals[0], prices=self.prices[0], rate=self.rate, pt_buy_threshold=0.1, pt_sell_threshold=0.1, maximize_cash_usage=True, allow_sell_short=False, moq_buy=0, moq_sell=0, print_log=True) print(f'day 1 result in complete looping: \n' f'cash_change: +{c_g:.2f} / {c_s:.2f}\n' f'amount_changed: \npurchased: {np.round(a_p, 2)}\nsold:{np.round(a_s, 2)}\n' f'----------------------------------\n') cash = 10000 + c_g + c_s amounts = np.zeros(7, dtype='float') + a_p + a_s self.assertAlmostEqual(cash, 7500) self.assertTrue(np.allclose(amounts, np.array([0, 0, 0, 0, 555.5555556, 0, 0]))) c_g, c_s, a_p, a_s, fee = qt.core._loop_step(signal_type=1, own_cash=self.ps_res_sb00[2][7], own_amounts=self.ps_res_sb00[2][0:7], available_cash=self.ps_res_sb00[2][7], available_amounts=self.ps_res_sb00[2][0:7], op=self.ps_signals[3], prices=self.prices[3], rate=self.rate, pt_buy_threshold=0.1, pt_sell_threshold=0.1, maximize_cash_usage=True, allow_sell_short=False, moq_buy=0, moq_sell=0, print_log=True) print(f'day 4 result in complete looping: \n' f'cash_change: + {c_g:.2f} / {c_s:.2f}\n' f'amount_changed: \npurchased: {np.round(a_p, 2)}\nsold:{np.round(a_s, 2)}\n' f'----------------------------------\n') cash = self.ps_res_sb00[2][7] + c_g + c_s amounts = self.ps_res_sb00[2][0:7] + a_p + a_s self.assertAlmostEqual(cash, self.ps_res_sb00[3][7], 2) self.assertTrue(np.allclose(amounts, self.ps_res_sb00[3][0:7])) c_g, c_s, a_p, a_s, fee = qt.core._loop_step(signal_type=1, own_cash=self.ps_res_sb00[30][7], own_amounts=self.ps_res_sb00[30][0:7], available_cash=self.ps_res_sb00[30][7], available_amounts=self.ps_res_sb00[30][0:7], op=self.ps_signals[31], prices=self.prices[31], rate=self.rate, pt_buy_threshold=0.1, pt_sell_threshold=0.1, maximize_cash_usage=True, allow_sell_short=False, moq_buy=0, moq_sell=0, print_log=True) print(f'day 32 result in complete looping: \n' f'cash_change: + {c_g:.2f} / {c_s:.2f}\n' f'amount_changed: \npurchased: {np.round(a_p, 2)}\nsold:{np.round(a_s, 2)}\n' f'----------------------------------\n') cash = self.ps_res_sb00[30][7] + c_g + c_s amounts = self.ps_res_sb00[30][0:7] + a_p + a_s self.assertAlmostEqual(cash, self.ps_res_sb00[31][7], 2) self.assertTrue(np.allclose(amounts, self.ps_res_sb00[31][0:7])) c_g, c_s, a_p, a_s, fee = qt.core._loop_step(signal_type=1, own_cash=self.ps_res_sb00[59][7] + 10000, own_amounts=self.ps_res_sb00[59][0:7], available_cash=self.ps_res_sb00[59][7] + 10000, available_amounts=self.ps_res_sb00[59][0:7], op=self.ps_signals[60], prices=self.prices[60], rate=self.rate, pt_buy_threshold=0.1, pt_sell_threshold=0.1, maximize_cash_usage=True, allow_sell_short=False, moq_buy=0, moq_sell=0, print_log=True) print(f'day 61 result in complete looping: \n' f'cash_change: + {c_g:.2f} / {c_s:.2f}\n' f'amount_changed: \npurchased: {np.round(a_p, 2)}\nsold:{np.round(a_s, 2)}\n' f'----------------------------------\n') cash = self.ps_res_sb00[59][7] + c_g + c_s + 10000 amounts = self.ps_res_sb00[59][0:7] + a_p + a_s self.assertAlmostEqual(cash, self.ps_res_sb00[60][7], 2) self.assertTrue(np.allclose(amounts, self.ps_res_sb00[60][0:7])) c_g, c_s, a_p, a_s, fee = qt.core._loop_step(signal_type=1, own_cash=cash, own_amounts=amounts, available_cash=cash, available_amounts=amounts, op=self.ps_signals[61], prices=self.prices[61], rate=self.rate, pt_buy_threshold=0.1, pt_sell_threshold=0.1, maximize_cash_usage=True, allow_sell_short=False, moq_buy=0, moq_sell=0, print_log=True) print(f'day 62 result in complete looping: \n' f'cash_change: + {c_g:.2f} / {c_s:.2f}\n' f'amount_changed: \npurchased: {np.round(a_p, 2)}\nsold:{np.round(a_s, 2)}\n' f'----------------------------------\n') cash = cash + c_g + c_s amounts = amounts + a_p + a_s self.assertAlmostEqual(cash, self.ps_res_sb00[61][7], 2) self.assertTrue(np.allclose(amounts, self.ps_res_sb00[61][0:7])) c_g, c_s, a_p, a_s, fee = qt.core._loop_step(signal_type=1, own_cash=self.ps_res_sb00[95][7], own_amounts=self.ps_res_sb00[95][0:7], available_cash=self.ps_res_sb00[95][7], available_amounts=self.ps_res_sb00[95][0:7], op=self.ps_signals[96], prices=self.prices[96], rate=self.rate, pt_buy_threshold=0.1, pt_sell_threshold=0.1, maximize_cash_usage=True, allow_sell_short=False, moq_buy=0, moq_sell=0, print_log=True) print(f'day 97 result in complete looping: \n' f'cash_change: + {c_g:.2f} / {c_s:.2f}\n' f'amount_changed: \npurchased: {np.round(a_p, 2)}\nsold:{np.round(a_s, 2)}\n' f'----------------------------------\n') cash = self.ps_res_sb00[96][7] + c_g + c_s amounts = self.ps_res_sb00[96][0:7] + a_p + a_s self.assertAlmostEqual(cash, self.ps_res_sb00[96][7], 2) self.assertTrue(np.allclose(amounts, self.ps_res_sb00[96][0:7])) c_g, c_s, a_p, a_s, fee = qt.core._loop_step(signal_type=1, own_cash=cash, own_amounts=amounts, available_cash=cash, available_amounts=amounts, op=self.ps_signals[97], prices=self.prices[97], rate=self.rate, pt_buy_threshold=0.1, pt_sell_threshold=0.1, maximize_cash_usage=True, allow_sell_short=False, moq_buy=0, moq_sell=0, print_log=True) print(f'day 98 result in complete looping: \n' f'cash_change: + {c_g:.2f} / {c_s:.2f}\n' f'amount_changed: \npurchased: {np.round(a_p, 2)}\nsold:{np.round(a_s, 2)}\n' f'----------------------------------\n') cash = cash + c_g + c_s amounts = amounts + a_p + a_s self.assertAlmostEqual(cash, self.ps_res_sb00[97][7], 2) self.assertTrue(np.allclose(amounts, self.ps_res_sb00[97][0:7])) def test_loop_step_ps_bs00(self): """ test loop step PS-signal, buy first""" c_g, c_s, a_p, a_s, fee = qt.core._loop_step(signal_type=1, own_cash=10000, own_amounts=np.zeros(7, dtype='float'), available_cash=10000, available_amounts=np.zeros(7, dtype='float'), op=self.ps_signals[0], prices=self.prices[0], rate=self.rate, pt_buy_threshold=0.1, pt_sell_threshold=0.1, maximize_cash_usage=False, allow_sell_short=False, moq_buy=0, moq_sell=0, print_log=True) print(f'day 1 result in complete looping: \n' f'cash_change: +{c_g:.2f} / {c_s:.2f}\n' f'amount_changed: \npurchased: {np.round(a_p, 2)}\nsold:{np.round(a_s, 2)}\n' f'----------------------------------\n') cash = 10000 + c_g + c_s amounts = np.zeros(7, dtype='float') + a_p + a_s self.assertAlmostEqual(cash, 7500) self.assertTrue(np.allclose(amounts, np.array([0, 0, 0, 0, 555.5555556, 0, 0]))) c_g, c_s, a_p, a_s, fee = qt.core._loop_step(signal_type=1, own_cash=self.ps_res_bs00[2][7], own_amounts=self.ps_res_sb00[2][0:7], available_cash=self.ps_res_bs00[2][7], available_amounts=self.ps_res_bs00[2][0:7], op=self.ps_signals[3], prices=self.prices[3], rate=self.rate, pt_buy_threshold=0.1, pt_sell_threshold=0.1, maximize_cash_usage=False, allow_sell_short=False, moq_buy=0, moq_sell=0, print_log=True) print(f'day 4 result in complete looping: \n' f'cash_change: + {c_g:.2f} / {c_s:.2f}\n' f'amount_changed: \npurchased: {np.round(a_p, 2)}\nsold:{np.round(a_s, 2)}\n' f'----------------------------------\n') cash = self.ps_res_bs00[2][7] + c_g + c_s amounts = self.ps_res_bs00[2][0:7] + a_p + a_s self.assertAlmostEqual(cash, self.ps_res_bs00[3][7], 2) self.assertTrue(np.allclose(amounts, self.ps_res_bs00[3][0:7])) c_g, c_s, a_p, a_s, fee = qt.core._loop_step(signal_type=1, own_cash=self.ps_res_bs00[30][7], own_amounts=self.ps_res_sb00[30][0:7], available_cash=self.ps_res_bs00[30][7], available_amounts=self.ps_res_bs00[30][0:7], op=self.ps_signals[31], prices=self.prices[31], rate=self.rate, pt_buy_threshold=0.1, pt_sell_threshold=0.1, maximize_cash_usage=False, allow_sell_short=False, moq_buy=0, moq_sell=0, print_log=True) print(f'day 32 result in complete looping: \n' f'cash_change: + {c_g:.2f} / {c_s:.2f}\n' f'amount_changed: \npurchased: {np.round(a_p, 2)}\nsold:{np.round(a_s, 2)}\n' f'----------------------------------\n') cash = self.ps_res_bs00[30][7] + c_g + c_s amounts = self.ps_res_bs00[30][0:7] + a_p + a_s self.assertAlmostEqual(cash, self.ps_res_bs00[31][7], 2) self.assertTrue(np.allclose(amounts, self.ps_res_bs00[31][0:7])) c_g, c_s, a_p, a_s, fee = qt.core._loop_step(signal_type=1, own_cash=self.ps_res_bs00[59][7] + 10000, own_amounts=self.ps_res_bs00[59][0:7], available_cash=self.ps_res_bs00[59][7] + 10000, available_amounts=self.ps_res_bs00[59][0:7], op=self.ps_signals[60], prices=self.prices[60], rate=self.rate, pt_buy_threshold=0.1, pt_sell_threshold=0.1, maximize_cash_usage=False, allow_sell_short=False, moq_buy=0, moq_sell=0, print_log=True) print(f'day 61 result in complete looping: \n' f'cash_change: + {c_g:.2f} / {c_s:.2f}\n' f'amount_changed: \npurchased: {np.round(a_p, 2)}\nsold:{np.round(a_s, 2)}\n' f'----------------------------------\n') cash = self.ps_res_bs00[59][7] + c_g + c_s + 10000 amounts = self.ps_res_bs00[59][0:7] + a_p + a_s self.assertAlmostEqual(cash, self.ps_res_bs00[60][7], 2) self.assertTrue(np.allclose(amounts, self.ps_res_bs00[60][0:7])) c_g, c_s, a_p, a_s, fee = qt.core._loop_step(signal_type=1, own_cash=cash, own_amounts=amounts, available_cash=cash, available_amounts=amounts, op=self.ps_signals[61], prices=self.prices[61], rate=self.rate, pt_buy_threshold=0.1, pt_sell_threshold=0.1, maximize_cash_usage=False, allow_sell_short=False, moq_buy=0, moq_sell=0, print_log=True) print(f'day 62 result in complete looping: \n' f'cash_change: + {c_g:.2f} / {c_s:.2f}\n' f'amount_changed: \npurchased: {np.round(a_p, 2)}\nsold:{np.round(a_s, 2)}\n' f'----------------------------------\n') cash = cash + c_g + c_s amounts = amounts + a_p + a_s self.assertAlmostEqual(cash, self.ps_res_bs00[61][7], 2) self.assertTrue(np.allclose(amounts, self.ps_res_bs00[61][0:7])) c_g, c_s, a_p, a_s, fee = qt.core._loop_step(signal_type=1, own_cash=self.ps_res_bs00[95][7], own_amounts=self.ps_res_bs00[95][0:7], available_cash=self.ps_res_bs00[95][7], available_amounts=self.ps_res_bs00[95][0:7], op=self.ps_signals[96], prices=self.prices[96], rate=self.rate, pt_buy_threshold=0.1, pt_sell_threshold=0.1, maximize_cash_usage=False, allow_sell_short=False, moq_buy=0, moq_sell=0, print_log=True) print(f'day 97 result in complete looping: \n' f'cash_change: + {c_g:.2f} / {c_s:.2f}\n' f'amount_changed: \npurchased: {np.round(a_p, 2)}\nsold:{np.round(a_s, 2)}\n' f'----------------------------------\n') cash = self.ps_res_bs00[96][7] + c_g + c_s amounts = self.ps_res_bs00[96][0:7] + a_p + a_s self.assertAlmostEqual(cash, self.ps_res_bs00[96][7], 2) self.assertTrue(np.allclose(amounts, self.ps_res_bs00[96][0:7])) c_g, c_s, a_p, a_s, fee = qt.core._loop_step(signal_type=1, own_cash=cash, own_amounts=amounts, available_cash=cash, available_amounts=amounts, op=self.ps_signals[97], prices=self.prices[97], rate=self.rate, pt_buy_threshold=0.1, pt_sell_threshold=0.1, maximize_cash_usage=False, allow_sell_short=False, moq_buy=0, moq_sell=0, print_log=True) print(f'day 98 result in complete looping: \n' f'cash_change: + {c_g:.2f} / {c_s:.2f}\n' f'amount_changed: \npurchased: {np.round(a_p, 2)}\nsold:{np.round(a_s, 2)}\n' f'----------------------------------\n') cash = cash + c_g + c_s amounts = amounts + a_p + a_s self.assertAlmostEqual(cash, self.ps_res_bs00[97][7], 2) self.assertTrue(np.allclose(amounts, self.ps_res_bs00[97][0:7])) def test_loop_step_vs_sb00(self): """test loop step of Volume Signal type of signals""" c_g, c_s, a_p, a_s, fee = qt.core._loop_step(signal_type=2, own_cash=10000, own_amounts=np.zeros(7, dtype='float'), available_cash=10000, available_amounts=np.zeros(7, dtype='float'), op=self.vs_signals[0], prices=self.prices[0], rate=self.rate, pt_buy_threshold=0.1, pt_sell_threshold=0.1, maximize_cash_usage=True, allow_sell_short=False, moq_buy=0, moq_sell=0, print_log=True) print(f'day 1 result in complete looping: \n' f'cash_change: +{c_g:.2f} / {c_s:.2f}\n' f'amount_changed: \npurchased: {np.round(a_p, 2)}\nsold:{np.round(a_s, 2)}\n' f'----------------------------------\n') cash = 10000 + c_g + c_s amounts = np.zeros(7, dtype='float') + a_p + a_s self.assertAlmostEqual(cash, 7750) self.assertTrue(np.allclose(amounts, np.array([0, 0, 0, 0, 500., 0, 0]))) c_g, c_s, a_p, a_s, fee = qt.core._loop_step(signal_type=2, own_cash=self.vs_res_sb00[2][7], own_amounts=self.vs_res_sb00[2][0:7], available_cash=self.vs_res_sb00[2][7], available_amounts=self.vs_res_sb00[2][0:7], op=self.vs_signals[3], prices=self.prices[3], rate=self.rate, pt_buy_threshold=0.1, pt_sell_threshold=0.1, maximize_cash_usage=True, allow_sell_short=False, moq_buy=0, moq_sell=0, print_log=True) print(f'day 4 result in complete looping: \n' f'cash_change: + {c_g:.2f} / {c_s:.2f}\n' f'amount_changed: \npurchased: {np.round(a_p, 2)}\nsold:{np.round(a_s, 2)}\n' f'----------------------------------\n') cash = self.vs_res_sb00[2][7] + c_g + c_s amounts = self.vs_res_sb00[2][0:7] + a_p + a_s self.assertAlmostEqual(cash, self.vs_res_sb00[3][7], 2) self.assertTrue(np.allclose(amounts, self.vs_res_sb00[3][0:7])) c_g, c_s, a_p, a_s, fee = qt.core._loop_step(signal_type=2, own_cash=self.vs_res_sb00[30][7], own_amounts=self.vs_res_sb00[30][0:7], available_cash=self.vs_res_sb00[30][7], available_amounts=self.vs_res_sb00[30][0:7], op=self.vs_signals[31], prices=self.prices[31], rate=self.rate, pt_buy_threshold=0.1, pt_sell_threshold=0.1, maximize_cash_usage=True, allow_sell_short=False, moq_buy=0, moq_sell=0, print_log=True) print(f'day 32 result in complete looping: \n' f'cash_change: + {c_g:.2f} / {c_s:.2f}\n' f'amount_changed: \npurchased: {np.round(a_p, 2)}\nsold:{np.round(a_s, 2)}\n' f'----------------------------------\n') cash = self.vs_res_sb00[30][7] + c_g + c_s amounts = self.vs_res_sb00[30][0:7] + a_p + a_s self.assertAlmostEqual(cash, self.vs_res_sb00[31][7], 2) self.assertTrue(np.allclose(amounts, self.vs_res_sb00[31][0:7])) c_g, c_s, a_p, a_s, fee = qt.core._loop_step(signal_type=2, own_cash=self.vs_res_sb00[59][7] + 10000, own_amounts=self.vs_res_sb00[59][0:7], available_cash=self.vs_res_sb00[59][7] + 10000, available_amounts=self.vs_res_sb00[59][0:7], op=self.vs_signals[60], prices=self.prices[60], rate=self.rate, pt_buy_threshold=0.1, pt_sell_threshold=0.1, maximize_cash_usage=True, allow_sell_short=False, moq_buy=0, moq_sell=0, print_log=True) print(f'day 61 result in complete looping: \n' f'cash_change: + {c_g:.2f} / {c_s:.2f}\n' f'amount_changed: \npurchased: {np.round(a_p, 2)}\nsold:{np.round(a_s, 2)}\n' f'----------------------------------\n') cash = self.vs_res_sb00[59][7] + c_g + c_s + 10000 amounts = self.vs_res_sb00[59][0:7] + a_p + a_s self.assertAlmostEqual(cash, self.vs_res_sb00[60][7], 2) self.assertTrue(np.allclose(amounts, self.vs_res_sb00[60][0:7])) c_g, c_s, a_p, a_s, fee = qt.core._loop_step(signal_type=2, own_cash=cash, own_amounts=amounts, available_cash=cash, available_amounts=amounts, op=self.vs_signals[61], prices=self.prices[61], rate=self.rate, pt_buy_threshold=0.1, pt_sell_threshold=0.1, maximize_cash_usage=True, allow_sell_short=False, moq_buy=0, moq_sell=0, print_log=True) print(f'day 62 result in complete looping: \n' f'cash_change: + {c_g:.2f} / {c_s:.2f}\n' f'amount_changed: \npurchased: {np.round(a_p, 2)}\nsold:{np.round(a_s, 2)}\n' f'----------------------------------\n') cash = cash + c_g + c_s amounts = amounts + a_p + a_s self.assertAlmostEqual(cash, self.vs_res_sb00[61][7], 2) self.assertTrue(np.allclose(amounts, self.vs_res_sb00[61][0:7])) c_g, c_s, a_p, a_s, fee = qt.core._loop_step(signal_type=2, own_cash=self.vs_res_sb00[95][7], own_amounts=self.vs_res_sb00[95][0:7], available_cash=self.vs_res_sb00[95][7], available_amounts=self.vs_res_sb00[95][0:7], op=self.vs_signals[96], prices=self.prices[96], rate=self.rate, pt_buy_threshold=0.1, pt_sell_threshold=0.1, maximize_cash_usage=True, allow_sell_short=False, moq_buy=0, moq_sell=0, print_log=True) print(f'day 97 result in complete looping: \n' f'cash_change: + {c_g:.2f} / {c_s:.2f}\n' f'amount_changed: \npurchased: {np.round(a_p, 2)}\nsold:{np.round(a_s, 2)}\n' f'----------------------------------\n') cash = self.vs_res_sb00[96][7] + c_g + c_s amounts = self.vs_res_sb00[96][0:7] + a_p + a_s self.assertAlmostEqual(cash, self.vs_res_sb00[96][7], 2) self.assertTrue(np.allclose(amounts, self.vs_res_sb00[96][0:7])) c_g, c_s, a_p, a_s, fee = qt.core._loop_step(signal_type=2, own_cash=cash, own_amounts=amounts, available_cash=cash, available_amounts=amounts, op=self.vs_signals[97], prices=self.prices[97], rate=self.rate, pt_buy_threshold=0.1, pt_sell_threshold=0.1, maximize_cash_usage=True, allow_sell_short=False, moq_buy=0, moq_sell=0, print_log=True) print(f'day 98 result in complete looping: \n' f'cash_change: + {c_g:.2f} / {c_s:.2f}\n' f'amount_changed: \npurchased: {np.round(a_p, 2)}\nsold:{np.round(a_s, 2)}\n' f'----------------------------------\n') cash = cash + c_g + c_s amounts = amounts + a_p + a_s self.assertAlmostEqual(cash, self.vs_res_sb00[97][7], 2) self.assertTrue(np.allclose(amounts, self.vs_res_sb00[97][0:7])) def test_loop_step_vs_bs00(self): """test loop step of Volume Signal type of signals""" c_g, c_s, a_p, a_s, fee = qt.core._loop_step(signal_type=2, own_cash=10000, own_amounts=np.zeros(7, dtype='float'), available_cash=10000, available_amounts=np.zeros(7, dtype='float'), op=self.vs_signals[0], prices=self.prices[0], rate=self.rate, pt_buy_threshold=0.1, pt_sell_threshold=0.1, maximize_cash_usage=False, allow_sell_short=False, moq_buy=0, moq_sell=0, print_log=True) print(f'day 1 result in complete looping: \n' f'cash_change: +{c_g:.2f} / {c_s:.2f}\n' f'amount_changed: \npurchased: {np.round(a_p, 2)}\nsold:{np.round(a_s, 2)}\n' f'----------------------------------\n') cash = 10000 + c_g + c_s amounts = np.zeros(7, dtype='float') + a_p + a_s self.assertAlmostEqual(cash, 7750) self.assertTrue(np.allclose(amounts, np.array([0, 0, 0, 0, 500., 0, 0]))) c_g, c_s, a_p, a_s, fee = qt.core._loop_step(signal_type=2, own_cash=self.vs_res_bs00[2][7], own_amounts=self.vs_res_bs00[2][0:7], available_cash=self.vs_res_bs00[2][7], available_amounts=self.vs_res_bs00[2][0:7], op=self.vs_signals[3], prices=self.prices[3], rate=self.rate, pt_buy_threshold=0.1, pt_sell_threshold=0.1, maximize_cash_usage=False, allow_sell_short=False, moq_buy=0, moq_sell=0, print_log=True) print(f'day 4 result in complete looping: \n' f'cash_change: + {c_g:.2f} / {c_s:.2f}\n' f'amount_changed: \npurchased: {np.round(a_p, 2)}\nsold:{np.round(a_s, 2)}\n' f'----------------------------------\n') cash = self.vs_res_bs00[2][7] + c_g + c_s amounts = self.vs_res_bs00[2][0:7] + a_p + a_s self.assertAlmostEqual(cash, self.vs_res_bs00[3][7], 2) self.assertTrue(np.allclose(amounts, self.vs_res_bs00[3][0:7])) c_g, c_s, a_p, a_s, fee = qt.core._loop_step(signal_type=2, own_cash=self.vs_res_bs00[30][7], own_amounts=self.vs_res_bs00[30][0:7], available_cash=self.vs_res_bs00[30][7], available_amounts=self.vs_res_bs00[30][0:7], op=self.vs_signals[31], prices=self.prices[31], rate=self.rate, pt_buy_threshold=0.1, pt_sell_threshold=0.1, maximize_cash_usage=False, allow_sell_short=False, moq_buy=0, moq_sell=0, print_log=True) print(f'day 32 result in complete looping: \n' f'cash_change: + {c_g:.2f} / {c_s:.2f}\n' f'amount_changed: \npurchased: {np.round(a_p, 2)}\nsold:{np.round(a_s, 2)}\n' f'----------------------------------\n') cash = self.vs_res_bs00[30][7] + c_g + c_s amounts = self.vs_res_bs00[30][0:7] + a_p + a_s self.assertAlmostEqual(cash, self.vs_res_bs00[31][7], 2) self.assertTrue(np.allclose(amounts, self.vs_res_bs00[31][0:7])) c_g, c_s, a_p, a_s, fee = qt.core._loop_step(signal_type=2, own_cash=self.vs_res_bs00[59][7] + 10000, own_amounts=self.vs_res_bs00[59][0:7], available_cash=self.vs_res_bs00[59][7] + 10000, available_amounts=self.vs_res_bs00[59][0:7], op=self.vs_signals[60], prices=self.prices[60], rate=self.rate, pt_buy_threshold=0.1, pt_sell_threshold=0.1, maximize_cash_usage=False, allow_sell_short=False, moq_buy=0, moq_sell=0, print_log=True) print(f'day 61 result in complete looping: \n' f'cash_change: + {c_g:.2f} / {c_s:.2f}\n' f'amount_changed: \npurchased: {np.round(a_p, 2)}\nsold:{np.round(a_s, 2)}\n' f'----------------------------------\n') cash = self.vs_res_bs00[59][7] + c_g + c_s + 10000 amounts = self.vs_res_bs00[59][0:7] + a_p + a_s self.assertAlmostEqual(cash, self.vs_res_bs00[60][7], 2) self.assertTrue(np.allclose(amounts, self.vs_res_bs00[60][0:7])) c_g, c_s, a_p, a_s, fee = qt.core._loop_step(signal_type=2, own_cash=cash, own_amounts=amounts, available_cash=cash, available_amounts=amounts, op=self.vs_signals[61], prices=self.prices[61], rate=self.rate, pt_buy_threshold=0.1, pt_sell_threshold=0.1, maximize_cash_usage=False, allow_sell_short=False, moq_buy=0, moq_sell=0, print_log=True) print(f'day 62 result in complete looping: \n' f'cash_change: + {c_g:.2f} / {c_s:.2f}\n' f'amount_changed: \npurchased: {np.round(a_p, 2)}\nsold:{np.round(a_s, 2)}\n' f'----------------------------------\n') cash = cash + c_g + c_s amounts = amounts + a_p + a_s self.assertAlmostEqual(cash, self.vs_res_bs00[61][7], 2) self.assertTrue(np.allclose(amounts, self.vs_res_bs00[61][0:7])) c_g, c_s, a_p, a_s, fee = qt.core._loop_step(signal_type=2, own_cash=self.vs_res_bs00[95][7], own_amounts=self.vs_res_bs00[95][0:7], available_cash=self.vs_res_bs00[95][7], available_amounts=self.vs_res_bs00[95][0:7], op=self.vs_signals[96], prices=self.prices[96], rate=self.rate, pt_buy_threshold=0.1, pt_sell_threshold=0.1, maximize_cash_usage=False, allow_sell_short=False, moq_buy=0, moq_sell=0, print_log=True) print(f'day 97 result in complete looping: \n' f'cash_change: + {c_g:.2f} / {c_s:.2f}\n' f'amount_changed: \npurchased: {np.round(a_p, 2)}\nsold:{np.round(a_s, 2)}\n' f'----------------------------------\n') cash = self.vs_res_bs00[96][7] + c_g + c_s amounts = self.vs_res_bs00[96][0:7] + a_p + a_s self.assertAlmostEqual(cash, self.vs_res_bs00[96][7], 2) self.assertTrue(np.allclose(amounts, self.vs_res_bs00[96][0:7])) c_g, c_s, a_p, a_s, fee = qt.core._loop_step(signal_type=2, own_cash=cash, own_amounts=amounts, available_cash=cash, available_amounts=amounts, op=self.vs_signals[97], prices=self.prices[97], rate=self.rate, pt_buy_threshold=0.1, pt_sell_threshold=0.1, maximize_cash_usage=False, allow_sell_short=False, moq_buy=0, moq_sell=0, print_log=True) print(f'day 98 result in complete looping: \n' f'cash_change: + {c_g:.2f} / {c_s:.2f}\n' f'amount_changed: \npurchased: {np.round(a_p, 2)}\nsold:{np.round(a_s, 2)}\n' f'----------------------------------\n') cash = cash + c_g + c_s amounts = amounts + a_p + a_s self.assertAlmostEqual(cash, self.vs_res_bs00[97][7], 2) self.assertTrue(np.allclose(amounts, self.vs_res_bs00[97][0:7])) def test_loop_pt(self): """ Test looping of PT proportion target signals, with stock delivery delay = 0 days cash delivery delay = 0 day buy-sell sequence = sell first """ print('Test looping of PT proportion target signals, with:\n' 'stock delivery delay = 0 days \n' 'cash delivery delay = 0 day \n' 'buy-sell sequence = sell first') res = apply_loop(op_type=0, op_list=self.pt_signal_hp, history_list=self.history_list, cash_plan=self.cash, cost_rate=self.rate, moq_buy=0, moq_sell=0, inflation_rate=0, print_log=False) self.assertIsInstance(res, pd.DataFrame) # print(f'in test_loop:\nresult of loop test is \n{res}') self.assertTrue(np.allclose(res, self.pt_res_bs00, 2)) print(f'test assertion errors in apply_loop: detect moqs that are not compatible') self.assertRaises(AssertionError, apply_loop, 0, self.ps_signal_hp, self.history_list, self.cash, self.rate, 0, 1, 0, False) self.assertRaises(AssertionError, apply_loop, 0, self.ps_signal_hp, self.history_list, self.cash, self.rate, 1, 5, 0, False) print(f'test loop results with moq equal to 100') res = apply_loop(op_type=0, op_list=self.ps_signal_hp, history_list=self.history_list, cash_plan=self.cash, cost_rate=self.rate2, moq_buy=100, moq_sell=1, inflation_rate=0, print_log=False) self.assertIsInstance(res, pd.DataFrame) # print(f'in test_loop:\nresult of loop test is \n{res}') def test_loop_pt_with_delay(self): """ Test looping of PT proportion target signals, with: stock delivery delay = 2 days cash delivery delay = 1 day use_sell_cash = False """ print('Test looping of PT proportion target signals, with:\n' 'stock delivery delay = 2 days \n' 'cash delivery delay = 1 day \n' 'maximize_cash = False (buy and sell at the same time)') res = apply_loop( op_type=0, op_list=self.pt_signal_hp, history_list=self.history_list, cash_plan=self.cash, cost_rate=self.rate, moq_buy=0, moq_sell=0, inflation_rate=0, cash_delivery_period=1, stock_delivery_period=2, print_log=False) self.assertIsInstance(res, pd.DataFrame) print(f'in test_loop:\nresult of loop test is \n{res}\n' f'result comparison line by line:') for i in range(len(res)): print(np.around(res.values[i])) print(np.around(self.pt_res_bs21[i])) print() self.assertTrue(np.allclose(res, self.pt_res_bs21, 3)) print(f'test assertion errors in apply_loop: detect moqs that are not compatible') self.assertRaises(AssertionError, apply_loop, 0, self.ps_signal_hp, self.history_list, self.cash, self.rate, 0, 1, 0, False) self.assertRaises(AssertionError, apply_loop, 0, self.ps_signal_hp, self.history_list, self.cash, self.rate, 1, 5, 0, False) print(f'test loop results with moq equal to 100') res = apply_loop( op_type=1, op_list=self.ps_signal_hp, history_list=self.history_list, cash_plan=self.cash, cost_rate=self.rate2, moq_buy=100, moq_sell=1, inflation_rate=0, print_log=False) self.assertIsInstance(res, pd.DataFrame) print(f'in test_loop:\nresult of loop test is \n{res}') def test_loop_pt_with_delay_use_cash(self): """ Test looping of PT proportion target signals, with: stock delivery delay = 2 days cash delivery delay = 0 day use sell cash = True (sell stock first to use cash when possible (not possible when cash delivery period != 0)) """ print('Test looping of PT proportion target signals, with:\n' 'stock delivery delay = 2 days \n' 'cash delivery delay = 1 day \n' 'maximize cash usage = True \n' 'but not applicable because cash delivery period == 1') res = apply_loop( op_type=0, op_list=self.pt_signal_hp, history_list=self.history_list, cash_plan=self.cash, cost_rate=self.rate, moq_buy=0, moq_sell=0, cash_delivery_period=0, stock_delivery_period=2, inflation_rate=0, max_cash_usage=True, print_log=True) self.assertIsInstance(res, pd.DataFrame) print(f'in test_loop:\nresult of loop test is \n{res}\n' f'result comparison line by line:') for i in range(len(res)): print(np.around(res.values[i])) print(np.around(self.pt_res_sb20[i])) print() self.assertTrue(np.allclose(res, self.pt_res_sb20, 3)) print(f'test assertion errors in apply_loop: detect moqs that are not compatible') self.assertRaises(AssertionError, apply_loop, 0, self.ps_signal_hp, self.history_list, self.cash, self.rate, 0, 1, 0, False) self.assertRaises(AssertionError, apply_loop, 0, self.ps_signal_hp, self.history_list, self.cash, self.rate, 1, 5, 0, False) print(f'test loop results with moq equal to 100') res = apply_loop( op_type=1, op_list=self.ps_signal_hp, history_list=self.history_list, cash_plan=self.cash, cost_rate=self.rate2, moq_buy=100, moq_sell=1, cash_delivery_period=1, stock_delivery_period=2, inflation_rate=0, print_log=True) self.assertIsInstance(res, pd.DataFrame) print(f'in test_loop:\nresult of loop test is \n{res}') def test_loop_ps(self): """ Test looping of PS Proportion Signal type of signals """ res = apply_loop(op_type=1, op_list=self.ps_signal_hp, history_list=self.history_list, cash_plan=self.cash, cost_rate=self.rate, moq_buy=0, moq_sell=0, inflation_rate=0, print_log=False) self.assertIsInstance(res, pd.DataFrame) print(f'in test_loop:\nresult of loop test is \n{res}') self.assertTrue(np.allclose(res, self.ps_res_bs00, 5)) print(f'test assertion errors in apply_loop: detect moqs that are not compatible') self.assertRaises(AssertionError, apply_loop, 0, self.ps_signal_hp, self.history_list, self.cash, self.rate, 0, 1, 0, False) self.assertRaises(AssertionError, apply_loop, 0, self.ps_signal_hp, self.history_list, self.cash, self.rate, 1, 5, 0, False) print(f'test loop results with moq equal to 100') res = apply_loop(op_type=1, op_list=self.ps_signal_hp, history_list=self.history_list, cash_plan=self.cash, cost_rate=self.rate2, moq_buy=100, moq_sell=1, inflation_rate=0, print_log=False) self.assertIsInstance(res, pd.DataFrame) print(f'in test_loop:\nresult of loop test is \n{res}') def test_loop_ps_with_delay(self): """ Test looping of PT proportion target signals, with: stock delivery delay = 2 days cash delivery delay = 1 day use_sell_cash = False """ print('Test looping of PT proportion target signals, with:\n' 'stock delivery delay = 2 days \n' 'cash delivery delay = 1 day \n' 'maximize_cash = False (buy and sell at the same time)') res = apply_loop( op_type=1, op_list=self.ps_signal_hp, history_list=self.history_list, cash_plan=self.cash, cost_rate=self.rate, moq_buy=0, moq_sell=0, inflation_rate=0, cash_delivery_period=1, stock_delivery_period=2, print_log=False) self.assertIsInstance(res, pd.DataFrame) print(f'in test_loop:\nresult of loop test is \n{res}\n' f'result comparison line by line:') for i in range(len(res)): print(np.around(res.values[i])) print(np.around(self.ps_res_bs21[i])) print() self.assertTrue(np.allclose(res, self.ps_res_bs21, 3)) print(f'test assertion errors in apply_loop: detect moqs that are not compatible') self.assertRaises(AssertionError, apply_loop, 0, self.ps_signal_hp, self.history_list, self.cash, self.rate, 0, 1, 0, False) self.assertRaises(AssertionError, apply_loop, 0, self.ps_signal_hp, self.history_list, self.cash, self.rate, 1, 5, 0, False) print(f'test loop results with moq equal to 100') res = apply_loop( op_type=1, op_list=self.ps_signal_hp, history_list=self.history_list, cash_plan=self.cash, cost_rate=self.rate2, moq_buy=100, moq_sell=1, inflation_rate=0, print_log=False) self.assertIsInstance(res, pd.DataFrame) print(f'in test_loop:\nresult of loop test is \n{res}') def test_loop_ps_with_delay_use_cash(self): """ Test looping of PT proportion target signals, with: stock delivery delay = 2 days cash delivery delay = 0 day use sell cash = True (sell stock first to use cash when possible (not possible when cash delivery period != 0)) """ print('Test looping of PT proportion target signals, with:\n' 'stock delivery delay = 2 days \n' 'cash delivery delay = 1 day \n' 'maximize cash usage = True \n' 'but not applicable because cash delivery period == 1') res = apply_loop( op_type=1, op_list=self.ps_signal_hp, history_list=self.history_list, cash_plan=self.cash, cost_rate=self.rate, moq_buy=0, moq_sell=0, cash_delivery_period=0, stock_delivery_period=2, inflation_rate=0, max_cash_usage=True, print_log=True) self.assertIsInstance(res, pd.DataFrame) print(f'in test_loop:\nresult of loop test is \n{res}\n' f'result comparison line by line:') for i in range(len(res)): print(np.around(res.values[i])) print(np.around(self.ps_res_sb20[i])) print() self.assertTrue(np.allclose(res, self.ps_res_sb20, 3)) print(f'test assertion errors in apply_loop: detect moqs that are not compatible') self.assertRaises(AssertionError, apply_loop, 0, self.ps_signal_hp, self.history_list, self.cash, self.rate, 0, 1, 0, False) self.assertRaises(AssertionError, apply_loop, 0, self.ps_signal_hp, self.history_list, self.cash, self.rate, 1, 5, 0, False) print(f'test loop results with moq equal to 100') res = apply_loop( op_type=1, op_list=self.ps_signal_hp, history_list=self.history_list, cash_plan=self.cash, cost_rate=self.rate2, moq_buy=100, moq_sell=1, cash_delivery_period=1, stock_delivery_period=2, inflation_rate=0, print_log=True) self.assertIsInstance(res, pd.DataFrame) print(f'in test_loop:\nresult of loop test is \n{res}') def test_loop_vs(self): """ Test looping of VS Volume Signal type of signals """ res = apply_loop(op_type=2, op_list=self.vs_signal_hp, history_list=self.history_list, cash_plan=self.cash, cost_rate=self.rate, moq_buy=0, moq_sell=0, inflation_rate=0, print_log=False) self.assertIsInstance(res, pd.DataFrame) print(f'in test_loop:\nresult of loop test is \n{res}') self.assertTrue(np.allclose(res, self.vs_res_bs00, 5)) print(f'test assertion errors in apply_loop: detect moqs that are not compatible') self.assertRaises(AssertionError, apply_loop, 0, self.ps_signal_hp, self.history_list, self.cash, self.rate, 0, 1, 0, False) self.assertRaises(AssertionError, apply_loop, 0, self.ps_signal_hp, self.history_list, self.cash, self.rate, 1, 5, 0, False) print(f'test loop results with moq equal to 100') res = apply_loop(op_type=2, op_list=self.vs_signal_hp, history_list=self.history_list, cash_plan=self.cash, cost_rate=self.rate2, moq_buy=100, moq_sell=1, inflation_rate=0, print_log=False) self.assertIsInstance(res, pd.DataFrame) print(f'in test_loop:\nresult of loop test is \n{res}') def test_loop_vs_with_delay(self): """ Test looping of PT proportion target signals, with: stock delivery delay = 2 days cash delivery delay = 1 day use_sell_cash = False """ print('Test looping of PT proportion target signals, with:\n' 'stock delivery delay = 2 days \n' 'cash delivery delay = 1 day \n' 'maximize_cash = False (buy and sell at the same time)') res = apply_loop( op_type=2, op_list=self.vs_signal_hp, history_list=self.history_list, cash_plan=self.cash, cost_rate=self.rate, moq_buy=0, moq_sell=0, inflation_rate=0, cash_delivery_period=1, stock_delivery_period=2, print_log=True) self.assertIsInstance(res, pd.DataFrame) print(f'in test_loop:\nresult of loop test is \n{res}\n' f'result comparison line by line:') for i in range(len(res)): print(np.around(res.values[i])) print(np.around(self.vs_res_bs21[i])) print() self.assertTrue(np.allclose(res, self.vs_res_bs21, 3)) print(f'test assertion errors in apply_loop: detect moqs that are not compatible') self.assertRaises(AssertionError, apply_loop, 0, self.vs_signal_hp, self.history_list, self.cash, self.rate, 0, 1, 0, False) self.assertRaises(AssertionError, apply_loop, 0, self.vs_signal_hp, self.history_list, self.cash, self.rate, 1, 5, 0, False) print(f'test loop results with moq equal to 100') res = apply_loop( op_type=1, op_list=self.vs_signal_hp, history_list=self.history_list, cash_plan=self.cash, cost_rate=self.rate2, moq_buy=100, moq_sell=1, inflation_rate=0, print_log=False) self.assertIsInstance(res, pd.DataFrame) print(f'in test_loop:\nresult of loop test is \n{res}') def test_loop_vs_with_delay_use_cash(self): """ Test looping of PT proportion target signals, with: stock delivery delay = 2 days cash delivery delay = 0 day use sell cash = True (sell stock first to use cash when possible (not possible when cash delivery period != 0)) """ print('Test looping of PT proportion target signals, with:\n' 'stock delivery delay = 2 days \n' 'cash delivery delay = 1 day \n' 'maximize cash usage = True \n' 'but not applicable because cash delivery period == 1') res = apply_loop( op_type=2, op_list=self.vs_signal_hp, history_list=self.history_list, cash_plan=self.cash, cost_rate=self.rate, moq_buy=0, moq_sell=0, cash_delivery_period=0, stock_delivery_period=2, inflation_rate=0, max_cash_usage=True, print_log=False) self.assertIsInstance(res, pd.DataFrame) print(f'in test_loop:\nresult of loop test is \n{res}\n' f'result comparison line by line:') for i in range(len(res)): print(np.around(res.values[i])) print(np.around(self.vs_res_sb20[i])) print() self.assertTrue(np.allclose(res, self.vs_res_sb20, 3)) print(f'test assertion errors in apply_loop: detect moqs that are not compatible') self.assertRaises(AssertionError, apply_loop, 0, self.vs_signal_hp, self.history_list, self.cash, self.rate, 0, 1, 0, False) self.assertRaises(AssertionError, apply_loop, 0, self.vs_signal_hp, self.history_list, self.cash, self.rate, 1, 5, 0, False) print(f'test loop results with moq equal to 100') res = apply_loop( op_type=1, op_list=self.vs_signal_hp, history_list=self.history_list, cash_plan=self.cash, cost_rate=self.rate2, moq_buy=100, moq_sell=1, cash_delivery_period=1, stock_delivery_period=2, inflation_rate=0, print_log=False) self.assertIsInstance(res, pd.DataFrame) print(f'in test_loop:\nresult of loop test is \n{res}') def test_loop_multiple_signal(self): """ Test looping of PS Proportion Signal type of signals """ res = apply_loop(op_type=1, op_list=self.multi_signal_hp, history_list=self.multi_history_list, cash_plan=self.cash, cost_rate=self.rate, moq_buy=0, moq_sell=0, cash_delivery_period=0, stock_delivery_period=2, max_cash_usage=True, inflation_rate=0, print_log=False) self.assertIsInstance(res, pd.DataFrame) print(f'in test_loop:\nresult of loop test is \n{res}\n' f'result comparison line by line:') for i in range(len(res)): print(np.around(res.values[i])) print(np.around(self.multi_res[i])) print() self.assertTrue(np.allclose(res, self.multi_res, 5)) print(f'test assertion errors in apply_loop: detect moqs that are not compatible') self.assertRaises(AssertionError, apply_loop, 0, self.ps_signal_hp, self.history_list, self.cash, self.rate, 0, 1, 0, False) self.assertRaises(AssertionError, apply_loop, 0, self.ps_signal_hp, self.history_list, self.cash, self.rate, 1, 5, 0, False) print(f'test loop results with moq equal to 100') res = apply_loop(op_type=1, op_list=self.multi_signal_hp, history_list=self.multi_history_list, cash_plan=self.cash, cost_rate=self.rate2, moq_buy=100, moq_sell=1, cash_delivery_period=0, stock_delivery_period=2, max_cash_usage=False, inflation_rate=0, print_log=True) self.assertIsInstance(res, pd.DataFrame) print(f'in test_loop:\nresult of loop test is \n{res}') class TestStrategy(unittest.TestCase): """ test all properties and methods of strategy base class""" def setUp(self) -> None: pass class TestLSStrategy(RollingTiming): """用于test测试的简单多空蒙板生成策略。基于RollingTiming滚动择时方法生成 该策略有两个参数,N与Price N用于计算OHLC价格平均值的N日简单移动平均,判断,当移动平均值大于等于Price时,状态为看多,否则为看空 """ def __init__(self): super().__init__(stg_name='test_LS', stg_text='test long/short strategy', par_count=2, par_types='discr, conti', par_bounds_or_enums=([1, 5], [2, 10]), data_types='close, open, high, low', data_freq='d', window_length=5) pass def _realize(self, hist_data: np.ndarray, params: tuple): n, price = params h = hist_data.T avg = (h[0] + h[1] + h[2] + h[3]) / 4 ma = sma(avg, n) if ma[-1] < price: return 0 else: return 1 class TestSelStrategy(SimpleSelecting): """用于Test测试的简单选股策略,基于Selecting策略生成 策略没有参数,选股周期为5D 在每个选股周期内,从股票池的三只股票中选出今日变化率 = (今收-昨收)/平均股价(OHLC平均股价)最高的两支,放入中选池,否则落选。 选股比例为平均分配 """ def __init__(self): super().__init__(stg_name='test_SEL', stg_text='test portfolio selection strategy', par_count=0, par_types='', par_bounds_or_enums=(), data_types='high, low, close', data_freq='d', sample_freq='10d', window_length=5) pass def _realize(self, hist_data: np.ndarray, params: tuple): avg = np.nanmean(hist_data, axis=(1, 2)) dif = (hist_data[:, :, 2] - np.roll(hist_data[:, :, 2], 1, 1)) dif_no_nan = np.array([arr[~np.isnan(arr)][-1] for arr in dif]) difper = dif_no_nan / avg large2 = difper.argsort()[1:] chosen = np.zeros_like(avg) chosen[large2] = 0.5 return chosen class TestSelStrategyDiffTime(SimpleSelecting): """用于Test测试的简单选股策略,基于Selecting策略生成 策略没有参数,选股周期为5D 在每个选股周期内,从股票池的三只股票中选出今日变化率 = (今收-昨收)/平均股价(OHLC平均股价)最高的两支,放入中选池,否则落选。 选股比例为平均分配 """ # TODO: This strategy is not working, find out why and improve def __init__(self): super().__init__(stg_name='test_SEL', stg_text='test portfolio selection strategy', par_count=0, par_types='', par_bounds_or_enums=(), data_types='close, low, open', data_freq='d', sample_freq='w', window_length=2) pass def _realize(self, hist_data: np.ndarray, params: tuple): avg = hist_data.mean(axis=1).squeeze() difper = (hist_data[:, :, 0] - np.roll(hist_data[:, :, 0], 1))[:, -1] / avg large2 = difper.argsort()[0:2] chosen = np.zeros_like(avg) chosen[large2] = 0.5 return chosen class TestSigStrategy(SimpleTiming): """用于Test测试的简单信号生成策略,基于SimpleTiming策略生成 策略有三个参数,第一个参数为ratio,另外两个参数为price1以及price2 ratio是k线形状比例的阈值,定义为abs((C-O)/(H-L))。当这个比值小于ratio阈值时,判断该K线为十字交叉(其实还有丁字等多种情形,但这里做了 简化处理。 信号生成的规则如下: 1,当某个K线出现十字交叉,且昨收与今收之差大于price1时,买入信号 2,当某个K线出现十字交叉,且昨收与今收之差小于price2时,卖出信号 """ def __init__(self): super().__init__(stg_name='test_SIG', stg_text='test signal creation strategy', par_count=3, par_types='conti, conti, conti', par_bounds_or_enums=([2, 10], [0, 3], [0, 3]), data_types='close, open, high, low', window_length=2) pass def _realize(self, hist_data: np.ndarray, params: tuple): r, price1, price2 = params h = hist_data.T ratio = np.abs((h[0] - h[1]) / (h[3] - h[2])) diff = h[0] - np.roll(h[0], 1) sig = np.where((ratio < r) & (diff > price1), 1, np.where((ratio < r) & (diff < price2), -1, 0)) return sig class MyStg(qt.RollingTiming): """自定义双均线择时策略策略""" def __init__(self): """这个均线择时策略只有三个参数: - SMA 慢速均线,所选择的股票 - FMA 快速均线 - M 边界值 策略的其他说明 """ """ 必须初始化的关键策略参数清单: """ super().__init__( pars=(20, 100, 0.01), par_count=3, par_types=['discr', 'discr', 'conti'], par_bounds_or_enums=[(10, 250), (10, 250), (0.0, 0.5)], stg_name='CUSTOM ROLLING TIMING STRATEGY', stg_text='Customized Rolling Timing Strategy for Testing', data_types='close', window_length=100, ) print(f'=====================\n====================\n' f'custom strategy initialized, \npars: {self.pars}\npar_count:{self.par_count}\npar_types:' f'{self.par_types}\n' f'{self.info()}') # 策略的具体实现代码写在策略的_realize()函数中 # 这个函数固定接受两个参数: hist_price代表特定组合的历史数据, params代表具体的策略参数 def _realize(self, hist_price, params): """策略的具体实现代码: s:短均线计算日期;l:长均线计算日期;m:均线边界宽度;hesitate:均线跨越类型""" f, s, m = params # 临时处理措施,在策略实现层对传入的数据切片,后续应该在策略实现层以外事先对数据切片,保证传入的数据符合data_types参数即可 h = hist_price.T # 计算长短均线的当前值 s_ma = qt.sma(h[0], s)[-1] f_ma = qt.sma(h[0], f)[-1] # 计算慢均线的停止边界,当快均线在停止边界范围内时,平仓,不发出买卖信号 s_ma_u = s_ma * (1 + m) s_ma_l = s_ma * (1 - m) # 根据观望模式在不同的点位产生Long/short/empty标记 if f_ma > s_ma_u: # 当快均线在慢均线停止范围以上时,持有多头头寸 return 1 elif s_ma_l < f_ma < s_ma_u: # 当均线在停止边界以内时,平仓 return 0 else: # f_ma < s_ma_l 当快均线在慢均线停止范围以下时,持有空头头寸 return -1 class TestOperator(unittest.TestCase): """全面测试Operator对象的所有功能。包括: 1, Strategy 参数的设置 2, 历史数据的获取与分配提取 3, 策略优化参数的批量设置和优化空间的获取 4, 策略输出值的正确性验证 5, 策略结果的混合结果确认 """ def setUp(self): """prepare data for Operator test""" print('start testing HistoryPanel object\n') # build up test data: a 4-type, 3-share, 50-day matrix of prices that contains nan values in some days # for some share_pool # for share1: data_rows = 50 share1_close = [10.04, 10, 10, 9.99, 9.97, 9.99, 10.03, 10.03, 10.06, 10.06, 10.11, 10.09, 10.07, 10.06, 10.09, 10.03, 10.03, 10.06, 10.08, 10, 9.99, 10.03, 10.03, 10.06, 10.03, 9.97, 9.94, 9.83, 9.77, 9.84, 9.91, 9.93, 9.96, 9.91, 9.91, 9.88, 9.91, 9.64, 9.56, 9.57, 9.55, 9.57, 9.61, 9.61, 9.55, 9.57, 9.63, 9.64, 9.65, 9.62] share1_open = [10.02, 10, 9.98, 9.97, 9.99, 10.01, 10.04, 10.06, 10.06, 10.11, 10.11, 10.07, 10.06, 10.09, 10.03, 10.02, 10.06, 10.08, 9.99, 10, 10.03, 10.02, 10.06, 10.03, 9.97, 9.94, 9.83, 9.78, 9.77, 9.91, 9.92, 9.97, 9.91, 9.9, 9.88, 9.91, 9.63, 9.64, 9.57, 9.55, 9.58, 9.61, 9.62, 9.55, 9.57, 9.61, 9.63, 9.64, 9.61, 9.56] share1_high = [10.07, 10, 10, 10, 10.03, 10.03, 10.04, 10.09, 10.1, 10.14, 10.11, 10.1, 10.09, 10.09, 10.1, 10.05, 10.07, 10.09, 10.1, 10, 10.04, 10.04, 10.06, 10.09, 10.05, 9.97, 9.96, 9.86, 9.77, 9.92, 9.94, 9.97, 9.97, 9.92, 9.92, 9.92, 9.93, 9.64, 9.58, 9.6, 9.58, 9.62, 9.62, 9.64, 9.59, 9.62, 9.63, 9.7, 9.66, 9.64] share1_low = [9.99, 10, 9.97, 9.97, 9.97, 9.98, 9.99, 10.03, 10.03, 10.04, 10.11, 10.07, 10.05, 10.03, 10.03, 10.01, 9.99, 10.03, 9.95, 10, 9.95, 10, 10.01, 9.99, 9.96, 9.89, 9.83, 9.77, 9.77, 9.8, 9.9, 9.91, 9.89, 9.89, 9.87, 9.85, 9.6, 9.64, 9.53, 9.55, 9.54, 9.55, 9.58, 9.54, 9.53, 9.53, 9.63, 9.64, 9.59, 9.56] # for share2: share2_close = [9.68, 9.87, 9.86, 9.87, 9.79, 9.82, 9.8, 9.66, 9.62, 9.58, 9.69, 9.78, 9.75, 9.96, 9.9, 10.04, 10.06, 10.08, 10.24, 10.24, 10.24, 9.86, 10.13, 10.12, 10.1, 10.25, 10.24, 10.22, 10.75, 10.64, 10.56, 10.6, 10.42, 10.25, 10.24, 10.49, 10.57, 10.63, 10.48, 10.37, 10.96, 11.02, np.nan, np.nan, 10.88, 10.87, 11.01, 11.01, 11.58, 11.8] share2_open = [9.88, 9.88, 9.89, 9.75, 9.74, 9.8, 9.62, 9.65, 9.58, 9.67, 9.81, 9.8, 10, 9.95, 10.1, 10.06, 10.14, 9.9, 10.2, 10.29, 9.86, 9.48, 10.01, 10.24, 10.26, 10.24, 10.12, 10.65, 10.64, 10.56, 10.42, 10.43, 10.29, 10.3, 10.44, 10.6, 10.67, 10.46, 10.39, 10.9, 11.01, 11.01, np.nan, np.nan, 10.82, 11.02, 10.96, 11.55, 11.74, 11.8] share2_high = [9.91, 10.04, 9.93, 10.04, 9.84, 9.88, 9.99, 9.7, 9.67, 9.71, 9.85, 9.9, 10, 10.2, 10.11, 10.18, 10.21, 10.26, 10.38, 10.47, 10.42, 10.07, 10.24, 10.27, 10.38, 10.43, 10.39, 10.65, 10.84, 10.65, 10.73, 10.63, 10.51, 10.35, 10.46, 10.63, 10.74, 10.76, 10.54, 11.02, 11.12, 11.17, np.nan, np.nan, 10.92, 11.15, 11.11, 11.55, 11.95, 11.93] share2_low = [9.63, 9.84, 9.81, 9.74, 9.67, 9.72, 9.57, 9.54, 9.51, 9.47, 9.68, 9.63, 9.75, 9.65, 9.9, 9.93, 10.03, 9.8, 10.14, 10.09, 9.78, 9.21, 9.11, 9.68, 10.05, 10.12, 9.89, 9.89, 10.59, 10.43, 10.34, 10.32, 10.21, 10.2, 10.18, 10.36, 10.51, 10.41, 10.32, 10.37, 10.87, 10.95, np.nan, np.nan, 10.65, 10.71, 10.75, 10.91, 11.31, 11.58] # for share3: share3_close = [6.64, 7.26, 7.03, 6.87, np.nan, 6.64, 6.85, 6.7, 6.39, 6.22, 5.92, 5.91, 6.11, 5.91, 6.23, 6.28, 6.28, 6.27, np.nan, 5.56, 5.67, 5.16, 5.69, 6.32, 6.14, 6.25, 5.79, 5.26, 5.05, 5.45, 6.06, 6.21, 5.69, 5.46, 6.02, 6.69, 7.43, 7.72, 8.16, 7.83, 8.7, 8.71, 8.88, 8.54, 8.87, 8.87, 8.18, 7.8, 7.97, 8.25] share3_open = [7.26, 7, 6.88, 6.91, np.nan, 6.81, 6.63, 6.45, 6.16, 6.24, 5.96, 5.97, 5.96, 6.2, 6.35, 6.11, 6.37, 5.58, np.nan, 5.65, 5.19, 5.42, 6.3, 6.15, 6.05, 5.89, 5.22, 5.2, 5.07, 6.04, 6.12, 5.85, 5.67, 6.02, 6.04, 7.07, 7.64, 7.99, 7.59, 8.73, 8.72, 8.97, 8.58, 8.71, 8.77, 8.4, 7.95, 7.76, 8.25, 7.51] share3_high = [7.41, 7.31, 7.14, 7, np.nan, 6.82, 6.96, 6.85, 6.5, 6.34, 6.04, 6.02, 6.12, 6.38, 6.43, 6.46, 6.43, 6.27, np.nan, 6.01, 5.67, 5.67, 6.35, 6.32, 6.43, 6.36, 5.79, 5.47, 5.65, 6.04, 6.14, 6.23, 5.83, 6.25, 6.27, 7.12, 7.82, 8.14, 8.27, 8.92, 8.76, 9.15, 8.9, 9.01, 9.16, 9, 8.27, 7.99, 8.33, 8.25] share3_low = [6.53, 6.87, 6.83, 6.7, np.nan, 6.63, 6.57, 6.41, 6.15, 6.07, 5.89, 5.82, 5.73, 5.81, 6.1, 6.06, 6.16, 5.57, np.nan, 5.51, 5.19, 5.12, 5.69, 6.01, 5.97, 5.86, 5.18, 5.19, 4.96, 5.45, 5.84, 5.85, 5.28, 5.42, 6.02, 6.69, 7.28, 7.64, 7.25, 7.83, 8.41, 8.66, 8.53, 8.54, 8.73, 8.27, 7.95, 7.67, 7.8, 7.51] # for sel_finance test shares_eps = np.array([[np.nan, np.nan, np.nan], [0.1, np.nan, np.nan], [np.nan, 0.2, np.nan], [np.nan, np.nan, 0.3], [np.nan, np.nan, np.nan], [np.nan, np.nan, np.nan], [np.nan, np.nan, np.nan], [np.nan, np.nan, 0.2], [0.1, np.nan, np.nan], [np.nan, 0.3, np.nan], [np.nan, np.nan, np.nan], [np.nan, np.nan, np.nan], [0.3, np.nan, np.nan], [np.nan, np.nan, np.nan], [np.nan, 0.3, np.nan], [np.nan, np.nan, np.nan], [np.nan, np.nan, 0.3], [np.nan, np.nan, np.nan], [np.nan, np.nan, np.nan], [np.nan, np.nan, np.nan], [np.nan, np.nan, np.nan], [np.nan, 0, 0.2], [np.nan, np.nan, np.nan], [np.nan, np.nan, np.nan], [0.1, np.nan, np.nan], [np.nan, np.nan, np.nan], [np.nan, np.nan, np.nan], [np.nan, np.nan, np.nan], [np.nan, np.nan, np.nan], [np.nan, np.nan, 0.2], [np.nan, np.nan, np.nan], [np.nan, np.nan, np.nan], [np.nan, np.nan, np.nan], [0.15, np.nan, np.nan], [np.nan, 0.1, np.nan], [np.nan, np.nan, np.nan], [0.1, np.nan, np.nan], [np.nan, np.nan, np.nan], [np.nan, np.nan, 0.3], [np.nan, np.nan, np.nan], [np.nan, np.nan, np.nan], [np.nan, np.nan, np.nan], [np.nan, np.nan, np.nan], [0.2, np.nan, np.nan], [np.nan, 0.5, np.nan], [0.4, np.nan, 0.3], [np.nan, np.nan, np.nan], [np.nan, 0.3, np.nan], [0.9, np.nan, np.nan], [np.nan, np.nan, 0.1]]) self.date_indices = ['2016-07-01', '2016-07-04', '2016-07-05', '2016-07-06', '2016-07-07', '2016-07-08', '2016-07-11', '2016-07-12', '2016-07-13', '2016-07-14', '2016-07-15', '2016-07-18', '2016-07-19', '2016-07-20', '2016-07-21', '2016-07-22', '2016-07-25', '2016-07-26', '2016-07-27', '2016-07-28', '2016-07-29', '2016-08-01', '2016-08-02', '2016-08-03', '2016-08-04', '2016-08-05', '2016-08-08', '2016-08-09', '2016-08-10', '2016-08-11', '2016-08-12', '2016-08-15', '2016-08-16', '2016-08-17', '2016-08-18', '2016-08-19', '2016-08-22', '2016-08-23', '2016-08-24', '2016-08-25', '2016-08-26', '2016-08-29', '2016-08-30', '2016-08-31', '2016-09-01', '2016-09-02', '2016-09-05', '2016-09-06', '2016-09-07', '2016-09-08'] self.shares = ['000010', '000030', '000039'] self.types = ['close', 'open', 'high', 'low'] self.sel_finance_tyeps = ['eps'] self.test_data_3D = np.zeros((3, data_rows, 4)) self.test_data_2D = np.zeros((data_rows, 3)) self.test_data_2D2 = np.zeros((data_rows, 4)) self.test_data_sel_finance = np.empty((3, data_rows, 1)) # Build up 3D data self.test_data_3D[0, :, 0] = share1_close self.test_data_3D[0, :, 1] = share1_open self.test_data_3D[0, :, 2] = share1_high self.test_data_3D[0, :, 3] = share1_low self.test_data_3D[1, :, 0] = share2_close self.test_data_3D[1, :, 1] = share2_open self.test_data_3D[1, :, 2] = share2_high self.test_data_3D[1, :, 3] = share2_low self.test_data_3D[2, :, 0] = share3_close self.test_data_3D[2, :, 1] = share3_open self.test_data_3D[2, :, 2] = share3_high self.test_data_3D[2, :, 3] = share3_low self.test_data_sel_finance[:, :, 0] = shares_eps.T self.hp1 = qt.HistoryPanel(values=self.test_data_3D, levels=self.shares, columns=self.types, rows=self.date_indices) print(f'in test Operator, history panel is created for timing test') self.hp1.info() self.hp2 = qt.HistoryPanel(values=self.test_data_sel_finance, levels=self.shares, columns=self.sel_finance_tyeps, rows=self.date_indices) print(f'in test_Operator, history panel is created for selection finance test:') self.hp2.info() self.op = qt.Operator(strategies='dma', signal_type='PS') self.op2 = qt.Operator(strategies='dma, macd, trix') def test_init(self): """ test initialization of Operator class""" op = qt.Operator() self.assertIsInstance(op, qt.Operator) self.assertEqual(op.signal_type, 'pt') self.assertIsInstance(op.strategies, list) self.assertEqual(len(op.strategies), 0) op = qt.Operator('dma') self.assertIsInstance(op, qt.Operator) self.assertIsInstance(op.strategies, list) self.assertIsInstance(op.strategies[0], TimingDMA) op = qt.Operator('dma, macd') self.assertIsInstance(op, qt.Operator) op = qt.Operator(['dma', 'macd']) self.assertIsInstance(op, qt.Operator) def test_repr(self): """ test basic representation of Opeartor class""" op = qt.Operator() self.assertEqual(op.__repr__(), 'Operator()') op = qt.Operator('macd, dma, trix, random, avg_low') self.assertEqual(op.__repr__(), 'Operator(macd, dma, trix, random, avg_low)') self.assertEqual(op['dma'].__repr__(), 'Q-TIMING(DMA)') self.assertEqual(op['macd'].__repr__(), 'R-TIMING(MACD)') self.assertEqual(op['trix'].__repr__(), 'R-TIMING(TRIX)') self.assertEqual(op['random'].__repr__(), 'SELECT(RANDOM)') self.assertEqual(op['avg_low'].__repr__(), 'FACTOR(AVG LOW)') def test_info(self): """Test information output of Operator""" print(f'test printing information of operator object') self.op.info() def test_get_strategy_by_id(self): """ test get_strategy_by_id()""" op = qt.Operator() self.assertIsInstance(op, qt.Operator) self.assertEqual(op.strategy_count, 0) self.assertEqual(op.strategy_ids, []) op = qt.Operator('macd, dma, trix') self.assertEqual(op.strategy_ids, ['macd', 'dma', 'trix']) self.assertIs(op.get_strategy_by_id('macd'), op.strategies[0]) self.assertIs(op.get_strategy_by_id(1), op.strategies[1]) self.assertIs(op.get_strategy_by_id('trix'), op.strategies[2]) def test_get_items(self): """ test method __getitem__(), it should be the same as geting strategies by id""" op = qt.Operator() self.assertIsInstance(op, qt.Operator) self.assertEqual(op.strategy_count, 0) self.assertEqual(op.strategy_ids, []) op = qt.Operator('macd, dma, trix') self.assertEqual(op.strategy_ids, ['macd', 'dma', 'trix']) self.assertIs(op['macd'], op.strategies[0]) self.assertIs(op['trix'], op.strategies[2]) self.assertIs(op[1], op.strategies[1]) self.assertIs(op[3], op.strategies[2]) def test_get_strategies_by_price_type(self): """ test get_strategies_by_price_type""" op = qt.Operator() self.assertIsInstance(op, qt.Operator) self.assertEqual(op.strategy_count, 0) self.assertEqual(op.strategy_ids, []) op = qt.Operator('macd, dma, trix') op.set_parameter('macd', price_type='open') op.set_parameter('dma', price_type='close') op.set_parameter('trix', price_type='open') stg_close = op.get_strategies_by_price_type('close') stg_open = op.get_strategies_by_price_type('open') stg_high = op.get_strategies_by_price_type('high') self.assertIsInstance(stg_close, list) self.assertIsInstance(stg_open, list) self.assertIsInstance(stg_high, list) self.assertEqual(stg_close, [op.strategies[1]]) self.assertEqual(stg_open, [op.strategies[0], op.strategies[2]]) self.assertEqual(stg_high, []) stg_wrong = op.get_strategies_by_price_type(123) self.assertIsInstance(stg_wrong, list) self.assertEqual(stg_wrong, []) def test_get_strategy_count_by_price_type(self): """ test get_strategy_count_by_price_type""" op = qt.Operator() self.assertIsInstance(op, qt.Operator) self.assertEqual(op.strategy_count, 0) self.assertEqual(op.strategy_ids, []) op = qt.Operator('macd, dma, trix') op.set_parameter('macd', price_type='open') op.set_parameter('dma', price_type='close') op.set_parameter('trix', price_type='open') stg_close = op.get_strategy_count_by_price_type('close') stg_open = op.get_strategy_count_by_price_type('open') stg_high = op.get_strategy_count_by_price_type('high') self.assertIsInstance(stg_close, int) self.assertIsInstance(stg_open, int) self.assertIsInstance(stg_high, int) self.assertEqual(stg_close, 1) self.assertEqual(stg_open, 2) self.assertEqual(stg_high, 0) stg_wrong = op.get_strategy_count_by_price_type(123) self.assertIsInstance(stg_wrong, int) self.assertEqual(stg_wrong, 0) def test_get_strategy_names_by_price_type(self): """ test get_strategy_names_by_price_type""" op = qt.Operator() self.assertIsInstance(op, qt.Operator) self.assertEqual(op.strategy_count, 0) self.assertEqual(op.strategy_ids, []) op = qt.Operator('macd, dma, trix') op.set_parameter('macd', price_type='open') op.set_parameter('dma', price_type='close') op.set_parameter('trix', price_type='open') stg_close = op.get_strategy_names_by_price_type('close') stg_open = op.get_strategy_names_by_price_type('open') stg_high = op.get_strategy_names_by_price_type('high') self.assertIsInstance(stg_close, list) self.assertIsInstance(stg_open, list) self.assertIsInstance(stg_high, list) self.assertEqual(stg_close, ['DMA']) self.assertEqual(stg_open, ['MACD', 'TRIX']) self.assertEqual(stg_high, []) stg_wrong = op.get_strategy_names_by_price_type(123) self.assertIsInstance(stg_wrong, list) self.assertEqual(stg_wrong, []) def test_get_strategy_id_by_price_type(self): """ test get_strategy_IDs_by_price_type""" print('-----Test get strategy IDs by price type------\n') op = qt.Operator() self.assertIsInstance(op, qt.Operator) self.assertEqual(op.strategy_count, 0) self.assertEqual(op.strategy_ids, []) op = qt.Operator('macd, dma, trix') op.set_parameter('macd', price_type='open') op.set_parameter('dma', price_type='close') op.set_parameter('trix', price_type='open') stg_close = op.get_strategy_id_by_price_type('close') stg_open = op.get_strategy_id_by_price_type('open') stg_high = op.get_strategy_id_by_price_type('high') self.assertIsInstance(stg_close, list) self.assertIsInstance(stg_open, list) self.assertIsInstance(stg_high, list) self.assertEqual(stg_close, ['dma']) self.assertEqual(stg_open, ['macd', 'trix']) self.assertEqual(stg_high, []) op.add_strategies('dma, macd') op.set_parameter('dma_1', price_type='open') op.set_parameter('macd', price_type='open') op.set_parameter('macd_1', price_type='high') op.set_parameter('trix', price_type='close') print(f'Operator strategy id:\n' f'{op.strategies} on memory pos:\n' f'{[id(stg) for stg in op.strategies]}') stg_close = op.get_strategy_id_by_price_type('close') stg_open = op.get_strategy_id_by_price_type('open') stg_high = op.get_strategy_id_by_price_type('high') stg_all = op.get_strategy_id_by_price_type() print(f'All IDs of strategies:\n' f'{stg_all}\n' f'All price types of strategies:\n' f'{[stg.price_type for stg in op.strategies]}') self.assertEqual(stg_close, ['dma', 'trix']) self.assertEqual(stg_open, ['macd', 'dma_1']) self.assertEqual(stg_high, ['macd_1']) stg_wrong = op.get_strategy_id_by_price_type(123) self.assertIsInstance(stg_wrong, list) self.assertEqual(stg_wrong, []) def test_property_strategies(self): """ test property strategies""" print(f'created a new simple Operator with only one strategy: DMA') op = qt.Operator('dma') strategies = op.strategies self.assertIsInstance(strategies, list) op.info() print(f'created the second simple Operator with three strategies') self.assertIsInstance(strategies[0], TimingDMA) op = qt.Operator('dma, macd, cdl') strategies = op.strategies op.info() self.assertIsInstance(strategies, list) self.assertIsInstance(strategies[0], TimingDMA) self.assertIsInstance(strategies[1], TimingMACD) self.assertIsInstance(strategies[2], TimingCDL) def test_property_strategy_count(self): """ test Property strategy_count, and the method get_strategy_count_by_price_type()""" self.assertEqual(self.op.strategy_count, 1) self.assertEqual(self.op2.strategy_count, 3) self.assertEqual(self.op.get_strategy_count_by_price_type(), 1) self.assertEqual(self.op2.get_strategy_count_by_price_type(), 3) self.assertEqual(self.op.get_strategy_count_by_price_type('close'), 1) self.assertEqual(self.op.get_strategy_count_by_price_type('high'), 0) self.assertEqual(self.op2.get_strategy_count_by_price_type('close'), 3) self.assertEqual(self.op2.get_strategy_count_by_price_type('open'), 0) def test_property_strategy_names(self): """ test property strategy_ids""" op = qt.Operator('dma') self.assertIsInstance(op.strategy_ids, list) names = op.strategy_ids[0] print(f'names are {names}') self.assertEqual(names, 'dma') op = qt.Operator('dma, macd, trix, cdl') self.assertIsInstance(op.strategy_ids, list) self.assertEqual(op.strategy_ids[0], 'dma') self.assertEqual(op.strategy_ids[1], 'macd') self.assertEqual(op.strategy_ids[2], 'trix') self.assertEqual(op.strategy_ids[3], 'cdl') op = qt.Operator('dma, macd, trix, dma, dma') self.assertIsInstance(op.strategy_ids, list) self.assertEqual(op.strategy_ids[0], 'dma') self.assertEqual(op.strategy_ids[1], 'macd') self.assertEqual(op.strategy_ids[2], 'trix') self.assertEqual(op.strategy_ids[3], 'dma_1') self.assertEqual(op.strategy_ids[4], 'dma_2') def test_property_strategy_blenders(self): """ test property strategy blenders including property setter, and test the method get_blender()""" print(f'------- Test property strategy blenders ---------') op = qt.Operator() self.assertIsInstance(op.strategy_blenders, dict) self.assertIsInstance(op.signal_type, str) self.assertEqual(op.strategy_blenders, {}) self.assertEqual(op.signal_type, 'pt') # test adding blender to empty operator op.strategy_blenders = '1 + 2' op.signal_type = 'proportion signal' self.assertEqual(op.strategy_blenders, {}) self.assertEqual(op.signal_type, 'ps') op.add_strategy('dma') op.strategy_blenders = '1+2' self.assertEqual(op.strategy_blenders, {'close': ['+', '2', '1']}) op.clear_strategies() self.assertEqual(op.strategy_blenders, {}) op.add_strategies('dma, trix, macd, dma') op.set_parameter('dma', price_type='open') op.set_parameter('trix', price_type='high') op.set_blender('open', '1+2') blender_open = op.get_blender('open') blender_close = op.get_blender('close') blender_high = op.get_blender('high') self.assertEqual(blender_open, ['+', '2', '1']) self.assertEqual(blender_close, None) self.assertEqual(blender_high, None) op.set_blender('open', '1+2+3') op.set_blender('abc', '1+2+3') blender_open = op.get_blender('open') blender_close = op.get_blender('close') blender_high = op.get_blender('high') blender_abc = op.get_blender('abc') self.assertEqual(op.strategy_blenders, {'open': ['+', '3', '+', '2', '1']}) self.assertEqual(blender_open, ['+', '3', '+', '2', '1']) self.assertEqual(blender_close, None) self.assertEqual(blender_high, None) self.assertEqual(blender_abc, None) op.set_blender('open', 123) blender_open = op.get_blender('open') self.assertEqual(blender_open, []) op.set_blender(None, '1+1') blender_open = op.get_blender('open') blender_close = op.get_blender('close') blender_high = op.get_blender('high') self.assertEqual(op.bt_price_types, ['close', 'high', 'open']) self.assertEqual(op.get_blender(), {'close': ['+', '1', '1'], 'open': ['+', '1', '1'], 'high': ['+', '1', '1']}) self.assertEqual(blender_open, ['+', '1', '1']) self.assertEqual(blender_close, ['+', '1', '1']) self.assertEqual(blender_high, ['+', '1', '1']) op.set_blender(None, ['1+1', '3+4']) blender_open = op.get_blender('open') blender_close = op.get_blender('close') blender_high = op.get_blender('high') self.assertEqual(blender_open, ['+', '4', '3']) self.assertEqual(blender_close, ['+', '1', '1']) self.assertEqual(blender_high, ['+', '4', '3']) self.assertEqual(op.view_blender('open'), '3+4') self.assertEqual(op.view_blender('close'), '1+1') self.assertEqual(op.view_blender('high'), '3+4') op.strategy_blenders = (['1+2', '2*3', '1+4']) blender_open = op.get_blender('open') blender_close = op.get_blender('close') blender_high = op.get_blender('high') self.assertEqual(blender_open, ['+', '4', '1']) self.assertEqual(blender_close, ['+', '2', '1']) self.assertEqual(blender_high, ['*', '3', '2']) self.assertEqual(op.view_blender('open'), '1+4') self.assertEqual(op.view_blender('close'), '1+2') self.assertEqual(op.view_blender('high'), '2*3') # test error inputs: # wrong type of price_type self.assertRaises(TypeError, op.set_blender, 1, '1+3') # price_type not found, no change is made op.set_blender('volume', '1+3') blender_open = op.get_blender('open') blender_close = op.get_blender('close') blender_high = op.get_blender('high') self.assertEqual(blender_open, ['+', '4', '1']) self.assertEqual(blender_close, ['+', '2', '1']) self.assertEqual(blender_high, ['*', '3', '2']) # price_type not valid, no change is made op.set_blender('closee', '1+2') blender_open = op.get_blender('open') blender_close = op.get_blender('close') blender_high = op.get_blender('high') self.assertEqual(blender_open, ['+', '4', '1']) self.assertEqual(blender_close, ['+', '2', '1']) self.assertEqual(blender_high, ['*', '3', '2']) # wrong type of blender, set to empty list op.set_blender('open', 55) blender_open = op.get_blender('open') blender_close = op.get_blender('close') blender_high = op.get_blender('high') self.assertEqual(blender_open, []) self.assertEqual(blender_close, ['+', '2', '1']) self.assertEqual(blender_high, ['*', '3', '2']) # wrong type of blender, set to empty list op.set_blender('close', ['1+2']) blender_open = op.get_blender('open') blender_close = op.get_blender('close') blender_high = op.get_blender('high') self.assertEqual(blender_open, []) self.assertEqual(blender_close, []) self.assertEqual(blender_high, ['*', '3', '2']) # can't parse blender, set to empty list op.set_blender('high', 'a+bc') blender_open = op.get_blender('open') blender_close = op.get_blender('close') blender_high = op.get_blender('high') self.assertEqual(blender_open, []) self.assertEqual(blender_close, []) self.assertEqual(blender_high, []) def test_property_singal_type(self): """ test property signal_type""" op = qt.Operator() self.assertIsInstance(op.signal_type, str) self.assertEqual(op.signal_type, 'pt') op = qt.Operator(signal_type='ps') self.assertIsInstance(op.signal_type, str) self.assertEqual(op.signal_type, 'ps') op = qt.Operator(signal_type='PS') self.assertEqual(op.signal_type, 'ps') op = qt.Operator(signal_type='proportion signal') self.assertEqual(op.signal_type, 'ps') print(f'"pt" will be the default type if wrong value is given') op = qt.Operator(signal_type='wrong value') self.assertEqual(op.signal_type, 'pt') print(f'test signal_type.setter') op.signal_type = 'ps' self.assertEqual(op.signal_type, 'ps') print(f'test error raising') self.assertRaises(TypeError, setattr, op, 'signal_type', 123) self.assertRaises(ValueError, setattr, op, 'signal_type', 'wrong value') def test_property_op_data_types(self): """ test property op_data_types""" op = qt.Operator() self.assertIsInstance(op.op_data_types, list) self.assertEqual(op.op_data_types, []) op = qt.Operator('macd, dma, trix') dt = op.op_data_types self.assertEqual(dt[0], 'close') op = qt.Operator('macd, cdl') dt = op.op_data_types self.assertEqual(dt[0], 'close') self.assertEqual(dt[1], 'high') self.assertEqual(dt[2], 'low') self.assertEqual(dt[3], 'open') self.assertEqual(dt, ['close', 'high', 'low', 'open']) op.add_strategy('dma') dt = op.op_data_types self.assertEqual(dt[0], 'close') self.assertEqual(dt[1], 'high') self.assertEqual(dt[2], 'low') self.assertEqual(dt[3], 'open') self.assertEqual(dt, ['close', 'high', 'low', 'open']) def test_property_op_data_type_count(self): """ test property op_data_type_count""" op = qt.Operator() self.assertIsInstance(op.op_data_type_count, int) self.assertEqual(op.op_data_type_count, 0) op = qt.Operator('macd, dma, trix') dtn = op.op_data_type_count self.assertEqual(dtn, 1) op = qt.Operator('macd, cdl') dtn = op.op_data_type_count self.assertEqual(dtn, 4) op.add_strategy('dma') dtn = op.op_data_type_count self.assertEqual(dtn, 4) def test_property_op_data_freq(self): """ test property op_data_freq""" op = qt.Operator() self.assertIsInstance(op.op_data_freq, str) self.assertEqual(len(op.op_data_freq), 0) self.assertEqual(op.op_data_freq, '') op = qt.Operator('macd, dma, trix') dtf = op.op_data_freq self.assertIsInstance(dtf, str) self.assertEqual(dtf[0], 'd') op.set_parameter('macd', data_freq='m') dtf = op.op_data_freq self.assertIsInstance(dtf, list) self.assertEqual(len(dtf), 2) self.assertEqual(dtf[0], 'd') self.assertEqual(dtf[1], 'm') def test_property_bt_price_types(self): """ test property bt_price_types""" print('------test property bt_price_tyeps-------') op = qt.Operator() self.assertIsInstance(op.bt_price_types, list) self.assertEqual(len(op.bt_price_types), 0) self.assertEqual(op.bt_price_types, []) op = qt.Operator('macd, dma, trix') btp = op.bt_price_types self.assertIsInstance(btp, list) self.assertEqual(btp[0], 'close') op.set_parameter('macd', price_type='open') btp = op.bt_price_types btpc = op.bt_price_type_count print(f'price_types are \n{btp}') self.assertIsInstance(btp, list) self.assertEqual(len(btp), 2) self.assertEqual(btp[0], 'close') self.assertEqual(btp[1], 'open') self.assertEqual(btpc, 2) op.add_strategies(['dma', 'macd']) op.set_parameter('dma_1', price_type='high') btp = op.bt_price_types btpc = op.bt_price_type_count self.assertEqual(btp[0], 'close') self.assertEqual(btp[1], 'high') self.assertEqual(btp[2], 'open') self.assertEqual(btpc, 3) op.remove_strategy('dma_1') btp = op.bt_price_types btpc = op.bt_price_type_count self.assertEqual(btp[0], 'close') self.assertEqual(btp[1], 'open') self.assertEqual(btpc, 2) op.remove_strategy('macd_1') btp = op.bt_price_types btpc = op.bt_price_type_count self.assertEqual(btp[0], 'close') self.assertEqual(btp[1], 'open') self.assertEqual(btpc, 2) def test_property_op_data_type_list(self): """ test property op_data_type_list""" op = qt.Operator() self.assertIsInstance(op.op_data_type_list, list) self.assertEqual(len(op.op_data_type_list), 0) self.assertEqual(op.op_data_type_list, []) op = qt.Operator('macd, dma, trix, cdl') ohd = op.op_data_type_list print(f'ohd is {ohd}') self.assertIsInstance(ohd, list) self.assertEqual(ohd[0], ['close']) op.set_parameter('macd', data_types='open, close') ohd = op.op_data_type_list print(f'ohd is {ohd}') self.assertIsInstance(ohd, list) self.assertEqual(len(ohd), 4) self.assertEqual(ohd[0], ['open', 'close']) self.assertEqual(ohd[1], ['close']) self.assertEqual(ohd[2], ['close']) self.assertEqual(ohd[3], ['open', 'high', 'low', 'close']) def test_property_op_history_data(self): """ Test this important function to get operation history data that shall be used in signal generation these data are stored in list of nd-arrays, each ndarray represents the data that is needed for each and every strategy """ print(f'------- Test getting operation history data ---------') op = qt.Operator() self.assertIsInstance(op.strategy_blenders, dict) self.assertIsInstance(op.signal_type, str) self.assertEqual(op.strategy_blenders, {}) self.assertEqual(op.op_history_data, {}) self.assertEqual(op.signal_type, 'pt') def test_property_opt_space_par(self): """ test property opt_space_par""" print(f'-----test property opt_space_par--------:\n') op = qt.Operator() self.assertIsInstance(op.opt_space_par, tuple) self.assertIsInstance(op.opt_space_par[0], list) self.assertIsInstance(op.opt_space_par[1], list) self.assertEqual(len(op.opt_space_par), 2) self.assertEqual(op.opt_space_par, ([], [])) op = qt.Operator('macd, dma, trix, cdl') osp = op.opt_space_par print(f'before setting opt_tags opt_space_par is empty:\n' f'osp is {osp}\n') self.assertIsInstance(osp, tuple) self.assertEqual(osp[0], []) self.assertEqual(osp[1], []) op.set_parameter('macd', opt_tag=1) op.set_parameter('dma', opt_tag=1) osp = op.opt_space_par print(f'after setting opt_tags opt_space_par is not empty:\n' f'osp is {osp}\n') self.assertIsInstance(osp, tuple) self.assertEqual(len(osp), 2) self.assertIsInstance(osp[0], list) self.assertIsInstance(osp[1], list) self.assertEqual(len(osp[0]), 6) self.assertEqual(len(osp[1]), 6) self.assertEqual(osp[0], [(10, 250), (10, 250), (10, 250), (10, 250), (10, 250), (10, 250)]) self.assertEqual(osp[1], ['discr', 'discr', 'discr', 'discr', 'discr', 'discr']) def test_property_opt_types(self): """ test property opt_tags""" print(f'-----test property opt_tags--------:\n') op = qt.Operator() self.assertIsInstance(op.opt_tags, list) self.assertEqual(len(op.opt_tags), 0) self.assertEqual(op.opt_tags, []) op = qt.Operator('macd, dma, trix, cdl') otp = op.opt_tags print(f'before setting opt_tags opt_space_par is empty:\n' f'otp is {otp}\n') self.assertIsInstance(otp, list) self.assertEqual(otp, [0, 0, 0, 0]) op.set_parameter('macd', opt_tag=1) op.set_parameter('dma', opt_tag=1) otp = op.opt_tags print(f'after setting opt_tags opt_space_par is not empty:\n' f'otp is {otp}\n') self.assertIsInstance(otp, list) self.assertEqual(len(otp), 4) self.assertEqual(otp, [1, 1, 0, 0]) def test_property_max_window_length(self): """ test property max_window_length""" print(f'-----test property max window length--------:\n') op = qt.Operator() self.assertIsInstance(op.max_window_length, int) self.assertEqual(op.max_window_length, 0) op = qt.Operator('macd, dma, trix, cdl') mwl = op.max_window_length print(f'before setting window_length the value is 270:\n' f'mwl is {mwl}\n') self.assertIsInstance(mwl, int) self.assertEqual(mwl, 270) op.set_parameter('macd', window_length=300) op.set_parameter('dma', window_length=350) mwl = op.max_window_length print(f'after setting window_length the value is new set value:\n' f'mwl is {mwl}\n') self.assertIsInstance(mwl, int) self.assertEqual(mwl, 350) def test_property_bt_price_type_count(self): """ test property bt_price_type_count""" print(f'-----test property bt_price_type_count--------:\n') op = qt.Operator() self.assertIsInstance(op.bt_price_type_count, int) self.assertEqual(op.bt_price_type_count, 0) op = qt.Operator('macd, dma, trix, cdl') otp = op.bt_price_type_count print(f'before setting price_type the price count is 1:\n' f'otp is {otp}\n') self.assertIsInstance(otp, int) self.assertEqual(otp, 1) op.set_parameter('macd', price_type='open') op.set_parameter('dma', price_type='open') otp = op.bt_price_type_count print(f'after setting price_type the price type count is 2:\n' f'otp is {otp}\n') self.assertIsInstance(otp, int) self.assertEqual(otp, 2) def test_property_set(self): """ test all property setters: setting following properties: - strategy_blenders - signal_type other properties can not be set""" print(f'------- Test setting properties ---------') op = qt.Operator() self.assertIsInstance(op.strategy_blenders, dict) self.assertIsInstance(op.signal_type, str) self.assertEqual(op.strategy_blenders, {}) self.assertEqual(op.signal_type, 'pt') op.strategy_blenders = '1 + 2' op.signal_type = 'proportion signal' self.assertEqual(op.strategy_blenders, {}) self.assertEqual(op.signal_type, 'ps') op = qt.Operator('macd, dma, trix, cdl') # TODO: 修改set_parameter(),使下面的用法成立 # a_to_sell.set_parameter('dma, cdl', price_type='open') op.set_parameter('dma', price_type='open') op.set_parameter('cdl', price_type='open') sb = op.strategy_blenders st = op.signal_type self.assertIsInstance(sb, dict) print(f'before setting: strategy_blenders={sb}') self.assertEqual(sb, {}) op.strategy_blenders = '1+2 * 3' sb = op.strategy_blenders print(f'after setting strategy_blender={sb}') self.assertEqual(sb, {'close': ['+', '*', '3', '2', '1'], 'open': ['+', '*', '3', '2', '1']}) op.strategy_blenders = ['1+2', '3-4'] sb = op.strategy_blenders print(f'after setting strategy_blender={sb}') self.assertEqual(sb, {'close': ['+', '2', '1'], 'open': ['-', '4', '3']}) def test_operator_ready(self): """test the method ready of Operator""" op = qt.Operator() print(f'operator is ready? "{op.ready}"') def test_operator_add_strategy(self): """test adding strategies to Operator""" op = qt.Operator('dma, all, urgent') self.assertIsInstance(op, qt.Operator) self.assertIsInstance(op.strategies[0], qt.TimingDMA) self.assertIsInstance(op.strategies[1], qt.SelectingAll) self.assertIsInstance(op.strategies[2], qt.RiconUrgent) self.assertIsInstance(op[0], qt.TimingDMA) self.assertIsInstance(op[1], qt.SelectingAll) self.assertIsInstance(op[2], qt.RiconUrgent) self.assertIsInstance(op['dma'], qt.TimingDMA) self.assertIsInstance(op['all'], qt.SelectingAll) self.assertIsInstance(op['urgent'], qt.RiconUrgent) self.assertEqual(op.strategy_count, 3) print(f'test adding strategies into existing op') print('test adding strategy by string') op.add_strategy('macd') self.assertIsInstance(op.strategies[0], qt.TimingDMA) self.assertIsInstance(op.strategies[3], qt.TimingMACD) self.assertEqual(op.strategy_count, 4) op.add_strategy('random') self.assertIsInstance(op.strategies[0], qt.TimingDMA) self.assertIsInstance(op.strategies[4], qt.SelectingRandom) self.assertEqual(op.strategy_count, 5) test_ls = TestLSStrategy() op.add_strategy(test_ls) self.assertIsInstance(op.strategies[0], qt.TimingDMA) self.assertIsInstance(op.strategies[5], TestLSStrategy) self.assertEqual(op.strategy_count, 6) print(f'Test different instance of objects are added to operator') op.add_strategy('dma') self.assertIsInstance(op.strategies[0], qt.TimingDMA) self.assertIsInstance(op.strategies[6], qt.TimingDMA) self.assertIsNot(op.strategies[0], op.strategies[6]) def test_operator_add_strategies(self): """ etst adding multiple strategies to Operator""" op = qt.Operator('dma, all, urgent') self.assertEqual(op.strategy_count, 3) print('test adding multiple strategies -- adding strategy by list of strings') op.add_strategies(['dma', 'macd']) self.assertEqual(op.strategy_count, 5) self.assertIsInstance(op.strategies[0], qt.TimingDMA) self.assertIsInstance(op.strategies[3], qt.TimingDMA) self.assertIsInstance(op.strategies[4], qt.TimingMACD) print('test adding multiple strategies -- adding strategy by comma separated strings') op.add_strategies('dma, macd') self.assertEqual(op.strategy_count, 7) self.assertIsInstance(op.strategies[0], qt.TimingDMA) self.assertIsInstance(op.strategies[5], qt.TimingDMA) self.assertIsInstance(op.strategies[6], qt.TimingMACD) print('test adding multiple strategies -- adding strategy by list of strategies') op.add_strategies([qt.TimingDMA(), qt.TimingMACD()]) self.assertEqual(op.strategy_count, 9) self.assertIsInstance(op.strategies[0], qt.TimingDMA) self.assertIsInstance(op.strategies[7], qt.TimingDMA) self.assertIsInstance(op.strategies[8], qt.TimingMACD) print('test adding multiple strategies -- adding strategy by list of strategy and str') op.add_strategies(['DMA', qt.TimingMACD()]) self.assertEqual(op.strategy_count, 11) self.assertIsInstance(op.strategies[0], qt.TimingDMA) self.assertIsInstance(op.strategies[9], qt.TimingDMA) self.assertIsInstance(op.strategies[10], qt.TimingMACD) self.assertIsNot(op.strategies[0], op.strategies[9]) self.assertIs(type(op.strategies[0]), type(op.strategies[9])) print('test adding fault data') self.assertRaises(AssertionError, op.add_strategies, 123) self.assertRaises(AssertionError, op.add_strategies, None) def test_opeartor_remove_strategy(self): """ test method remove strategy""" op = qt.Operator('dma, all, urgent') op.add_strategies(['dma', 'macd']) op.add_strategies(['DMA', TestLSStrategy()]) self.assertEqual(op.strategy_count, 7) print('test removing strategies from Operator') op.remove_strategy('dma') self.assertEqual(op.strategy_count, 6) self.assertEqual(op.strategy_ids, ['all', 'urgent', 'dma_1', 'macd', 'dma_2', 'custom']) self.assertEqual(op.strategies[0], op['all']) self.assertEqual(op.strategies[1], op['urgent']) self.assertEqual(op.strategies[2], op['dma_1']) self.assertEqual(op.strategies[3], op['macd']) self.assertEqual(op.strategies[4], op['dma_2']) self.assertEqual(op.strategies[5], op['custom']) op.remove_strategy('dma_1') self.assertEqual(op.strategy_count, 5) self.assertEqual(op.strategy_ids, ['all', 'urgent', 'macd', 'dma_2', 'custom']) self.assertEqual(op.strategies[0], op['all']) self.assertEqual(op.strategies[1], op['urgent']) self.assertEqual(op.strategies[2], op['macd']) self.assertEqual(op.strategies[3], op['dma_2']) self.assertEqual(op.strategies[4], op['custom']) def test_opeartor_clear_strategies(self): """ test operator clear strategies""" op = qt.Operator('dma, all, urgent') op.add_strategies(['dma', 'macd']) op.add_strategies(['DMA', TestLSStrategy()]) self.assertEqual(op.strategy_count, 7) print('test removing strategies from Operator') op.clear_strategies() self.assertEqual(op.strategy_count, 0) self.assertEqual(op.strategy_ids, []) op.add_strategy('dma', pars=(12, 123, 25)) self.assertEqual(op.strategy_count, 1) self.assertEqual(op.strategy_ids, ['dma']) self.assertEqual(type(op.strategies[0]), TimingDMA) self.assertEqual(op.strategies[0].pars, (12, 123, 25)) op.clear_strategies() self.assertEqual(op.strategy_count, 0) self.assertEqual(op.strategy_ids, []) def test_operator_prepare_data(self): """test processes that related to prepare data""" test_ls = TestLSStrategy() test_sel = TestSelStrategy() test_sig = TestSigStrategy() self.op = qt.Operator(strategies=[test_ls, test_sel, test_sig]) too_early_cash = qt.CashPlan(dates='2016-01-01', amounts=10000) early_cash = qt.CashPlan(dates='2016-07-01', amounts=10000) on_spot_cash = qt.CashPlan(dates='2016-07-08', amounts=10000) no_trade_cash = qt.CashPlan(dates='2016-07-08, 2016-07-30, 2016-08-11, 2016-09-03', amounts=[10000, 10000, 10000, 10000]) # 在所有策略的参数都设置好之前调用prepare_data会发生assertion Error self.assertRaises(AssertionError, self.op.prepare_data, hist_data=self.hp1, cash_plan=qt.CashPlan(dates='2016-07-08', amounts=10000)) late_cash = qt.CashPlan(dates='2016-12-31', amounts=10000) multi_cash = qt.CashPlan(dates='2016-07-08, 2016-08-08', amounts=[10000, 10000]) self.op.set_parameter(stg_id='custom', pars={'000300': (5, 10.), '000400': (5, 10.), '000500': (5, 6.)}) self.assertEqual(self.op.strategies[0].pars, {'000300': (5, 10.), '000400': (5, 10.), '000500': (5, 6.)}) self.op.set_parameter(stg_id='custom_1', pars=()) self.assertEqual(self.op.strategies[1].pars, ()), self.op.set_parameter(stg_id='custom_2', pars=(0.2, 0.02, -0.02)) self.assertEqual(self.op.strategies[2].pars, (0.2, 0.02, -0.02)), self.op.prepare_data(hist_data=self.hp1, cash_plan=on_spot_cash) self.assertIsInstance(self.op._op_history_data, dict) self.assertEqual(len(self.op._op_history_data), 3) # test if automatic strategy blenders are set self.assertEqual(self.op.strategy_blenders, {'close': ['+', '2', '+', '1', '0']}) tim_hist_data = self.op._op_history_data['custom'] sel_hist_data = self.op._op_history_data['custom_1'] ric_hist_data = self.op._op_history_data['custom_2'] print(f'in test_prepare_data in TestOperator:') print('selecting history data:\n', sel_hist_data) print('originally passed data in correct sequence:\n', self.test_data_3D[:, 3:, [2, 3, 0]]) print('difference is \n', sel_hist_data - self.test_data_3D[:, :, [2, 3, 0]]) self.assertTrue(np.allclose(sel_hist_data, self.test_data_3D[:, :, [2, 3, 0]], equal_nan=True)) self.assertTrue(np.allclose(tim_hist_data, self.test_data_3D, equal_nan=True)) self.assertTrue(np.allclose(ric_hist_data, self.test_data_3D[:, 3:, :], equal_nan=True)) # raises Value Error if empty history panel is given empty_hp = qt.HistoryPanel() correct_hp = qt.HistoryPanel(values=np.random.randint(10, size=(3, 50, 4)), columns=self.types, levels=self.shares, rows=self.date_indices) too_many_shares = qt.HistoryPanel(values=np.random.randint(10, size=(5, 50, 4))) too_many_types = qt.HistoryPanel(values=np.random.randint(10, size=(3, 50, 5))) # raises Error when history panel is empty self.assertRaises(ValueError, self.op.prepare_data, empty_hp, on_spot_cash) # raises Error when first investment date is too early self.assertRaises(AssertionError, self.op.prepare_data, correct_hp, early_cash) # raises Error when last investment date is too late self.assertRaises(AssertionError, self.op.prepare_data, correct_hp, late_cash) # raises Error when some of the investment dates are on no-trade-days self.assertRaises(ValueError, self.op.prepare_data, correct_hp, no_trade_cash) # raises Error when number of shares in history data does not fit self.assertRaises(AssertionError, self.op.prepare_data, too_many_shares, on_spot_cash) # raises Error when too early cash investment date self.assertRaises(AssertionError, self.op.prepare_data, correct_hp, too_early_cash) # raises Error when number of d_types in history data does not fit self.assertRaises(AssertionError, self.op.prepare_data, too_many_types, on_spot_cash) # test the effect of data type sequence in strategy definition def test_operator_generate(self): """ Test signal generation process of operator objects :return: """ # 使用test模块的自定义策略生成三种交易策略 test_ls = TestLSStrategy() test_sel = TestSelStrategy() test_sel2 = TestSelStrategyDiffTime() test_sig = TestSigStrategy() print('--Test PT type signal generation--') # 测试PT类型的信号生成: # 创建一个Operator对象,信号类型为PT(比例目标信号) # 这个Operator对象包含两个策略,分别为LS-Strategy以及Sel-Strategy,代表择时和选股策略 # 两个策略分别生成PT信号后混合成一个信号输出 self.op = qt.Operator(strategies=[test_ls, test_sel]) self.op.set_parameter(stg_id='custom', pars={'000010': (5, 10.), '000030': (5, 10.), '000039': (5, 6.)}) self.op.set_parameter(stg_id=1, pars=()) # self.a_to_sell.set_blender(blender='0+1+2') self.op.prepare_data(hist_data=self.hp1, cash_plan=qt.CashPlan(dates='2016-07-08', amounts=10000)) print('--test operator information in normal mode--') self.op.info() self.assertEqual(self.op.strategy_blenders, {'close': ['+', '1', '0']}) self.op.set_blender(None, '0*1') self.assertEqual(self.op.strategy_blenders, {'close': ['*', '1', '0']}) print('--test operation signal created in Proportional Target (PT) Mode--') op_list = self.op.create_signal(hist_data=self.hp1) self.assertTrue(isinstance(op_list, HistoryPanel)) backtest_price_types = op_list.htypes self.assertEqual(backtest_price_types[0], 'close') self.assertEqual(op_list.shape, (3, 45, 1)) reduced_op_list = op_list.values.squeeze().T print(f'op_list created, it is a 3 share/45 days/1 htype array, to make comparison happen, \n' f'it will be squeezed to a 2-d array to compare on share-wise:\n' f'{reduced_op_list}') target_op_values = np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.5, 0.0, 0.0], [0.5, 0.0, 0.0], [0.5, 0.0, 0.0], [0.5, 0.0, 0.0], [0.5, 0.0, 0.0], [0.5, 0.0, 0.0], [0.5, 0.0, 0.0], [0.5, 0.0, 0.0], [0.5, 0.0, 0.0], [0.5, 0.0, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.0, 0.0], [0.5, 0.0, 0.0], [0.5, 0.5, 0.0], [0.0, 0.5, 0.0], [0.0, 0.5, 0.0], [0.0, 0.5, 0.0], [0.0, 0.5, 0.0], [0.0, 0.5, 0.0], [0.0, 0.5, 0.0], [0.0, 0.5, 0.0], [0.0, 0.5, 0.0], [0.0, 0.5, 0.0], [0.0, 0.5, 0.0], [0.0, 0.5, 0.0], [0.0, 0.5, 0.0], [0.0, 0.5, 0.0], [0.0, 0.5, 0.0], [0.0, 0.5, 0.0], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.0], [0.0, 0.5, 0.0], [0.0, 0.5, 0.0]]) self.assertTrue(np.allclose(target_op_values, reduced_op_list, equal_nan=True)) print('--Test two separate signal generation for different price types--') # 测试两组PT类型的信号生成: # 在Operator对象中增加两个SigStrategy策略,策略类型相同但是策略的参数不同,回测价格类型为"OPEN" # Opeartor应该生成两组交易信号,分别用于"close"和"open"两中不同的价格类型 # 这里需要重新生成两个新的交易策略对象,否则在op的strategies列表中产生重复的对象引用,从而引起错误 test_ls = TestLSStrategy() test_sel = TestSelStrategy() self.op.add_strategies([test_ls, test_sel]) self.op.set_parameter(stg_id='custom_2', price_type='open') self.op.set_parameter(stg_id='custom_3', price_type='open') self.assertEqual(self.op['custom'].price_type, 'close') self.assertEqual(self.op['custom_2'].price_type, 'open') self.op.set_parameter(stg_id='custom_2', pars={'000010': (5, 10.), '000030': (5, 10.), '000039': (5, 6.)}) self.op.set_parameter(stg_id='custom_3', pars=()) self.op.set_blender(blender='0 or 1', price_type='open') self.op.prepare_data(hist_data=self.hp1, cash_plan=qt.CashPlan(dates='2016-07-08', amounts=10000)) print('--test how operator information is printed out--') self.op.info() self.assertEqual(self.op.strategy_blenders, {'close': ['*', '1', '0'], 'open': ['or', '1', '0']}) print('--test opeartion signal created in Proportional Target (PT) Mode--') op_list = self.op.create_signal(hist_data=self.hp1) self.assertTrue(isinstance(op_list, HistoryPanel)) signal_close = op_list['close'].squeeze().T signal_open = op_list['open'].squeeze().T self.assertEqual(signal_close.shape, (45, 3)) self.assertEqual(signal_open.shape, (45, 3)) target_op_close = np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.5, 0.0, 0.0], [0.5, 0.0, 0.0], [0.5, 0.0, 0.0], [0.5, 0.0, 0.0], [0.5, 0.0, 0.0], [0.5, 0.0, 0.0], [0.5, 0.0, 0.0], [0.5, 0.0, 0.0], [0.5, 0.0, 0.0], [0.5, 0.0, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.0, 0.0], [0.5, 0.0, 0.0], [0.5, 0.5, 0.0], [0.0, 0.5, 0.0], [0.0, 0.5, 0.0], [0.0, 0.5, 0.0], [0.0, 0.5, 0.0], [0.0, 0.5, 0.0], [0.0, 0.5, 0.0], [0.0, 0.5, 0.0], [0.0, 0.5, 0.0], [0.0, 0.5, 0.0], [0.0, 0.5, 0.0], [0.0, 0.5, 0.0], [0.0, 0.5, 0.0], [0.0, 0.5, 0.0], [0.0, 0.5, 0.0], [0.0, 0.5, 0.0], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.0], [0.0, 0.5, 0.0], [0.0, 0.5, 0.0]]) target_op_open = np.array([[0.5, 0.5, 1.0], [0.5, 0.5, 1.0], [1.0, 0.5, 1.0], [1.0, 0.5, 1.0], [1.0, 0.5, 1.0], [1.0, 0.5, 1.0], [1.0, 0.5, 1.0], [1.0, 0.5, 1.0], [1.0, 0.5, 1.0], [1.0, 0.5, 1.0], [1.0, 0.5, 1.0], [1.0, 0.5, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 0.0], [1.0, 1.0, 0.0], [1.0, 1.0, 0.0], [1.0, 0.5, 0.0], [1.0, 0.5, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.5], [0.0, 1.0, 0.5], [0.0, 1.0, 0.5], [0.0, 1.0, 0.5], [0.0, 1.0, 0.5], [0.0, 1.0, 0.5], [0.0, 1.0, 0.5], [0.5, 1.0, 0.0], [0.5, 1.0, 0.0], [0.5, 1.0, 1.0], [0.5, 1.0, 1.0], [0.5, 1.0, 1.0], [0.5, 1.0, 1.0], [0.5, 1.0, 1.0], [0.5, 1.0, 1.0], [0.0, 1.0, 1.0], [0.0, 1.0, 1.0], [0.0, 1.0, 1.0], [0.0, 1.0, 1.0], [0.0, 1.0, 1.0], [0.0, 1.0, 1.0], [0.5, 1.0, 1.0], [0.5, 1.0, 1.0], [0.5, 1.0, 1.0]]) signal_pairs = [[list(sig1), list(sig2), sig1 == sig2] for sig1, sig2 in zip(list(target_op_close), list(signal_close))] print(f'signals side by side:\n' f'{signal_pairs}') self.assertTrue(np.allclose(target_op_close, signal_close, equal_nan=True)) signal_pairs = [[list(sig1), list(sig2), sig1 == sig2] for sig1, sig2 in zip(list(target_op_open), list(signal_open))] print(f'signals side by side:\n' f'{signal_pairs}') self.assertTrue(np.allclose(target_op_open, signal_open, equal_nan=True)) print('--Test two separate signal generation for different price types--') # 更多测试集合 def test_stg_parameter_setting(self): """ test setting parameters of strategies test the method set_parameters :return: """ op = qt.Operator(strategies='dma, all, urgent') print(op.strategies, '\n', [qt.TimingDMA, qt.SelectingAll, qt.RiconUrgent]) print(f'info of Timing strategy in new op: \n{op.strategies[0].info()}') # TODO: allow set_parameters to a list of strategies or str-listed strategies # TODO: allow set_parameters to all strategies of specific bt price type print(f'Set up strategy parameters by strategy id') op.set_parameter('dma', pars=(5, 10, 5), opt_tag=1, par_boes=((5, 10), (5, 15), (10, 15)), window_length=10, data_types=['close', 'open', 'high']) op.set_parameter('all', window_length=20) op.set_parameter('all', price_type='high') print(f'Can also set up strategy parameters by strategy index') op.set_parameter(2, price_type='open') op.set_parameter(2, opt_tag=1, pars=(9, -0.09), window_length=10) self.assertEqual(op.strategies[0].pars, (5, 10, 5)) self.assertEqual(op.strategies[0].par_boes, ((5, 10), (5, 15), (10, 15))) self.assertEqual(op.strategies[2].pars, (9, -0.09)) self.assertEqual(op.op_data_freq, 'd') self.assertEqual(op.op_data_types, ['close', 'high', 'open']) self.assertEqual(op.opt_space_par, ([(5, 10), (5, 15), (10, 15), (1, 40), (-0.5, 0.5)], ['discr', 'discr', 'discr', 'discr', 'conti'])) self.assertEqual(op.max_window_length, 20) print(f'KeyError will be raised if wrong strategy id is given') self.assertRaises(KeyError, op.set_parameter, stg_id='t-1', pars=(1, 2)) self.assertRaises(KeyError, op.set_parameter, stg_id='wrong_input', pars=(1, 2)) print(f'ValueError will be raised if parameter can be set') self.assertRaises(ValueError, op.set_parameter, stg_id=0, pars=('wrong input', 'wrong input')) # test blenders of different price types # test setting blenders to different price types # TODO: to allow operands like "and", "or", "not", "xor" # a_to_sell.set_blender('close', '0 and 1 or 2') # self.assertEqual(a_to_sell.get_blender('close'), 'str-1.2') self.assertEqual(op.bt_price_types, ['close', 'high', 'open']) op.set_blender('open', '0 & 1 | 2') self.assertEqual(op.get_blender('open'), ['|', '2', '&', '1', '0']) op.set_blender('high', '(0|1) & 2') self.assertEqual(op.get_blender('high'), ['&', '2', '|', '1', '0']) op.set_blender('close', '0 & 1 | 2') self.assertEqual(op.get_blender(), {'close': ['|', '2', '&', '1', '0'], 'high': ['&', '2', '|', '1', '0'], 'open': ['|', '2', '&', '1', '0']}) self.assertEqual(op.opt_space_par, ([(5, 10), (5, 15), (10, 15), (1, 40), (-0.5, 0.5)], ['discr', 'discr', 'discr', 'discr', 'conti'])) self.assertEqual(op.opt_tags, [1, 0, 1]) def test_signal_blend(self): self.assertEqual(blender_parser('0 & 1'), ['&', '1', '0']) self.assertEqual(blender_parser('0 or 1'), ['or', '1', '0']) self.assertEqual(blender_parser('0 & 1 | 2'), ['|', '2', '&', '1', '0']) blender = blender_parser('0 & 1 | 2') self.assertEqual(signal_blend([1, 1, 1], blender), 1) self.assertEqual(signal_blend([1, 0, 1], blender), 1) self.assertEqual(signal_blend([1, 1, 0], blender), 1) self.assertEqual(signal_blend([0, 1, 1], blender), 1) self.assertEqual(signal_blend([0, 0, 1], blender), 1) self.assertEqual(signal_blend([1, 0, 0], blender), 0) self.assertEqual(signal_blend([0, 1, 0], blender), 0) self.assertEqual(signal_blend([0, 0, 0], blender), 0) # parse: '0 & ( 1 | 2 )' self.assertEqual(blender_parser('0 & ( 1 | 2 )'), ['&', '|', '2', '1', '0']) blender = blender_parser('0 & ( 1 | 2 )') self.assertEqual(signal_blend([1, 1, 1], blender), 1) self.assertEqual(signal_blend([1, 0, 1], blender), 1) self.assertEqual(signal_blend([1, 1, 0], blender), 1) self.assertEqual(signal_blend([0, 1, 1], blender), 0) self.assertEqual(signal_blend([0, 0, 1], blender), 0) self.assertEqual(signal_blend([1, 0, 0], blender), 0) self.assertEqual(signal_blend([0, 1, 0], blender), 0) self.assertEqual(signal_blend([0, 0, 0], blender), 0) # parse: '(1-2)/3 + 0' self.assertEqual(blender_parser('(1-2)/3 + 0'), ['+', '0', '/', '3', '-', '2', '1']) blender = blender_parser('(1-2)/3 + 0') self.assertEqual(signal_blend([5, 9, 1, 4], blender), 7) # pars: '(0*1/2*(3+4))+5*(6+7)-8' self.assertEqual(blender_parser('(0*1/2*(3+4))+5*(6+7)-8'), ['-', '8', '+', '*', '+', '7', '6', '5', '*', '+', '4', '3', '/', '2', '*', '1', '0']) blender = blender_parser('(0*1/2*(3+4))+5*(6+7)-8') self.assertEqual(signal_blend([1, 1, 1, 1, 1, 1, 1, 1, 1], blender), 3) self.assertEqual(signal_blend([2, 1, 4, 3, 5, 5, 2, 2, 10], blender), 14) # parse: '0/max(2,1,3 + 5)+4' self.assertEqual(blender_parser('0/max(2,1,3 + 5)+4'), ['+', '4', '/', 'max(3)', '+', '5', '3', '1', '2', '0']) blender = blender_parser('0/max(2,1,3 + 5)+4') self.assertEqual(signal_blend([8.0, 4, 3, 5.0, 0.125, 5], blender), 0.925) self.assertEqual(signal_blend([2, 1, 4, 3, 5, 5, 2, 2, 10], blender), 5.25) print('speed test') import time st = time.time() blender = blender_parser('0+max(1,2,(3+4)*5, max(6, (7+8)*9), 10-11) * (12+13)') res = [] for i in range(10000): res = signal_blend([1, 1, 2, 3, 4, 5, 3, 4, 5, 6, 7, 8, 2, 3], blender) et = time.time() print(f'total time for RPN processing: {et - st}, got result: {res}') blender = blender_parser("0 + 1 * 2") self.assertEqual(signal_blend([1, 2, 3], blender), 7) blender = blender_parser("(0 + 1) * 2") self.assertEqual(signal_blend([1, 2, 3], blender), 9) blender = blender_parser("(0+1) * 2") self.assertEqual(signal_blend([1, 2, 3], blender), 9) blender = blender_parser("(0 + 1) * 2") self.assertEqual(signal_blend([1, 2, 3], blender), 9) # TODO: 目前对于-(1+2)这样的表达式还无法处理 # self.a_to_sell.set_blender('selecting', "-(0 + 1) * 2") # self.assertEqual(self.a_to_sell.signal_blend([1, 2, 3]), -9) blender = blender_parser("(0-1)/2 + 3") print(f'RPN of notation: "(0-1)/2 + 3" is:\n' f'{" ".join(blender[::-1])}') self.assertAlmostEqual(signal_blend([1, 2, 3, 0.0], blender), -0.33333333) blender = blender_parser("0 + 1 / 2") print(f'RPN of notation: "0 + 1 / 2" is:\n' f'{" ".join(blender[::-1])}') self.assertAlmostEqual(signal_blend([1, math.pi, 4], blender), 1.78539816) blender = blender_parser("(0 + 1) / 2") print(f'RPN of notation: "(0 + 1) / 2" is:\n' f'{" ".join(blender[::-1])}') self.assertEqual(signal_blend([1, 2, 3], blender), 1) blender = blender_parser("(0 + 1 * 2) / 3") print(f'RPN of notation: "(0 + 1 * 2) / 3" is:\n' f'{" ".join(blender[::-1])}') self.assertAlmostEqual(signal_blend([3, math.e, 10, 10], blender), 3.0182818284590454) blender = blender_parser("0 / 1 * 2") print(f'RPN of notation: "0 / 1 * 2" is:\n' f'{" ".join(blender[::-1])}') self.assertEqual(signal_blend([1, 3, 6], blender), 2) blender = blender_parser("(0 - 1 + 2) * 4") print(f'RPN of notation: "(0 - 1 + 2) * 4" is:\n' f'{" ".join(blender[::-1])}') self.assertAlmostEqual(signal_blend([1, 1, -1, np.nan, math.pi], blender), -3.141592653589793) blender = blender_parser("0 * 1") print(f'RPN of notation: "0 * 1" is:\n' f'{" ".join(blender[::-1])}') self.assertAlmostEqual(signal_blend([math.pi, math.e], blender), 8.539734222673566) blender = blender_parser('abs(3-sqrt(2) / cos(1))') print(f'RPN of notation: "abs(3-sqrt(2) / cos(1))" is:\n' f'{" ".join(blender[::-1])}') self.assertEqual(blender, ['abs(1)', '-', '/', 'cos(1)', '1', 'sqrt(1)', '2', '3']) blender = blender_parser('0/max(2,1,3 + 5)+4') print(f'RPN of notation: "0/max(2,1,3 + 5)+4" is:\n' f'{" ".join(blender[::-1])}') self.assertEqual(blender, ['+', '4', '/', 'max(3)', '+', '5', '3', '1', '2', '0']) blender = blender_parser('1 + sum(1,2,3+3, sum(1, 2) + 3) *5') print(f'RPN of notation: "1 + sum(1,2,3+3, sum(1, 2) + 3) *5" is:\n' f'{" ".join(blender[::-1])}') self.assertEqual(blender, ['+', '*', '5', 'sum(4)', '+', '3', 'sum(2)', '2', '1', '+', '3', '3', '2', '1', '1']) blender = blender_parser('1+sum(1,2,(3+5)*4, sum(3, (4+5)*6), 7-8) * (2+3)') print(f'RPN of notation: "1+sum(1,2,(3+5)*4, sum(3, (4+5)*6), 7-8) * (2+3)" is:\n' f'{" ".join(blender[::-1])}') self.assertEqual(blender, ['+', '*', '+', '3', '2', 'sum(5)', '-', '8', '7', 'sum(2)', '*', '6', '+', '5', '4', '3', '*', '4', '+', '5', '3', '2', '1', '1']) # TODO: ndarray type of signals to be tested: def test_set_opt_par(self): """ test setting opt pars in batch""" print(f'--------- Testing setting Opt Pars: set_opt_par -------') op = qt.Operator('dma, random, crossline') op.set_parameter('dma', pars=(5, 10, 5), opt_tag=1, par_boes=((5, 10), (5, 15), (10, 15)), window_length=10, data_types=['close', 'open', 'high']) self.assertEqual(op.strategies[0].pars, (5, 10, 5)) self.assertEqual(op.strategies[1].pars, (0.5,)) self.assertEqual(op.strategies[2].pars, (35, 120, 10, 'buy')) self.assertEqual(op.opt_tags, [1, 0, 0]) op.set_opt_par((5, 12, 9)) self.assertEqual(op.strategies[0].pars, (5, 12, 9)) self.assertEqual(op.strategies[1].pars, (0.5,)) self.assertEqual(op.strategies[2].pars, (35, 120, 10, 'buy')) op.set_parameter('crossline', pars=(5, 10, 5, 'sell'), opt_tag=1, par_boes=((5, 10), (5, 15), (10, 15), ('buy', 'sell', 'none')), window_length=10, data_types=['close', 'open', 'high']) self.assertEqual(op.opt_tags, [1, 0, 1]) op.set_opt_par((5, 12, 9, 8, 26, 9, 'buy')) self.assertEqual(op.strategies[0].pars, (5, 12, 9)) self.assertEqual(op.strategies[1].pars, (0.5,)) self.assertEqual(op.strategies[2].pars, (8, 26, 9, 'buy')) op.set_opt_par((9, 200, 155, 8, 26, 9, 'buy', 5, 12, 9)) self.assertEqual(op.strategies[0].pars, (9, 200, 155)) self.assertEqual(op.strategies[1].pars, (0.5,)) self.assertEqual(op.strategies[2].pars, (8, 26, 9, 'buy')) # test set_opt_par when opt_tag is set to be 2 (enumerate type of parameters) op.set_parameter('crossline', pars=(5, 10, 5, 'sell'), opt_tag=2, par_boes=((5, 10), (5, 15), (10, 15), ('buy', 'sell', 'none')), window_length=10, data_types=['close', 'open', 'high']) self.assertEqual(op.opt_tags, [1, 0, 2]) self.assertEqual(op.strategies[0].pars, (9, 200, 155)) self.assertEqual(op.strategies[1].pars, (0.5,)) self.assertEqual(op.strategies[2].pars, (5, 10, 5, 'sell')) op.set_opt_par((5, 12, 9, (8, 26, 9, 'buy'))) self.assertEqual(op.strategies[0].pars, (5, 12, 9)) self.assertEqual(op.strategies[1].pars, (0.5,)) self.assertEqual(op.strategies[2].pars, (8, 26, 9, 'buy')) # Test Errors # Not enough values for parameter op.set_parameter('crossline', opt_tag=1) self.assertRaises(ValueError, op.set_opt_par, (5, 12, 9, 8)) # wrong type of input self.assertRaises(AssertionError, op.set_opt_par, [5, 12, 9, 7, 15, 12, 'sell']) def test_stg_attribute_get_and_set(self): self.stg = qt.TimingCrossline() self.stg_type = 'R-TIMING' self.stg_name = "CROSSLINE" self.stg_text = 'Moving average crossline strategy, determine long/short position according to the cross ' \ 'point' \ ' of long and short term moving average prices ' self.pars = (35, 120, 10, 'buy') self.par_boes = [(10, 250), (10, 250), (1, 100), ('buy', 'sell', 'none')] self.par_count = 4 self.par_types = ['discr', 'discr', 'conti', 'enum'] self.opt_tag = 0 self.data_types = ['close'] self.data_freq = 'd' self.sample_freq = 'd' self.window_length = 270 self.assertEqual(self.stg.stg_type, self.stg_type) self.assertEqual(self.stg.stg_name, self.stg_name) self.assertEqual(self.stg.stg_text, self.stg_text) self.assertEqual(self.stg.pars, self.pars) self.assertEqual(self.stg.par_types, self.par_types) self.assertEqual(self.stg.par_boes, self.par_boes) self.assertEqual(self.stg.par_count, self.par_count) self.assertEqual(self.stg.opt_tag, self.opt_tag) self.assertEqual(self.stg.data_freq, self.data_freq) self.assertEqual(self.stg.sample_freq, self.sample_freq) self.assertEqual(self.stg.data_types, self.data_types) self.assertEqual(self.stg.window_length, self.window_length) self.stg.stg_name = 'NEW NAME' self.stg.stg_text = 'NEW TEXT' self.assertEqual(self.stg.stg_name, 'NEW NAME') self.assertEqual(self.stg.stg_text, 'NEW TEXT') self.stg.pars = (1, 2, 3, 4) self.assertEqual(self.stg.pars, (1, 2, 3, 4)) self.stg.par_count = 3 self.assertEqual(self.stg.par_count, 3) self.stg.par_boes = [(1, 10), (1, 10), (1, 10), (1, 10)] self.assertEqual(self.stg.par_boes, [(1, 10), (1, 10), (1, 10), (1, 10)]) self.stg.par_types = ['conti', 'conti', 'discr', 'enum'] self.assertEqual(self.stg.par_types, ['conti', 'conti', 'discr', 'enum']) self.stg.par_types = 'conti, conti, discr, conti' self.assertEqual(self.stg.par_types, ['conti', 'conti', 'discr', 'conti']) self.stg.data_types = 'close, open' self.assertEqual(self.stg.data_types, ['close', 'open']) self.stg.data_types = ['close', 'high', 'low'] self.assertEqual(self.stg.data_types, ['close', 'high', 'low']) self.stg.data_freq = 'w' self.assertEqual(self.stg.data_freq, 'w') self.stg.window_length = 300 self.assertEqual(self.stg.window_length, 300) def test_rolling_timing(self): stg = TestLSStrategy() stg_pars = {'000100': (5, 10), '000200': (5, 10), '000300': (5, 6)} stg.set_pars(stg_pars) history_data = self.hp1.values output = stg.generate(hist_data=history_data) self.assertIsInstance(output, np.ndarray) self.assertEqual(output.shape, (45, 3)) lsmask = np.array([[0., 0., 1.], [0., 0., 1.], [1., 0., 1.], [1., 0., 1.], [1., 0., 1.], [1., 0., 1.], [1., 0., 1.], [1., 0., 1.], [1., 0., 1.], [1., 0., 1.], [1., 0., 1.], [1., 0., 1.], [1., 1., 1.], [1., 1., 1.], [1., 1., 1.], [1., 1., 0.], [1., 1., 0.], [1., 1., 0.], [1., 0., 0.], [1., 0., 0.], [1., 1., 0.], [0., 1., 0.], [0., 1., 0.], [0., 1., 0.], [0., 1., 0.], [0., 1., 0.], [0., 1., 0.], [0., 1., 0.], [0., 1., 0.], [0., 1., 0.], [0., 1., 1.], [0., 1., 1.], [0., 1., 1.], [0., 1., 1.], [0., 1., 1.], [0., 1., 1.], [0., 1., 1.], [0., 1., 1.], [0., 1., 1.], [0., 1., 1.], [0., 1., 1.], [0., 1., 1.], [0., 1., 1.], [0., 1., 1.], [0., 1., 1.]]) # TODO: Issue to be solved: the np.nan value are converted to 0 in the lsmask,这样做可能会有意想不到的后果 # TODO: 需要解决nan值的问题 self.assertEqual(output.shape, lsmask.shape) self.assertTrue(np.allclose(output, lsmask, equal_nan=True)) def test_sel_timing(self): stg = TestSelStrategy() stg_pars = () stg.set_pars(stg_pars) history_data = self.hp1['high, low, close', :, :] seg_pos, seg_length, seg_count = stg._seg_periods(dates=self.hp1.hdates, freq=stg.sample_freq) self.assertEqual(list(seg_pos), [0, 5, 11, 19, 26, 33, 41, 47, 49]) self.assertEqual(list(seg_length), [5, 6, 8, 7, 7, 8, 6, 2]) self.assertEqual(seg_count, 8) output = stg.generate(hist_data=history_data, shares=self.hp1.shares, dates=self.hp1.hdates) self.assertIsInstance(output, np.ndarray) self.assertEqual(output.shape, (45, 3)) selmask = np.array([[0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0]]) self.assertEqual(output.shape, selmask.shape) self.assertTrue(np.allclose(output, selmask)) def test_simple_timing(self): stg = TestSigStrategy() stg_pars = (0.2, 0.02, -0.02) stg.set_pars(stg_pars) history_data = self.hp1['close, open, high, low', :, 3:50] output = stg.generate(hist_data=history_data, shares=self.shares, dates=self.date_indices) self.assertIsInstance(output, np.ndarray) self.assertEqual(output.shape, (45, 3)) sigmatrix = np.array([[0.0, 1.0, 0.0], [0.0, 0.0, 0.0], [0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, -1.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [-1.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 1.0], [0.0, 1.0, 0.0], [0.0, 1.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, -1.0], [0.0, 0.0, 0.0], [0.0, 1.0, 0.0]]) side_by_side_array = np.array([[i, out_line, sig_line] for i, out_line, sig_line in zip(range(len(output)), output, sigmatrix)]) print(f'output and signal matrix lined up side by side is \n' f'{side_by_side_array}') self.assertEqual(sigmatrix.shape, output.shape) self.assertTrue(np.allclose(output, sigmatrix)) def test_sel_finance(self): """Test selecting_finance strategy, test all built-in strategy parameters""" stg = SelectingFinanceIndicator() stg_pars = (False, 'even', 'greater', 0, 0, 0.67) stg.set_pars(stg_pars) stg.window_length = 5 stg.data_freq = 'd' stg.sample_freq = '10d' stg.sort_ascending = False stg.condition = 'greater' stg.lbound = 0 stg.ubound = 0 stg._poq = 0.67 history_data = self.hp2.values print(f'Start to test financial selection parameter {stg_pars}') seg_pos, seg_length, seg_count = stg._seg_periods(dates=self.hp1.hdates, freq=stg.sample_freq) self.assertEqual(list(seg_pos), [0, 5, 11, 19, 26, 33, 41, 47, 49]) self.assertEqual(list(seg_length), [5, 6, 8, 7, 7, 8, 6, 2]) self.assertEqual(seg_count, 8) output = stg.generate(hist_data=history_data, shares=self.hp1.shares, dates=self.hp1.hdates) self.assertIsInstance(output, np.ndarray) self.assertEqual(output.shape, (45, 3)) selmask = np.array([[0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.5, 0.0, 0.5], [0.5, 0.0, 0.5], [0.5, 0.0, 0.5], [0.5, 0.0, 0.5], [0.5, 0.0, 0.5], [0.5, 0.0, 0.5], [0.5, 0.0, 0.5], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.5, 0.0, 0.5], [0.5, 0.0, 0.5], [0.5, 0.0, 0.5], [0.5, 0.0, 0.5], [0.5, 0.0, 0.5], [0.5, 0.0, 0.5], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0]]) self.assertEqual(output.shape, selmask.shape) self.assertTrue(np.allclose(output, selmask)) # test single factor, get mininum factor stg_pars = (True, 'even', 'less', 1, 1, 0.67) stg.sort_ascending = True stg.condition = 'less' stg.lbound = 1 stg.ubound = 1 stg.set_pars(stg_pars) print(f'Start to test financial selection parameter {stg_pars}') output = stg.generate(hist_data=history_data, shares=self.hp1.shares, dates=self.hp1.hdates) selmask = np.array([[0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.0, 0.5], [0.5, 0.0, 0.5], [0.5, 0.0, 0.5], [0.5, 0.0, 0.5], [0.5, 0.0, 0.5], [0.5, 0.0, 0.5], [0.5, 0.0, 0.5], [0.5, 0.0, 0.5], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.0, 0.5], [0.5, 0.0, 0.5], [0.5, 0.0, 0.5]]) self.assertEqual(output.shape, selmask.shape) self.assertTrue(np.allclose(output, selmask)) # test single factor, get max factor in linear weight stg_pars = (False, 'linear', 'greater', 0, 0, 0.67) stg.sort_ascending = False stg.weighting = 'linear' stg.condition = 'greater' stg.lbound = 0 stg.ubound = 0 stg.set_pars(stg_pars) print(f'Start to test financial selection parameter {stg_pars}') output = stg.generate(hist_data=history_data, shares=self.hp1.shares, dates=self.hp1.hdates) selmask = np.array([[0.00000, 0.33333, 0.66667], [0.00000, 0.33333, 0.66667], [0.00000, 0.33333, 0.66667], [0.00000, 0.33333, 0.66667], [0.00000, 0.33333, 0.66667], [0.00000, 0.33333, 0.66667], [0.00000, 0.66667, 0.33333], [0.00000, 0.66667, 0.33333], [0.00000, 0.66667, 0.33333], [0.00000, 0.66667, 0.33333], [0.00000, 0.66667, 0.33333], [0.00000, 0.66667, 0.33333], [0.00000, 0.66667, 0.33333], [0.00000, 0.66667, 0.33333], [0.00000, 0.33333, 0.66667], [0.00000, 0.33333, 0.66667], [0.00000, 0.33333, 0.66667], [0.00000, 0.33333, 0.66667], [0.00000, 0.33333, 0.66667], [0.00000, 0.33333, 0.66667], [0.00000, 0.33333, 0.66667], [0.33333, 0.00000, 0.66667], [0.33333, 0.00000, 0.66667], [0.33333, 0.00000, 0.66667], [0.33333, 0.00000, 0.66667], [0.33333, 0.00000, 0.66667], [0.33333, 0.00000, 0.66667], [0.33333, 0.00000, 0.66667], [0.00000, 0.00000, 1.00000], [0.00000, 0.00000, 1.00000], [0.00000, 0.00000, 1.00000], [0.00000, 0.00000, 1.00000], [0.00000, 0.00000, 1.00000], [0.00000, 0.00000, 1.00000], [0.00000, 0.00000, 1.00000], [0.00000, 0.00000, 1.00000], [0.33333, 0.00000, 0.66667], [0.33333, 0.00000, 0.66667], [0.33333, 0.00000, 0.66667], [0.33333, 0.00000, 0.66667], [0.33333, 0.00000, 0.66667], [0.33333, 0.00000, 0.66667], [0.33333, 0.66667, 0.00000], [0.33333, 0.66667, 0.00000], [0.33333, 0.66667, 0.00000]]) self.assertEqual(output.shape, selmask.shape) self.assertTrue(np.allclose(output, selmask)) # test single factor, get max factor in linear weight stg_pars = (False, 'proportion', 'greater', 0, 0, 0.67) stg.sort_ascending = False stg.weighting = 'proportion' stg.condition = 'greater' stg.lbound = 0 stg.ubound = 0 stg.set_pars(stg_pars) print(f'Start to test financial selection parameter {stg_pars}') output = stg.generate(hist_data=history_data, shares=self.hp1.shares, dates=self.hp1.hdates) selmask = np.array([[0.00000, 0.08333, 0.91667], [0.00000, 0.08333, 0.91667], [0.00000, 0.08333, 0.91667], [0.00000, 0.08333, 0.91667], [0.00000, 0.08333, 0.91667], [0.00000, 0.08333, 0.91667], [0.00000, 0.91667, 0.08333], [0.00000, 0.91667, 0.08333], [0.00000, 0.91667, 0.08333], [0.00000, 0.91667, 0.08333], [0.00000, 0.91667, 0.08333], [0.00000, 0.91667, 0.08333], [0.00000, 0.91667, 0.08333], [0.00000, 0.91667, 0.08333], [0.00000, 0.50000, 0.50000], [0.00000, 0.50000, 0.50000], [0.00000, 0.50000, 0.50000], [0.00000, 0.50000, 0.50000], [0.00000, 0.50000, 0.50000], [0.00000, 0.50000, 0.50000], [0.00000, 0.50000, 0.50000], [0.08333, 0.00000, 0.91667], [0.08333, 0.00000, 0.91667], [0.08333, 0.00000, 0.91667], [0.08333, 0.00000, 0.91667], [0.08333, 0.00000, 0.91667], [0.08333, 0.00000, 0.91667], [0.08333, 0.00000, 0.91667], [0.00000, 0.00000, 1.00000], [0.00000, 0.00000, 1.00000], [0.00000, 0.00000, 1.00000], [0.00000, 0.00000, 1.00000], [0.00000, 0.00000, 1.00000], [0.00000, 0.00000, 1.00000], [0.00000, 0.00000, 1.00000], [0.00000, 0.00000, 1.00000], [0.08333, 0.00000, 0.91667], [0.08333, 0.00000, 0.91667], [0.08333, 0.00000, 0.91667], [0.08333, 0.00000, 0.91667], [0.08333, 0.00000, 0.91667], [0.08333, 0.00000, 0.91667], [0.08333, 0.91667, 0.00000], [0.08333, 0.91667, 0.00000], [0.08333, 0.91667, 0.00000]]) self.assertEqual(output.shape, selmask.shape) self.assertTrue(np.allclose(output, selmask, 0.001)) # test single factor, get max factor in linear weight, threshold 0.2 stg_pars = (False, 'even', 'greater', 0.2, 0.2, 0.67) stg.sort_ascending = False stg.weighting = 'even' stg.condition = 'greater' stg.lbound = 0.2 stg.ubound = 0.2 stg.set_pars(stg_pars) print(f'Start to test financial selection parameter {stg_pars}') output = stg.generate(hist_data=history_data, shares=self.hp1.shares, dates=self.hp1.hdates) selmask = np.array([[0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.5, 0.5], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0], [0.5, 0.5, 0.0]]) self.assertEqual(output.shape, selmask.shape) self.assertTrue(np.allclose(output, selmask, 0.001)) def test_tokenizer(self): self.assertListEqual(_exp_to_token('1+1'), ['1', '+', '1']) print(_exp_to_token('1+1')) self.assertListEqual(_exp_to_token('1 & 1'), ['1', '&', '1']) print(_exp_to_token('1&1')) self.assertListEqual(_exp_to_token('1 and 1'), ['1', 'and', '1']) print(_exp_to_token('1 and 1')) self.assertListEqual(_exp_to_token('1 or 1'), ['1', 'or', '1']) print(_exp_to_token('1 or 1')) self.assertListEqual(_exp_to_token('(1 - 1 + -1) * pi'), ['(', '1', '-', '1', '+', '-1', ')', '*', 'pi']) print(_exp_to_token('(1 - 1 + -1) * pi')) self.assertListEqual(_exp_to_token('abs(5-sqrt(2) / cos(pi))'), ['abs(', '5', '-', 'sqrt(', '2', ')', '/', 'cos(', 'pi', ')', ')']) print(_exp_to_token('abs(5-sqrt(2) / cos(pi))')) self.assertListEqual(_exp_to_token('sin(pi) + 2.14'), ['sin(', 'pi', ')', '+', '2.14']) print(_exp_to_token('sin(pi) + 2.14')) self.assertListEqual(_exp_to_token('(1-2)/3.0 + 0.0000'), ['(', '1', '-', '2', ')', '/', '3.0', '+', '0.0000']) print(_exp_to_token('(1-2)/3.0 + 0.0000')) self.assertListEqual(_exp_to_token('-(1. + .2) * max(1, 3, 5)'), ['-', '(', '1.', '+', '.2', ')', '*', 'max(', '1', ',', '3', ',', '5', ')']) print(_exp_to_token('-(1. + .2) * max(1, 3, 5)')) self.assertListEqual(_exp_to_token('(x + e * 10) / 10'), ['(', 'x', '+', 'e', '*', '10', ')', '/', '10']) print(_exp_to_token('(x + e * 10) / 10')) self.assertListEqual(_exp_to_token('8.2/((-.1+abs3(3,4,5))*0.12)'), ['8.2', '/', '(', '(', '-.1', '+', 'abs3(', '3', ',', '4', ',', '5', ')', ')', '*', '0.12', ')']) print(_exp_to_token('8.2/((-.1+abs3(3,4,5))*0.12)')) self.assertListEqual(_exp_to_token('8.2/abs3(3,4,25.34 + 5)*0.12'), ['8.2', '/', 'abs3(', '3', ',', '4', ',', '25.34', '+', '5', ')', '*', '0.12']) print(_exp_to_token('8.2/abs3(3,4,25.34 + 5)*0.12')) class TestLog(unittest.TestCase): def test_init(self): pass class TestConfig(unittest.TestCase): """测试Config对象以及QT_CONFIG变量的设置和获取值""" def test_init(self): pass def test_invest(self): pass def test_pars_string_to_type(self): _parse_string_kwargs('000300', 'asset_pool', _valid_qt_kwargs()) class TestHistoryPanel(unittest.TestCase): def setUp(self): print('start testing HistoryPanel object\n') self.data = np.random.randint(10, size=(5, 10, 4)) self.index = pd.date_range(start='20200101', freq='d', periods=10) self.index2 = ['2016-07-01', '2016-07-04', '2016-07-05', '2016-07-06', '2016-07-07', '2016-07-08', '2016-07-11', '2016-07-12', '2016-07-13', '2016-07-14'] self.index3 = '2016-07-01, 2016-07-04, 2016-07-05, 2016-07-06, 2016-07-07, ' \ '2016-07-08, 2016-07-11, 2016-07-12, 2016-07-13, 2016-07-14' self.shares = '000100,000101,000102,000103,000104' self.htypes = 'close,open,high,low' self.data2 = np.random.randint(10, size=(10, 5)) self.data3 = np.random.randint(10, size=(10, 4)) self.data4 = np.random.randint(10, size=(10)) self.hp = qt.HistoryPanel(values=self.data, levels=self.shares, columns=self.htypes, rows=self.index) self.hp2 = qt.HistoryPanel(values=self.data2, levels=self.shares, columns='close', rows=self.index) self.hp3 = qt.HistoryPanel(values=self.data3, levels='000100', columns=self.htypes, rows=self.index2) self.hp4 = qt.HistoryPanel(values=self.data4, levels='000100', columns='close', rows=self.index3) self.hp5 = qt.HistoryPanel(values=self.data) self.hp6 = qt.HistoryPanel(values=self.data, levels=self.shares, rows=self.index3) def test_properties(self): """ test all properties of HistoryPanel """ self.assertFalse(self.hp.is_empty) self.assertEqual(self.hp.row_count, 10) self.assertEqual(self.hp.column_count, 4) self.assertEqual(self.hp.level_count, 5) self.assertEqual(self.hp.shape, (5, 10, 4)) self.assertSequenceEqual(self.hp.htypes, ['close', 'open', 'high', 'low']) self.assertSequenceEqual(self.hp.shares, ['000100', '000101', '000102', '000103', '000104']) self.assertSequenceEqual(list(self.hp.hdates), list(self.index)) self.assertDictEqual(self.hp.columns, {'close': 0, 'open': 1, 'high': 2, 'low': 3}) self.assertDictEqual(self.hp.levels, {'000100': 0, '000101': 1, '000102': 2, '000103': 3, '000104': 4}) row_dict = {Timestamp('2020-01-01 00:00:00', freq='D'): 0, Timestamp('2020-01-02 00:00:00', freq='D'): 1, Timestamp('2020-01-03 00:00:00', freq='D'): 2, Timestamp('2020-01-04 00:00:00', freq='D'): 3, Timestamp('2020-01-05 00:00:00', freq='D'): 4, Timestamp('2020-01-06 00:00:00', freq='D'): 5, Timestamp('2020-01-07 00:00:00', freq='D'): 6, Timestamp('2020-01-08 00:00:00', freq='D'): 7, Timestamp('2020-01-09 00:00:00', freq='D'): 8, Timestamp('2020-01-10 00:00:00', freq='D'): 9} self.assertDictEqual(self.hp.rows, row_dict) def test_len(self): """ test the function len(HistoryPanel) :return: """ self.assertEqual(len(self.hp), 10) def test_empty_history_panel(self): """测试空HP或者特殊HP如维度标签为纯数字的HP""" test_hp = qt.HistoryPanel(self.data) self.assertFalse(test_hp.is_empty) self.assertIsInstance(test_hp, qt.HistoryPanel) self.assertEqual(test_hp.shape[0], 5) self.assertEqual(test_hp.shape[1], 10) self.assertEqual(test_hp.shape[2], 4) self.assertEqual(test_hp.level_count, 5) self.assertEqual(test_hp.row_count, 10) self.assertEqual(test_hp.column_count, 4) self.assertEqual(test_hp.shares, list(range(5))) self.assertEqual(test_hp.hdates, list(pd.date_range(start='20200730', periods=10, freq='d'))) self.assertEqual(test_hp.htypes, list(range(4))) self.assertTrue(np.allclose(test_hp.values, self.data)) print(f'shares: {test_hp.shares}\nhtypes: {test_hp.htypes}') print(test_hp) # HistoryPanel should be empty if no value is given empty_hp = qt.HistoryPanel() self.assertTrue(empty_hp.is_empty) self.assertIsInstance(empty_hp, qt.HistoryPanel) self.assertEqual(empty_hp.shape[0], 0) self.assertEqual(empty_hp.shape[1], 0) self.assertEqual(empty_hp.shape[2], 0) self.assertEqual(empty_hp.level_count, 0) self.assertEqual(empty_hp.row_count, 0) self.assertEqual(empty_hp.column_count, 0) # HistoryPanel should also be empty if empty value (np.array([])) is given empty_hp = qt.HistoryPanel(np.empty((5, 0, 4)), levels=self.shares, columns=self.htypes) self.assertTrue(empty_hp.is_empty) self.assertIsInstance(empty_hp, qt.HistoryPanel) self.assertEqual(empty_hp.shape[0], 0) self.assertEqual(empty_hp.shape[1], 0) self.assertEqual(empty_hp.shape[2], 0) self.assertEqual(empty_hp.level_count, 0) self.assertEqual(empty_hp.row_count, 0) self.assertEqual(empty_hp.column_count, 0) def test_create_history_panel(self): """ test the creation of a HistoryPanel object by passing all data explicitly """ self.assertIsInstance(self.hp, qt.HistoryPanel) self.assertEqual(self.hp.shape[0], 5) self.assertEqual(self.hp.shape[1], 10) self.assertEqual(self.hp.shape[2], 4) self.assertEqual(self.hp.level_count, 5) self.assertEqual(self.hp.row_count, 10) self.assertEqual(self.hp.column_count, 4) self.assertEqual(list(self.hp.levels.keys()), self.shares.split(',')) self.assertEqual(list(self.hp.columns.keys()), self.htypes.split(',')) self.assertEqual(list(self.hp.rows.keys())[0], pd.Timestamp('20200101')) self.assertIsInstance(self.hp2, qt.HistoryPanel) self.assertEqual(self.hp2.shape[0], 5) self.assertEqual(self.hp2.shape[1], 10) self.assertEqual(self.hp2.shape[2], 1) self.assertEqual(self.hp2.level_count, 5) self.assertEqual(self.hp2.row_count, 10) self.assertEqual(self.hp2.column_count, 1) self.assertEqual(list(self.hp2.levels.keys()), self.shares.split(',')) self.assertEqual(list(self.hp2.columns.keys()), ['close']) self.assertEqual(list(self.hp2.rows.keys())[0], pd.Timestamp('20200101')) self.assertIsInstance(self.hp3, qt.HistoryPanel) self.assertEqual(self.hp3.shape[0], 1) self.assertEqual(self.hp3.shape[1], 10) self.assertEqual(self.hp3.shape[2], 4) self.assertEqual(self.hp3.level_count, 1) self.assertEqual(self.hp3.row_count, 10) self.assertEqual(self.hp3.column_count, 4) self.assertEqual(list(self.hp3.levels.keys()), ['000100']) self.assertEqual(list(self.hp3.columns.keys()), self.htypes.split(',')) self.assertEqual(list(self.hp3.rows.keys())[0], pd.Timestamp('2016-07-01')) self.assertIsInstance(self.hp4, qt.HistoryPanel) self.assertEqual(self.hp4.shape[0], 1) self.assertEqual(self.hp4.shape[1], 10) self.assertEqual(self.hp4.shape[2], 1) self.assertEqual(self.hp4.level_count, 1) self.assertEqual(self.hp4.row_count, 10) self.assertEqual(self.hp4.column_count, 1) self.assertEqual(list(self.hp4.levels.keys()), ['000100']) self.assertEqual(list(self.hp4.columns.keys()), ['close']) self.assertEqual(list(self.hp4.rows.keys())[0], pd.Timestamp('2016-07-01')) self.hp5.info() self.assertIsInstance(self.hp5, qt.HistoryPanel) self.assertTrue(np.allclose(self.hp5.values, self.data)) self.assertEqual(self.hp5.shape[0], 5) self.assertEqual(self.hp5.shape[1], 10) self.assertEqual(self.hp5.shape[2], 4) self.assertEqual(self.hp5.level_count, 5) self.assertEqual(self.hp5.row_count, 10) self.assertEqual(self.hp5.column_count, 4) self.assertEqual(list(self.hp5.levels.keys()), [0, 1, 2, 3, 4]) self.assertEqual(list(self.hp5.columns.keys()), [0, 1, 2, 3]) self.assertEqual(list(self.hp5.rows.keys())[0], pd.Timestamp('2020-07-30')) self.hp6.info() self.assertIsInstance(self.hp6, qt.HistoryPanel) self.assertTrue(np.allclose(self.hp6.values, self.data)) self.assertEqual(self.hp6.shape[0], 5) self.assertEqual(self.hp6.shape[1], 10) self.assertEqual(self.hp6.shape[2], 4) self.assertEqual(self.hp6.level_count, 5) self.assertEqual(self.hp6.row_count, 10) self.assertEqual(self.hp6.column_count, 4) self.assertEqual(list(self.hp6.levels.keys()), ['000100', '000101', '000102', '000103', '000104']) self.assertEqual(list(self.hp6.columns.keys()), [0, 1, 2, 3]) self.assertEqual(list(self.hp6.rows.keys())[0], pd.Timestamp('2016-07-01')) print('test creating HistoryPanel with very limited data') print('test creating HistoryPanel with 2D data') temp_data = np.random.randint(10, size=(7, 3)).astype('float') temp_hp = qt.HistoryPanel(temp_data) # Error testing during HistoryPanel creating # shape does not match self.assertRaises(AssertionError, qt.HistoryPanel, self.data, levels=self.shares, columns='close', rows=self.index) # valus is not np.ndarray self.assertRaises(TypeError, qt.HistoryPanel, list(self.data)) # dimension/shape does not match self.assertRaises(AssertionError, qt.HistoryPanel, self.data2, levels='000100', columns=self.htypes, rows=self.index) # value dimension over 3 self.assertRaises(AssertionError, qt.HistoryPanel, np.random.randint(10, size=(5, 10, 4, 2))) # lebel value not valid self.assertRaises(ValueError, qt.HistoryPanel, self.data2, levels=self.shares, columns='close', rows='a,b,c,d,e,f,g,h,i,j') def test_history_panel_slicing(self): """测试HistoryPanel的各种切片方法 包括通过标签名称切片,通过数字切片,通过逗号分隔的标签名称切片,通过冒号分隔的标签名称切片等切片方式""" self.assertTrue(np.allclose(self.hp['close'], self.data[:, :, 0:1])) self.assertTrue(np.allclose(self.hp['close,open'], self.data[:, :, 0:2])) self.assertTrue(np.allclose(self.hp[['close', 'open']], self.data[:, :, 0:2])) self.assertTrue(np.allclose(self.hp['close:high'], self.data[:, :, 0:3])) self.assertTrue(np.allclose(self.hp['close,high'], self.data[:, :, [0, 2]])) self.assertTrue(np.allclose(self.hp[:, '000100'], self.data[0:1, :, ])) self.assertTrue(np.allclose(self.hp[:, '000100,000101'], self.data[0:2, :])) self.assertTrue(np.allclose(self.hp[:, ['000100', '000101']], self.data[0:2, :])) self.assertTrue(np.allclose(self.hp[:, '000100:000102'], self.data[0:3, :])) self.assertTrue(np.allclose(self.hp[:, '000100,000102'], self.data[[0, 2], :])) self.assertTrue(np.allclose(self.hp['close,open', '000100,000102'], self.data[[0, 2], :, 0:2])) print('start testing HistoryPanel') data = np.random.randint(10, size=(10, 5)) # index = pd.date_range(start='20200101', freq='d', periods=10) shares = '000100,000101,000102,000103,000104' dtypes = 'close' df = pd.DataFrame(data) print('=========================\nTesting HistoryPanel creation from DataFrame') hp = qt.dataframe_to_hp(df=df, shares=shares, htypes=dtypes) hp.info() hp = qt.dataframe_to_hp(df=df, shares='000100', htypes='close, open, high, low, middle', column_type='htypes') hp.info() print('=========================\nTesting HistoryPanel creation from initialization') data = np.random.randint(10, size=(5, 10, 4)).astype('float') index = pd.date_range(start='20200101', freq='d', periods=10) dtypes = 'close, open, high,low' data[0, [5, 6, 9], [0, 1, 3]] = np.nan data[1:4, [4, 7, 6, 2], [1, 1, 3, 0]] = np.nan data[4:5, [2, 9, 1, 2], [0, 3, 2, 1]] = np.nan hp = qt.HistoryPanel(data, levels=shares, columns=dtypes, rows=index) hp.info() print('==========================\n输出close类型的所有历史数据\n') self.assertTrue(np.allclose(hp['close', :, :], data[:, :, 0:1], equal_nan=True)) print(f'==========================\n输出close和open类型的所有历史数据\n') self.assertTrue(np.allclose(hp[[0, 1], :, :], data[:, :, 0:2], equal_nan=True)) print(f'==========================\n输出第一只股票的所有类型历史数据\n') self.assertTrue(np.allclose(hp[:, [0], :], data[0:1, :, :], equal_nan=True)) print('==========================\n输出第0、1、2个htype对应的所有股票全部历史数据\n') self.assertTrue(np.allclose(hp[[0, 1, 2]], data[:, :, 0:3], equal_nan=True)) print('==========================\n输出close、high两个类型的所有历史数据\n') self.assertTrue(np.allclose(hp[['close', 'high']], data[:, :, [0, 2]], equal_nan=True)) print('==========================\n输出0、1两个htype的所有历史数据\n') self.assertTrue(np.allclose(hp[[0, 1]], data[:, :, 0:2], equal_nan=True)) print('==========================\n输出close、high两个类型的所有历史数据\n') self.assertTrue(np.allclose(hp['close,high'], data[:, :, [0, 2]], equal_nan=True)) print('==========================\n输出close起到high止的三个类型的所有历史数据\n') self.assertTrue(np.allclose(hp['close:high'], data[:, :, 0:3], equal_nan=True)) print('==========================\n输出0、1、3三个股票的全部历史数据\n') self.assertTrue(np.allclose(hp[:, [0, 1, 3]], data[[0, 1, 3], :, :], equal_nan=True)) print('==========================\n输出000100、000102两只股票的所有历史数据\n') self.assertTrue(np.allclose(hp[:, ['000100', '000102']], data[[0, 2], :, :], equal_nan=True)) print('==========================\n输出0、1、2三个股票的历史数据\n', hp[:, 0: 3]) self.assertTrue(np.allclose(hp[:, 0: 3], data[0:3, :, :], equal_nan=True)) print('==========================\n输出000100、000102两只股票的所有历史数据\n') self.assertTrue(np.allclose(hp[:, '000100, 000102'], data[[0, 2], :, :], equal_nan=True)) print('==========================\n输出所有股票的0-7日历史数据\n') self.assertTrue(np.allclose(hp[:, :, 0:8], data[:, 0:8, :], equal_nan=True)) print('==========================\n输出000100股票的0-7日历史数据\n') self.assertTrue(np.allclose(hp[:, '000100', 0:8], data[0, 0:8, :], equal_nan=True)) print('==========================\nstart testing multy axis slicing of HistoryPanel object') print('==========================\n输出000100、000120两只股票的close、open两组历史数据\n', hp['close,open', ['000100', '000102']]) print('==========================\n输出000100、000120两只股票的close到open三组历史数据\n', hp['close,open', '000100, 000102']) print(f'historyPanel: hp:\n{hp}') print(f'data is:\n{data}') hp.htypes = 'open,high,low,close' hp.info() hp.shares = ['000300', '600227', '600222', '000123', '000129'] hp.info() def test_segment(self): """测试历史数据片段的获取""" test_hp = qt.HistoryPanel(self.data, levels=self.shares, columns=self.htypes, rows=self.index2) self.assertFalse(test_hp.is_empty) self.assertIsInstance(test_hp, qt.HistoryPanel) self.assertEqual(test_hp.shape[0], 5) self.assertEqual(test_hp.shape[1], 10) self.assertEqual(test_hp.shape[2], 4) print(f'Test segment with None parameters') seg1 = test_hp.segment() seg2 = test_hp.segment('20150202') seg3 = test_hp.segment(end_date='20201010') self.assertIsInstance(seg1, qt.HistoryPanel) self.assertIsInstance(seg2, qt.HistoryPanel) self.assertIsInstance(seg3, qt.HistoryPanel) # check values self.assertTrue(np.allclose( seg1.values, test_hp.values )) self.assertTrue(np.allclose( seg2.values, test_hp.values )) self.assertTrue(np.allclose( seg3.values, test_hp.values )) # check that htypes and shares should be same self.assertEqual(seg1.htypes, test_hp.htypes) self.assertEqual(seg1.shares, test_hp.shares) self.assertEqual(seg2.htypes, test_hp.htypes) self.assertEqual(seg2.shares, test_hp.shares) self.assertEqual(seg3.htypes, test_hp.htypes) self.assertEqual(seg3.shares, test_hp.shares) # check that hdates are the same self.assertEqual(seg1.hdates, test_hp.hdates) self.assertEqual(seg2.hdates, test_hp.hdates) self.assertEqual(seg3.hdates, test_hp.hdates) print(f'Test segment with proper dates') seg1 = test_hp.segment() seg2 = test_hp.segment('20160704') seg3 = test_hp.segment(start_date='2016-07-05', end_date='20160708') self.assertIsInstance(seg1, qt.HistoryPanel) self.assertIsInstance(seg2, qt.HistoryPanel) self.assertIsInstance(seg3, qt.HistoryPanel) # check values self.assertTrue(np.allclose( seg1.values, test_hp[:, :, :] )) self.assertTrue(np.allclose( seg2.values, test_hp[:, :, 1:10] )) self.assertTrue(np.allclose( seg3.values, test_hp[:, :, 2:6] )) # check that htypes and shares should be same self.assertEqual(seg1.htypes, test_hp.htypes) self.assertEqual(seg1.shares, test_hp.shares) self.assertEqual(seg2.htypes, test_hp.htypes) self.assertEqual(seg2.shares, test_hp.shares) self.assertEqual(seg3.htypes, test_hp.htypes) self.assertEqual(seg3.shares, test_hp.shares) # check that hdates are the same self.assertEqual(seg1.hdates, test_hp.hdates) self.assertEqual(seg2.hdates, test_hp.hdates[1:10]) self.assertEqual(seg3.hdates, test_hp.hdates[2:6]) print(f'Test segment with non-existing but in range dates') seg1 = test_hp.segment() seg2 = test_hp.segment('20160703') seg3 = test_hp.segment(start_date='2016-07-03', end_date='20160710') self.assertIsInstance(seg1, qt.HistoryPanel) self.assertIsInstance(seg2, qt.HistoryPanel) self.assertIsInstance(seg3, qt.HistoryPanel) # check values self.assertTrue(np.allclose( seg1.values, test_hp[:, :, :] )) self.assertTrue(np.allclose( seg2.values, test_hp[:, :, 1:10] )) self.assertTrue(np.allclose( seg3.values, test_hp[:, :, 1:6] )) # check that htypes and shares should be same self.assertEqual(seg1.htypes, test_hp.htypes) self.assertEqual(seg1.shares, test_hp.shares) self.assertEqual(seg2.htypes, test_hp.htypes) self.assertEqual(seg2.shares, test_hp.shares) self.assertEqual(seg3.htypes, test_hp.htypes) self.assertEqual(seg3.shares, test_hp.shares) # check that hdates are the same self.assertEqual(seg1.hdates, test_hp.hdates) self.assertEqual(seg2.hdates, test_hp.hdates[1:10]) self.assertEqual(seg3.hdates, test_hp.hdates[1:6]) print(f'Test segment with out-of-range dates') seg1 = test_hp.segment(start_date='2016-05-03', end_date='20160910') self.assertIsInstance(seg1, qt.HistoryPanel) # check values self.assertTrue(np.allclose( seg1.values, test_hp[:, :, :] )) # check that htypes and shares should be same self.assertEqual(seg1.htypes, test_hp.htypes) self.assertEqual(seg1.shares, test_hp.shares) # check that hdates are the same self.assertEqual(seg1.hdates, test_hp.hdates) def test_slice(self): """测试历史数据切片的获取""" test_hp = qt.HistoryPanel(self.data, levels=self.shares, columns=self.htypes, rows=self.index2) self.assertFalse(test_hp.is_empty) self.assertIsInstance(test_hp, qt.HistoryPanel) self.assertEqual(test_hp.shape[0], 5) self.assertEqual(test_hp.shape[1], 10) self.assertEqual(test_hp.shape[2], 4) print(f'Test slice with shares') share = '000101' slc = test_hp.slice(shares=share) self.assertIsInstance(slc, qt.HistoryPanel) self.assertEqual(slc.shares, ['000101']) self.assertEqual(slc.htypes, test_hp.htypes) self.assertEqual(slc.hdates, test_hp.hdates) self.assertTrue(np.allclose(slc.values, test_hp[:, '000101'])) share = '000101, 000103' slc = test_hp.slice(shares=share) self.assertIsInstance(slc, qt.HistoryPanel) self.assertEqual(slc.shares, ['000101', '000103']) self.assertEqual(slc.htypes, test_hp.htypes) self.assertEqual(slc.hdates, test_hp.hdates) self.assertTrue(np.allclose(slc.values, test_hp[:, '000101, 000103'])) print(f'Test slice with htypes') htype = 'open' slc = test_hp.slice(htypes=htype) self.assertIsInstance(slc, qt.HistoryPanel) self.assertEqual(slc.shares, test_hp.shares) self.assertEqual(slc.htypes, ['open']) self.assertEqual(slc.hdates, test_hp.hdates) self.assertTrue(np.allclose(slc.values, test_hp['open'])) htype = 'open, close' slc = test_hp.slice(htypes=htype) self.assertIsInstance(slc, qt.HistoryPanel) self.assertEqual(slc.shares, test_hp.shares) self.assertEqual(slc.htypes, ['open', 'close']) self.assertEqual(slc.hdates, test_hp.hdates) self.assertTrue(np.allclose(slc.values, test_hp['open, close'])) # test that slicing of "open, close" does NOT equal to "close, open" self.assertFalse(np.allclose(slc.values, test_hp['close, open'])) print(f'Test slicing with both htypes and shares') share = '000103, 000101' htype = 'high, low, close' slc = test_hp.slice(shares=share, htypes=htype) self.assertIsInstance(slc, qt.HistoryPanel) self.assertEqual(slc.shares, ['000103', '000101']) self.assertEqual(slc.htypes, ['high', 'low', 'close']) self.assertEqual(slc.hdates, test_hp.hdates) self.assertTrue(np.allclose(slc.values, test_hp['high, low, close', '000103, 000101'])) print(f'Test Error cases') # duplicated input htype = 'open, close, open' self.assertRaises(AssertionError, test_hp.slice, htypes=htype) def test_relabel(self): new_shares_list = ['000001', '000002', '000003', '000004', '000005'] new_shares_str = '000001, 000002, 000003, 000004, 000005' new_htypes_list = ['close', 'volume', 'value', 'exchange'] new_htypes_str = 'close, volume, value, exchange' temp_hp = self.hp.copy() temp_hp.re_label(shares=new_shares_list) print(temp_hp.info()) print(temp_hp.htypes) self.assertTrue(np.allclose(self.hp.values, temp_hp.values)) self.assertEqual(self.hp.htypes, temp_hp.htypes) self.assertEqual(self.hp.hdates, temp_hp.hdates) self.assertEqual(temp_hp.shares, new_shares_list) temp_hp = self.hp.copy() temp_hp.re_label(shares=new_shares_str) self.assertTrue(np.allclose(self.hp.values, temp_hp.values)) self.assertEqual(self.hp.htypes, temp_hp.htypes) self.assertEqual(self.hp.hdates, temp_hp.hdates) self.assertEqual(temp_hp.shares, new_shares_list) temp_hp = self.hp.copy() temp_hp.re_label(htypes=new_htypes_list) self.assertTrue(np.allclose(self.hp.values, temp_hp.values)) self.assertEqual(self.hp.shares, temp_hp.shares) self.assertEqual(self.hp.hdates, temp_hp.hdates) self.assertEqual(temp_hp.htypes, new_htypes_list) temp_hp = self.hp.copy() temp_hp.re_label(htypes=new_htypes_str) self.assertTrue(np.allclose(self.hp.values, temp_hp.values)) self.assertEqual(self.hp.shares, temp_hp.shares) self.assertEqual(self.hp.hdates, temp_hp.hdates) self.assertEqual(temp_hp.htypes, new_htypes_list) print(f'test errors raising') temp_hp = self.hp.copy() self.assertRaises(AssertionError, temp_hp.re_label, htypes=new_shares_str) self.assertRaises(TypeError, temp_hp.re_label, htypes=123) self.assertRaises(AssertionError, temp_hp.re_label, htypes='wrong input!') def test_csv_to_hp(self): pass def test_hdf_to_hp(self): pass def test_hp_join(self): # TODO: 这里需要加强,需要用具体的例子确认hp_join的结果正确 # TODO: 尤其是不同的shares、htypes、hdates,以及它们在顺 # TODO: 序不同的情况下是否能正确地组合 print(f'join two simple HistoryPanels with same shares') temp_hp = self.hp.join(self.hp2, same_shares=True) self.assertIsInstance(temp_hp, qt.HistoryPanel) def test_df_to_hp(self): print(f'test converting DataFrame to HistoryPanel') data = np.random.randint(10, size=(10, 5)) df1 = pd.DataFrame(data) df2 = pd.DataFrame(data, columns=str_to_list(self.shares)) df3 = pd.DataFrame(data[:, 0:4]) df4 = pd.DataFrame(data[:, 0:4], columns=str_to_list(self.htypes)) hp = qt.dataframe_to_hp(df1, htypes='close') self.assertIsInstance(hp, qt.HistoryPanel) self.assertEqual(hp.shares, [0, 1, 2, 3, 4]) self.assertEqual(hp.htypes, ['close']) self.assertEqual(hp.hdates, [pd.Timestamp('1970-01-01 00:00:00'), pd.Timestamp('1970-01-01 00:00:00.000000001'), pd.Timestamp('1970-01-01 00:00:00.000000002'), pd.Timestamp('1970-01-01 00:00:00.000000003'), pd.Timestamp('1970-01-01 00:00:00.000000004'), pd.Timestamp('1970-01-01 00:00:00.000000005'), pd.Timestamp('1970-01-01 00:00:00.000000006'), pd.Timestamp('1970-01-01 00:00:00.000000007'), pd.Timestamp('1970-01-01 00:00:00.000000008'), pd.Timestamp('1970-01-01 00:00:00.000000009')]) hp = qt.dataframe_to_hp(df2, shares=self.shares, htypes='close') self.assertIsInstance(hp, qt.HistoryPanel) self.assertEqual(hp.shares, str_to_list(self.shares)) self.assertEqual(hp.htypes, ['close']) hp = qt.dataframe_to_hp(df3, shares='000100', column_type='htypes') self.assertIsInstance(hp, qt.HistoryPanel) self.assertEqual(hp.shares, ['000100']) self.assertEqual(hp.htypes, [0, 1, 2, 3]) hp = qt.dataframe_to_hp(df4, shares='000100', htypes=self.htypes, column_type='htypes') self.assertIsInstance(hp, qt.HistoryPanel) self.assertEqual(hp.shares, ['000100']) self.assertEqual(hp.htypes, str_to_list(self.htypes)) hp.info() self.assertRaises(KeyError, qt.dataframe_to_hp, df1) def test_to_dataframe(self): """ 测试HistoryPanel对象的to_dataframe方法 """ print(f'START TEST == test_to_dataframe') print(f'test converting test hp to dataframe with share == "000102":') df_test = self.hp.to_dataframe(share='000102') self.assertIsInstance(df_test, pd.DataFrame) self.assertEqual(list(self.hp.hdates), list(df_test.index)) self.assertEqual(list(self.hp.htypes), list(df_test.columns)) values = df_test.values self.assertTrue(np.allclose(self.hp[:, '000102'], values)) print(f'test DataFrame conversion with share == "000100"') df_test = self.hp.to_dataframe(share='000100') self.assertIsInstance(df_test, pd.DataFrame) self.assertEqual(list(self.hp.hdates), list(df_test.index)) self.assertEqual(list(self.hp.htypes), list(df_test.columns)) values = df_test.values self.assertTrue(np.allclose(self.hp[:, '000100'], values)) print(f'test DataFrame conversion error: type incorrect') self.assertRaises(AssertionError, self.hp.to_dataframe, share=3.0) print(f'test DataFrame error raising with share not found error') self.assertRaises(KeyError, self.hp.to_dataframe, share='000300') print(f'test DataFrame conversion with htype == "close"') df_test = self.hp.to_dataframe(htype='close') self.assertIsInstance(df_test, pd.DataFrame) self.assertEqual(list(self.hp.hdates), list(df_test.index)) self.assertEqual(list(self.hp.shares), list(df_test.columns)) values = df_test.values self.assertTrue(np.allclose(self.hp['close'].T, values)) print(f'test DataFrame conversion with htype == "high"') df_test = self.hp.to_dataframe(htype='high') self.assertIsInstance(df_test, pd.DataFrame) self.assertEqual(list(self.hp.hdates), list(df_test.index)) self.assertEqual(list(self.hp.shares), list(df_test.columns)) values = df_test.values self.assertTrue(np.allclose(self.hp['high'].T, values)) print(f'test DataFrame conversion with htype == "high" and dropna') v = self.hp.values.astype('float') v[:, 3, :] = np.nan v[:, 4, :] = np.inf test_hp = qt.HistoryPanel(v, levels=self.shares, columns=self.htypes, rows=self.index) df_test = test_hp.to_dataframe(htype='high', dropna=True) self.assertIsInstance(df_test, pd.DataFrame) self.assertEqual(list(self.hp.hdates[:3]) + list(self.hp.hdates[4:]), list(df_test.index)) self.assertEqual(list(self.hp.shares), list(df_test.columns)) values = df_test.values target_values = test_hp['high'].T target_values = target_values[np.where(~np.isnan(target_values))].reshape(9, 5) self.assertTrue(np.allclose(target_values, values)) print(f'test DataFrame conversion with htype == "high", dropna and treat infs as na') v = self.hp.values.astype('float') v[:, 3, :] = np.nan v[:, 4, :] = np.inf test_hp = qt.HistoryPanel(v, levels=self.shares, columns=self.htypes, rows=self.index) df_test = test_hp.to_dataframe(htype='high', dropna=True, inf_as_na=True) self.assertIsInstance(df_test, pd.DataFrame) self.assertEqual(list(self.hp.hdates[:3]) + list(self.hp.hdates[5:]), list(df_test.index)) self.assertEqual(list(self.hp.shares), list(df_test.columns)) values = df_test.values target_values = test_hp['high'].T target_values = target_values[np.where(~np.isnan(target_values) & ~np.isinf(target_values))].reshape(8, 5) self.assertTrue(np.allclose(target_values, values)) print(f'test DataFrame conversion error: type incorrect') self.assertRaises(AssertionError, self.hp.to_dataframe, htype=pd.DataFrame()) print(f'test DataFrame error raising with share not found error') self.assertRaises(KeyError, self.hp.to_dataframe, htype='non_type') print(f'Raises ValueError when both or none parameter is given') self.assertRaises(KeyError, self.hp.to_dataframe) self.assertRaises(KeyError, self.hp.to_dataframe, share='000100', htype='close') def test_to_df_dict(self): """测试HistoryPanel公有方法to_df_dict""" print('test convert history panel slice by share') df_dict = self.hp.to_df_dict('share') self.assertEqual(self.hp.shares, list(df_dict.keys())) df_dict = self.hp.to_df_dict() self.assertEqual(self.hp.shares, list(df_dict.keys())) print('test convert historypanel slice by htype ') df_dict = self.hp.to_df_dict('htype') self.assertEqual(self.hp.htypes, list(df_dict.keys())) print('test raise assertion error') self.assertRaises(AssertionError, self.hp.to_df_dict, by='random text') self.assertRaises(AssertionError, self.hp.to_df_dict, by=3) print('test empty hp') df_dict = qt.HistoryPanel().to_df_dict('share') self.assertEqual(df_dict, {}) def test_stack_dataframes(self): print('test stack dataframes in a list') df1 = pd.DataFrame({'a': [1, 2, 3, 4], 'b': [2, 3, 4, 5], 'c': [3, 4, 5, 6]}) df1.index = ['20200101', '20200102', '20200103', '20200104'] df2 = pd.DataFrame({'b': [4, 3, 2, 1], 'd': [1, 1, 1, 1], 'c': [6, 5, 4, 3]}) df2.index = ['20200101', '20200102', '20200104', '20200105'] df3 = pd.DataFrame({'a': [6, 6, 6, 6], 'd': [4, 4, 4, 4], 'b': [2, 4, 6, 8]}) df3.index = ['20200101', '20200102', '20200103', '20200106'] values1 = np.array([[[1., 2., 3., np.nan], [2., 3., 4., np.nan], [3., 4., 5., np.nan], [4., 5., 6., np.nan], [np.nan, np.nan, np.nan, np.nan], [np.nan, np.nan, np.nan, np.nan]], [[np.nan, 4., 6., 1.], [np.nan, 3., 5., 1.], [np.nan, np.nan, np.nan, np.nan], [np.nan, 2., 4., 1.], [np.nan, 1., 3., 1.], [np.nan, np.nan, np.nan, np.nan]], [[6., 2., np.nan, 4.], [6., 4., np.nan, 4.], [6., 6., np.nan, 4.], [np.nan, np.nan, np.nan, np.nan], [np.nan, np.nan, np.nan, np.nan], [6., 8., np.nan, 4.]]]) values2 = np.array([[[1., np.nan, 6.], [2., np.nan, 6.], [3., np.nan, 6.], [4., np.nan, np.nan], [np.nan, np.nan, np.nan], [np.nan, np.nan, 6.]], [[2., 4., 2.], [3., 3., 4.], [4., np.nan, 6.], [5., 2., np.nan], [np.nan, 1., np.nan], [np.nan, np.nan, 8.]], [[3., 6., np.nan], [4., 5., np.nan], [5., np.nan, np.nan], [6., 4., np.nan], [np.nan, 3., np.nan], [np.nan, np.nan, np.nan]], [[np.nan, 1., 4.], [np.nan, 1., 4.], [np.nan, np.nan, 4.], [np.nan, 1., np.nan], [np.nan, 1., np.nan], [np.nan, np.nan, 4.]]]) print(df1.rename(index=pd.to_datetime)) print(df2.rename(index=pd.to_datetime)) print(df3.rename(index=pd.to_datetime)) hp1 = stack_dataframes([df1, df2, df3], stack_along='shares', shares=['000100', '000200', '000300']) hp2 = stack_dataframes([df1, df2, df3], stack_along='shares', shares='000100, 000300, 000200') print('hp1 is:\n', hp1) print('hp2 is:\n', hp2) self.assertEqual(hp1.htypes, ['a', 'b', 'c', 'd']) self.assertEqual(hp1.shares, ['000100', '000200', '000300']) self.assertTrue(np.allclose(hp1.values, values1, equal_nan=True)) self.assertEqual(hp2.htypes, ['a', 'b', 'c', 'd']) self.assertEqual(hp2.shares, ['000100', '000300', '000200']) self.assertTrue(np.allclose(hp2.values, values1, equal_nan=True)) hp3 = stack_dataframes([df1, df2, df3], stack_along='htypes', htypes=['close', 'high', 'low']) hp4 = stack_dataframes([df1, df2, df3], stack_along='htypes', htypes='open, close, high') print('hp3 is:\n', hp3.values) print('hp4 is:\n', hp4.values) self.assertEqual(hp3.htypes, ['close', 'high', 'low']) self.assertEqual(hp3.shares, ['a', 'b', 'c', 'd']) self.assertTrue(np.allclose(hp3.values, values2, equal_nan=True)) self.assertEqual(hp4.htypes, ['open', 'close', 'high']) self.assertEqual(hp4.shares, ['a', 'b', 'c', 'd']) self.assertTrue(np.allclose(hp4.values, values2, equal_nan=True)) print('test stack dataframes in a dict') df1 = pd.DataFrame({'a': [1, 2, 3, 4], 'b': [2, 3, 4, 5], 'c': [3, 4, 5, 6]}) df1.index = ['20200101', '20200102', '20200103', '20200104'] df2 = pd.DataFrame({'b': [4, 3, 2, 1], 'd': [1, 1, 1, 1], 'c': [6, 5, 4, 3]}) df2.index = ['20200101', '20200102', '20200104', '20200105'] df3 = pd.DataFrame({'a': [6, 6, 6, 6], 'd': [4, 4, 4, 4], 'b': [2, 4, 6, 8]}) df3.index = ['20200101', '20200102', '20200103', '20200106'] values1 = np.array([[[1., 2., 3., np.nan], [2., 3., 4., np.nan], [3., 4., 5., np.nan], [4., 5., 6., np.nan], [np.nan, np.nan, np.nan, np.nan], [np.nan, np.nan, np.nan, np.nan]], [[np.nan, 4., 6., 1.], [np.nan, 3., 5., 1.], [np.nan, np.nan, np.nan, np.nan], [np.nan, 2., 4., 1.], [np.nan, 1., 3., 1.], [np.nan, np.nan, np.nan, np.nan]], [[6., 2., np.nan, 4.], [6., 4., np.nan, 4.], [6., 6., np.nan, 4.], [np.nan, np.nan, np.nan, np.nan], [np.nan, np.nan, np.nan, np.nan], [6., 8., np.nan, 4.]]]) values2 = np.array([[[1., np.nan, 6.], [2., np.nan, 6.], [3., np.nan, 6.], [4., np.nan, np.nan], [np.nan, np.nan, np.nan], [np.nan, np.nan, 6.]], [[2., 4., 2.], [3., 3., 4.], [4., np.nan, 6.], [5., 2., np.nan], [np.nan, 1., np.nan], [np.nan, np.nan, 8.]], [[3., 6., np.nan], [4., 5., np.nan], [5., np.nan, np.nan], [6., 4., np.nan], [np.nan, 3., np.nan], [np.nan, np.nan, np.nan]], [[np.nan, 1., 4.], [np.nan, 1., 4.], [np.nan, np.nan, 4.], [np.nan, 1., np.nan], [np.nan, 1., np.nan], [np.nan, np.nan, 4.]]]) print(df1.rename(index=pd.to_datetime)) print(df2.rename(index=pd.to_datetime)) print(df3.rename(index=pd.to_datetime)) hp1 = stack_dataframes(dfs={'000001.SZ': df1, '000002.SZ': df2, '000003.SZ': df3}, stack_along='shares') hp2 = stack_dataframes(dfs={'000001.SZ': df1, '000002.SZ': df2, '000003.SZ': df3}, stack_along='shares', shares='000100, 000300, 000200') print('hp1 is:\n', hp1) print('hp2 is:\n', hp2) self.assertEqual(hp1.htypes, ['a', 'b', 'c', 'd']) self.assertEqual(hp1.shares, ['000001.SZ', '000002.SZ', '000003.SZ']) self.assertTrue(np.allclose(hp1.values, values1, equal_nan=True)) self.assertEqual(hp2.htypes, ['a', 'b', 'c', 'd']) self.assertEqual(hp2.shares, ['000100', '000300', '000200']) self.assertTrue(np.allclose(hp2.values, values1, equal_nan=True)) hp3 = stack_dataframes(dfs={'close': df1, 'high': df2, 'low': df3}, stack_along='htypes') hp4 = stack_dataframes(dfs={'close': df1, 'low': df2, 'high': df3}, stack_along='htypes', htypes='open, close, high') print('hp3 is:\n', hp3.values) print('hp4 is:\n', hp4.values) self.assertEqual(hp3.htypes, ['close', 'high', 'low']) self.assertEqual(hp3.shares, ['a', 'b', 'c', 'd']) self.assertTrue(np.allclose(hp3.values, values2, equal_nan=True)) self.assertEqual(hp4.htypes, ['open', 'close', 'high']) self.assertEqual(hp4.shares, ['a', 'b', 'c', 'd']) self.assertTrue(np.allclose(hp4.values, values2, equal_nan=True)) def test_to_csv(self): pass def test_to_hdf(self): pass def test_fill_na(self): """测试填充无效值""" print(self.hp) new_values = self.hp.values.astype(float) new_values[[0, 1, 3, 2], [1, 3, 0, 2], [1, 3, 2, 2]] = np.nan print(new_values) temp_hp = qt.HistoryPanel(values=new_values, levels=self.hp.levels, rows=self.hp.rows, columns=self.hp.columns) self.assertTrue(np.allclose(temp_hp.values[[0, 1, 3, 2], [1, 3, 0, 2], [1, 3, 2, 2]], np.nan, equal_nan=True)) temp_hp.fillna(2.3) filled_values = new_values.copy() filled_values[[0, 1, 3, 2], [1, 3, 0, 2], [1, 3, 2, 2]] = 2.3 self.assertTrue(np.allclose(temp_hp.values, filled_values, equal_nan=True)) def test_fill_inf(self): """测试填充无限值""" def test_get_history_panel(self): # TODO: implement this test case # test get only one line of data pass def test_get_price_type_raw_data(self): shares = '000039.SZ, 600748.SH, 000040.SZ' start = '20200101' end = '20200131' htypes = 'open, high, low, close' target_price_000039 = [[9.45, 9.49, 9.12, 9.17], [9.46, 9.56, 9.4, 9.5], [9.7, 9.76, 9.5, 9.51], [9.7, 9.75, 9.7, 9.72], [9.73, 9.77, 9.7, 9.73], [9.83, 9.85, 9.71, 9.72], [9.85, 9.85, 9.75, 9.79], [9.96, 9.96, 9.83, 9.86], [9.87, 9.94, 9.77, 9.93], [9.82, 9.9, 9.76, 9.87], [9.8, 9.85, 9.77, 9.82], [9.84, 9.86, 9.71, 9.72], [9.83, 9.93, 9.81, 9.86], [9.7, 9.87, 9.7, 9.82], [9.83, 9.86, 9.69, 9.79], [9.8, 9.94, 9.8, 9.86]] target_price_600748 = [[5.68, 5.68, 5.32, 5.37], [5.62, 5.68, 5.46, 5.65], [5.72, 5.72, 5.61, 5.62], [5.76, 5.77, 5.6, 5.73], [5.78, 5.84, 5.73, 5.75], [5.89, 5.91, 5.76, 5.77], [6.03, 6.04, 5.87, 5.89], [5.94, 6.07, 5.94, 6.02], [5.96, 5.98, 5.88, 5.97], [6.04, 6.06, 5.95, 5.96], [5.98, 6.04, 5.96, 6.03], [6.1, 6.11, 5.89, 5.94], [6.02, 6.12, 6., 6.1], [5.96, 6.05, 5.88, 6.01], [6.03, 6.03, 5.95, 5.99], [6.02, 6.12, 5.99, 5.99]] target_price_000040 = [[3.63, 3.83, 3.63, 3.65], [3.99, 4.07, 3.97, 4.03], [4.1, 4.11, 3.93, 3.95], [4.12, 4.13, 4.06, 4.11], [4.13, 4.19, 4.07, 4.13], [4.27, 4.28, 4.11, 4.12], [4.37, 4.38, 4.25, 4.29], [4.34, 4.5, 4.32, 4.41], [4.28, 4.35, 4.2, 4.34], [4.41, 4.43, 4.29, 4.31], [4.42, 4.45, 4.36, 4.41], [4.51, 4.56, 4.33, 4.35], [4.35, 4.55, 4.31, 4.55], [4.3, 4.41, 4.22, 4.36], [4.27, 4.44, 4.23, 4.34], [4.23, 4.27, 4.18, 4.25]] print(f'test get price type raw data with single thread') df_list = get_price_type_raw_data(start=start, end=end, shares=shares, htypes=htypes, freq='d') self.assertIsInstance(df_list, dict) self.assertEqual(len(df_list), 3) self.assertTrue(np.allclose(df_list['000039.SZ'].values, np.array(target_price_000039))) self.assertTrue(np.allclose(df_list['600748.SH'].values, np.array(target_price_600748))) self.assertTrue(np.allclose(df_list['000040.SZ'].values, np.array(target_price_000040))) print(f'in get financial report type raw data, got DataFrames: \n"000039.SZ":\n' f'{df_list["000039.SZ"]}\n"600748.SH":\n' f'{df_list["600748.SH"]}\n"000040.SZ":\n{df_list["000040.SZ"]}') print(f'test get price type raw data with with multi threads') df_list = get_price_type_raw_data(start=start, end=end, shares=shares, htypes=htypes, freq='d', parallel=10) self.assertIsInstance(df_list, dict) self.assertEqual(len(df_list), 3) self.assertTrue(np.allclose(df_list['000039.SZ'].values, np.array(target_price_000039))) self.assertTrue(np.allclose(df_list['600748.SH'].values, np.array(target_price_600748))) self.assertTrue(np.allclose(df_list['000040.SZ'].values, np.array(target_price_000040))) print(f'in get financial report type raw data, got DataFrames: \n"000039.SZ":\n' f'{df_list["000039.SZ"]}\n"600748.SH":\n' f'{df_list["600748.SH"]}\n"000040.SZ":\n{df_list["000040.SZ"]}') def test_get_financial_report_type_raw_data(self): shares = '000039.SZ, 600748.SH, 000040.SZ' start = '20160101' end = '20201231' htypes = 'eps,basic_eps,diluted_eps,total_revenue,revenue,total_share,' \ 'cap_rese,undistr_porfit,surplus_rese,net_profit' target_eps_000039 = [[1.41], [0.1398], [-0.0841], [-0.1929], [0.37], [0.1357], [0.1618], [0.1191], [1.11], [0.759], [0.3061], [0.1409], [0.81], [0.4187], [0.2554], [0.1624], [0.14], [-0.0898], [-0.1444], [0.1291]] target_eps_600748 = [[0.41], [0.22], [0.22], [0.09], [0.42], [0.23], [0.22], [0.09], [0.36], [0.16], [0.15], [0.07], [0.47], [0.19], [0.12], [0.07], [0.32], [0.22], [0.14], [0.07]] target_eps_000040 = [[-0.6866], [-0.134], [-0.189], [-0.036], [-0.6435], [0.05], [0.062], [0.0125], [0.8282], [1.05], [0.985], [0.811], [0.41], [0.242], [0.113], [0.027], [0.19], [0.17], [0.17], [0.064]] target_basic_eps_000039 = [[1.3980000e-01, 1.3980000e-01, 6.3591954e+10, 6.3591954e+10], [-8.4100000e-02, -8.4100000e-02, 3.9431807e+10, 3.9431807e+10], [-1.9290000e-01, -1.9290000e-01, 1.5852177e+10, 1.5852177e+10], [3.7000000e-01, 3.7000000e-01, 8.5815341e+10, 8.5815341e+10], [1.3570000e-01, 1.3430000e-01, 6.1660271e+10, 6.1660271e+10], [1.6180000e-01, 1.6040000e-01, 4.2717729e+10, 4.2717729e+10], [1.1910000e-01, 1.1900000e-01, 1.9099547e+10, 1.9099547e+10], [1.1100000e+00, 1.1000000e+00, 9.3497622e+10, 9.3497622e+10], [7.5900000e-01, 7.5610000e-01, 6.6906147e+10, 6.6906147e+10], [3.0610000e-01, 3.0380000e-01, 4.3560398e+10, 4.3560398e+10], [1.4090000e-01, 1.4050000e-01, 1.9253639e+10, 1.9253639e+10], [8.1000000e-01, 8.1000000e-01, 7.6299930e+10, 7.6299930e+10], [4.1870000e-01, 4.1710000e-01, 5.3962706e+10, 5.3962706e+10], [2.5540000e-01, 2.5440000e-01, 3.3387152e+10, 3.3387152e+10], [1.6240000e-01, 1.6200000e-01, 1.4675987e+10, 1.4675987e+10], [1.4000000e-01, 1.4000000e-01, 5.1111652e+10, 5.1111652e+10], [-8.9800000e-02, -8.9800000e-02, 3.4982614e+10, 3.4982614e+10], [-1.4440000e-01, -1.4440000e-01, 2.3542843e+10, 2.3542843e+10], [1.2910000e-01, 1.2860000e-01, 1.0412416e+10, 1.0412416e+10], [7.2000000e-01, 7.1000000e-01, 5.8685804e+10, 5.8685804e+10]] target_basic_eps_600748 = [[2.20000000e-01, 2.20000000e-01, 5.29423397e+09, 5.29423397e+09], [2.20000000e-01, 2.20000000e-01, 4.49275653e+09, 4.49275653e+09], [9.00000000e-02, 9.00000000e-02, 1.59067065e+09, 1.59067065e+09], [4.20000000e-01, 4.20000000e-01, 8.86555586e+09, 8.86555586e+09], [2.30000000e-01, 2.30000000e-01, 5.44850143e+09, 5.44850143e+09], [2.20000000e-01, 2.20000000e-01, 4.34978927e+09, 4.34978927e+09], [9.00000000e-02, 9.00000000e-02, 1.73793793e+09, 1.73793793e+09], [3.60000000e-01, 3.60000000e-01, 8.66375241e+09, 8.66375241e+09], [1.60000000e-01, 1.60000000e-01, 4.72875116e+09, 4.72875116e+09], [1.50000000e-01, 1.50000000e-01, 3.76879016e+09, 3.76879016e+09], [7.00000000e-02, 7.00000000e-02, 1.31785454e+09, 1.31785454e+09], [4.70000000e-01, 4.70000000e-01, 7.23391685e+09, 7.23391685e+09], [1.90000000e-01, 1.90000000e-01, 3.76072215e+09, 3.76072215e+09], [1.20000000e-01, 1.20000000e-01, 2.35845364e+09, 2.35845364e+09], [7.00000000e-02, 7.00000000e-02, 1.03831865e+09, 1.03831865e+09], [3.20000000e-01, 3.20000000e-01, 6.48880919e+09, 6.48880919e+09], [2.20000000e-01, 2.20000000e-01, 3.72209142e+09, 3.72209142e+09], [1.40000000e-01, 1.40000000e-01, 2.22563924e+09, 2.22563924e+09], [7.00000000e-02, 7.00000000e-02, 8.96647052e+08, 8.96647052e+08], [4.80000000e-01, 4.80000000e-01, 6.61917508e+09, 6.61917508e+09]] target_basic_eps_000040 = [[-1.34000000e-01, -1.34000000e-01, 2.50438755e+09, 2.50438755e+09], [-1.89000000e-01, -1.89000000e-01, 1.32692347e+09, 1.32692347e+09], [-3.60000000e-02, -3.60000000e-02, 5.59073338e+08, 5.59073338e+08], [-6.43700000e-01, -6.43700000e-01, 6.80576162e+09, 6.80576162e+09], [5.00000000e-02, 5.00000000e-02, 6.38891620e+09, 6.38891620e+09], [6.20000000e-02, 6.20000000e-02, 5.23267082e+09, 5.23267082e+09], [1.25000000e-02, 1.25000000e-02, 2.22420874e+09, 2.22420874e+09], [8.30000000e-01, 8.30000000e-01, 8.67628947e+09, 8.67628947e+09], [1.05000000e+00, 1.05000000e+00, 5.29431716e+09, 5.29431716e+09], [9.85000000e-01, 9.85000000e-01, 3.56822382e+09, 3.56822382e+09], [8.11000000e-01, 8.11000000e-01, 1.06613439e+09, 1.06613439e+09], [4.10000000e-01, 4.10000000e-01, 8.13102532e+09, 8.13102532e+09], [2.42000000e-01, 2.42000000e-01, 5.17971521e+09, 5.17971521e+09], [1.13000000e-01, 1.13000000e-01, 3.21704120e+09, 3.21704120e+09], [2.70000000e-02, 2.70000000e-02, 8.41966738e+08, 8.24272235e+08], [1.90000000e-01, 1.90000000e-01, 3.77350171e+09, 3.77350171e+09], [1.70000000e-01, 1.70000000e-01, 2.38643892e+09, 2.38643892e+09], [1.70000000e-01, 1.70000000e-01, 1.29127117e+09, 1.29127117e+09], [6.40000000e-02, 6.40000000e-02, 6.03256858e+08, 6.03256858e+08], [1.30000000e-01, 1.30000000e-01, 1.66572918e+09, 1.66572918e+09]] target_total_share_000039 = [[3.5950140e+09, 4.8005360e+09, 2.1573660e+10, 3.5823430e+09], [3.5860750e+09, 4.8402300e+09, 2.0750827e+10, 3.5823430e+09], [3.5860750e+09, 4.9053550e+09, 2.0791307e+10, 3.5823430e+09], [3.5845040e+09, 4.8813110e+09, 2.1482857e+10, 3.5823430e+09], [3.5831490e+09, 4.9764250e+09, 2.0926816e+10, 3.2825850e+09], [3.5825310e+09, 4.8501270e+09, 2.1020418e+10, 3.2825850e+09], [2.9851110e+09, 5.4241420e+09, 2.2438350e+10, 3.2825850e+09], [2.9849890e+09, 4.1284000e+09, 2.2082769e+10, 3.2825850e+09], [2.9849610e+09, 4.0838010e+09, 2.1045994e+10, 3.2815350e+09], [2.9849560e+09, 4.2491510e+09, 1.9694345e+10, 3.2815350e+09], [2.9846970e+09, 4.2351600e+09, 2.0016361e+10, 3.2815350e+09], [2.9828890e+09, 4.2096630e+09, 1.9734494e+10, 3.2815350e+09], [2.9813960e+09, 3.4564240e+09, 1.8562738e+10, 3.2793790e+09], [2.9803530e+09, 3.0759650e+09, 1.8076208e+10, 3.2793790e+09], [2.9792680e+09, 3.1376690e+09, 1.7994776e+10, 3.2793790e+09], [2.9785770e+09, 3.1265850e+09, 1.7495053e+10, 3.2793790e+09], [2.9783640e+09, 3.1343850e+09, 1.6740840e+10, 3.2035780e+09], [2.9783590e+09, 3.1273880e+09, 1.6578389e+10, 3.2035780e+09], [2.9782780e+09, 3.1169280e+09, 1.8047639e+10, 3.2035780e+09], [2.9778200e+09, 3.1818630e+09, 1.7663145e+10, 3.2035780e+09]] target_total_share_600748 = [[1.84456289e+09, 2.60058426e+09, 5.72443733e+09, 4.58026529e+08], [1.84456289e+09, 2.60058426e+09, 5.72096899e+09, 4.58026529e+08], [1.84456289e+09, 2.60058426e+09, 5.65738237e+09, 4.58026529e+08], [1.84456289e+09, 2.60058426e+09, 5.50257806e+09, 4.58026529e+08], [1.84456289e+09, 2.59868164e+09, 5.16741523e+09, 4.44998882e+08], [1.84456289e+09, 2.59684471e+09, 5.14677280e+09, 4.44998882e+08], [1.84456289e+09, 2.59684471e+09, 4.94955591e+09, 4.44998882e+08], [1.84456289e+09, 2.59684471e+09, 4.79001451e+09, 4.44998882e+08], [1.84456289e+09, 3.11401684e+09, 4.46326988e+09, 4.01064256e+08], [1.84456289e+09, 3.11596723e+09, 4.45419136e+09, 4.01064256e+08], [1.84456289e+09, 3.11596723e+09, 4.39652948e+09, 4.01064256e+08], [1.84456289e+09, 3.18007783e+09, 4.26608403e+09, 4.01064256e+08], [1.84456289e+09, 3.10935622e+09, 3.78417688e+09, 3.65651701e+08], [1.84456289e+09, 3.10935622e+09, 3.65806574e+09, 3.65651701e+08], [1.84456289e+09, 3.10935622e+09, 3.62063090e+09, 3.65651701e+08], [1.84456289e+09, 3.10935622e+09, 3.50063915e+09, 3.65651701e+08], [1.41889453e+09, 3.55940850e+09, 3.22272993e+09, 3.62124939e+08], [1.41889453e+09, 3.56129650e+09, 3.11477476e+09, 3.62124939e+08], [1.41889453e+09, 3.59632888e+09, 3.06836903e+09, 3.62124939e+08], [1.08337087e+09, 3.37400726e+07, 3.00918704e+09, 3.62124939e+08]] target_total_share_000040 = [[1.48687387e+09, 1.06757900e+10, 8.31900755e+08, 2.16091994e+08], [1.48687387e+09, 1.06757900e+10, 7.50177302e+08, 2.16091994e+08], [1.48687387e+09, 1.06757899e+10, 9.90255974e+08, 2.16123282e+08], [1.48687387e+09, 1.06757899e+10, 1.03109866e+09, 2.16091994e+08], [1.48687387e+09, 1.06757910e+10, 2.07704745e+09, 2.16123282e+08], [1.48687387e+09, 1.06757910e+10, 2.09608665e+09, 2.16123282e+08], [1.48687387e+09, 1.06803833e+10, 2.13354083e+09, 2.16123282e+08], [1.48687387e+09, 1.06804090e+10, 2.11489364e+09, 2.16123282e+08], [1.33717327e+09, 8.87361727e+09, 2.42939924e+09, 1.88489589e+08], [1.33717327e+09, 8.87361727e+09, 2.34220254e+09, 1.88489589e+08], [1.33717327e+09, 8.87361727e+09, 2.16390368e+09, 1.88489589e+08], [1.33717327e+09, 8.87361727e+09, 1.07961915e+09, 1.88489589e+08], [1.33717327e+09, 8.87361727e+09, 8.58866066e+08, 1.88489589e+08], [1.33717327e+09, 8.87361727e+09, 6.87024393e+08, 1.88489589e+08], [1.33717327e+09, 8.87361727e+09, 5.71554565e+08, 1.88489589e+08], [1.33717327e+09, 8.87361727e+09, 5.54241222e+08, 1.88489589e+08], [1.33717327e+09, 8.87361726e+09, 5.10059576e+08, 1.88489589e+08], [1.33717327e+09, 8.87361726e+09, 4.59351639e+08, 1.88489589e+08], [4.69593364e+08, 2.78355875e+08, 4.13430814e+08, 1.88489589e+08], [4.69593364e+08, 2.74235459e+08, 3.83557678e+08, 1.88489589e+08]] target_net_profit_000039 = [[np.nan], [2.422180e+08], [np.nan], [2.510113e+09], [np.nan], [1.102220e+09], [np.nan], [4.068455e+09], [np.nan], [1.315957e+09], [np.nan], [3.158415e+09], [np.nan], [1.066509e+09], [np.nan], [7.349830e+08], [np.nan], [-5.411600e+08], [np.nan], [2.271961e+09]] target_net_profit_600748 = [[np.nan], [4.54341757e+08], [np.nan], [9.14476670e+08], [np.nan], [5.25360283e+08], [np.nan], [9.24502415e+08], [np.nan], [4.66560302e+08], [np.nan], [9.15265285e+08], [np.nan], [2.14639674e+08], [np.nan], [7.45093049e+08], [np.nan], [2.10967312e+08], [np.nan], [6.04572711e+08]] target_net_profit_000040 = [[np.nan], [-2.82458846e+08], [np.nan], [-9.57130872e+08], [np.nan], [9.22114527e+07], [np.nan], [1.12643819e+09], [np.nan], [1.31715269e+09], [np.nan], [5.39940093e+08], [np.nan], [1.51440838e+08], [np.nan], [1.75339071e+08], [np.nan], [8.04740415e+07], [np.nan], [6.20445815e+07]] print('test get financial data, in multi thread mode') df_list = get_financial_report_type_raw_data(start=start, end=end, shares=shares, htypes=htypes, parallel=4) self.assertIsInstance(df_list, tuple) self.assertEqual(len(df_list), 4) self.assertEqual(len(df_list[0]), 3) self.assertEqual(len(df_list[1]), 3) self.assertEqual(len(df_list[2]), 3) self.assertEqual(len(df_list[3]), 3) # 检查确认所有数据类型正确 self.assertTrue(all(isinstance(item, pd.DataFrame) for subdict in df_list for item in subdict.values())) # 检查是否有空数据 print(all(item.empty for subdict in df_list for item in subdict.values())) # 检查获取的每组数据正确,且所有数据的顺序一致, 如果取到空数据,则忽略 if df_list[0]['000039.SZ'].empty: print(f'income data for "000039.SZ" is empty') else: self.assertTrue(np.allclose(df_list[0]['000039.SZ'].values, target_basic_eps_000039)) if df_list[0]['600748.SH'].empty: print(f'income data for "600748.SH" is empty') else: self.assertTrue(np.allclose(df_list[0]['600748.SH'].values, target_basic_eps_600748)) if df_list[0]['000040.SZ'].empty: print(f'income data for "000040.SZ" is empty') else: self.assertTrue(np.allclose(df_list[0]['000040.SZ'].values, target_basic_eps_000040)) if df_list[1]['000039.SZ'].empty: print(f'indicator data for "000039.SZ" is empty') else: self.assertTrue(np.allclose(df_list[1]['000039.SZ'].values, target_eps_000039)) if df_list[1]['600748.SH'].empty: print(f'indicator data for "600748.SH" is empty') else: self.assertTrue(np.allclose(df_list[1]['600748.SH'].values, target_eps_600748)) if df_list[1]['000040.SZ'].empty: print(f'indicator data for "000040.SZ" is empty') else: self.assertTrue(np.allclose(df_list[1]['000040.SZ'].values, target_eps_000040)) if df_list[2]['000039.SZ'].empty: print(f'balance data for "000039.SZ" is empty') else: self.assertTrue(np.allclose(df_list[2]['000039.SZ'].values, target_total_share_000039)) if df_list[2]['600748.SH'].empty: print(f'balance data for "600748.SH" is empty') else: self.assertTrue(np.allclose(df_list[2]['600748.SH'].values, target_total_share_600748)) if df_list[2]['000040.SZ'].empty: print(f'balance data for "000040.SZ" is empty') else: self.assertTrue(np.allclose(df_list[2]['000040.SZ'].values, target_total_share_000040)) if df_list[3]['000039.SZ'].empty: print(f'cash flow data for "000039.SZ" is empty') else: self.assertTrue(np.allclose(df_list[3]['000039.SZ'].values, target_net_profit_000039, equal_nan=True)) if df_list[3]['600748.SH'].empty: print(f'cash flow data for "600748.SH" is empty') else: self.assertTrue(np.allclose(df_list[3]['600748.SH'].values, target_net_profit_600748, equal_nan=True)) if df_list[3]['000040.SZ'].empty: print(f'cash flow data for "000040.SZ" is empty') else: self.assertTrue(np.allclose(df_list[3]['000040.SZ'].values, target_net_profit_000040, equal_nan=True)) print('test get financial data, in single thread mode') df_list = get_financial_report_type_raw_data(start=start, end=end, shares=shares, htypes=htypes, parallel=0) self.assertIsInstance(df_list, tuple) self.assertEqual(len(df_list), 4) self.assertEqual(len(df_list[0]), 3) self.assertEqual(len(df_list[1]), 3) self.assertEqual(len(df_list[2]), 3) self.assertEqual(len(df_list[3]), 3) # 检查确认所有数据类型正确 self.assertTrue(all(isinstance(item, pd.DataFrame) for subdict in df_list for item in subdict.values())) # 检查是否有空数据,因为网络问题,有可能会取到空数据 self.assertFalse(all(item.empty for subdict in df_list for item in subdict.values())) # 检查获取的每组数据正确,且所有数据的顺序一致, 如果取到空数据,则忽略 if df_list[0]['000039.SZ'].empty: print(f'income data for "000039.SZ" is empty') else: self.assertTrue(np.allclose(df_list[0]['000039.SZ'].values, target_basic_eps_000039)) if df_list[0]['600748.SH'].empty: print(f'income data for "600748.SH" is empty') else: self.assertTrue(np.allclose(df_list[0]['600748.SH'].values, target_basic_eps_600748)) if df_list[0]['000040.SZ'].empty: print(f'income data for "000040.SZ" is empty') else: self.assertTrue(np.allclose(df_list[0]['000040.SZ'].values, target_basic_eps_000040)) if df_list[1]['000039.SZ'].empty: print(f'indicator data for "000039.SZ" is empty') else: self.assertTrue(np.allclose(df_list[1]['000039.SZ'].values, target_eps_000039)) if df_list[1]['600748.SH'].empty: print(f'indicator data for "600748.SH" is empty') else: self.assertTrue(np.allclose(df_list[1]['600748.SH'].values, target_eps_600748)) if df_list[1]['000040.SZ'].empty: print(f'indicator data for "000040.SZ" is empty') else: self.assertTrue(np.allclose(df_list[1]['000040.SZ'].values, target_eps_000040)) if df_list[2]['000039.SZ'].empty: print(f'balance data for "000039.SZ" is empty') else: self.assertTrue(np.allclose(df_list[2]['000039.SZ'].values, target_total_share_000039)) if df_list[2]['600748.SH'].empty: print(f'balance data for "600748.SH" is empty') else: self.assertTrue(
np.allclose(df_list[2]['600748.SH'].values, target_total_share_600748)
numpy.allclose
import numpy as np import logging logger = logging.getLogger(name=__name__) from ...sgmcmc_sampler import SGMCMCHelper from ..._utils import random_categorical, lower_tri_mat_inv class SLDSHelper(SGMCMCHelper): """ LGSSM Helper forward_message (dict) with keys x (dict): log_constant (double) log scaling const mean_precision (ndarray) mean precision precision (ndarray) precision z (dict): prob_vector (ndarray) dimension num_states log_constant (double) log scaling const x_prev (ndarray) z_prev (ndarray) backward_message (dict) with keys x (dict): log_constant (double) log scaling const mean_precision (ndarray) mean precision precision (ndarray) precision z (dict): likelihood_vector (ndarray) dimension num_states log_constant (double) log scaling const x_next (ndarray) z_next (ndarray) """ def __init__(self, num_states, n, m, forward_message=None, backward_message=None, **kwargs): self.num_states = num_states self.n = n self.m = m if forward_message is None: forward_message = { 'x': { 'log_constant': 0.0, 'mean_precision': np.zeros(self.n), 'precision': np.eye(self.n)/10, }, 'z': { 'log_constant': 0.0, 'prob_vector': np.ones(self.num_states)/self.num_states, }, } self.default_forward_message=forward_message if backward_message is None: backward_message = { 'x': { 'log_constant': 0.0, 'mean_precision': np.zeros(self.n), 'precision': np.zeros((self.n, self.n)), }, 'z': { 'log_constant': np.log(self.num_states), 'likelihood_vector': np.ones(self.num_states)/self.num_states, }, } self.default_backward_message=backward_message return def _forward_messages(self, observations, parameters, forward_message, x=None, z=None, **kwargs): if z is not None: if x is not None: raise ValueError("Either x or z can be conditioned on") # Forward Messages conditioned on z return self._x_forward_messages( observations=observations, z=z, parameters=parameters, forward_message=forward_message, **kwargs ) elif x is not None: # Forward Messages conditioned on z return self._z_forward_messages( observations=observations, x=x, parameters=parameters, forward_message=forward_message, **kwargs ) else: raise ValueError("Requires x or z be passed to condition on") def _backward_messages(self, observations, parameters, backward_message, x=None, z=None, **kwargs): if z is not None: if x is not None: raise ValueError("Either x or z can be conditioned on") # Forward Messages conditioned on z return self._x_backward_messages( observations=observations, z=z, parameters=parameters, backward_message=backward_message, **kwargs ) elif x is not None: # Forward Messages conditioned on z return self._z_backward_messages( observations=observations, x=x, parameters=parameters, backward_message=backward_message, **kwargs ) else: raise ValueError("Requires x or z be passed to condition on") ## Helper Functions conditioned on z def _x_forward_messages(self, observations, z, parameters, forward_message, weights=None, tqdm=None, only_return_last=False): # Return list of forward messages Pr(x_{t} | y_{<=t}, z) # y is num_obs x m matrix num_obs = np.shape(observations)[0] if not only_return_last: forward_messages = [None]*(num_obs+1) forward_messages[0] = forward_message mean_precision = forward_message['x']['mean_precision'] precision = forward_message['x']['precision'] log_constant = forward_message['x']['log_constant'] z_prev = forward_message.get('z_prev', None) Pi = parameters.pi A = parameters.A LQinv = parameters.LQinv Qinv = np.array([np.dot(LQinv_k, LQinv_k.T) for LQinv_k in LQinv]) AtQinv = np.array([np.dot(A_k.T, Qinv_k) for (A_k, Qinv_k) in zip(A, Qinv)]) AtQinvA = np.array([np.dot(AtQinv_k, A_k) for (A_k, AtQinv_k) in zip(A, AtQinv)]) C = parameters.C LRinv = parameters.LRinv Rinv = np.dot(LRinv, LRinv.T) CtRinv = np.dot(C.T, Rinv) CtRinvC = np.dot(CtRinv, C) pbar = range(num_obs) if tqdm is not None: pbar = tqdm(pbar) pbar.set_description("forward messages") for t in pbar: y_cur = observations[t] z_cur = z[t] weight_t = 1.0 if weights is None else weights[t] # Calculate Predict Parameters J = np.linalg.solve(AtQinvA[z_cur] + precision, AtQinv[z_cur]) pred_mean_precision = np.dot(J.T, mean_precision) pred_precision = Qinv[z_cur] - np.dot(AtQinv[z_cur].T, J) # Calculate Observation Parameters y_mean = np.dot(C, np.linalg.solve(pred_precision, pred_mean_precision)) y_precision = Rinv - np.dot(CtRinv.T, np.linalg.solve(CtRinvC + pred_precision, CtRinv)) log_constant += weight_t * ( -0.5 * np.dot(y_cur-y_mean, np.dot(y_precision, y_cur-y_mean)) + \ 0.5 * np.linalg.slogdet(y_precision)[1] + \ -0.5 * self.m * np.log(2*np.pi) ) if z_prev is not None: log_constant += weight_t * np.log(Pi[z_prev, z_cur]) # Calculate Filtered Parameters new_mean_precision = pred_mean_precision + np.dot(CtRinv, y_cur) new_precision = pred_precision + CtRinvC # Save Messages mean_precision = new_mean_precision precision = new_precision z_prev = z_cur if not only_return_last: forward_messages[t+1] = dict( x={ 'mean_precision': mean_precision, 'precision': precision, 'log_constant': log_constant, }, z_prev=z_prev, ) if only_return_last: last_message = dict( x={ 'mean_precision': mean_precision, 'precision': precision, 'log_constant': log_constant, }, z_prev=z_prev, ) return last_message else: return forward_messages def _x_backward_messages(self, observations, z, parameters, backward_message, weights=None, tqdm=None, only_return_last=False): # Return list of backward messages Pr(y_{>t} | x_t, z) # y is num_obs x n matrix num_obs = np.shape(observations)[0] if not only_return_last: backward_messages = [None]*(num_obs+1) backward_messages[-1] = backward_message mean_precision = backward_message['x']['mean_precision'] precision = backward_message['x']['precision'] log_constant = backward_message['x']['log_constant'] z_next = backward_message.get('z_next', None) Pi = parameters.pi A = parameters.A LQinv = parameters.LQinv Qinv = np.array([np.dot(LQinv_k, LQinv_k.T) for LQinv_k in LQinv]) AtQinv = np.array([np.dot(A_k.T, Qinv_k) for (A_k, Qinv_k) in zip(A, Qinv)]) AtQinvA = np.array([np.dot(AtQinv_k, A_k) for (A_k, AtQinv_k) in zip(A, AtQinv)]) C = parameters.C LRinv = parameters.LRinv Rinv = np.dot(LRinv, LRinv.T) CtRinv = np.dot(C.T, Rinv) CtRinvC = np.dot(CtRinv, C) pbar = reversed(range(num_obs)) if tqdm is not None: pbar = tqdm(pbar) pbar.set_description("backward messages") for t in pbar: y_cur = observations[t] z_cur = z[t] weight_t = 1.0 if weights is None else weights[t] # Helper Values xi = Qinv[z_cur] + precision + CtRinvC L = np.linalg.solve(xi, AtQinv[z_cur].T) vi = mean_precision + np.dot(CtRinv, y_cur) # Calculate new parameters log_constant += weight_t * ( -0.5 * self.m * np.log(2.0*np.pi) + \ np.sum(np.log(np.diag(LRinv))) + \ np.sum(np.log(np.diag(LQinv[z_cur]))) + \ -0.5 * np.linalg.slogdet(xi)[1] + \ -0.5 * np.dot(y_cur, np.dot(Rinv, y_cur)) + \ 0.5 * np.dot(vi, np.linalg.solve(xi, vi)) ) if z_next is not None: log_constant += weight_t * np.log(Pi[z_cur, z_next]) new_mean_precision = np.dot(L.T, vi) new_precision = AtQinvA[z_cur] - np.dot(AtQinv[z_cur], L) # Save Messages mean_precision = new_mean_precision precision = new_precision z_next = z_cur if not only_return_last: backward_messages[t] = dict(x={ 'mean_precision': mean_precision, 'precision': precision, 'log_constant': log_constant, }, z_next=z_next) if only_return_last: last_message = dict(x={ 'mean_precision': mean_precision, 'precision': precision, 'log_constant': log_constant, }, z_next=z_next) return last_message else: return backward_messages def _x_marginal_loglikelihood(self, observations, z, parameters, forward_message=None, backward_message=None, weights=None, **kwargs): # Run forward pass + combine with backward pass # y is num_obs x m matrix # forward_pass is Pr(x_{T-1} | y_{<=T-1}) forward_pass = self._forward_message( observations=observations, z=z, parameters=parameters, forward_message=forward_message, weights=weights, **kwargs) weight_T = 1.0 if weights is None else weights[-1] # Calculate the marginal loglikelihood of forward + backward message f_mean_precision = forward_pass['x']['mean_precision'] f_precision = forward_pass['x']['precision'] c_mean_precision = f_mean_precision + backward_message['x']['mean_precision'] c_precision = f_precision + backward_message['x']['precision'] loglikelihood = forward_pass['x']['log_constant'] + \ (backward_message['x']['log_constant'] + \ +0.5 * np.linalg.slogdet(f_precision)[1] + \ -0.5 * np.linalg.slogdet(c_precision)[1] + \ -0.5 * np.dot(f_mean_precision, np.linalg.solve(f_precision, f_mean_precision) ) + \ 0.5 * np.dot(c_mean_precision, np.linalg.solve(c_precision, c_mean_precision) ) ) * weight_T z_next = backward_message.get('z_next') z_prev = forward_pass.get('z_prev') if (z_next is not None) and (z_prev is not None): loglikelihood = loglikelihood + weight_T * np.log( parameters.pi[z_prev, z_next]) return loglikelihood def _x_gradient_marginal_loglikelihood(self, observations, z, parameters, forward_message=None, backward_message=None, weights=None, tqdm=None): Pi, expanded_pi = parameters.pi, parameters.expanded_pi A, LQinv, C, LRinv = \ parameters.A, parameters.LQinv, parameters.C, parameters.LRinv # Forward Pass # forward_messages = [Pr(x_{t} | z, y_{-inf:t}), y{t}] for t=-1,...,T-1 forward_messages = self.forward_pass( observations=observations, z=z, parameters=parameters, forward_message=forward_message, include_init_message=True) # Backward Pass # backward_messages = [Pr(y_{t+1:inf} | z,x_{t}), y{t}] for t=-1,...,T-1 backward_messages = self.backward_pass( observations=observations, z=z, parameters=parameters, backward_message=backward_message, include_init_message=True) # Gradients grad = {var: np.zeros_like(value) for var, value in parameters.as_dict().items()} grad['LQinv'] = np.zeros_like(parameters.LQinv) grad['LRinv'] = np.zeros_like(parameters.LRinv) # Helper Constants Rinv = np.dot(LRinv, LRinv.T) RinvC = np.dot(Rinv, C) CtRinvC = np.dot(C.T, RinvC) LRinv_diaginv = np.diag(np.diag(LRinv)**-1) Qinv = np.array([np.dot(LQinv_k, LQinv_k.T) for LQinv_k in LQinv]) QinvA = np.array([np.dot(Qinv_k, A_k) for (A_k, Qinv_k) in zip(A, Qinv)]) AtQinvA = np.array([np.dot(A_k.T, QinvA_k) for (A_k, QinvA_k) in zip(A, QinvA)]) LQinv_diaginv = np.array([np.diag(np.diag(LQinv_k)**-1) for LQinv_k in LQinv]) # Emission Gradients p_bar = zip(forward_messages[1:], backward_messages[1:], observations) if tqdm is not None: pbar = tqdm(pbar) pbar.set_description("emission gradient loglike") for t, (forward_t, backward_t, y_t) in enumerate(p_bar): weight_t = 1.0 if weights is None else weights[t] # Pr(x_t | y) c_mean_precision = \ forward_t['x']['mean_precision'] + \ backward_t['x']['mean_precision'] c_precision = \ forward_t['x']['precision'] + backward_t['x']['precision'] x_mean = np.linalg.solve(c_precision, c_mean_precision) xxt_mean = np.linalg.inv(c_precision) + np.outer(x_mean, x_mean) # Gradient of C grad['C'] += weight_t * (np.outer(np.dot(Rinv, y_t), x_mean) + \ -1.0 * np.dot(RinvC, xxt_mean)) # Gradient of LRinv #raise NotImplementedError("SHOULD CHECK THE MATH FOR LRINV") Cxyt = np.outer(np.dot(C, x_mean), y_t) CxxtCt = np.dot(C, np.dot(xxt_mean, C.T)) grad['LRinv'] += weight_t * (LRinv_diaginv + \ -1.0*np.dot(np.outer(y_t, y_t) - Cxyt - Cxyt.T + CxxtCt, LRinv)) # Transition Gradients p_bar = zip(forward_messages[0:-1], backward_messages[1:], observations, z) if tqdm is not None: pbar = tqdm(pbar) pbar.set_description("transition gradient loglike") for t, (forward_t, backward_t, y_t, z_t) in enumerate(p_bar): weight_t = 1.0 if weights is None else weights[t] # Pr(x_t, x_t+1 | y) c_mean_precision = \ np.concatenate([ forward_t['x']['mean_precision'], backward_t['x']['mean_precision'] + np.dot(RinvC.T,y_t) ]) c_precision = \ np.block([ [forward_t['x']['precision'] + AtQinvA[z_t], -QinvA[z_t].T], [-QinvA[z_t], backward_t['x']['precision'] + CtRinvC + Qinv[z_t]] ]) c_mean = np.linalg.solve(c_precision, c_mean_precision) c_cov = np.linalg.inv(c_precision) xp_mean = c_mean[0:self.n] xn_mean = c_mean[self.n:] xpxpt_mean = c_cov[0:self.n, 0:self.n] + np.outer(xp_mean, xp_mean) xnxpt_mean = c_cov[self.n:, 0:self.n] + np.outer(xn_mean, xp_mean) xnxnt_mean = c_cov[self.n:, self.n:] + np.outer(xn_mean, xn_mean) # Gradient of A grad['A'][z_t] += weight_t * (np.dot(Qinv[z_t], xnxpt_mean - np.dot(A[z_t],xpxpt_mean))) # Gradient of LQinv Axpxnt = np.dot(A[z_t], xnxpt_mean.T) AxpxptAt = np.dot(A[z_t], np.dot(xpxpt_mean, A[z_t].T)) grad['LQinv'][z_t] += weight_t * (LQinv_diaginv[z_t] + \ -1.0*np.dot(xnxnt_mean - Axpxnt - Axpxnt.T + AxpxptAt, LQinv[z_t])) # Latent State Gradients z_prev = forward_message.get('z_prev') if forward_message is not None else None for t, z_t in enumerate(z): weight_t = 1.0 if weights is None else weights[t] if z_prev is not None: if parameters.pi_type == "logit": logit_pi_grad_t = -Pi[z_prev] + 0.0 logit_pi_grad_t[z_t] += 1.0 grad['logit_pi'][z_prev] += weight_t * logit_pi_grad_t elif parameters.pi_type == "expanded": expanded_pi_grad_t = - Pi[z_prev] / expanded_pi[z_prev] expanded_pi_grad_t[z_t] += 1.0 / expanded_pi[z_prev, z_t] grad['expanded_pi'][z_prev] += weight_t * expanded_pi_grad_t z_prev = z_t grad['LQinv_vec'] = np.array([grad_LQinv_k[np.tril_indices(self.n)] for grad_LQinv_k in grad.pop('LQinv')]) grad['LRinv_vec'] = grad.pop('LRinv')[np.tril_indices(self.m)] return grad def _x_predictive_loglikelihood(self, observations, z, parameters, lag=10, forward_message=None, backward_message=None, **kwargs): if forward_message is None: forward_message = self.default_forward_message if backward_message is None: backward_message = self.default_backward_message # Calculate Filtered if lag == 0: forward_messages = self.forward_pass( observations=observations, z=z, parameters=parameters, forward_message=forward_message, **kwargs) else: forward_messages = self.forward_pass( observations=observations[0:-lag], z=z[0:-lag], parameters=parameters, forward_message=forward_message, **kwargs) loglike = 0.0 A = parameters.A Q = parameters.Q C = parameters.C R = parameters.R for t in range(lag, np.shape(observations)[0]): y_cur = observations[t] z_cur = z[t] # Calculate Pr(x_t | y_{<=t-lag}, theta) mean_precision = forward_messages[t-lag]['x']['mean_precision'] precision = forward_messages[t-lag]['x']['precision'] mean = np.linalg.solve(precision, mean_precision) var = np.linalg.inv(precision) for l in range(lag): mean = np.dot(A[z_cur], mean) var = np.dot(A[z_cur], np.dot(var, A[z_cur].T)) + Q[z_cur] y_mean = np.dot(C, mean) y_var = np.dot(C, np.dot(var, C.T)) + R log_like_t = -0.5 * np.dot(y_cur - y_mean, np.linalg.solve(y_var, y_cur - y_mean)) + \ -0.5 * np.linalg.slogdet(y_var)[1] + \ -0.5 * self.m * np.log(2*np.pi) loglike += log_like_t return loglike def _x_latent_var_sample(self, observations, z, parameters, forward_message=None, backward_message=None, distribution='smoothed', tqdm=None): """ Sample latent vars from observations Args: observations (ndarray): num_obs by n observations z (ndarray): num_obs latent states parameters (LGSSMParameters): parameters forward_message (dict): alpha message backward_message (dict): beta message distr (string): 'smoothed', 'filtered', 'predict' smoothed: sample X from Pr(X | Y, theta) filtered: sample X_t from Pr(X_t | Y_<=t, theta) iid for all t predictive: sample X_t from Pr(X_t | Y_<t, theta) iid for all t Returns x (ndarray): num_obs sampled latent values (in R^n) """ if forward_message is None: forward_message = self.default_forward_message if backward_message is None: backward_message = self.default_backward_message A = parameters.A LQinv = parameters.LQinv Qinv = np.array([np.dot(LQinv_k, LQinv_k.T) for LQinv_k in LQinv]) AtQinv = np.array([np.dot(A_k.T, Qinv_k) for (A_k, Qinv_k) in zip(A, Qinv)]) AtQinvA = np.array([np.dot(AtQinv_k, A_k) for (A_k, AtQinv_k) in zip(A, AtQinv)]) L = np.shape(observations)[0] if distribution == 'smoothed': # Forward Pass forward_messages = self.forward_pass( observations=observations, z=z, parameters=parameters, forward_message=forward_message, include_init_message=False, tqdm=tqdm ) # Backward Sampler x = np.zeros((L, self.n)) x_cov = np.linalg.inv(forward_messages[-1]['x']['precision']) x_mean = np.dot(x_cov, forward_messages[-1]['x']['mean_precision']) x[-1, :] = np.random.multivariate_normal(mean=x_mean, cov=x_cov) pbar = reversed(range(L-1)) if tqdm is not None: pbar = tqdm(pbar) pbar.set_description("backward smoothed sampling x") for t in pbar: x_next = x[t+1,:] z_next = z[t+1] x_cov = np.linalg.inv(forward_messages[t]['x']['precision'] + AtQinvA[z_next]) x_mean = np.dot(x_cov, forward_messages[t]['x']['mean_precision'] +
np.dot(AtQinv[z_next], x_next)
numpy.dot
#!/usr/bin/python2.7 # -*- coding:utf-8 -*- # Author: NetworkRanger # Date: 2018/12/22 下午6:39 # 11.2 TensorFlow可视化: Tensorboard # 1. 导入必要的编程库 import os import io import time import numpy as np import matplotlib.pyplot as plt import tensorflow as tf # 2. 初始化计算图会话,创建summary-writer将Tensorboard summary写入Tensorboard文件夹 sess = tf.Session() # Create a visualizer object summary_writer = tf.train.SummaryWriter('tensorboard', tf.get_default_graph()) # 3. 确保summary_writer写入的Tensorboardyyywr夹存在 if not os.path.exists('tensorboard'): os.makedirs('tensorboard') # 4. 设置模型参数,为模型生成线性数据集。注意,设置真实斜率true_slope为2(注:迭代训练时,我们将随着时间的变化可视化斜率,起到取到真实斜率值) batch_size = 50 generations = 100 # Create sample input data x_data = np.arange(1000)/10. true_slope = 2. y_data = x_data * true_slope +
np.random.normal(loc=0.0, scale=25, size=1000)
numpy.random.normal
from cmstk.structure.util import metric_tensor, cartesian_fractional_matrix from cmstk.structure.util import fractional_cartesian_matrix, position_index from cmstk.structure.util import volume from cmstk.util import within_one_percent import numpy as np def test_metric_tensor_triclinic(): vectors = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) # parameters of Microcline # https://www.mindat.org/min-2704.html a, b, c = 8.5784, 12.96, 7.2112 alpha, beta, gamma = 90.3, 116.05, 89 mt = metric_tensor(a, b, c, alpha, beta, gamma) for i, v in enumerate(vectors): res = np.matmul(v, mt) res = np.matmul(res, v) if i == 0: assert within_one_percent(res, 73.59) elif i == 1: assert within_one_percent(res, 167.96) elif i == 2: assert within_one_percent(res, 52) v = np.sqrt(np.linalg.det(mt)) assert within_one_percent(v, 720.16) def test_metric_tensor_monoclinic(): vectors = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) # parameters of Orthoclase # https://www.mindat.org/min-3026.html a, b, c = 8.5632, 12.963, 7.299 alpha, beta, gamma = 90, 116.073, 90 mt = metric_tensor(a, b, c, alpha, beta, gamma) for i, v in enumerate(vectors): res = np.matmul(v, mt) res = np.matmul(res, v) if i == 0: assert within_one_percent(res, 73.33) elif i == 1: assert within_one_percent(res, 168.04) elif i == 2: assert within_one_percent(res, 53.28) v = np.sqrt(np.linalg.det(mt)) assert within_one_percent(v, 727.77) def test_metric_tensor_orthorhombic(): vectors = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) # parameters of Aragonite # https://www.mindat.org/min-307.html a, b, c = 4.9611, 7.9672, 5.7407 alpha, beta, gamma = 90, 90, 90 mt = metric_tensor(a, b, c, alpha, beta, gamma) for i, v in enumerate(vectors): res =
np.matmul(v, mt)
numpy.matmul
""" Gmsh format 2.2 """ import numpy as np from flow import Flow from element import Element from element_search import find_neighbors from text.text_flow import write_flow from text.text_elements import write_elements from text.text_geometries import write_geometries #============================================================================== def intIt(l): return np.array([int(e) for e in l]) def floatIt(l): return np.array([float(e) for e in l]) def extract_msh(path_msh): f = open(path_msh, 'r') nodes_X, nodes_Y = [], [] elements = [] line = f.readline() # ... # $Nodes\n # n_nodes # ... while line != '$Nodes\n': line = f.readline() line = f.readline() n_nodes = int(line.strip()) for i in range(n_nodes): # line = id x y z line = f.readline() coord = floatIt(line.strip().split()) nodes_X.append(coord[1]) nodes_Y.append(coord[2]) # ... # $Elements\n # n_elements # ... while line != '$Elements\n': line = f.readline() line = f.readline() n_elements = int(line.strip()) count = 0 for i in range(n_elements): # element_id element_type ... ... nodes_id line = f.readline() coord = intIt(line.strip().split()) element_type = coord[1] if element_type == 9: # 6-node second order triangle count += 1 e = Element(count) e.nodes = np.array(coord[-6:]) elements.append(e) # if element_type == 1: # 2-node line # e.element_type = 1 # e.nodes = coord[-2:] # # elif element_type == 2: # 3-node triangle # e.element_type = 2 # e.nodes = coord[-3:] # # elif element_type == 3: # 4-node quadrangle # e.element_type = 3 # e.nodes = coord[-4:] # # elif element_type == 8: # 3-node second order line # e.element_type = 8 # e.nodes = coord[-3:] # # elif element_type == 9: # 6-node second order triangle # e.element_type = 9 # e.nodes = coord[-6:] # # elif element_type == 10: # 9-node second order quadrangle # e.element_type = 10 # e.nodes = coord[-9:] # # elif element_type == 15: # 1-node point # e.element_type = 15 # e.nodes = coord[-1:] # # elements.append(e) f.close() return np.array(nodes_X), np.array(nodes_Y), np.array(elements) def generate_poiseuille(path_msh, parent_folder): single_nodes_X, single_nodes_Y, elements = extract_msh(path_msh) d = np.max(single_nodes_Y) - np.min(single_nodes_Y) y_middle = np.min(single_nodes_Y) + d/2 n_nodes = len(single_nodes_X) mu = 1e-3 p = 2*mu*single_nodes_X U = d**2/4 - (single_nodes_Y - y_middle)**2 V = np.zeros(n_nodes) nodes_X, nodes_Y = np.array([]), np.array([]) Us, Vs, ps = np.array([]), np.array([]), np.array([]) Nt = 101 times = np.linspace(0, 1, Nt) for t in times: nodes_X = np.vstack([nodes_X, single_nodes_X]) if nodes_X.size else single_nodes_X nodes_Y = np.vstack([nodes_Y, single_nodes_Y]) if nodes_Y.size else single_nodes_Y Us = np.vstack([Us, U]) if Us.size else U Vs = np.vstack([Vs, V]) if Vs.size else V ps = np.vstack([ps, p]) if ps.size else p Re, Ur = 1e-3*1*d/mu, np.inf # Reynolds number and reduced velocity are not # defined in the Hagen-Poiseuille problem flow = Flow() flow.Re, flow.Ur = Re, Ur flow.times = times flow.nodes_X, flow.nodes_Y = nodes_X, nodes_Y flow.Us, flow.Vs, flow.ps = Us, Vs, ps write_flow(flow, parent_folder + 'flows/poiseuille') find_neighbors(elements) write_elements(elements, parent_folder + 'elements/poiseuille') write_geometries(np.array([]), parent_folder + 'geometries/poiseuille') def generate_periodic(path_msh, parent_folder): single_nodes_X, single_nodes_Y, elements = extract_msh(path_msh) d = np.max(single_nodes_Y) - np.min(single_nodes_Y) Nt = 101 times = np.linspace(0, 1, Nt) period = 0.25 w = 2*np.pi/period # U = U0*cos(wt) with U0 = 1 # Navier-Stokes, uniform: # rho dU/dt + 0 = - dp/dx with rho = 1 # dp/dx = rhoU0*w*sin(wt) # p = p0 + rhoU0*w*sin(wt) with p0 = 0 nodes_X, nodes_Y = np.array([]), np.array([]) Us, Vs, ps = np.array([]), np.array([]), np.array([]) for t in times: nodes_X = np.vstack([nodes_X, single_nodes_X]) if nodes_X.size else single_nodes_X nodes_Y = np.vstack([nodes_Y, single_nodes_Y]) if nodes_Y.size else single_nodes_Y U = 0*nodes_X + np.cos(w*t) V = 0*nodes_X p = 0*nodes_X + w*np.sin(w*t) Us = np.vstack([Us, U]) if Us.size else U Vs = np.vstack([Vs, V]) if Vs.size else V ps = np.vstack([ps, p]) if ps.size else p Re, Ur = 1*1*d/1e-6, np.inf flow = Flow() flow.Re, flow.Ur = Re, Ur flow.times = times flow.nodes_X, flow.nodes_Y = nodes_X, nodes_Y flow.Us, flow.Vs, flow.ps = Us, Vs, ps write_flow(flow, parent_folder + 'flows/periodic') find_neighbors(elements) write_elements(elements, parent_folder + 'elements/periodic') write_geometries(np.array([]), parent_folder + 'geometries/periodic') def generate_inviscid(path_msh, parent_folder): single_nodes_X, single_nodes_Y, elements = extract_msh(path_msh) rs = np.sqrt(single_nodes_X**2 + single_nodes_Y**2) thetas = np.arctan2(single_nodes_Y, single_nodes_X) Ur, Utheta, p = [], [], [] for r, theta in zip(rs, thetas): if r == 0: Ur.append(0) Utheta.append(0) p.append(0) else: Ur.append((1 - (0.5/r)**2)*np.cos(theta)) Utheta.append((1 + (0.5/r)**2)*np.sin(theta)) p.append(2*(0.5/r)**2 * np.cos(2*theta) - (0.5/r)**4) Ur = np.array(Ur) Utheta = np.array(Utheta) p = np.array(p) U = Ur*np.cos(thetas) - Utheta*
np.sin(thetas)
numpy.sin
# -*- coding: utf-8 -*- """ Created on Wed Mar 5 16:57:00 2014 @author: hash """ import numpy as np import skrf as rf import scipy as sp class ResonantDoubleLoop(object): def __init__(self, CT1, CT2, plasma, C=np.tile(60e-12,4)): """ Resonant Double Loop Initializer Parameters ----------- CT1, CT2: :class: ConjugateT Conjugate-T objects plasma: :class: 'skrf.network' Plasma network C=[C1H, C1B, C2H, C2B]: 4 elements array Capacitor values in Farad """ self.CT1 = CT1 self.CT2 = CT2 self.plasma = plasma self.C = C @property def C(self): """ Returns the capacitor set values """ return self._C @C.setter def C(self, C): """ Set the capacitor values Parameters ----------- C=[C1H, C1B, C2H, C2B]: 4 elements array Capacitor values in Farad """ self._C = C self.CT1.C = [self.C[0], self.C[1]] self.CT2.C = [self.C[2], self.C[3]] # update the network self.network = self.get_network() def get_network(self, freq=None): ''' Connect the both RDLs to the 4-ports plasma and return the resulting network Parameters ---------- freq : list or string frequency slicing indicator. Default is None (all frequencies). Slicing indicator as in http://scikit-rf.readthedocs.io/en/latest/tutorials/Networks.html#Slicing Returns ---------- antenna : :class: 'skrf.network' 2 ports network ''' # renormalize the characteritic impedance of the conjugate-T ports 2 & 3 # to the plasma port characteristic impedances self.CT1.z0[1:] = np.array([self.plasma.z0[0,0], self.plasma.z0[0,2]]) self.CT2.z0[1:] = np.array([self.plasma.z0[0,1], self.plasma.z0[0,3]]) # Should we renormalize as well the bridge output port z0 to the plasma port z0 ? self.CT1.network = self.CT1.get_network().renormalize( np.tile([self.CT1.z0[0], self.plasma.z0[0,0], self.plasma.z0[0,2]], (len(self.CT1.get_network()),1) )) self.CT2.network = self.CT2.get_network().renormalize( np.tile([self.CT2.z0[0], self.plasma.z0[0,1], self.plasma.z0[0,3]], (len(self.CT2.get_network()),1) )) # frequency slicing (if any) plasma = self.plasma[freq] CT1 = self.CT1.get_network()[freq] CT2 = self.CT2.get_network()[freq] # connect the network together temp1 = rf.connect(plasma, 0, CT1, 1) temp2 = rf.innerconnect(temp1, 1, 4) # watch out ! plasma ports 0 & 2 to RDL (TOPICA indexing) network = rf.innerconnect(rf.connect(temp2, 0, CT2, 1), 0, 3) network.name = 'antenna' return(network) def match(self, power_in, phase_in, f_match, Z_match): """ Match the resonant double antenna for a given matching frequency and impedance Parameters ---------- power_in : 2 element array Input wave powers [Watts] phase_in : 2 element array Input wave phases [rad] f_match: scalar Matching frequency in [Hz] Z_match: 2-elements array Matching impedance of each transmission line in [Ohm] Returns ---------- sol: scipy.optimize.solution Solution found """ success = False while success == False: # a random number centered on 70 pF +/- 50pF C0 = 70 + (-1 + 2*np.random.rand(4))*40 sol = sp.optimize.least_squares(fun=self._match_function, x0=C0, args=(power_in, phase_in, f_match, Z_match), bounds=(15,150) ) success = sol.success print(success, sol.x) for Cm in sol.x: if np.isclose(sol.x, 12).any() or np.isclose(sol.x, 150).any(): #(Cm < 12) or (Cm > 150): success = False print('Bad solution found (out of range capacitor) ! Re-doing...') print('Solution found : C={}'.format(sol.x)) # Apply the solution self.C = sol.x*1e-12 return(sol) def _match_function(self, C, power_in, phase_in, f_match, Z_match): """ Match a double RDL on a given plasma. Parameters ----------- C = [C1H, C1B, C2H, C2B] : capacitor values in pF a_in=[a1, a2] : 2 elements array Power waves input f_match : number Matching frequency in Hz Z_match = [Z1_match, Z2_match] : (characteristic) impedances to match with Returns ----------- y = [Re[Z1_active] - Re[Z1_match], Im[Z1_active] - Im[Z1_match], Re[Z2_active] - Re[Z2_match], Im[Z2_active] - Im[Z2_match]] : Matching criteria. """ self.C = C * 1e-12 # create the antenna network with the given capacitor values network = self.get_network() # optimization target index_f_match = np.argmin(np.abs(network.frequency.f - f_match)) Z_active = self.get_z_active(power_in, phase_in) y = [np.real(Z_active[index_f_match,0]) - np.real(Z_match[0]), np.imag(Z_active[index_f_match,0]) - np.imag(Z_match[0]), np.real(Z_active[index_f_match,1]) - np.real(Z_match[1]), np.imag(Z_active[index_f_match,1]) - np.imag(Z_match[1])] return(np.asarray(y)) def get_power_waves(self, power_in, phase_in): ''' Returns the input power waves from power and phase excitations. Arguments --------- - power_in [2x1] : input RF power in each ConjugateT [W] - phase_in [2x1] : input phase in each ConjugateT [rad] Returns --------- - a_in [2x1] : input power waves ''' # Wath out the factor 2 in the power wave definition # This is expected from the power wave definition # as the power is defined by P = 1/2 V.I --> P = 1/2 a^2 a_in = np.sqrt(2*np.array(power_in)) * np.exp(1j*np.array(phase_in)) return a_in def get_s_active(self, power_in, phase_in): """ Get the "active" scattering parameters S1act and S2act. These "active" scattering parameters are defined by [from HFSS definition] Sn_active = \sum_{k=1}^N S_{nk} a_k / a_n Arguments --------- - power_in [2x1] : input RF power in each ConjugateT [W] - phase_in [2x1] : input phase in each ConjugateT [rad] Returns ---------- Sact=[S1_active, S2_active]: 2 elements array active scattering parameters """ a_in = self.get_power_waves(power_in, phase_in) S = self.get_network().s S1_active = (S[:,0,0]*a_in[0] + S[:,0,1]*a_in[1])/a_in[0] S2_active = (S[:,1,0]*a_in[0] + S[:,1,1]*a_in[1])/a_in[1] # transpose in order to have an array f x 2 return(np.transpose([S1_active, S2_active])) def get_z_active(self, power_in, phase_in): """ Get the "active" impedance parameters Z1act and Z2act. These "active" impedance parameters are defined by [from HFSS] definition Zn_active = Z0_n * (1+Sn_active)/(1-Sn_active) Arguments --------- - power_in [2x1] : input RF power in each ConjugateT [W] - phase_in [2x1] : input phase in each ConjugateT [rad] Returns ---------- Zact=[Z1_active, Z2_active]: 2 elements array active impedance parameters """ # active s parameters Sact = self.get_s_active(power_in, phase_in) # port characteristic impedances Z0 = self.get_network().z0 # active impedance parameters Z1_active = Z0[:,0]*(1+Sact[:,0])/(1-Sact[:,0]) Z2_active = Z0[:,1]*(1+Sact[:,1])/(1-Sact[:,1]) # transpose in order to have an array f x 2 return(np.transpose([Z1_active, Z2_active])) def get_vswr_active(self, power_in, phase_in): """ Get the "active" VSWR vswr_1_act and vswr_2_act. These "active" VSWR are defined by [from HFSS definition] vswr_n_active = Z0_n * (1+|Sn_active|)/(1-|Sn_active|) Arguments --------- - power_in [2x1] : input RF power in each ConjugateT [W] - phase_in [2x1] : input phase in each ConjugateT [rad] Returns ---------- vswr_act=[vswr1_active, vswr2_active]: 2 elements array active VSWR """ # active s parameters Sact = self.get_s_active(power_in, phase_in) # active vswr parameters vswr1_active = (1+np.abs(Sact[:,0]))/(1-np.abs(Sact[:,0])) vswr2_active = (1+np.abs(Sact[:,1]))/(1-np.abs(Sact[:,1])) # transpose in order to have an array f x 2 return(np.transpose([vswr1_active, vswr2_active])) def get_f(self): """ Returns the frequency values of the network Returns ------- f : (f,) array Frequency values of the network alias to self.get_network().frequency.f """ return(self.get_network().frequency.f) def get_currents_and_voltages(self, power_in, phase_in, freq=None): """ Returns the currents and voltages at the capacitors (plasma side) for a prescribed power excitation. Arguments --------- - power_in [2x1] : input RF power in each ConjugateT [W] - phase_in [2x1] : input phase in each ConjugateT [rad] - freq (None) : selected frequencies as a list. If None, return results for all network frequencies Returns --------- - I_capa [fx2]: capacitor currents in [A] - V_capa [fx2]: capacitor voltages in [A] """ a_in = self.get_power_waves(power_in, phase_in) # For each frequencies of the network _a = [] _b = [] for idx, f in enumerate(self.CT1.frequency[freq].f): S_CT1 = self.CT1.get_network()[freq].s[idx] S_CT2 = self.CT2.get_network()[freq].s[idx] S_plasma = self.plasma.s[idx] # convenience matrices A = np.array([[S_CT1[1,0], 0 ], [0 , S_CT2[1,0] ], [S_CT1[2,0], 0 ], [0 , S_CT2[2,0]]]) C = np.array([[S_CT1[1,1], 0, S_CT1[1,2], 0], [0, S_CT2[1,1], 0, S_CT2[1,2]], [S_CT1[2,1], 0, S_CT1[2,2], 0], [0, S_CT2[2,1], 0, S_CT2[2,2]]]) _a_plasma = np.linalg.inv(np.eye(4) - C.dot(S_plasma)).dot(A).dot(a_in) _b_plasma = S_plasma.dot(_a_plasma) _a.append(_a_plasma) _b.append(_b_plasma) a_plasma = np.column_stack(_a) b_plasma = np.column_stack(_b) # Deduces Currents and Voltages from power waves z0 = np.concatenate((self.CT1.z0[1:], self.CT2.z0[1:])) I_plasma = (a_plasma - b_plasma).T / np.sqrt(
np.real(z0)
numpy.real
#!/usr/bin/env python import numpy as np import os import unittest if __package__ is "" or "None": # py2 and py3 compatible print("setting __package__ to gwsurrogate.new so relative imports work") __package__="gwsurrogate.new" from gwsurrogate.new import surrogate, nodeFunction TEST_FILE = 'test.h5' # Gets created and deleted def _tear_down(): if os.path.isfile(TEST_FILE): os.remove(TEST_FILE) def _set_up(): # Don't overwrite this in case it's actually needed by something else if os.path.isfile(TEST_FILE): raise Exception("{} already exists! Please move or remove it.") class BaseTest(unittest.TestCase): def setUp(self): _set_up() def tearDown(self): _tear_down() class SplinterpTester(BaseTest): def setUp(self): super(SplinterpTester, self).setUp() xmin = 0. xmax = 10. n_sparse = 60 n_dense = 237 self.abs_tol = 1.e-4 self.x_sparse = np.linspace(xmin, xmax, n_sparse) self.x_dense = np.linspace(xmin, xmax, n_dense) def test_real(self): y_sparse = np.sin(self.x_sparse) y_dense = np.sin(self.x_dense) y_interp = surrogate._splinterp(self.x_dense, self.x_sparse, y_sparse) self.assertLess(np.max(abs(y_interp - y_dense)), self.abs_tol) def test_complex(self): y_sparse = np.exp(1.j*self.x_sparse) y_dense = np.exp(1.j*self.x_dense) y_interp = surrogate._splinterp(self.x_dense, self.x_sparse, y_sparse) self.assertLess(np.max(abs(y_interp - y_dense)), self.abs_tol) class ParamSpaceTester(BaseTest): def _test_ParamDim_nudge(self, tol, xmin, xmax): pd = surrogate.ParamDim("mass", xmin, xmax, rtol=tol/(xmax - xmin)) self.assertEqual(pd.nudge(xmin - 0.9*tol), xmin + tol) self.assertEqual(pd.nudge(xmax + 0.9*tol), xmax - tol) with self.assertRaises(Exception): pd.nudge(xmin - 1.1*tol) with self.assertRaises(Exception): pd.nudge(xmax + 1.1*tol) for x in [xmin + tol, 0.5*(xmin + xmax), xmax - tol]: self.assertEqual(pd.nudge(x), x) def test_ParamDim(self): # Test nudge self._test_ParamDim_nudge(1.e-4, 0., 1.) self._test_ParamDim_nudge(1.e-4, 5., 123) # Test save/load pd = surrogate.ParamDim("Length in beardseconds", 0.1, 1.e5) pd.save(TEST_FILE) pd2 = surrogate.ParamDim("", 0, 1) pd2.load(TEST_FILE) self.assertEqual(pd2.name, "Length in beardseconds") self.assertEqual(pd2.min_val, 0.1) self.assertEqual(pd2.max_val, 1.e5) def _test_ParamSpace_nudge(self, xmins, xmaxs, tols): params = [] for xmin, xmax, tol in zip(xmins, xmaxs, tols): pd = surrogate.ParamDim("x", xmin, xmax, rtol=tol/(xmax - xmin)) params.append(pd) ps = surrogate.ParamSpace("param space", params) # Nudge all xmin = np.array([x for x in xmins]) xmax = np.array([x for x in xmaxs]) for i in range(len(xmins)): xmin[i] -= 0.9 * tols[i] xmax[i] += 0.9 * tols[i] xmin = ps.nudge_params(xmin) xmax = ps.nudge_params(xmax) for i in range(len(xmins)): self.assertEqual(xmin[i], xmins[i] + tols[i]) self.assertEqual(xmax[i], xmaxs[i] - tols[i]) # Nudge one xmin = np.array([x for x in xmins]) xmax = np.array([x for x in xmaxs]) for i in range(len(xmins)): xmin[i] -= 0.9 * tols[i] xmax[i] += 0.9 * tols[i] xmin = ps.nudge_params(xmin) xmax = ps.nudge_params(xmax) self.assertEqual(xmin[i], xmins[i] + tols[i]) self.assertEqual(xmax[i], xmaxs[i] - tols[i]) # Check Exceptions for i in range(len(xmins)): xmin = np.array([x for x in xmins]) xmax = np.array([x for x in xmaxs]) xmin[i] -= 1.1*tols[i] xmax[i] += 1.1*tols[i] with self.assertRaises(Exception): ps.nudge_params(xmin) with self.assertRaises(Exception): ps.nudge_params(xmax) # Check unmodified x = np.array([x + tol for x, tol in zip(xmins, tols)]) check_params = [1*x] for i in range(len(xmins)): x[i] += 0.5*(xmaxs[i] - xmins[i]) - tols[i] check_params.append(1*x) for i in range(len(xmins)): x[i] += 0.5*(xmaxs[i] - xmins[i]) - tols[i] check_params.append(1*x) for x in check_params: x2 = ps.nudge_params(x) for xi, xi2 in zip(x, x2): self.assertEqual(xi, xi2) return ps def test_ParamSpace(self): ps = self._test_ParamSpace_nudge([0.], [1.], [1.e-4]) ps = self._test_ParamSpace_nudge([1., 2., 100.], [1.1, 100., 101.], [1.e-4, 1.e-5, 1.e-6]) # Test saving/loading ps.save(TEST_FILE) ps2 = surrogate.ParamSpace("", []) ps2.load(TEST_FILE) self.assertEqual(ps.name, ps2.name) self.assertEqual(ps.dim, ps2.dim) for i in range(ps.dim): pd = ps._params[i] pd2 = ps2._params[i] self.assertEqual(pd.min_val, pd2.min_val) self.assertEqual(pd.max_val, pd2.max_val) self.assertEqual(pd.tol, pd2.tol) class SingleFunctionSurrogateTester(BaseTest): def test_SingleFunctionSurrogate_NoChecks(self): ei = np.array([
np.ones(10)
numpy.ones
from math import gamma from typing import Dict, List, Tuple import matplotlib.pyplot as plt import numpy as np import torch import torch.nn.functional as F import torch.optim as optim from atcenv.MASAC.buffer import ReplayBuffer from atcenv.MASAC.mactor_critic import Actor, CriticQ, CriticV from torch.nn.utils.clip_grad import clip_grad_norm_ GAMMMA = 0.99 TAU =5e-3 INITIAL_RANDOM_STEPS = 100 POLICY_UPDATE_FREQUENCE = 2 NUM_AGENTS = 10 BUFFER_SIZE = 1000000 BATCH_SIZE = 256 ACTION_DIM = 2 STATE_DIM = 14 NUMBER_INTRUDERS_STATE = 2 MEANS = [57000,57000,0,0,0,0,0,0] STDS = [31500,31500,100000,100000,1,1,1,1] class MaSacAgent: def __init__(self): self.memory = ReplayBuffer(STATE_DIM,ACTION_DIM, BUFFER_SIZE, BATCH_SIZE) try: self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu") print('DEVICE USED: ', torch.cuda.device(torch.cuda.current_device()), torch.cuda.get_device_name(0)) except: # Cuda isn't available self.device = torch.device("cpu") print('DEVICE USED: CPU') self.target_alpha = -np.prod((ACTION_DIM,)).item() self.log_alpha = torch.zeros(1, requires_grad=True, device=self.device) self.alpha_optimizer = optim.Adam([self.log_alpha], lr=3e-4) self.actor = Actor(STATE_DIM, ACTION_DIM).to(self.device) self.vf = CriticV(STATE_DIM).to(self.device) self.vf_target = CriticV(STATE_DIM).to(self.device) self.vf_target.load_state_dict(self.vf.state_dict()) self.qf1 = CriticQ(STATE_DIM + ACTION_DIM).to(self.device) self.qf2 = CriticQ(STATE_DIM + ACTION_DIM).to(self.device) self.actor_optimizer = optim.Adam(self.actor.parameters(), lr=3e-4) self.vf_optimizer = optim.Adam(self.vf.parameters(), lr=3e-4) self.qf1_optimizer = optim.Adam(self.qf1.parameters(), lr=3e-4) self.qf2_optimizer = optim.Adam(self.qf2.parameters(), lr=3e-4) self.transition = [[] for i in range(NUM_AGENTS)] self.total_step = 0 self.is_test = False def do_step(self, state, max_speed, min_speed, test = False, batch = False): if not test and self.total_step < INITIAL_RANDOM_STEPS and not self.is_test: selected_action = np.random.uniform(-1, 1, (len(state), ACTION_DIM)) else: selected_action = [] for i in range(len(state)): action = self.actor(torch.FloatTensor(state[i]).to(self.device))[0].detach().cpu().numpy() selected_action.append(action) selected_action = np.array(selected_action) selected_action =
np.clip(selected_action, -1, 1)
numpy.clip
""" Running this script creates two files results.csv and results.plk in the 'user/raw' directory containing the relevant parameters and the estimated power/level of the tests. We use the following numbering of experiments: uniform mnist 1 2 3 4 5 6 7 8 9 10 11 12 Experiments i and i+1 are the same but using the uniform and mnist data. We first run the uniform experiments followed by the mnist experiments. The settings of all those experiments can be understood by their relations to the figures presented in our paper: Figure 3 and 4: experiments 1 and 3 Figure 5: experiments 2 and 4 Figure 6: experiments 9 and 10 Figure 7: experiments 1, 2, 3 and 4 Figure 8: experiments 7 and 8 Figure 9: experiments 1, 2, 11 and 12 Table 1: experiments 5 and 6 The figures and table can be created by running the figures.py script. """ import numpy as np import itertools import pandas as pd from mnist import download_mnist, load_mnist from pathlib import Path from seed import generate_seed from sample_test import sample_and_test_uniform, sample_and_test_mnist import argparse # create results directory if it does not exist Path("user/raw").mkdir(exist_ok=True, parents=True) # panda dataframe: lists of indices and entries index_vals = [] results = [] # parameters shared for all experiments alpha = 0.05 B1 = 500 B2 = 500 B3 = 100 kernel_types = ["gaussian", "laplace"] k_num = len(kernel_types) approx_types = ["wild bootstrap", "permutation"] a_num = len(approx_types) ############# UNIFORM ############# # parameters for all uniform experiments s = 1 perturbation_multipliers = [2.7, 7.3] bandwidth_multipliers = np.linspace(0.1, 1, 10) e_num = 2 p_num = 4 # Experiment 1 exp = "1: uniform alternative" repetitions = 500 sample_sizes = [500, 2000] L = [(-6, -2), (-4, 0), (-2, 2)] l_num = len(L) function_types = ["uniform", "increasing", "decreasing", "centred", "ost"] f_num = len(function_types) for a, k, e, l, f, p in itertools.product( range(a_num), range(k_num), range(2), range(l_num), range(f_num), range(p_num) ): if (a, l) not in [(1, 0), (1, 2)] and (e, p) != (1, 3): approx_type = approx_types[a] kernel_type = kernel_types[k] d = e + 1 n = m = sample_sizes[e] perturbation_multiplier = perturbation_multipliers[e] l_minus, l_plus = L[l] l_minus_l_plus = L[l] function_type = function_types[f] perturbation = p + 1 perturbation_or_Qi = perturbation test_output_list = [] for i in range(repetitions): seed = generate_seed(k, e, l, f, p, i) test_output_list.append( sample_and_test_uniform( function_type, seed, kernel_type, approx_type, m, n, d, perturbation, s, perturbation_multiplier, alpha, l_minus, l_plus, B1, B2, B3, bandwidth_multipliers, ) ) power = np.mean(test_output_list) index_val = ( exp, d, repetitions, m, n, approx_type, kernel_type, l_minus_l_plus, function_type, perturbation_or_Qi, ) index_vals.append(index_val) results.append(power) print('Experiment 1 completed.') # Experiment 3 exp = "3: uniform alternative" repetitions = 500 sample_sizes = [500, 2000] l_minus = l_plus = None l_minus_l_plus = None function_types = ["median", "split", "split (doubled sample sizes)"] f_num = len(function_types) for a, k, e, f, p in itertools.product( range(a_num), range(k_num), range(e_num), range(f_num), range(p_num) ): if (e, p) != (1, 3): approx_type = approx_types[a] kernel_type = kernel_types[k] d = e + 1 n = m = sample_sizes[e] perturbation_multiplier = perturbation_multipliers[e] function_type = function_types[f] perturbation = p + 1 perturbation_or_Qi = perturbation test_output_list = [] for i in range(repetitions): seed = generate_seed(k, e, 3, f, p, i) test_output_list.append( sample_and_test_uniform( function_type, seed, kernel_type, approx_type, m, n, d, perturbation, s, perturbation_multiplier, alpha, l_minus, l_plus, B1, B2, B3, bandwidth_multipliers, ) ) power = np.mean(test_output_list) index_val = ( exp, d, repetitions, m, n, approx_type, kernel_type, l_minus_l_plus, function_type, perturbation_or_Qi, ) index_vals.append(index_val) results.append(power) print('Experiment 3 completed.') # Experiment 5 exp = "5: uniform null" repetitions = 5000 sample_sizes = [500, 2000] function_types = [ "uniform", "increasing", "decreasing", "centred", "ost", "median", "split", ] f_num = len(function_types) L = [(-4, 0)] l_num = len(L) l_minus, l_plus = L[0] l_minus_l_plus = L[0] perturbation = 0 perturbation_or_Qi = perturbation for a, k, e, f in itertools.product( range(a_num), range(k_num), range(e_num), range(f_num) ): approx_type = approx_types[a] kernel_type = kernel_types[k] d = e + 1 n = m = sample_sizes[e] function_type = function_types[f] test_output_list = [] for i in range(repetitions): seed = generate_seed(k, e, 0, f, 5, i) test_output_list.append( sample_and_test_uniform( function_type, seed, kernel_type, approx_type, m, n, d, perturbation, s, perturbation_multiplier, alpha, l_minus, l_plus, B1, B2, B3, bandwidth_multipliers, ) ) power = np.mean(test_output_list) index_val = ( exp, d, repetitions, m, n, approx_type, kernel_type, l_minus_l_plus, function_type, perturbation_or_Qi, ) index_vals.append(index_val) results.append(power) print('Experiment 5 completed.') # Experiment 7 exp = "7: uniform alternative" repetitions = 500 sample_sizes_m = [100, 250] sample_sizes_n = [1000, 2000, 3000, 4000, 5000] v_num = len(sample_sizes_n) function_types = ["uniform", "increasing", "decreasing", "centred"] f_num = len(function_types) l_minus, l_plus = (-4, 0) l_minus_l_plus = (-4, 0) perturbations = [3, 2] approx_type = "permutation" for k, e, f, v in itertools.product( range(k_num), range(e_num), range(f_num), range(v_num) ): kernel_type = kernel_types[k] d = e + 1 n = sample_sizes_n[v] m = sample_sizes_m[e] perturbation_multiplier = perturbation_multipliers[e] function_type = function_types[f] perturbation = perturbations[e] perturbation_or_Qi = perturbation test_output_list = [] for i in range(repetitions): seed = generate_seed(k, e, 3, f, v, i) test_output_list.append( sample_and_test_uniform( function_type, seed, kernel_type, approx_type, m, n, d, perturbation, s, perturbation_multiplier, alpha, l_minus, l_plus, B1, B2, B3, bandwidth_multipliers, ) ) power = np.mean(test_output_list) index_val = ( exp, d, repetitions, m, n, approx_type, kernel_type, l_minus_l_plus, function_type, perturbation_or_Qi, ) index_vals.append(index_val) results.append(power) print('Experiment 7 completed.') # Experiment 9 exp = "9: uniform alternative" repetitions = 500 sample_sizes = [500, 2000] function_types = ["uniform", "centred"] f_num = len(function_types) L = [(-2, -2), (-3, -1), (-4, 0), (-5, 1), (-6, 2), (-7, 3), (-8, 4), (-9, 5)] l_num = len(L) perturbations = [3, 2] approx_type = "wild bootstrap" for k, e, l, f in itertools.product( range(k_num), range(e_num), range(l_num), range(f_num) ): kernel_type = kernel_types[k] d = e + 1 n = m = sample_sizes[e] perturbation_multiplier = perturbation_multipliers[e] l_minus, l_plus = L[l] l_minus_l_plus = L[l] function_type = function_types[f] perturbation = perturbations[e] p = perturbation - 1 perturbation_or_Qi = perturbation test_output_list = [] for i in range(repetitions): seed = generate_seed(k, e, l, f, p, i) test_output_list.append( sample_and_test_uniform( function_type, seed, kernel_type, approx_type, m, n, d, perturbation, s, perturbation_multiplier, alpha, l_minus, l_plus, B1, B2, B3, bandwidth_multipliers, ) ) power = np.mean(test_output_list) index_val = ( exp, d, repetitions, m, n, approx_type, kernel_type, l_minus_l_plus, function_type, perturbation_or_Qi, ) index_vals.append(index_val) results.append(power) print('Experiment 9 completed.') # Experiment 11 exp = "11: uniform alternative" repetitions = 500 function_types = ["ost"] f = 0 function_type = function_types[f] l_minus, l_plus = (-4, 0) l_minus_l_plus = (-4, 0) l = 3 approx_type = None sample_sizes = [ [int(i * 10 ** 5) for i in [0.25, 0.5, 0.75, 1]], [int(i * 10 ** 5) for i in [2.5, 5, 7.5, 10]], ] v_num = len(sample_sizes[0]) for v, k, e, p in itertools.product( range(v_num), range(k_num), range(e_num), range(p_num) ): if (e, p) != (1, 3): kernel_type = kernel_types[k] d = e + 1 n = m = sample_sizes[e][v] perturbation_multiplier = perturbation_multipliers[e] function_type = function_types[f] perturbation = p + 1 perturbation_or_Qi = perturbation test_output_list = [] for i in range(repetitions): seed = generate_seed(k, e, 3, 0, p, i) test_output_list.append( sample_and_test_uniform( function_type, seed, kernel_type, approx_type, m, n, d, perturbation, s, perturbation_multiplier, alpha, l_minus, l_plus, B1, B2, B3, bandwidth_multipliers, ) ) power = np.mean(test_output_list) index_val = ( exp, d, repetitions, m, n, approx_type, kernel_type, l_minus_l_plus, function_type, perturbation_or_Qi, ) index_vals.append(index_val) results.append(power) print('Experiment 11 completed.') ############# MNIST ############# # parameters for all mnist experiments p_num = 5 d = None Q_list = ["Q1", "Q2", "Q3", "Q4", "Q5"] bandwidth_multipliers = np.array([2 ** i for i in range(10, 21)]) Path("mnist_dataset").mkdir(exist_ok=True) if Path("mnist_dataset/mnist_7x7.data").is_file() == False: download_mnist() P, Q_list = load_mnist() Q_list_str = ["Q1", "Q2", "Q3", "Q4", "Q5"] # Experiment 2 exp = "2: mnist alternative" repetitions = 500 sample_size = 500 function_types = ["uniform", "increasing", "decreasing", "centred", "ost"] f_num = len(function_types) L = [[(8, 12), (10, 14), (12, 16)], [(10, 14), (12, 16), (14, 18)]] l_num = len(L[0]) for a, k, l, f, p in itertools.product( range(a_num), range(k_num), range(l_num), range(f_num), range(p_num) ): if (a, l) not in [(1, 0), (1, 2)]: approx_type = approx_types[a] kernel_type = kernel_types[k] n = m = sample_size l_minus, l_plus = L[k][l] l_minus_l_plus = L[k][l] function_type = function_types[f] Qi = Q_list[p] perturbation_or_Qi = Q_list_str[p] test_output_list = [] for i in range(repetitions): seed = generate_seed(k, 2, l, f, p, i) test_output_list.append( sample_and_test_mnist( P, Qi, function_type, seed, kernel_type, approx_type, m, n, alpha, l_minus, l_plus, B1, B2, B3, bandwidth_multipliers, ) ) power = np.mean(test_output_list) index_val = ( exp, d, repetitions, m, n, approx_type, kernel_type, l_minus_l_plus, function_type, perturbation_or_Qi, ) index_vals.append(index_val) results.append(power) print('Experiment 2 completed.') # Experiment 4 exp = "4: mnist alternative" repetitions = 500 sample_size = 500 function_types = ["median", "split", "split (doubled sample sizes)"] f_num = len(function_types) l_minus = l_plus = None l_minus_l_plus = None for a, k, f, p in itertools.product( range(a_num), range(k_num), range(f_num), range(p_num) ): approx_type = approx_types[a] kernel_type = kernel_types[k] n = m = sample_size function_type = function_types[f] Qi = Q_list[p] perturbation_or_Qi = Q_list_str[p] test_output_list = [] for i in range(repetitions): seed = generate_seed(k, 2, 3, f, p, i) test_output_list.append( sample_and_test_mnist( P, Qi, function_type, seed, kernel_type, approx_type, m, n, alpha, l_minus, l_plus, B1, B2, B3, bandwidth_multipliers, ) ) power = np.mean(test_output_list) index_val = ( exp, d, repetitions, m, n, approx_type, kernel_type, l_minus_l_plus, function_type, perturbation_or_Qi, ) index_vals.append(index_val) results.append(power) print('Experiment 4 completed.') # Experiment 6 exp = "6: mnist null" repetitions = 5000 sample_size = 500 function_types = [ "uniform", "increasing", "decreasing", "centred", "ost", "median", "split", ] f_num = len(function_types) L = [(10, 14), (12, 16)] for a, k, f in itertools.product(range(a_num), range(k_num), range(f_num)): approx_type = approx_types[a] kernel_type = kernel_types[k] n = m = sample_size function_type = function_types[f] l_minus, l_plus = L[k] l_minus_l_plus = L[k] perturbation_or_Qi = "P" test_output_list = [] for i in range(repetitions): seed = generate_seed(k, 2, l, f, 5, i) test_output_list.append( sample_and_test_mnist( P, P, function_type, seed, kernel_type, approx_type, m, n, alpha, l_minus, l_plus, B1, B2, B3, bandwidth_multipliers, ) ) power = np.mean(test_output_list) index_val = ( exp, d, repetitions, m, n, approx_type, kernel_type, l_minus_l_plus, function_type, perturbation_or_Qi, ) index_vals.append(index_val) results.append(power) print('Experiment 6 completed.') # Experiment 8 exp = "8: mnist alternative" repetitions = 500 sample_size_m = 100 sample_sizes_n = [200, 400, 600, 800, 1000] v_num = len(sample_sizes_n) function_types = ["uniform", "increasing", "decreasing", "centred"] f_num = len(function_types) L = [(10, 14), (12, 16)] approx_type = "permutation" for k, f, v in itertools.product(range(k_num), range(f_num), range(v_num)): kernel_type = kernel_types[k] n = sample_sizes_n[v] m = sample_size_m function_type = function_types[f] Qi = Q_list[2] perturbation_or_Qi = Q_list_str[2] test_output_list = [] for i in range(repetitions): seed = generate_seed(k, 2, 3, f, v, i) test_output_list.append( sample_and_test_mnist( P, Qi, function_type, seed, kernel_type, approx_type, m, n, alpha, l_minus, l_plus, B1, B2, B3, bandwidth_multipliers, ) ) power = np.mean(test_output_list) index_val = ( exp, d, repetitions, m, n, approx_type, kernel_type, l_minus_l_plus, function_type, perturbation_or_Qi, ) index_vals.append(index_val) results.append(power) print('Experiment 8 completed.') # Experiment 10 exp = "10: mnist alternative" repetitions = 500 sample_sizes = 500 function_types = ["uniform", "centred"] f_num = len(function_types) L = [ [(12, 12), (11, 13), (10, 14), (9, 15), (8, 16), (7, 17), (6, 18), (5, 19)], [(14, 14), (13, 15), (12, 16), (11, 17), (10, 18), (9, 19), (8, 20), (7, 21)], ] l_num = len(L[0]) approx_type = "wild bootstrap" for k, l, f in itertools.product(range(k_num), range(l_num), range(f_num)): kernel_type = kernel_types[k] n = m = sample_sizes l_minus, l_plus = L[k][l] l_minus_l_plus = L[k][l] function_type = function_types[f] Qi = Q_list[2] perturbation_or_Qi = Q_list_str[2] test_output_list = [] for i in range(repetitions): seed = generate_seed(k, 2, l, f, v, i) test_output_list.append( sample_and_test_mnist( P, Qi, function_type, seed, kernel_type, approx_type, m, n, alpha, l_minus, l_plus, B1, B2, B3, bandwidth_multipliers, ) ) power = np.mean(test_output_list) index_val = ( exp, d, repetitions, m, n, approx_type, kernel_type, l_minus_l_plus, function_type, perturbation_or_Qi, ) index_vals.append(index_val) results.append(power) print('Experiment 10 completed.') # Experiment 12 exp = "12: mnist alternative" repetitions = 500 function_types = ["ost"] f = 0 function_type = function_types[f] L = [(10, 14), (12, 16)] l = 3 approx_type = None sample_sizes = [int(i * 10 ** 5) for i in [0.5, 1, 1.5, 2, 2.5]] v_num = len(sample_sizes) for v, k, p in itertools.product(range(v_num), range(k_num), range(p_num)): kernel_type = kernel_types[k] n = m = sample_sizes[v] function_type = function_types[f] l_minus, l_plus = L[k] l_minus_l_plus = L[k] Qi = Q_list[p] perturbation_or_Qi = Q_list_str[p] test_output_list = [] for i in range(repetitions): seed = generate_seed(k, 2, 3, f, p, i) test_output_list.append( sample_and_test_mnist( P, Qi, function_type, seed, kernel_type, approx_type, m, n, alpha, l_minus, l_plus, B1, B2, B3, bandwidth_multipliers, ) ) power =
np.mean(test_output_list)
numpy.mean
import math import numpy as np import numpy.linalg as lin import scipy.optimize.nnls as nnls import scipy.optimize as opt # import cv2 import time from joblib import Parallel, delayed from itertools import product # Function Definitions def unmixGradProjMatrixNNLS(image, A, tolerance=1e-4, maxiter=100): """ Performs NNLS via Gradient Projection of the primal problem. Terminates when duality gap falls below tolerance """ if image.ndim == 2: (n1, n3) = image.shape n2 = 1; elif image.ndim == 3: (n1, n2, n3) = image.shape k = A.shape[1] # Reshape to n3 x n1*n2 matrix image = image.reshape(n1*n2,n3).T # Precompute Quantities ATA = np.dot(A.T,A) pinvA = np.linalg.pinv(A) ATimage = np.dot(A.T,image) alpha = np.linalg.norm(ATA,ord=2) # Start with thresholded pseudo-inverse X = np.dot(pinvA, image) X[X < 0] = 0 # See if meets convergence criterion grad = np.dot(ATA,X) - ATimage gradthresh = np.array(grad) gradthresh[gradthresh < 0] = 0 gap = np.tensordot(X, gradthresh)/(n1*n2*k) iter = 0 while (gap > tolerance) and (iter < maxiter): iter += 1 # Gradient Step X = X - grad/alpha # Projection X[X < 0] = 0 # See if meets convergence criterion grad = np.dot(ATA,X) - ATimage gradthresh = np.array(grad) gradthresh[gradthresh < 0] = 0 gap = np.tensordot(X, gradthresh)/(n1*n2*k) # Reshape back to n1 x n2 x k image X = X.T.reshape(n1,n2,k) return X def unmixGradProjMatrixMinArcNNLS(image, A, tolerance=1e-4): """ Performs NNLS via Gradient Projection of the primal problem. Includes minimization along projection arc Terminates when duality gap falls below tolerance """ if image.ndim == 2: (n1, n3) = image.shape n2 = 1; elif image.ndim == 3: (n1, n2, n3) = image.shape k = A.shape[1] # Reshape to n3 x n1*n2 matrix image = image.reshape(n1*n2,n3).T # Precompute Quantities ATA = np.dot(A.T,A) pinvA = np.linalg.pinv(A) ATimage =
np.dot(A.T,image)
numpy.dot
import cv2 import numpy as np import matplotlib.pyplot as plt import torch def draw_skeleton(input_image, joints, draw_edges=True, vis=None, radius=None): """ joints is 3 x 19. but if not will transpose it. 0: Right ankle 1: Right knee 2: Right hip 3: Left hip 4: Left knee 5: Left ankle 6: Right wrist 7: Right elbow 8: Right shoulder 9: Left shoulder 10: Left elbow 11: Left wrist 12: Neck 13: Head top 14: nose 15: left_eye 16: right_eye 17: left_ear 18: right_ear """ if radius is None: radius = max(4, (np.mean(input_image.shape[:2]) * 0.01).astype(int)) colors = { 'pink': np.array([197, 27, 125]), # L lower leg 'light_pink': np.array([233, 163, 201]), # L upper leg 'light_green': np.array([161, 215, 106]), # L lower arm 'green': np.array([77, 146, 33]), # L upper arm 'red': np.array([215, 48, 39]), # head 'light_red': np.array([252, 146, 114]), # head 'light_orange': np.array([252, 141, 89]), # chest 'purple': np.array([118, 42, 131]), # R lower leg 'light_purple': np.array([175, 141, 195]), # R upper 'light_blue':
np.array([145, 191, 219])
numpy.array
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import numpy as np import pandas as pd from covid_epidemiology import model from covid_epidemiology.src.models.shared import model_utils class ModelUtilsTest(unittest.TestCase): def test_update_metric_to_predictions(self): metric_to_predictions = { "Infected": [ model.Prediction( time_horizon=1, predicted_value=20, ground_truth=12) ] } gt_data = [7, 2, 5, 7] got = model_utils.update_metric_to_predictions( metric="recovered_cases", values=np.array([[12], [23]], np.float32), metric_to_predictions=metric_to_predictions, train_end_of_window=2, gt_data=gt_data) wanted = { "Infected": [ model.Prediction( time_horizon=1, predicted_value=20, ground_truth=12) ], "recovered_cases": [ model.Prediction( time_horizon=1, predicted_value=12, ground_truth=5), model.Prediction( time_horizon=2, predicted_value=23, ground_truth=7) ], } self.assertEqual(wanted, got) def test_update_metric_to_predictions_with_quantiles(self): metric_to_predictions = {} gt_data = [7, 2, 5, 7] got = model_utils.update_metric_to_predictions( metric="recovered_cases", values=np.array([[12, 14], [23, 25]], np.float32), metric_to_predictions=metric_to_predictions, train_end_of_window=2, gt_data=gt_data, quantiles=[0.1, 0.9], metric_string_format="{metric}_{quantile}_quantile") wanted = { "recovered_cases_0.1_quantile": [ model.Prediction( time_horizon=1, predicted_value=12, ground_truth=5), model.Prediction( time_horizon=2, predicted_value=23, ground_truth=7) ], "recovered_cases_0.9_quantile": [ model.Prediction( time_horizon=1, predicted_value=14, ground_truth=5), model.Prediction( time_horizon=2, predicted_value=25, ground_truth=7) ], } self.assertEqual(wanted, got) def test_update_metric_to_predictions_offset(self): metric_to_predictions = { "Infected": [ model.Prediction( time_horizon=1, predicted_value=20, ground_truth=12) ] } gt_data = [7, 2, 5, 7] got = model_utils.update_metric_to_predictions( metric="recovered_cases", values=np.array([[12], [23]], np.float32), metric_to_predictions=metric_to_predictions, train_end_of_window=2, gt_data=gt_data, time_horizon_offset=2) wanted = { "Infected": [ model.Prediction( time_horizon=1, predicted_value=20, ground_truth=12) ], "recovered_cases": [ model.Prediction( time_horizon=-1, predicted_value=12, ground_truth=5), model.Prediction( time_horizon=0, predicted_value=23, ground_truth=7) ], } self.assertEqual(wanted, got) def test_populate_gt_list(self): gt_list = np.zeros((2, 4)) gt_indicator = np.ones((2, 4)) location_to_gt = { "IR": pd.Series([12, 4, 5]), "US": pd.Series([3, 4, 5, 6, 7]) } gt_list, gt_indicator = model_utils.populate_gt_list( 0, location_to_gt, "IR", 4, gt_list, gt_indicator) gt_list, gt_indicator = model_utils.populate_gt_list( 1, location_to_gt, "US", 4, gt_list, gt_indicator) wanted =
np.array([[12, 4, 5, 0], [3, 4, 5, 6]], np.float32)
numpy.array
#!/usr/bin/env python # Copyright 2019 Division of Medical Image Computing, German Cancer Research Center (DKFZ). # # 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. # ============================================================================== """ Parts are based on https://github.com/multimodallearning/pytorch-mask-rcnn published under MIT license. """ import warnings warnings.filterwarnings('ignore', '.*From scipy 0.13.0, the output shape of zoom()*') import numpy as np import scipy.misc import scipy.ndimage import scipy.interpolate from scipy.ndimage.measurements import label as lb import torch import tqdm from custom_extensions.nms import nms from custom_extensions.roi_align import roi_align ############################################################ # Segmentation Processing ############################################################ def sum_tensor(input, axes, keepdim=False): axes = np.unique(axes) if keepdim: for ax in axes: input = input.sum(ax, keepdim=True) else: for ax in sorted(axes, reverse=True): input = input.sum(int(ax)) return input def get_one_hot_encoding(y, n_classes): """ transform a numpy label array to a one-hot array of the same shape. :param y: array of shape (b, 1, y, x, (z)). :param n_classes: int, number of classes to unfold in one-hot encoding. :return y_ohe: array of shape (b, n_classes, y, x, (z)) """ dim = len(y.shape) - 2 if dim == 2: y_ohe = np.zeros((y.shape[0], n_classes, y.shape[2], y.shape[3])).astype('int32') elif dim == 3: y_ohe = np.zeros((y.shape[0], n_classes, y.shape[2], y.shape[3], y.shape[4])).astype('int32') else: raise Exception("invalid dimensions {} encountered".format(y.shape)) for cl in np.arange(n_classes): y_ohe[:, cl][y[:, 0] == cl] = 1 return y_ohe def dice_per_batch_inst_and_class(pred, y, n_classes, convert_to_ohe=True, smooth=1e-8): ''' computes dice scores per batch instance and class. :param pred: prediction array of shape (b, 1, y, x, (z)) (e.g. softmax prediction with argmax over dim 1) :param y: ground truth array of shape (b, 1, y, x, (z)) (contains int [0, ..., n_classes] :param n_classes: int :return: dice scores of shape (b, c) ''' if convert_to_ohe: pred = get_one_hot_encoding(pred, n_classes) y = get_one_hot_encoding(y, n_classes) axes = tuple(range(2, len(pred.shape))) intersect = np.sum(pred*y, axis=axes) denominator = np.sum(pred, axis=axes)+np.sum(y, axis=axes) dice = (2.0*intersect + smooth) / (denominator + smooth) return dice def dice_per_batch_and_class(pred, targ, n_classes, convert_to_ohe=True, smooth=1e-8): ''' computes dice scores per batch and class. :param pred: prediction array of shape (b, 1, y, x, (z)) (e.g. softmax prediction with argmax over dim 1) :param targ: ground truth array of shape (b, 1, y, x, (z)) (contains int [0, ..., n_classes]) :param n_classes: int :param smooth: Laplacian smooth, https://en.wikipedia.org/wiki/Additive_smoothing :return: dice scores of shape (b, c) ''' if convert_to_ohe: pred = get_one_hot_encoding(pred, n_classes) targ = get_one_hot_encoding(targ, n_classes) axes = (0, *list(range(2, len(pred.shape)))) #(0,2,3(,4)) intersect = np.sum(pred * targ, axis=axes) denominator = np.sum(pred, axis=axes) + np.sum(targ, axis=axes) dice = (2.0 * intersect + smooth) / (denominator + smooth) assert dice.shape==(n_classes,), "dice shp {}".format(dice.shape) return dice def batch_dice(pred, y, false_positive_weight=1.0, smooth=1e-6): ''' compute soft dice over batch. this is a differentiable score and can be used as a loss function. only dice scores of foreground classes are returned, since training typically does not benefit from explicit background optimization. Pixels of the entire batch are considered a pseudo-volume to compute dice scores of. This way, single patches with missing foreground classes can not produce faulty gradients. :param pred: (b, c, y, x, (z)), softmax probabilities (network output). :param y: (b, c, y, x, (z)), one hote encoded segmentation mask. :param false_positive_weight: float [0,1]. For weighting of imbalanced classes, reduces the penalty for false-positive pixels. Can be beneficial sometimes in data with heavy fg/bg imbalances. :return: soft dice score (float).This function discards the background score and returns the mena of foreground scores. ''' if len(pred.size()) == 4: axes = (0, 2, 3) intersect = sum_tensor(pred * y, axes, keepdim=False) denom = sum_tensor(false_positive_weight*pred + y, axes, keepdim=False) return torch.mean(( (2*intersect + smooth) / (denom + smooth))[1:]) #only fg dice here. elif len(pred.size()) == 5: axes = (0, 2, 3, 4) intersect = sum_tensor(pred * y, axes, keepdim=False) denom = sum_tensor(false_positive_weight*pred + y, axes, keepdim=False) return torch.mean(( (2*intersect + smooth) / (denom + smooth))[1:]) #only fg dice here. else: raise ValueError('wrong input dimension in dice loss') ############################################################ # Bounding Boxes ############################################################ def compute_iou_2D(box, boxes, box_area, boxes_area): """Calculates IoU of the given box with the array of the given boxes. box: 1D vector [y1, x1, y2, x2] THIS IS THE GT BOX boxes: [boxes_count, (y1, x1, y2, x2)] box_area: float. the area of 'box' boxes_area: array of length boxes_count. Note: the areas are passed in rather than calculated here for efficency. Calculate once in the caller to avoid duplicate work. """ # 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_iou_3D(box, boxes, box_volume, boxes_volume): """Calculates IoU of the given box with the array of the given boxes. box: 1D vector [y1, x1, y2, x2, z1, z2] (typically gt box) boxes: [boxes_count, (y1, x1, y2, x2, z1, z2)] box_area: float. the area of 'box' boxes_area: array of length boxes_count. Note: the areas are passed in rather than calculated here for efficency. Calculate once in the caller to avoid duplicate work. """ # 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]) z1 = np.maximum(box[4], boxes[:, 4]) z2 = np.minimum(box[5], boxes[:, 5]) intersection = np.maximum(x2 - x1, 0) * np.maximum(y2 - y1, 0) * np.maximum(z2 - z1, 0) union = box_volume + boxes_volume[:] - intersection[:] iou = intersection / union return iou def compute_overlaps(boxes1, boxes2): """Computes IoU overlaps between two sets of boxes. boxes1, boxes2: [N, (y1, x1, y2, x2)]. / 3D: (z1, z2)) For better performance, pass the largest set first and the smaller second. :return: (#boxes1, #boxes2), ious of each box of 1 machted with each of 2 """ # Areas of anchors and GT boxes if boxes1.shape[1] == 4: area1 = (boxes1[:, 2] - boxes1[:, 0]) * (boxes1[:, 3] - boxes1[:, 1]) area2 = (boxes2[:, 2] - boxes2[:, 0]) * (boxes2[:, 3] - boxes2[:, 1]) # Compute overlaps to generate matrix [boxes1 count, boxes2 count] # Each cell contains the IoU value. overlaps = np.zeros((boxes1.shape[0], boxes2.shape[0])) for i in range(overlaps.shape[1]): box2 = boxes2[i] #this is the gt box overlaps[:, i] = compute_iou_2D(box2, boxes1, area2[i], area1) return overlaps else: # Areas of anchors and GT boxes volume1 = (boxes1[:, 2] - boxes1[:, 0]) * (boxes1[:, 3] - boxes1[:, 1]) * (boxes1[:, 5] - boxes1[:, 4]) volume2 = (boxes2[:, 2] - boxes2[:, 0]) * (boxes2[:, 3] - boxes2[:, 1]) * (boxes2[:, 5] - boxes2[:, 4]) # Compute overlaps to generate matrix [boxes1 count, boxes2 count] # Each cell contains the IoU value. overlaps = np.zeros((boxes1.shape[0], boxes2.shape[0])) for i in range(boxes2.shape[0]): box2 = boxes2[i] # this is the gt box overlaps[:, i] = compute_iou_3D(box2, boxes1, volume2[i], volume1) return overlaps def box_refinement(box, gt_box): """Compute refinement needed to transform box to gt_box. box and gt_box are [N, (y1, x1, y2, x2)] / 3D: (z1, z2)) """ height = box[:, 2] - box[:, 0] width = box[:, 3] - box[:, 1] center_y = box[:, 0] + 0.5 * height center_x = box[:, 1] + 0.5 * width gt_height = gt_box[:, 2] - gt_box[:, 0] gt_width = gt_box[:, 3] - gt_box[:, 1] gt_center_y = gt_box[:, 0] + 0.5 * gt_height gt_center_x = gt_box[:, 1] + 0.5 * gt_width dy = (gt_center_y - center_y) / height dx = (gt_center_x - center_x) / width dh = torch.log(gt_height / height) dw = torch.log(gt_width / width) result = torch.stack([dy, dx, dh, dw], dim=1) if box.shape[1] > 4: depth = box[:, 5] - box[:, 4] center_z = box[:, 4] + 0.5 * depth gt_depth = gt_box[:, 5] - gt_box[:, 4] gt_center_z = gt_box[:, 4] + 0.5 * gt_depth dz = (gt_center_z - center_z) / depth dd = torch.log(gt_depth / depth) result = torch.stack([dy, dx, dz, dh, dw, dd], dim=1) return result def unmold_mask_2D(mask, bbox, image_shape): """Converts a mask generated by the neural network into a format similar to it's original shape. mask: [height, width] of type float. A small, typically 28x28 mask. bbox: [y1, x1, y2, x2]. The box to fit the mask in. Returns a binary mask with the same size as the original image. """ y1, x1, y2, x2 = bbox out_zoom = [y2 - y1, x2 - x1] zoom_factor = [i / j for i, j in zip(out_zoom, mask.shape)] mask = scipy.ndimage.zoom(mask, zoom_factor, order=1).astype(np.float32) # Put the mask in the right location. full_mask = np.zeros(image_shape[:2]) #only y,x full_mask[y1:y2, x1:x2] = mask return full_mask def unmold_mask_2D_torch(mask, bbox, image_shape): """Converts a mask generated by the neural network into a format similar to it's original shape. mask: [height, width] of type float. A small, typically 28x28 mask. bbox: [y1, x1, y2, x2]. The box to fit the mask in. Returns a binary mask with the same size as the original image. """ y1, x1, y2, x2 = bbox out_zoom = [(y2 - y1).float(), (x2 - x1).float()] zoom_factor = [i / j for i, j in zip(out_zoom, mask.shape)] mask = mask.unsqueeze(0).unsqueeze(0) mask = torch.nn.functional.interpolate(mask, scale_factor=zoom_factor) mask = mask[0][0] #mask = scipy.ndimage.zoom(mask.cpu().numpy(), zoom_factor, order=1).astype(np.float32) #mask = torch.from_numpy(mask).cuda() # Put the mask in the right location. full_mask = torch.zeros(image_shape[:2]) # only y,x full_mask[y1:y2, x1:x2] = mask return full_mask def unmold_mask_3D(mask, bbox, image_shape): """Converts a mask generated by the neural network into a format similar to it's original shape. mask: [height, width] of type float. A small, typically 28x28 mask. bbox: [y1, x1, y2, x2, z1, z2]. The box to fit the mask in. Returns a binary mask with the same size as the original image. """ y1, x1, y2, x2, z1, z2 = bbox out_zoom = [y2 - y1, x2 - x1, z2 - z1] zoom_factor = [i/j for i,j in zip(out_zoom, mask.shape)] mask = scipy.ndimage.zoom(mask, zoom_factor, order=1).astype(np.float32) # Put the mask in the right location. full_mask = np.zeros(image_shape[:3]) full_mask[y1:y2, x1:x2, z1:z2] = mask return full_mask def nms_numpy(box_coords, scores, thresh): """ non-maximum suppression on 2D or 3D boxes in numpy. :param box_coords: [y1,x1,y2,x2 (,z1,z2)] with y1<=y2, x1<=x2, z1<=z2. :param scores: ranking scores (higher score == higher rank) of boxes. :param thresh: IoU threshold for clustering. :return: """ y1 = box_coords[:, 0] x1 = box_coords[:, 1] y2 = box_coords[:, 2] x2 = box_coords[:, 3] assert np.all(y1 <= y2) and np.all(x1 <= x2), """"the definition of the coordinates is crucially important here: coordinates of which maxima are taken need to be the lower coordinates""" areas = (x2 - x1) * (y2 - y1) is_3d = box_coords.shape[1] == 6 if is_3d: # 3-dim case z1 = box_coords[:, 4] z2 = box_coords[:, 5] assert np.all(z1<=z2), """"the definition of the coordinates is crucially important here: coordinates of which maxima are taken need to be the lower coordinates""" areas *= (z2 - z1) order = scores.argsort()[::-1] keep = [] while order.size > 0: # order is the sorted index. maps order to index: order[1] = 24 means (rank1, ix 24) i = order[0] # highest scoring element yy1 = np.maximum(y1[i], y1[order]) # highest scoring element still in >order<, is compared to itself, that is okay. xx1 = np.maximum(x1[i], x1[order]) yy2 = np.minimum(y2[i], y2[order]) xx2 = np.minimum(x2[i], x2[order]) h = np.maximum(0.0, yy2 - yy1) w = np.maximum(0.0, xx2 - xx1) inter = h * w if is_3d: zz1 = np.maximum(z1[i], z1[order]) zz2 = np.minimum(z2[i], z2[order]) d = np.maximum(0.0, zz2 - zz1) inter *= d iou = inter / (areas[i] + areas[order] - inter) non_matches = np.nonzero(iou <= thresh)[0] # get all elements that were not matched and discard all others. order = order[non_matches] keep.append(i) return keep ############################################################ # M-RCNN ############################################################ def refine_proposals(rpn_pred_probs, rpn_pred_deltas, proposal_count, batch_anchors, cf): """ Receives anchor scores and selects a subset to pass as proposals to the second stage. Filtering is done based on anchor scores and non-max suppression to remove overlaps. It also applies bounding box refinement details to anchors. :param rpn_pred_probs: (b, n_anchors, 2) :param rpn_pred_deltas: (b, n_anchors, (y, x, (z), log(h), log(w), (log(d)))) :return: batch_normalized_props: Proposals in normalized coordinates (b, proposal_count, (y1, x1, y2, x2, (z1), (z2), score)) :return: batch_out_proposals: Box coords + RPN foreground scores for monitoring/plotting (b, proposal_count, (y1, x1, y2, x2, (z1), (z2), score)) """ std_dev = torch.from_numpy(cf.rpn_bbox_std_dev[None]).float().cuda() norm = torch.from_numpy(cf.scale).float().cuda() anchors = batch_anchors.clone() batch_scores = rpn_pred_probs[:, :, 1] # norm deltas batch_deltas = rpn_pred_deltas * std_dev batch_normalized_props = [] batch_out_proposals = [] # loop over batch dimension. for ix in range(batch_scores.shape[0]): scores = batch_scores[ix] deltas = batch_deltas[ix] non_nans = deltas == deltas assert torch.all(non_nans), "deltas have nans: {}".format(deltas[~non_nans]) non_nans = anchors == anchors assert torch.all(non_nans), "anchors have nans: {}".format(anchors[~non_nans]) # improve performance by trimming to top anchors by score # and doing the rest on the smaller subset. pre_nms_limit = min(cf.pre_nms_limit, anchors.size()[0]) scores, order = scores.sort(descending=True) order = order[:pre_nms_limit] scores = scores[:pre_nms_limit] deltas = deltas[order, :] # apply deltas to anchors to get refined anchors and filter with non-maximum suppression. if batch_deltas.shape[-1] == 4: boxes = apply_box_deltas_2D(anchors[order, :], deltas) non_nans = boxes == boxes assert torch.all(non_nans), "unnormalized boxes before clip/after delta apply have nans: {}".format(boxes[~non_nans]) boxes = clip_boxes_2D(boxes, cf.window) else: boxes = apply_box_deltas_3D(anchors[order, :], deltas) boxes = clip_boxes_3D(boxes, cf.window) non_nans = boxes == boxes assert torch.all(non_nans), "unnormalized boxes before nms/after clip have nans: {}".format(boxes[~non_nans]) # boxes are y1,x1,y2,x2, torchvision-nms requires x1,y1,x2,y2, but consistent swap x<->y is irrelevant. keep = nms.nms(boxes, scores, cf.rpn_nms_threshold) keep = keep[:proposal_count] boxes = boxes[keep, :] rpn_scores = scores[keep][:, None] # pad missing boxes with 0. if boxes.shape[0] < proposal_count: n_pad_boxes = proposal_count - boxes.shape[0] zeros = torch.zeros([n_pad_boxes, boxes.shape[1]]).cuda() boxes = torch.cat([boxes, zeros], dim=0) zeros = torch.zeros([n_pad_boxes, rpn_scores.shape[1]]).cuda() rpn_scores = torch.cat([rpn_scores, zeros], dim=0) # concat box and score info for monitoring/plotting. batch_out_proposals.append(torch.cat((boxes, rpn_scores), 1).cpu().data.numpy()) # normalize dimensions to range of 0 to 1. non_nans = boxes == boxes assert torch.all(non_nans), "unnormalized boxes after nms have nans: {}".format(boxes[~non_nans]) normalized_boxes = boxes / norm where = normalized_boxes <=1 assert torch.all(where), "normalized box coords >1 found:\n {}\n".format(normalized_boxes[~where]) # add again batch dimension batch_normalized_props.append(torch.cat((normalized_boxes, rpn_scores), 1).unsqueeze(0)) batch_normalized_props = torch.cat(batch_normalized_props) batch_out_proposals = np.array(batch_out_proposals) return batch_normalized_props, batch_out_proposals def pyramid_roi_align(feature_maps, rois, pool_size, pyramid_levels, dim): """ Implements ROI Pooling on multiple levels of the feature pyramid. :param feature_maps: list of feature maps, each of shape (b, c, y, x , (z)) :param rois: proposals (normalized coords.) as returned by RPN. contain info about original batch element allocation. (n_proposals, (y1, x1, y2, x2, (z1), (z2), batch_ixs) :param pool_size: list of poolsizes in dims: [x, y, (z)] :param pyramid_levels: list. [0, 1, 2, ...] :return: pooled: pooled feature map rois (n_proposals, c, poolsize_y, poolsize_x, (poolsize_z)) Output: Pooled regions in the shape: [num_boxes, height, width, channels]. The width and height are those specific in the pool_shape in the layer constructor. """ boxes = rois[:, :dim*2] batch_ixs = rois[:, dim*2] # Assign each ROI to a level in the pyramid based on the ROI area. if dim == 2: y1, x1, y2, x2 = boxes.chunk(4, dim=1) else: y1, x1, y2, x2, z1, z2 = boxes.chunk(6, dim=1) h = y2 - y1 w = x2 - x1 # Equation 1 in https://arxiv.org/abs/1612.03144. Account for # the fact that our coordinates are normalized here. # divide sqrt(h*w) by 1 instead image_area. roi_level = (4 + torch.log2(torch.sqrt(h*w))).round().int().clamp(pyramid_levels[0], pyramid_levels[-1]) # if Pyramid contains additional level P6, adapt the roi_level assignment accordingly. if len(pyramid_levels) == 5: roi_level[h*w > 0.65] = 5 # Loop through levels and apply ROI pooling to each. pooled = [] box_to_level = [] fmap_shapes = [f.shape for f in feature_maps] for level_ix, level in enumerate(pyramid_levels): ix = roi_level == level if not ix.any(): continue ix = torch.nonzero(ix)[:, 0] level_boxes = boxes[ix, :] # re-assign rois to feature map of original batch element. ind = batch_ixs[ix].int() # Keep track of which box is mapped to which level box_to_level.append(ix) # Stop gradient propogation to ROI proposals level_boxes = level_boxes.detach() if len(pool_size) == 2: # remap to feature map coordinate system y_exp, x_exp = fmap_shapes[level_ix][2:] # exp = expansion level_boxes.mul_(torch.tensor([y_exp, x_exp, y_exp, x_exp], dtype=torch.float32).cuda()) pooled_features = roi_align.roi_align_2d(feature_maps[level_ix], torch.cat((ind.unsqueeze(1).float(), level_boxes), dim=1), pool_size) else: y_exp, x_exp, z_exp = fmap_shapes[level_ix][2:] level_boxes.mul_(torch.tensor([y_exp, x_exp, y_exp, x_exp, z_exp, z_exp], dtype=torch.float32).cuda()) pooled_features = roi_align.roi_align_3d(feature_maps[level_ix], torch.cat((ind.unsqueeze(1).float(), level_boxes), dim=1), pool_size) pooled.append(pooled_features) # Pack pooled features into one tensor pooled = torch.cat(pooled, dim=0) # Pack box_to_level mapping into one array and add another # column representing the order of pooled boxes box_to_level = torch.cat(box_to_level, dim=0) # Rearrange pooled features to match the order of the original boxes _, box_to_level = torch.sort(box_to_level) pooled = pooled[box_to_level, :, :] return pooled def roi_align_3d_numpy(input: np.ndarray, rois, output_size: tuple, spatial_scale: float = 1., sampling_ratio: int = -1) -> np.ndarray: """ This fct mainly serves as a verification method for 3D CUDA implementation of RoIAlign, it's highly inefficient due to the nested loops. :param input: (ndarray[N, C, H, W, D]): input feature map :param rois: list (N,K(n), 6), K(n) = nr of rois in batch-element n, single roi of format (y1,x1,y2,x2,z1,z2) :param output_size: :param spatial_scale: :param sampling_ratio: :return: (List[N, K(n), C, output_size[0], output_size[1], output_size[2]]) """ out_height, out_width, out_depth = output_size coord_grid = tuple([np.linspace(0, input.shape[dim] - 1, num=input.shape[dim]) for dim in range(2, 5)]) pooled_rois = [[]] * len(rois) assert len(rois) == input.shape[0], "batch dim mismatch, rois: {}, input: {}".format(len(rois), input.shape[0]) print("Numpy 3D RoIAlign progress:", end="\n") for b in range(input.shape[0]): for roi in tqdm.tqdm(rois[b]): y1, x1, y2, x2, z1, z2 = np.array(roi) * spatial_scale roi_height = max(float(y2 - y1), 1.) roi_width = max(float(x2 - x1), 1.) roi_depth = max(float(z2 - z1), 1.) if sampling_ratio <= 0: sampling_ratio_h = int(np.ceil(roi_height / out_height)) sampling_ratio_w = int(np.ceil(roi_width / out_width)) sampling_ratio_d = int(np.ceil(roi_depth / out_depth)) else: sampling_ratio_h = sampling_ratio_w = sampling_ratio_d = sampling_ratio # == n points per bin bin_height = roi_height / out_height bin_width = roi_width / out_width bin_depth = roi_depth / out_depth n_points = sampling_ratio_h * sampling_ratio_w * sampling_ratio_d pooled_roi = np.empty((input.shape[1], out_height, out_width, out_depth), dtype="float32") for chan in range(input.shape[1]): lin_interpolator = scipy.interpolate.RegularGridInterpolator(coord_grid, input[b, chan], method="linear") for bin_iy in range(out_height): for bin_ix in range(out_width): for bin_iz in range(out_depth): bin_val = 0. for i in range(sampling_ratio_h): for j in range(sampling_ratio_w): for k in range(sampling_ratio_d): loc_ijk = [ y1 + bin_iy * bin_height + (i + 0.5) * (bin_height / sampling_ratio_h), x1 + bin_ix * bin_width + (j + 0.5) * (bin_width / sampling_ratio_w), z1 + bin_iz * bin_depth + (k + 0.5) * (bin_depth / sampling_ratio_d)] # print("loc_ijk", loc_ijk) if not (np.any([c < -1.0 for c in loc_ijk]) or loc_ijk[0] > input.shape[2] or loc_ijk[1] > input.shape[3] or loc_ijk[2] > input.shape[4]): for catch_case in range(3): # catch on-border cases if int(loc_ijk[catch_case]) == input.shape[catch_case + 2] - 1: loc_ijk[catch_case] = input.shape[catch_case + 2] - 1 bin_val += lin_interpolator(loc_ijk) pooled_roi[chan, bin_iy, bin_ix, bin_iz] = bin_val / n_points pooled_rois[b].append(pooled_roi) return np.array(pooled_rois) def refine_detections(cf, batch_ixs, rois, deltas, scores, regressions): """ Refine classified proposals (apply deltas to rpn rois), filter overlaps (nms) and return final detections. :param rois: (n_proposals, 2 * dim) normalized boxes as proposed by RPN. n_proposals = batch_size * POST_NMS_ROIS :param deltas: (n_proposals, n_classes, 2 * dim) box refinement deltas as predicted by mrcnn bbox regressor. :param batch_ixs: (n_proposals) batch element assignment info for re-allocation. :param scores: (n_proposals, n_classes) probabilities for all classes per roi as predicted by mrcnn classifier. :param regressions: (n_proposals, n_classes, regression_features (+1 for uncertainty if predicted) regression vector :return: result: (n_final_detections, (y1, x1, y2, x2, (z1), (z2), batch_ix, pred_class_id, pred_score, *regression vector features)) """ # class IDs per ROI. Since scores of all classes are of interest (not just max class), all are kept at this point. class_ids = [] fg_classes = cf.head_classes - 1 # repeat vectors to fill in predictions for all foreground classes. for ii in range(1, fg_classes + 1): class_ids += [ii] * rois.shape[0] class_ids = torch.from_numpy(np.array(class_ids)).cuda() batch_ixs = batch_ixs.repeat(fg_classes) rois = rois.repeat(fg_classes, 1) deltas = deltas.repeat(fg_classes, 1, 1) scores = scores.repeat(fg_classes, 1) regressions = regressions.repeat(fg_classes, 1, 1) # get class-specific scores and bounding box deltas idx = torch.arange(class_ids.size()[0]).long().cuda() # using idx instead of slice [:,] squashes first dimension. #len(class_ids)>scores.shape[1] --> probs is broadcasted by expansion from fg_classes-->len(class_ids) batch_ixs = batch_ixs[idx] deltas_specific = deltas[idx, class_ids] class_scores = scores[idx, class_ids] regressions = regressions[idx, class_ids] # apply bounding box deltas. re-scale to image coordinates. std_dev = torch.from_numpy(np.reshape(cf.rpn_bbox_std_dev, [1, cf.dim * 2])).float().cuda() scale = torch.from_numpy(cf.scale).float().cuda() refined_rois = apply_box_deltas_2D(rois, deltas_specific * std_dev) * scale if cf.dim == 2 else \ apply_box_deltas_3D(rois, deltas_specific * std_dev) * scale # round and cast to int since we're dealing with pixels now refined_rois = clip_to_window(cf.window, refined_rois) refined_rois = torch.round(refined_rois) # filter out low confidence boxes keep = idx keep_bool = (class_scores >= cf.model_min_confidence) if not 0 in torch.nonzero(keep_bool).size(): score_keep = torch.nonzero(keep_bool)[:, 0] pre_nms_class_ids = class_ids[score_keep] pre_nms_rois = refined_rois[score_keep] pre_nms_scores = class_scores[score_keep] pre_nms_batch_ixs = batch_ixs[score_keep] for j, b in enumerate(unique1d(pre_nms_batch_ixs)): bixs = torch.nonzero(pre_nms_batch_ixs == b)[:, 0] bix_class_ids = pre_nms_class_ids[bixs] bix_rois = pre_nms_rois[bixs] bix_scores = pre_nms_scores[bixs] for i, class_id in enumerate(unique1d(bix_class_ids)): ixs = torch.nonzero(bix_class_ids == class_id)[:, 0] # nms expects boxes sorted by score. ix_rois = bix_rois[ixs] ix_scores = bix_scores[ixs] ix_scores, order = ix_scores.sort(descending=True) ix_rois = ix_rois[order, :] class_keep = nms.nms(ix_rois, ix_scores, cf.detection_nms_threshold) # map indices back. class_keep = keep[score_keep[bixs[ixs[order[class_keep]]]]] # merge indices over classes for current batch element b_keep = class_keep if i == 0 else unique1d(torch.cat((b_keep, class_keep))) # only keep top-k boxes of current batch-element top_ids = class_scores[b_keep].sort(descending=True)[1][:cf.model_max_instances_per_batch_element] b_keep = b_keep[top_ids] # merge indices over batch elements. batch_keep = b_keep if j == 0 else unique1d(torch.cat((batch_keep, b_keep))) keep = batch_keep else: keep = torch.tensor([0]).long().cuda() # arrange output output = [refined_rois[keep], batch_ixs[keep].unsqueeze(1)] output += [class_ids[keep].unsqueeze(1).float(), class_scores[keep].unsqueeze(1)] output += [regressions[keep]] result = torch.cat(output, dim=1) # shape: (n_keeps, catted feats), catted feats: [0:dim*2] are box_coords, [dim*2] are batch_ics, # [dim*2+1] are class_ids, [dim*2+2] are scores, [dim*2+3:] are regression vector features (incl uncertainty) return result def loss_example_mining(cf, batch_proposals, batch_gt_boxes, batch_gt_masks, batch_roi_scores, batch_gt_class_ids, batch_gt_regressions): """ Subsamples proposals for mrcnn losses and generates targets. Sampling is done per batch element, seems to have positive effects on training, as opposed to sampling over entire batch. Negatives are sampled via stochastic hard-example mining (SHEM), where a number of negative proposals is drawn from larger pool of highest scoring proposals for stochasticity. Scoring is obtained here as the max over all foreground probabilities as returned by mrcnn_classifier (worked better than loss-based class-balancing methods like "online hard-example mining" or "focal loss".) Classification-regression duality: regressions can be given along with classes (at least fg/bg, only class scores are used for ranking). :param batch_proposals: (n_proposals, (y1, x1, y2, x2, (z1), (z2), batch_ixs). boxes as proposed by RPN. n_proposals here is determined by batch_size * POST_NMS_ROIS. :param mrcnn_class_logits: (n_proposals, n_classes) :param batch_gt_boxes: list over batch elements. Each element is a list over the corresponding roi target coordinates. :param batch_gt_masks: list over batch elements. Each element is binary mask of shape (n_gt_rois, c, y, x, (z)) :param batch_gt_class_ids: list over batch elements. Each element is a list over the corresponding roi target labels. if no classes predicted (only fg/bg from RPN): expected as pseudo classes [0, 1] for bg, fg. :param batch_gt_regressions: list over b elements. Each element is a regression target vector. if None--> pseudo :return: sample_indices: (n_sampled_rois) indices of sampled proposals to be used for loss functions. :return: target_class_ids: (n_sampled_rois)containing target class labels of sampled proposals. :return: target_deltas: (n_sampled_rois, 2 * dim) containing target deltas of sampled proposals for box refinement. :return: target_masks: (n_sampled_rois, y, x, (z)) containing target masks of sampled proposals. """ # normalization of target coordinates #global sample_regressions if cf.dim == 2: h, w = cf.patch_size scale = torch.from_numpy(np.array([h, w, h, w])).float().cuda() else: h, w, z = cf.patch_size scale = torch.from_numpy(np.array([h, w, h, w, z, z])).float().cuda() positive_count = 0 negative_count = 0 sample_positive_indices = [] sample_negative_indices = [] sample_deltas = [] sample_masks = [] sample_class_ids = [] if batch_gt_regressions is not None: sample_regressions = [] else: target_regressions = torch.FloatTensor().cuda() std_dev = torch.from_numpy(cf.bbox_std_dev).float().cuda() # loop over batch and get positive and negative sample rois. for b in range(len(batch_gt_boxes)): gt_masks = torch.from_numpy(batch_gt_masks[b]).float().cuda() gt_class_ids = torch.from_numpy(batch_gt_class_ids[b]).int().cuda() if batch_gt_regressions is not None: gt_regressions = torch.from_numpy(batch_gt_regressions[b]).float().cuda() #if np.any(batch_gt_class_ids[b] > 0): # skip roi selection for no gt images. if np.any([len(coords)>0 for coords in batch_gt_boxes[b]]): gt_boxes = torch.from_numpy(batch_gt_boxes[b]).float().cuda() / scale else: gt_boxes = torch.FloatTensor().cuda() # get proposals and indices of current batch element. proposals = batch_proposals[batch_proposals[:, -1] == b][:, :-1] batch_element_indices = torch.nonzero(batch_proposals[:, -1] == b).squeeze(1) # Compute overlaps matrix [proposals, gt_boxes] if not 0 in gt_boxes.size(): if gt_boxes.shape[1] == 4: assert cf.dim == 2, "gt_boxes shape {} doesnt match cf.dim{}".format(gt_boxes.shape, cf.dim) overlaps = bbox_overlaps_2D(proposals, gt_boxes) else: assert cf.dim == 3, "gt_boxes shape {} doesnt match cf.dim{}".format(gt_boxes.shape, cf.dim) overlaps = bbox_overlaps_3D(proposals, gt_boxes) # Determine positive and negative ROIs roi_iou_max = torch.max(overlaps, dim=1)[0] # 1. Positive ROIs are those with >= 0.5 IoU with a GT box positive_roi_bool = roi_iou_max >= (0.5 if cf.dim == 2 else 0.3) # 2. Negative ROIs are those with < 0.1 with every GT box. negative_roi_bool = roi_iou_max < (0.1 if cf.dim == 2 else 0.01) else: positive_roi_bool = torch.FloatTensor().cuda() negative_roi_bool = torch.from_numpy(np.array([1]*proposals.shape[0])).cuda() # Sample Positive ROIs if not 0 in torch.nonzero(positive_roi_bool).size(): positive_indices = torch.nonzero(positive_roi_bool).squeeze(1) positive_samples = int(cf.train_rois_per_image * cf.roi_positive_ratio) rand_idx = torch.randperm(positive_indices.size()[0]) rand_idx = rand_idx[:positive_samples].cuda() positive_indices = positive_indices[rand_idx] positive_samples = positive_indices.size()[0] positive_rois = proposals[positive_indices, :] # Assign positive ROIs to GT boxes. positive_overlaps = overlaps[positive_indices, :] roi_gt_box_assignment = torch.max(positive_overlaps, dim=1)[1] roi_gt_boxes = gt_boxes[roi_gt_box_assignment, :] roi_gt_class_ids = gt_class_ids[roi_gt_box_assignment] if batch_gt_regressions is not None: roi_gt_regressions = gt_regressions[roi_gt_box_assignment] # Compute bbox refinement targets for positive ROIs deltas = box_refinement(positive_rois, roi_gt_boxes) deltas /= std_dev roi_masks = gt_masks[roi_gt_box_assignment] assert roi_masks.shape[1] == 1, "gt masks have more than one channel --> is this desired?" # Compute mask targets boxes = positive_rois box_ids = torch.arange(roi_masks.shape[0]).cuda().unsqueeze(1).float() if len(cf.mask_shape) == 2: y_exp, x_exp = roi_masks.shape[2:] # exp = expansion boxes.mul_(torch.tensor([y_exp, x_exp, y_exp, x_exp], dtype=torch.float32).cuda()) masks = roi_align.roi_align_2d(roi_masks, torch.cat((box_ids, boxes), dim=1), cf.mask_shape) else: y_exp, x_exp, z_exp = roi_masks.shape[2:] # exp = expansion boxes.mul_(torch.tensor([y_exp, x_exp, y_exp, x_exp, z_exp, z_exp], dtype=torch.float32).cuda()) masks = roi_align.roi_align_3d(roi_masks, torch.cat((box_ids, boxes), dim=1), cf.mask_shape) masks = masks.squeeze(1) # Threshold mask pixels at 0.5 to have GT masks be 0 or 1 to use with # binary cross entropy loss. masks = torch.round(masks) sample_positive_indices.append(batch_element_indices[positive_indices]) sample_deltas.append(deltas) sample_masks.append(masks) sample_class_ids.append(roi_gt_class_ids) if batch_gt_regressions is not None: sample_regressions.append(roi_gt_regressions) positive_count += positive_samples else: positive_samples = 0 # Sample negative ROIs. Add enough to maintain positive:negative ratio, but at least 1. Sample via SHEM. if not 0 in torch.nonzero(negative_roi_bool).size(): negative_indices = torch.nonzero(negative_roi_bool).squeeze(1) r = 1.0 / cf.roi_positive_ratio b_neg_count = np.max((int(r * positive_samples - positive_samples), 1)) roi_scores_neg = batch_roi_scores[batch_element_indices[negative_indices]] raw_sampled_indices = shem(roi_scores_neg, b_neg_count, cf.shem_poolsize) sample_negative_indices.append(batch_element_indices[negative_indices[raw_sampled_indices]]) negative_count += raw_sampled_indices.size()[0] if len(sample_positive_indices) > 0: target_deltas = torch.cat(sample_deltas) target_masks = torch.cat(sample_masks) target_class_ids = torch.cat(sample_class_ids) if batch_gt_regressions is not None: target_regressions = torch.cat(sample_regressions) # Pad target information with zeros for negative ROIs. if positive_count > 0 and negative_count > 0: sample_indices = torch.cat((torch.cat(sample_positive_indices), torch.cat(sample_negative_indices)), dim=0) zeros = torch.zeros(negative_count, cf.dim * 2).cuda() target_deltas = torch.cat([target_deltas, zeros], dim=0) zeros = torch.zeros(negative_count, *cf.mask_shape).cuda() target_masks = torch.cat([target_masks, zeros], dim=0) zeros = torch.zeros(negative_count).int().cuda() target_class_ids = torch.cat([target_class_ids, zeros], dim=0) if batch_gt_regressions is not None: # regression targets need to have 0 as background/negative with below practice if 'regression_bin' in cf.prediction_tasks: zeros = torch.zeros(negative_count, dtype=torch.float).cuda() else: zeros = torch.zeros(negative_count, cf.regression_n_features, dtype=torch.float).cuda() target_regressions = torch.cat([target_regressions, zeros], dim=0) elif positive_count > 0: sample_indices = torch.cat(sample_positive_indices) elif negative_count > 0: sample_indices = torch.cat(sample_negative_indices) target_deltas = torch.zeros(negative_count, cf.dim * 2).cuda() target_masks = torch.zeros(negative_count, *cf.mask_shape).cuda() target_class_ids = torch.zeros(negative_count).int().cuda() if batch_gt_regressions is not None: if 'regression_bin' in cf.prediction_tasks: target_regressions = torch.zeros(negative_count, dtype=torch.float).cuda() else: target_regressions = torch.zeros(negative_count, cf.regression_n_features, dtype=torch.float).cuda() else: sample_indices = torch.LongTensor().cuda() target_class_ids = torch.IntTensor().cuda() target_deltas = torch.FloatTensor().cuda() target_masks = torch.FloatTensor().cuda() target_regressions = torch.FloatTensor().cuda() return sample_indices, target_deltas, target_masks, target_class_ids, target_regressions ############################################################ # Anchors ############################################################ def generate_anchors(scales, ratios, shape, feature_stride, anchor_stride): """ scales: 1D array of anchor sizes in pixels. Example: [32, 64, 128] ratios: 1D array of anchor ratios of width/height. Example: [0.5, 1, 2] shape: [height, width] spatial shape of the feature map over which to generate anchors. feature_stride: Stride of the feature map relative to the image in pixels. anchor_stride: Stride of anchors on the feature map. For example, if the value is 2 then generate anchors for every other feature map pixel. """ # Get all combinations of scales and ratios scales, ratios = np.meshgrid(np.array(scales), np.array(ratios)) scales = scales.flatten() ratios = ratios.flatten() # Enumerate heights and widths from scales and ratios heights = scales / np.sqrt(ratios) widths = scales * np.sqrt(ratios) # Enumerate shifts in feature space shifts_y = np.arange(0, shape[0], anchor_stride) * feature_stride shifts_x = np.arange(0, shape[1], anchor_stride) * feature_stride shifts_x, shifts_y = np.meshgrid(shifts_x, shifts_y) # Enumerate combinations of shifts, widths, and heights box_widths, box_centers_x = np.meshgrid(widths, shifts_x) box_heights, box_centers_y = np.meshgrid(heights, shifts_y) # Reshape to get a list of (y, x) and a list of (h, w) box_centers = np.stack([box_centers_y, box_centers_x], axis=2).reshape([-1, 2]) box_sizes = np.stack([box_heights, box_widths], axis=2).reshape([-1, 2]) # Convert to corner coordinates (y1, x1, y2, x2) boxes = np.concatenate([box_centers - 0.5 * box_sizes, box_centers + 0.5 * box_sizes], axis=1) return boxes def generate_anchors_3D(scales_xy, scales_z, ratios, shape, feature_stride_xy, feature_stride_z, anchor_stride): """ scales: 1D array of anchor sizes in pixels. Example: [32, 64, 128] ratios: 1D array of anchor ratios of width/height. Example: [0.5, 1, 2] shape: [height, width] spatial shape of the feature map over which to generate anchors. feature_stride: Stride of the feature map relative to the image in pixels. anchor_stride: Stride of anchors on the feature map. For example, if the value is 2 then generate anchors for every other feature map pixel. """ # Get all combinations of scales and ratios scales_xy, ratios_meshed = np.meshgrid(np.array(scales_xy), np.array(ratios)) scales_xy = scales_xy.flatten() ratios_meshed = ratios_meshed.flatten() # Enumerate heights and widths from scales and ratios heights = scales_xy / np.sqrt(ratios_meshed) widths = scales_xy * np.sqrt(ratios_meshed) depths = np.tile(np.array(scales_z), len(ratios_meshed)//np.array(scales_z)[..., None].shape[0]) # Enumerate shifts in feature space shifts_y = np.arange(0, shape[0], anchor_stride) * feature_stride_xy #translate from fm positions to input coords. shifts_x = np.arange(0, shape[1], anchor_stride) * feature_stride_xy shifts_z = np.arange(0, shape[2], anchor_stride) * (feature_stride_z) shifts_x, shifts_y, shifts_z = np.meshgrid(shifts_x, shifts_y, shifts_z) # Enumerate combinations of shifts, widths, and heights box_widths, box_centers_x = np.meshgrid(widths, shifts_x) box_heights, box_centers_y = np.meshgrid(heights, shifts_y) box_depths, box_centers_z = np.meshgrid(depths, shifts_z) # Reshape to get a list of (y, x, z) and a list of (h, w, d) box_centers = np.stack( [box_centers_y, box_centers_x, box_centers_z], axis=2).reshape([-1, 3]) box_sizes = np.stack([box_heights, box_widths, box_depths], axis=2).reshape([-1, 3]) # Convert to corner coordinates (y1, x1, y2, x2, z1, z2) boxes = np.concatenate([box_centers - 0.5 * box_sizes, box_centers + 0.5 * box_sizes], axis=1) boxes = np.transpose(np.array([boxes[:, 0], boxes[:, 1], boxes[:, 3], boxes[:, 4], boxes[:, 2], boxes[:, 5]]), axes=(1, 0)) return boxes def generate_pyramid_anchors(logger, cf): """Generate anchors at different levels of a feature pyramid. Each scale is associated with a level of the pyramid, but each ratio is used in all levels of the pyramid. from configs: :param scales: cf.RPN_ANCHOR_SCALES , for conformity with retina nets: scale entries need to be list, e.g. [[4], [8], [16], [32]] :param ratios: cf.RPN_ANCHOR_RATIOS , e.g. [0.5, 1, 2] :param feature_shapes: cf.BACKBONE_SHAPES , e.g. [array of shapes per feature map] [80, 40, 20, 10, 5] :param feature_strides: cf.BACKBONE_STRIDES , e.g. [2, 4, 8, 16, 32, 64] :param anchors_stride: cf.RPN_ANCHOR_STRIDE , e.g. 1 :return anchors: (N, (y1, x1, y2, x2, (z1), (z2)). All generated anchors in one array. Sorted with the same order of the given scales. So, anchors of scale[0] come first, then anchors of scale[1], and so on. """ scales = cf.rpn_anchor_scales ratios = cf.rpn_anchor_ratios feature_shapes = cf.backbone_shapes anchor_stride = cf.rpn_anchor_stride pyramid_levels = cf.pyramid_levels feature_strides = cf.backbone_strides logger.info("anchor scales {} and feature map shapes {}".format(scales, feature_shapes)) expected_anchors = [np.prod(feature_shapes[level]) * len(ratios) * len(scales['xy'][level]) for level in pyramid_levels] anchors = [] for lix, level in enumerate(pyramid_levels): if len(feature_shapes[level]) == 2: anchors.append(generate_anchors(scales['xy'][level], ratios, feature_shapes[level], feature_strides['xy'][level], anchor_stride)) elif len(feature_shapes[level]) == 3: anchors.append(generate_anchors_3D(scales['xy'][level], scales['z'][level], ratios, feature_shapes[level], feature_strides['xy'][level], feature_strides['z'][level], anchor_stride)) else: raise Exception("invalid feature_shapes[{}] size {}".format(level, feature_shapes[level])) logger.info("level {}: expected anchors {}, built anchors {}.".format(level, expected_anchors[lix], anchors[-1].shape)) out_anchors = np.concatenate(anchors, axis=0) logger.info("Total: expected anchors {}, built anchors {}.".format(np.sum(expected_anchors), out_anchors.shape)) return out_anchors def apply_box_deltas_2D(boxes, deltas): """Applies the given deltas to the given boxes. boxes: [N, 4] where each row is y1, x1, y2, x2 deltas: [N, 4] where each row is [dy, dx, log(dh), log(dw)] """ # Convert to y, x, h, w non_nans = boxes == boxes assert torch.all(non_nans), "boxes at beginning of delta apply have nans: {}".format( boxes[~non_nans]) height = boxes[:, 2] - boxes[:, 0] width = boxes[:, 3] - boxes[:, 1] center_y = boxes[:, 0] + 0.5 * height center_x = boxes[:, 1] + 0.5 * width # Apply deltas center_y += deltas[:, 0] * height center_x += deltas[:, 1] * width # clip delta preds in order to avoid infs and later nans after exponentiation. height *= torch.exp(torch.clamp(deltas[:, 2], max=6.)) width *= torch.exp(torch.clamp(deltas[:, 3], max=6.)) non_nans = width == width assert torch.all(non_nans), "inside delta apply, width has nans: {}".format( width[~non_nans]) # 0.*inf results in nan. fix nans to zeros? # height[height!=height] = 0. # width[width!=width] = 0. non_nans = height == height assert torch.all(non_nans), "inside delta apply, height has nans directly after setting to zero: {}".format( height[~non_nans]) non_nans = width == width assert torch.all(non_nans), "inside delta apply, width has nans directly after setting to zero: {}".format( width[~non_nans]) # Convert back to y1, x1, y2, x2 y1 = center_y - 0.5 * height x1 = center_x - 0.5 * width y2 = y1 + height x2 = x1 + width result = torch.stack([y1, x1, y2, x2], dim=1) non_nans = result == result assert torch.all(non_nans), "inside delta apply, result has nans: {}".format(result[~non_nans]) return result def apply_box_deltas_3D(boxes, deltas): """Applies the given deltas to the given boxes. boxes: [N, 6] where each row is y1, x1, y2, x2, z1, z2 deltas: [N, 6] where each row is [dy, dx, dz, log(dh), log(dw), log(dd)] """ # Convert to y, x, h, w height = boxes[:, 2] - boxes[:, 0] width = boxes[:, 3] - boxes[:, 1] depth = boxes[:, 5] - boxes[:, 4] center_y = boxes[:, 0] + 0.5 * height center_x = boxes[:, 1] + 0.5 * width center_z = boxes[:, 4] + 0.5 * depth # Apply deltas center_y += deltas[:, 0] * height center_x += deltas[:, 1] * width center_z += deltas[:, 2] * depth height *= torch.exp(deltas[:, 3]) width *= torch.exp(deltas[:, 4]) depth *= torch.exp(deltas[:, 5]) # Convert back to y1, x1, y2, x2 y1 = center_y - 0.5 * height x1 = center_x - 0.5 * width z1 = center_z - 0.5 * depth y2 = y1 + height x2 = x1 + width z2 = z1 + depth result = torch.stack([y1, x1, y2, x2, z1, z2], dim=1) return result def clip_boxes_2D(boxes, window): """ boxes: [N, 4] each col is y1, x1, y2, x2 window: [4] in the form y1, x1, y2, x2 """ boxes = torch.stack( \ [boxes[:, 0].clamp(float(window[0]), float(window[2])), boxes[:, 1].clamp(float(window[1]), float(window[3])), boxes[:, 2].clamp(float(window[0]), float(window[2])), boxes[:, 3].clamp(float(window[1]), float(window[3]))], 1) return boxes def clip_boxes_3D(boxes, window): """ boxes: [N, 6] each col is y1, x1, y2, x2, z1, z2 window: [6] in the form y1, x1, y2, x2, z1, z2 """ boxes = torch.stack( \ [boxes[:, 0].clamp(float(window[0]), float(window[2])), boxes[:, 1].clamp(float(window[1]), float(window[3])), boxes[:, 2].clamp(float(window[0]), float(window[2])), boxes[:, 3].clamp(float(window[1]), float(window[3])), boxes[:, 4].clamp(float(window[4]), float(window[5])), boxes[:, 5].clamp(float(window[4]), float(window[5]))], 1) return boxes from matplotlib import pyplot as plt def clip_boxes_numpy(boxes, window): """ boxes: [N, 4] each col is y1, x1, y2, x2 / [N, 6] in 3D. window: iamge shape (y, x, (z)) """ if boxes.shape[1] == 4: boxes = np.concatenate( (np.clip(boxes[:, 0], 0, window[0])[:, None], np.clip(boxes[:, 1], 0, window[0])[:, None], np.clip(boxes[:, 2], 0, window[1])[:, None], np.clip(boxes[:, 3], 0, window[1])[:, None]), 1 ) else: boxes = np.concatenate( (np.clip(boxes[:, 0], 0, window[0])[:, None], np.clip(boxes[:, 1], 0, window[0])[:, None], np.clip(boxes[:, 2], 0, window[1])[:, None], np.clip(boxes[:, 3], 0, window[1])[:, None], np.clip(boxes[:, 4], 0, window[2])[:, None], np.clip(boxes[:, 5], 0, window[2])[:, None]), 1 ) return boxes def bbox_overlaps_2D(boxes1, boxes2): """Computes IoU overlaps between two sets of boxes. boxes1, boxes2: [N, (y1, x1, y2, x2)]. """ # 1. Tile boxes2 and repeate boxes1. This allows us to compare # every boxes1 against every boxes2 without loops. # TF doesn't have an equivalent to np.repeate() so simulate it # using tf.tile() and tf.reshape. boxes1_repeat = boxes2.size()[0] boxes2_repeat = boxes1.size()[0] boxes1 = boxes1.repeat(1,boxes1_repeat).view(-1,4) boxes2 = boxes2.repeat(boxes2_repeat,1) # 2. Compute intersections b1_y1, b1_x1, b1_y2, b1_x2 = boxes1.chunk(4, dim=1) b2_y1, b2_x1, b2_y2, b2_x2 = boxes2.chunk(4, dim=1) y1 = torch.max(b1_y1, b2_y1)[:, 0] x1 = torch.max(b1_x1, b2_x1)[:, 0] y2 = torch.min(b1_y2, b2_y2)[:, 0] x2 = torch.min(b1_x2, b2_x2)[:, 0] #--> expects x1<x2 & y1<y2 zeros = torch.zeros(y1.size()[0], requires_grad=False) if y1.is_cuda: zeros = zeros.cuda() intersection = torch.max(x2 - x1, zeros) * torch.max(y2 - y1, zeros) # 3. Compute unions b1_area = (b1_y2 - b1_y1) * (b1_x2 - b1_x1) b2_area = (b2_y2 - b2_y1) * (b2_x2 - b2_x1) union = b1_area[:,0] + b2_area[:,0] - intersection # 4. Compute IoU and reshape to [boxes1, boxes2] iou = intersection / union assert torch.all(iou<=1), "iou score>1 produced in bbox_overlaps_2D" overlaps = iou.view(boxes2_repeat, boxes1_repeat) #--> per gt box: ious of all proposal boxes with that gt box return overlaps def bbox_overlaps_3D(boxes1, boxes2): """Computes IoU overlaps between two sets of boxes. boxes1, boxes2: [N, (y1, x1, y2, x2, z1, z2)]. """ # 1. Tile boxes2 and repeate boxes1. This allows us to compare # every boxes1 against every boxes2 without loops. # TF doesn't have an equivalent to np.repeate() so simulate it # using tf.tile() and tf.reshape. boxes1_repeat = boxes2.size()[0] boxes2_repeat = boxes1.size()[0] boxes1 = boxes1.repeat(1,boxes1_repeat).view(-1,6) boxes2 = boxes2.repeat(boxes2_repeat,1) # 2. Compute intersections b1_y1, b1_x1, b1_y2, b1_x2, b1_z1, b1_z2 = boxes1.chunk(6, dim=1) b2_y1, b2_x1, b2_y2, b2_x2, b2_z1, b2_z2 = boxes2.chunk(6, dim=1) y1 = torch.max(b1_y1, b2_y1)[:, 0] x1 = torch.max(b1_x1, b2_x1)[:, 0] y2 = torch.min(b1_y2, b2_y2)[:, 0] x2 = torch.min(b1_x2, b2_x2)[:, 0] z1 = torch.max(b1_z1, b2_z1)[:, 0] z2 = torch.min(b1_z2, b2_z2)[:, 0] zeros = torch.zeros(y1.size()[0], requires_grad=False) if y1.is_cuda: zeros = zeros.cuda() intersection = torch.max(x2 - x1, zeros) * torch.max(y2 - y1, zeros) * torch.max(z2 - z1, zeros) # 3. Compute unions b1_volume = (b1_y2 - b1_y1) * (b1_x2 - b1_x1) * (b1_z2 - b1_z1) b2_volume = (b2_y2 - b2_y1) * (b2_x2 - b2_x1) * (b2_z2 - b2_z1) union = b1_volume[:,0] + b2_volume[:,0] - intersection # 4. Compute IoU and reshape to [boxes1, boxes2] iou = intersection / union overlaps = iou.view(boxes2_repeat, boxes1_repeat) return overlaps def gt_anchor_matching(cf, anchors, gt_boxes, gt_class_ids=None): """Given the anchors and GT boxes, compute overlaps and identify positive anchors and deltas to refine them to match their corresponding GT boxes. anchors: [num_anchors, (y1, x1, y2, x2, (z1), (z2))] gt_boxes: [num_gt_boxes, (y1, x1, y2, x2, (z1), (z2))] gt_class_ids (optional): [num_gt_boxes] Integer class IDs for one stage detectors. in RPN case of Mask R-CNN, set all positive matches to 1 (foreground) Returns: anchor_class_matches: [N] (int32) matches between anchors and GT boxes. 1 = positive anchor, -1 = negative anchor, 0 = neutral anchor_delta_targets: [N, (dy, dx, (dz), log(dh), log(dw), (log(dd)))] Anchor bbox deltas. """ anchor_class_matches = np.zeros([anchors.shape[0]], dtype=np.int32) anchor_delta_targets = np.zeros((cf.rpn_train_anchors_per_image, 2*cf.dim)) anchor_matching_iou = cf.anchor_matching_iou if gt_boxes is None: anchor_class_matches = np.full(anchor_class_matches.shape, fill_value=-1) return anchor_class_matches, anchor_delta_targets # for mrcnn: anchor matching is done for RPN loss, so positive labels are all 1 (foreground) if gt_class_ids is None: gt_class_ids = np.array([1] * len(gt_boxes)) # Compute overlaps [num_anchors, num_gt_boxes] overlaps = compute_overlaps(anchors, gt_boxes) # Match anchors to GT Boxes # If an anchor overlaps a GT box with IoU >= anchor_matching_iou then it's positive. # If an anchor overlaps a GT box with IoU < 0.1 then it's negative. # Neutral anchors are those that don't match the conditions above, # and they don't influence the loss function. # However, don't keep any GT box unmatched (rare, but happens). Instead, # match it to the closest anchor (even if its max IoU is < 0.1). # 1. Set negative anchors first. They get overwritten below if a GT box is # matched to them. Skip boxes in crowd areas. anchor_iou_argmax = np.argmax(overlaps, axis=1) anchor_iou_max = overlaps[np.arange(overlaps.shape[0]), anchor_iou_argmax] if anchors.shape[1] == 4: anchor_class_matches[(anchor_iou_max < 0.1)] = -1 elif anchors.shape[1] == 6: anchor_class_matches[(anchor_iou_max < 0.01)] = -1 else: raise ValueError('anchor shape wrong {}'.format(anchors.shape)) # 2. Set an anchor for each GT box (regardless of IoU value). gt_iou_argmax = np.argmax(overlaps, axis=0) for ix, ii in enumerate(gt_iou_argmax): anchor_class_matches[ii] = gt_class_ids[ix] # 3. Set anchors with high overlap as positive. above_thresh_ixs = np.argwhere(anchor_iou_max >= anchor_matching_iou) anchor_class_matches[above_thresh_ixs] = gt_class_ids[anchor_iou_argmax[above_thresh_ixs]] # Subsample to balance positive anchors. ids = np.where(anchor_class_matches > 0)[0] extra = len(ids) - (cf.rpn_train_anchors_per_image // 2) if extra > 0: # Reset the extra ones to neutral ids = np.random.choice(ids, extra, replace=False) anchor_class_matches[ids] = 0 # Leave all negative proposals negative for now and sample from them later in online hard example mining. # For positive anchors, compute shift and scale needed to transform them to match the corresponding GT boxes. ids = np.where(anchor_class_matches > 0)[0] ix = 0 # index into anchor_delta_targets for i, a in zip(ids, anchors[ids]): # closest gt box (it might have IoU < anchor_matching_iou) gt = gt_boxes[anchor_iou_argmax[i]] # convert coordinates to center plus width/height. gt_h = gt[2] - gt[0] gt_w = gt[3] - gt[1] gt_center_y = gt[0] + 0.5 * gt_h gt_center_x = gt[1] + 0.5 * gt_w # Anchor a_h = a[2] - a[0] a_w = a[3] - a[1] a_center_y = a[0] + 0.5 * a_h a_center_x = a[1] + 0.5 * a_w if cf.dim == 2: anchor_delta_targets[ix] = [ (gt_center_y - a_center_y) / a_h, (gt_center_x - a_center_x) / a_w, np.log(gt_h / a_h), np.log(gt_w / a_w), ] else: gt_d = gt[5] - gt[4] gt_center_z = gt[4] + 0.5 * gt_d a_d = a[5] - a[4] a_center_z = a[4] + 0.5 * a_d anchor_delta_targets[ix] = [ (gt_center_y - a_center_y) / a_h, (gt_center_x - a_center_x) / a_w, (gt_center_z - a_center_z) / a_d, np.log(gt_h / a_h), np.log(gt_w / a_w), np.log(gt_d / a_d) ] # normalize. anchor_delta_targets[ix] /= cf.rpn_bbox_std_dev ix += 1 return anchor_class_matches, anchor_delta_targets def clip_to_window(window, boxes): """ window: (y1, x1, y2, x2) / 3D: (z1, z2). The window in the image we want to clip to. boxes: [N, (y1, x1, y2, x2)] / 3D: (z1, z2) """ boxes[:, 0] = boxes[:, 0].clamp(float(window[0]), float(window[2])) boxes[:, 1] = boxes[:, 1].clamp(float(window[1]), float(window[3])) boxes[:, 2] = boxes[:, 2].clamp(float(window[0]), float(window[2])) boxes[:, 3] = boxes[:, 3].clamp(float(window[1]), float(window[3])) if boxes.shape[1] > 5: boxes[:, 4] = boxes[:, 4].clamp(float(window[4]), float(window[5])) boxes[:, 5] = boxes[:, 5].clamp(float(window[4]), float(window[5])) return boxes ############################################################ # Connected Componenent Analysis ############################################################ def get_coords(binary_mask, n_components, dim): """ loops over batch to perform connected component analysis on binary input mask. computes box coordinates around n_components - biggest components (rois). :param binary_mask: (b, y, x, (z)). binary mask for one specific foreground class. :param n_components: int. number of components to extract per batch element and class. :return: coords (b, n, (y1, x1, y2, x2 (,z1, z2)) :return: batch_components (b, n, (y1, x1, y2, x2, (z1), (z2)) """ assert len(binary_mask.shape)==dim+1 binary_mask = binary_mask.astype('uint8') batch_coords = [] batch_components = [] for ix,b in enumerate(binary_mask): clusters, n_cands = lb(b) # performs connected component analysis. uniques, counts = np.unique(clusters, return_counts=True) keep_uniques = uniques[1:][
np.argsort(counts[1:])
numpy.argsort
import numpy as np from PuzzleLib.Backend import gpuarray from PuzzleLib.Backend.gpuarray import memoryPool as memPool from PuzzleLib.Modules.Module import ModuleError, Module class KMaxPool(Module): def __init__(self, topk, axis, name=None): super().__init__(name) self.registerBlueprint(locals()) self.topk = topk self.axis = axis self.indices = None @staticmethod def sliceAlongAxis(ary, axis, start, end): ary =
np.rollaxis(ary, axis)
numpy.rollaxis
# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import import math import cv2 import random import numpy as np import types from PIL import Image from paddle.vision.transforms import CenterCrop from . import cv2_func as F _cv2_str_to_interpolation = { 'nearest': cv2.INTER_NEAREST, 'linear': cv2.INTER_LINEAR, 'area': cv2.INTER_AREA, 'cubic': cv2.INTER_CUBIC, 'lanczos4': cv2.INTER_LANCZOS4, } class Compose(object): def __init__(self, trans): self.trans = trans def __call__(self, img): for t in self.trans: img = t(img) return img class ByolNormalize(object): def __init__(self, mean=None, std=None): if mean is None or std is None: self.mean = None self.std = None else: # HWC self.mean = np.array(mean, dtype='float32').reshape([1, 1, 3]) self.std = np.array(std, dtype='float32').reshape([1, 1, 3]) def __call__(self, img): img = np.array(img) return F.normalize(img, self.mean, self.std) class Resize(object): """ size, int or (h, w)""" def __init__(self, size, interpolation='linear'): assert isinstance(size, int) or len(size) == 2 self.size = size self.interpolation = _cv2_str_to_interpolation[interpolation] def __call__(self, img): return F.resize(img, self.size, self.interpolation) class ToCHW(object): def __call__(self, img): return F.to_chw(img) class ToRGB(object): def __call__(self, img): return F.to_rgb_bgr(img) class Lambda(object): def __init__(self, lambd): assert isinstance(lambd, types.LambdaType) self.lambd = lambd def __call__(self, img): return self.lambd(img) class RandomTransforms(object): def __init__(self, trans): assert isinstance(trans, (list, tuple)) self.trans = trans def __call__(self, *args, **kwargs): raise NotImplementedError() class RandomApply(RandomTransforms): def __init__(self, trans, p=0.5): super(RandomApply, self).__init__(trans) self.p = p def __call__(self, img): if self.p < random.random(): return img for t in self.trans: img = t(img) return img class ByolRandomHorizontalFlip(object): def __init__(self, p=0.5): self.p = p def __call__(self, img): if random.random() < self.p: return F.hflip(img) return img class ByolRandomVerticalFlip(object): def __init__(self, p=0.5): self.p = p def __call__(self, img): if
np.random.uniform()
numpy.random.uniform
import os import sys import numpy as np import matplotlib.pyplot as plt sys.path.insert(0, os.getcwd() + '/../../tools/') import wb import trf # revise this function to config the dataset used to train different model def data(): # ptb + wsj93 experiments return data_ptb() + data_wsj92nbest() def data_verfy(paths): for w in paths: if not os.path.isfile(w): print('[ERROR] no such file: ' + w) return paths def data_ptb(): root = './data/ptb/' train = root + 'ptb.train.txt' valid = root + 'ptb.valid.txt' test = root + 'ptb.test.txt' return data_verfy([train, valid, test]) def data_wsj92nbest(): root = './data/WSJ92-test-data/' nbest = root + '1000best.sent' trans = root + 'transcript.txt' ac = root + '1000best.acscore' lm = root + '1000best.lmscore' return data_verfy([nbest, trans, ac, lm]) def log_add(a,b): if a>b: return a + np.log(1 + np.exp(b-a)) else: return b + np.log(np.exp(a-b) + 1) def log_sub(a,b): if a>b: return a + np.log(abs(1 - np.exp(b-a))) else: return b + np.log(abs(np.exp(a-b) - 1)) def log_sum(a): s = a[0] for i in a[1:]: s = log_add(s, i) return s def log_mean(a): return log_sum(a) - np.log(len(a)) def log_var(a): m = log_mean(a) b = [] for i in a: b.append(log_sub(i, m) * 2) return log_mean(b) def mat_mean(mat): m = [] for a in np.array(mat): m.append(np.log(np.mean(np.exp(a)))) return m def mat_var(mat): var = [] for a in np.array(mat): var.append(np.log(np.var(np.exp(a)))) return var def load_ais_weight(logfile): logw = [] with open(logfile) as f: for line in f: if line.find('logz') == 0: a = line.split() cur_logw = [float(i) for i in a[4:]] logw.append(cur_logw) return logw def revise_logz(read_trf, write_trf, logz): with open(read_trf) as f1, open(write_trf, 'wt') as f2: nline = 0 for line in f1: nline+=1 if nline == 4: a = line.split() print(a) for i in range(len(logz)): a[i+1] = '{}'.format(logz[i]) print(a) f2.write(' '.join(a) + '\n') elif nline == 5: a = line.split() print(a) for i in range(len(logz)): a[i+1] = '{}'.format(logz[i] - logz[0]) print(a) f2.write(' '.join(a) + '\n') else: f2.write(line) def main(): if len(sys.argv) == 1: print('\"python run.py -train\" train LSTM\n', '\"python run.py -rescore\" rescore nbest\n', '\"python run.py -wer\" compute WER' ) run_times = range(0, 1) # for multiple run bindir = '../../tools/trf/bin/' workdir = 'trflm/' fres = wb.FRes('models_ppl.txt') model = trf.model(bindir, workdir) class_num = 200 train = workdir + 'train.id' valid = workdir + 'valid.id' test = workdir + 'test.id' vocab = workdir + 'vocab_c{}.list'.format(class_num) thread = 18 ais_chain = 10 ais_inter = 200000 if '-wer' in sys.argv: # calculate mean of the WER of 10 TRFs after AIS res_list = [] for runnum in run_times: name = 'trf_c200_g4_w_c_ws_cs_wsh_csh_tied.run{}.ais{}_{}'.format(runnum, ais_chain, ais_inter) res = fres.Get(name)[1:] if run_times.index(runnum) == 0: res_list = [[] for i in range(len(res))] for i in range(len(res)): res_list[i].append(res[i]) name = 'trf_c200_g4_w_c_ws_cs_wsh_csh_tied.runavg.ais{}_{}'.format(ais_chain, ais_inter) head = fres.GetHead()[1:] for i in range(len(head)): mean = np.mean(res_list[i]) std = np.std(res_list[i]) fres.Add(name, [head[i]], ['{:.2f}+{:.2f}'.format(mean, std)]) if '-ais' in sys.argv: for runnum in run_times: write_model = workdir + 'trf_c200_g4_w_c_ws_cs_wsh_csh_tied.run{}'.format(runnum) [read_nbest, read_templ, read_acscore] = data()[3:6] write_templ_id = workdir + os.path.split(read_templ)[1] + '.id' v = trf.ReadVocab(vocab) trf.NbestToID(read_templ, write_templ_id, v) # run asi to calculate the normalization constnts of models ais_model = '{}.ais{}_{}'.format(write_model, ais_chain, ais_inter) if not os.path.exists(ais_model + '.model'): config = ' -vocab {0} -read {1}.model -write {2}.model -log {2}.log'.format(vocab, write_model, ais_model) config += ' -norm-method AIS -AIS-chain {} -AIS-inter {} -thread {} '.format(ais_chain, ais_inter, thread) config += ' -norm-len-max {} '.format(trf.FileMaxLen(read_nbest)-1) # just compute the needed length model.use(config) # rescore and compute wer write_lmscore = ais_model + '.lmscore' config = ' -vocab {} -read {}.model'.format(vocab, ais_model) config += ' -nbest {} -test {} '.format(read_nbest, write_templ_id) # calculate the ppl of test set config += ' -lmscore {} '.format(write_lmscore) LL_templ = model.use(config, False) PPL_templ = wb.LL2PPL(-LL_templ, write_templ_id) [wer, lmscale, acscale] = wb.TuneWER(read_nbest, read_templ, write_lmscore, read_acscore,
np.linspace(0.1, 0.9, 9)
numpy.linspace
import numpy as np import copy from io import StringIO import sys import h5py from scipy.optimize import minimize import lmfit import emcee from dynesty import NestedSampler from dynesty.utils import resample_equal from .parameters import Parameters from .likelihood import computeRedChiSq, lnprob, ln_like, ptform from . import plots_s5 as plots #FINDME: Keep reload statements for easy testing from importlib import reload reload(plots) def lsqfitter(lc, model, meta, log, calling_function='lsq', **kwargs): """Perform least-squares fit. Parameters ---------- lc: eureka.S5_lightcurve_fitting.lightcurve.LightCurve The lightcurve data object model: eureka.S5_lightcurve_fitting.models.CompositeModel The composite model to fit meta: MetaClass The metadata object log: logedit.Logedit The open log in which notes from this step can be added. **kwargs: Arbitrary keyword arguments. Returns ------- best_model: eureka.S5_lightcurve_fitting.models.CompositeModel The composite model after fitting Notes ----- History: - December 29-30, 2021 <NAME> Updated documentation and arguments. Reduced repeated code. Also saving covariance matrix for later estimation of sampler step size. - January 7-22, 2022 <NAME> Adding ability to do a single shared fit across all channels - February 28-March 1, 2022 <NAME> Adding scatter_ppm parameter """ # Group the different variable types freenames, freepars, prior1, prior2, priortype, indep_vars = group_variables(model) neg_lnprob = lambda theta, lc, model, prior1, prior2, priortype, freenames: -lnprob(theta, lc, model, prior1, prior2, priortype, freenames) if not hasattr(meta, 'lsq_method'): log.writelog('No lsq optimization method specified - using Nelder-Mead by default.') meta.lsq_method = 'Nelder-Mead' if not hasattr(meta, 'lsq_tol'): log.writelog('No lsq tolerance specified - using 1e-6 by default.') meta.lsq_tol = 1e-6 results = minimize(neg_lnprob, freepars, args=(lc, model, prior1, prior2, priortype, freenames), method=meta.lsq_method, tol=meta.lsq_tol) if meta.run_verbose: log.writelog("\nVerbose lsq results: {}\n".format(results)) else: log.writelog("Success?: {}".format(results.success)) log.writelog(results.message) # Get the best fit params fit_params = results.x # Save the fit ASAP save_fit(meta, lc, calling_function, fit_params, freenames) # Make a new model instance best_model = copy.copy(model) best_model.components[0].update(fit_params, freenames) model.update(fit_params, freenames) if "scatter_ppm" in freenames: ind = [i for i in np.arange(len(freenames)) if freenames[i][0:11] == "scatter_ppm"] lc.unc_fit = np.ones_like(lc.flux) * fit_params[ind[0]] * 1e-6 if len(ind)>1: for chan in np.arange(lc.flux.size//lc.time.size): lc.unc_fit[chan*lc.time.size:(chan+1)*lc.time.size] = fit_params[ind[chan]] * 1e-6 # Save the covariance matrix in case it's needed to estimate step size for a sampler model_lc = model.eval() # FINDME # Commented out for now because op.least_squares() doesn't provide covariance matrix # Need to compute using Jacobian matrix instead (hess_inv = (J.T J)^{-1}) # if results[1] is not None: # residuals = (lc.flux - model_lc) # cov_mat = results[1]*np.var(residuals) # else: # # Sometimes lsq will fail to converge and will return a None covariance matrix # cov_mat = None cov_mat = None best_model.__setattr__('cov_mat',cov_mat) # Plot fit if meta.isplots_S5 >= 1: plots.plot_fit(lc, model, meta, fitter=calling_function) # Compute reduced chi-squared chi2red = computeRedChiSq(lc, model, meta, freenames, log) print('\nLSQ RESULTS:') for freenames_i, fit_params_i in zip(freenames, fit_params): log.writelog('{0}: {1}'.format(freenames_i, fit_params_i)) log.writelog('') # Plot Allan plot if meta.isplots_S5 >= 3 and calling_function=='lsq': # This plot is only really useful if you're actually using the lsq fitter, otherwise don't make it plots.plot_rms(lc, model, meta, fitter=calling_function) # Plot residuals distribution if meta.isplots_S5 >= 3 and calling_function=='lsq': plots.plot_res_distr(lc, model, meta, fitter=calling_function) best_model.__setattr__('chi2red',chi2red) best_model.__setattr__('fit_params',fit_params) return best_model def demcfitter(lc, model, meta, log, **kwargs): """Perform sampling using Differential Evolution Markov Chain. This is an empty placeholder function to be filled later. Parameters ---------- lc: eureka.S5_lightcurve_fitting.lightcurve.LightCurve The lightcurve data object model: eureka.S5_lightcurve_fitting.models.CompositeModel The composite model to fit meta: MetaClass The metadata object log: logedit.Logedit The open log in which notes from this step can be added. **kwargs: Arbitrary keyword arguments. Returns ------- best_model: eureka.S5_lightcurve_fitting.models.CompositeModel The composite model after fitting Notes ----- History: - December 29, 2021 <NAME> Updated documentation and arguments """ best_model = None return best_model def emceefitter(lc, model, meta, log, **kwargs): """Perform sampling using emcee. Parameters ---------- lc: eureka.S5_lightcurve_fitting.lightcurve.LightCurve The lightcurve data object model: eureka.S5_lightcurve_fitting.models.CompositeModel The composite model to fit meta: MetaClass The metadata object log: logedit.Logedit The open log in which notes from this step can be added. **kwargs: Arbitrary keyword arguments. Returns ------- best_model: eureka.S5_lightcurve_fitting.models.CompositeModel The composite model after fitting Notes ----- History: - December 29, 2021 <NAME> Updated documentation. Reduced repeated code. - January 7-22, 2022 <NAME> Adding ability to do a single shared fit across all channels - February 23-25, 2022 <NAME> Added log-uniform and Gaussian priors. - February 28-March 1, 2022 <NAME> Adding scatter_ppm parameter. Added statements to avoid some initial state issues. """ if not hasattr(meta, 'lsq_first') or meta.lsq_first: # Only call lsq fitter first if asked or lsq_first option wasn't passed (allowing backwards compatibility) log.writelog('\nCalling lsqfitter first...') # RUN LEAST SQUARES lsq_sol = lsqfitter(lc, model, meta, log, calling_function='emcee_lsq', **kwargs) # SCALE UNCERTAINTIES WITH REDUCED CHI2 if meta.rescale_err: lc.unc *=
np.sqrt(lsq_sol.chi2red)
numpy.sqrt
import numpy as np import sys import fire import GMMEM import GMMVB def createData(): """Create 3-dimensional data that is divided into 4 clusters. Args: None. Returns: X (numpy ndarray): Input data whose size is (N, 3). """ # The number of data at each cluster N1 = 4000 N2 = 3000 N3 = 2000 N4 = 1000 # Mean values Mu1 = [5, -5, -5] Mu2 = [-5, 5, 5] Mu3 = [-5, -5, -5] Mu4 = [5, 5, 5] # Variance-covariance matrices Sigma1 = [[1, 0, -0.25], [0, 1, 0], [-0.25, 0, 1]] Sigma2 = [[1, 0, 0], [0, 1, -0.25], [0, -0.25, 1]] Sigma3 = [[1, 0.25, 0], [0.25, 1, 0], [0, 0, 1]] Sigma4 = [[1, 0, 0], [0, 1, 0], [0, 0, 1]] # Generate data from Gaussian distribution X1 = np.random.multivariate_normal(Mu1, Sigma1, N1) X2 = np.random.multivariate_normal(Mu2, Sigma2, N2) X3 =
np.random.multivariate_normal(Mu3, Sigma3, N3)
numpy.random.multivariate_normal
#!/usr/bin/env python3 # coding: utf-8 import forgi # only for residue coloring import matplotlib.patches as mpatches import sys import random import string import RNA import numpy as np import os import subprocess from dataclasses import dataclass, field import pandas as pd # import seaborn as sns from scipy import optimize import matplotlib.pyplot as plt from matplotlib.collections import LineCollection, CircleCollection, EllipseCollection import matplotlib.patheffects as path_effects import matplotlib.path as mpath Path = mpath.Path @dataclass class pos_data: backbone: list aucg_bonds: list gu_bonds: list annotation_lines: list annotation_chars: list annotation_numbers: list @dataclass class circular_data: textpos: list backbone: list lines: list annotation_lines: list annotation_numbers: list def matrix_rotation(p, origin=(0, 0), degrees=0): # cite source if not origin: origin = p.mean(axis=0) angle = np.deg2rad(degrees) R = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]]) o = np.atleast_2d(origin) p = np.atleast_2d(p) return np.squeeze((R @ (p.T-o.T) + o.T).T) class pyrnaplot: def __init__(self, sequence, s) -> None: self.sequence = sequence self.s = s self.pt = RNA.ptable(self.s) self.textoffset = 0, 0 self.plot_scalar = 0 self.coords_naview = [] self.naview_layout = None # pos_data dataclass self.coords_circular = [] self.circular_layout = None # pos_data dataclass # colouring cg = forgi.load_rna(self.s, "any", allow_many=True)[0] self.cstring = cg.to_element_string() self.forgi_coding = {'f': 'orange', 't': 'orange', 's': 'green', 'h': 'blue', 'i': 'yellow', 'm': 'red'} def get_naview_coords(self, rotate=0): c = [] for i, coord in enumerate(RNA.naview_xy_coordinates(self.s)): if i == len(self.s): break c.append((coord.X, coord.Y)) c = np.array(c).astype(float) if rotate != 0: c = matrix_rotation(c, origin=False, degrees=-rotate) return c def get_circular_coords(self): # this just creates dot along a unit circle with len(s) points c = [] for i, coord in enumerate(RNA.simple_circplot_coordinates(self.s)): if i == len(self.s): break c.append((coord.X, coord.Y)) c = np.array(c).astype(float) return c def naview_plot_layout(self, coordinates=False): if not isinstance(coordinates, bool): self.coords_naview = coordinates else: self.coords_naview = self.get_naview_coords() c = self.coords_naview backbone = [] aucg_bonds = [] gu_bonds = [] annotation_lines = [] annotation_chars = [] annotation_numbers = [] for i, ch in enumerate(self.sequence): x, y = c[i] + self.textoffset # print (i, c, x, y) annotation_chars.append(((x, y), ch)) # ax.text(x, y, ch, size=16*plot_modifier, ha="center", va="center") # AU, CG, GU bonds if self.pt[i+1] > i: # print ("link", i, pt1[i+1]-1) char1 = self.sequence[i] char2 = self.sequence[self.pt[i+1]-1] pos1 = c[i] pos2 = c[self.pt[i+1]-1] if pos1[0] < pos2[0]: pos1, pos2 = pos2, pos1 bond_identifier = str(i+1) + "-" + str(self.pt[i+1]) if (char1 == "G" and char2 == "U") or (char1 == "U" and char2 == "G"): midpoint = (pos1+pos2)/2 # gu_bonds.append((midpoint[0], midpoint[1])) gu_bonds.append((bond_identifier, midpoint)) else: v = pos2-pos1 l = np.linalg.norm(v) # euclidean distance v /= l pos1 = pos1 + v*5 pos2 = pos2 - v*5 aucg_bonds.append((bond_identifier, pos1, pos2)) # backbone if i+1 == len(self.sequence): continue pos1 = c[i] pos2 = c[i+1] if pos1[0] < pos2[0]: pos1, pos2 = pos2, pos1 v = pos2-pos1 l = np.linalg.norm(v) if l > 12: # ignore short lines v /= l # normalize to unit vector cutoff = 1.2*self.plot_scalar pos1 = pos1 + v*6 # 4 pos2 = pos2 - v*6 link = [pos1, pos2] # line1, = ax.plot(*zip(*link)) # links.append(((pos1[0], pos1[1]),(pos2[0], pos2[1]))) backbone.append((pos1, pos2)) else: # add a dummy placeholder backbone if invisible backbone.append(((pos1+pos2)/2, (pos1+pos2)/2)) # annotations: calculate normal vector if i % 10 == 9 or i == 0: # start counting at 1, not 0 if i == 0: lastpos = c[i] else: lastpos = c[i-1] nextpos = c[i+1] v = nextpos-lastpos l = np.linalg.norm(v) v /= l # normalize to unit vector v = np.array([v[1], -v[0]]) # 90° rotation pos1 = c[i] + v*6 pos2 = pos1 + v*18 # 13 length vector charpos = pos2 + v*6 annotation_lines.append((pos1, pos2)) annotation_numbers.append((charpos, i+1)) self.naview_layout = pos_data( backbone, aucg_bonds, gu_bonds, annotation_lines, annotation_chars, annotation_numbers) return self.naview_layout def naview_plot(self, dpi=72, rotate=0, coordinates=False): textoffset = -0.5, -0.9 # textoffset = 0, 0 border = 30 if not isinstance(coordinates, bool): self.coords_naview = coordinates else: self.coords_naview = self.get_naview_coords() if rotate != 0: self.coords_naview = matrix_rotation( self.coords_naview, origin=False, degrees=-rotate) self.naview_plot_layout(coordinates) c = self.coords_naview # set plot dimensions and estimate a scalar for text / object rendering limits = c.min()*1.1, c.max()*1.1 xmax, ymax = c.max(axis=0) + [border, border] xmin, ymin = c.min(axis=0) - [border, border] xlength = abs(xmax-xmin) ylength = abs(ymax-ymin) ratio = xlength/ylength # inverse distance, adjust font size / bond size according to total plot length self.plot_scalar = 1/abs(limits[1]-limits[0])*300 if ratio > 1: self.plot_scalar *= ratio # matplotlib start fig = plt.figure(figsize=(10*ratio, 10), dpi=dpi) ax = fig.add_subplot(1, 1, 1) # plt.rcParams.update({ # "text.usetex": False, # # "font.family": "serif", # "font.family": "sans-serif", # "font.sans-serif": ["Helvetica"]}) plt.tight_layout() ax.set_xlim((xmin, xmax)) ax.set_ylim((ymin, ymax)) ax.axis("off") ax.scatter(c[:, 0], c[:, 1], alpha=0.0) # get the location of all our text & lines l = self.naview_layout # discard info which would interfer with LineCollection (identifiers i[0] are needed for movies) l.aucg_bonds = [(i[1], i[2]) for i in l.aucg_bonds] l.gu_bonds = [i[1] for i in l.aucg_bonds] backbonecollection = LineCollection( l.backbone, colors="grey", linewidths=2.0*self.plot_scalar, path_effects=[path_effects.Stroke(capstyle="round")]) aucgcollection = LineCollection(l.aucg_bonds, colors="red", linewidths=2.5 * self.plot_scalar, path_effects=[path_effects.Stroke(capstyle="round")]) annotationcollection = LineCollection( l.annotation_lines, colors="grey", linewidths=1.2*self.plot_scalar, path_effects=[path_effects.Stroke(capstyle="round")]) ax.add_collection(backbonecollection) ax.add_collection(aucgcollection) ax.add_collection(annotationcollection) circlesizes = [8*self.plot_scalar**2] * len(l.gu_bonds) coll = CircleCollection( circlesizes, offsets=l.gu_bonds, color="red", transOffset=ax.transData) ax.add_collection(coll) for i, ((x, y), ch) in enumerate(l.annotation_chars): text = ax.text(x, y, ch, size=16*self.plot_scalar, ha="center", va="center") c = self.forgi_coding[self.cstring[i]] text.set_path_effects([path_effects.Stroke(linewidth=4, foreground=c, alpha=0.3), path_effects.Normal()]) for (x, y), ch in l.annotation_numbers: ax.text(x, y, ch, size=12*self.plot_scalar, ha="center", va="center") def circular_plot_layout(self): if not self.coords_circular: self.coords_circular = self.get_circular_coords() r = self.coords_circular angle_multiplier = 4 line_modifier = 1/len(self.sequence) * 100 # print (line_modifier) textpos = [] backbone = [] lines = [] annotation_lines = [] annotation_numbers = [] for i, e in enumerate(self.sequence): pos = r[i]*1.08 textpos.append((pos, e)) # circle bezier segments if i+1 != len(self.sequence): pos1 = r[i] pos2 = r[i+1] midpoint = (pos2+pos1)/2 midpoint /= np.linalg.norm(midpoint) # * 0.99 v = midpoint-pos1 v += pos1 backbone.append((pos1, v, pos2)) # annotations: calculate normal vector if i % 10 == 9 or i == 0: # start counting at 1, not 0 pos1 = r[i] pos2 = r[i]*1.14 pos3 = r[i]*1.18 annotation_lines.append((pos1, pos2)) annotation_numbers.append((pos3, i+1)) if self.pt[i+1] > i: # print ("link", i, pt1[i+1]-1) char1 = self.sequence[i] char2 = self.sequence[self.pt[i+1]-1] # position 1 and adjacent nodes for normal vector if i == 0: pos1l = r[-1] else: pos1l = r[i-1] pos1 = r[i] pos1r = r[i+1] pos2l = r[self.pt[i+1]-2] pos2 = r[self.pt[i+1]-1] if self.pt[i+1] == len(self.sequence): pos2r = r[0] else: pos2r = r[self.pt[i+1]] midpoint = (pos1+pos2)/2 midpointdist = np.linalg.norm(midpoint) # distance to origin l12 = np.linalg.norm(pos2-pos1) / angle_multiplier # print ("l", l12, midpointdist) v1 = pos1l-pos1r v1 = np.array([v1[1], -v1[0]]) # 90° rotation v1 /= np.linalg.norm(v1) v1 *= l12 bezierpos1 = pos1+v1 v2 = pos2l-pos2r v2 = np.array([v2[1], -v2[0]]) # *15 # 90° rotation v2 /=
np.linalg.norm(v2)
numpy.linalg.norm
#!/usr/bin/env python # ------------------------------------------------------------------------------------------------------% # Created by "Thieu" at 14:05, 28/01/2021 % # % # Email: <EMAIL> % # Homepage: https://www.researchgate.net/profile/Nguyen_Thieu2 % # Github: https://github.com/thieu1995 % # ------------------------------------------------------------------------------------------------------% ### Reading all results files to find True pareto-fronts (Reference Fronts) from time import time from pathlib import Path from copy import deepcopy from config import Config, OptExp, OptParas from pandas import read_csv, DataFrame, to_numeric from numpy import array, zeros, vstack, hstack, min, max, mean, std from utils.io_util import load_tasks, load_nodes from utils.metric_util import * from utils.visual.scatter import visualize_front_3d def inside_loop(my_model, n_trials, n_timebound, epoch, fe, end_paras): for pop_size in OptExp.POP_SIZE: if Config.TIME_BOUND_KEY: path_results = f'{Config.RESULTS_DATA}/{n_timebound}s/task_{my_model["problem"]["n_tasks"]}/{Config.METRICS}/{my_model["name"]}/{n_trials}' else: path_results = f'{Config.RESULTS_DATA}/no_time_bound/task_{my_model["problem"]["n_tasks"]}/{Config.METRICS}/{my_model["name"]}/{n_trials}' name_paras = f'{epoch}_{pop_size}_{end_paras}' file_name = f'{path_results}/experiment_results/{name_paras}-results.csv' df = read_csv(file_name, usecols=["Power", "Latency", "Cost"]) return df.values def getting_results_for_task(models): matrix_fit = zeros((1, 6)) for n_task in OptExp.N_TASKS: for my_model in models: tasks = load_tasks(f'{Config.INPUT_DATA}/tasks_{n_task}.json') problem = deepcopy(my_model['problem']) problem["tasks"] = tasks problem["n_tasks"] = n_task problem["shape"] = [len(problem["clouds"]) + len(problem["fogs"]), n_task] my_model['problem'] = problem for n_trials in range(OptExp.N_TRIALS): if Config.TIME_BOUND_KEY: for n_timebound in OptExp.TIME_BOUND_VALUES: if Config.MODE == "epoch": for epoch in OptExp.EPOCH: end_paras = f"{epoch}" df_matrix = inside_loop(my_model, n_trials, n_timebound, epoch, None, end_paras) df_name = array([[n_task, my_model["name"], n_trials], ] * len(df_matrix)) matrix = hstack(df_name, df_matrix) matrix_fit = vstack((matrix_fit, matrix)) else: if Config.MODE == "epoch": for epoch in OptExp.EPOCH: end_paras = f"{epoch}" df_matrix = inside_loop(my_model, n_trials, None, epoch, None, end_paras) df_name = array([[n_task, my_model["name"], n_trials], ] * len(df_matrix)) matrix = hstack((df_name, df_matrix)) matrix_fit = vstack((matrix_fit, matrix)) return matrix_fit[1:] starttime = time() clouds, fogs, peers = load_nodes(f'{Config.INPUT_DATA}/nodes_2_8_5.json') problem = { "clouds": clouds, "fogs": fogs, "peers": peers, "n_clouds": len(clouds), "n_fogs": len(fogs), "n_peers": len(peers), } models = [ {"name": "NSGA-II", "class": "BaseNSGA_II", "param_grid": OptParas.NSGA_II, "problem": problem}, {"name": "NSGA-III", "class": "BaseNSGA_III", "param_grid": OptParas.NSGA_III, "problem": problem}, {"name": "MO-ALO", "class": "BaseMO_ALO", "param_grid": OptParas.MO_ALO, "problem": problem}, {"name": "MO-SSA", "class": "BaseMO_SSA", "param_grid": OptParas.MO_SSA, "problem": problem}, ] ## Load all results of all trials matrix_results = getting_results_for_task(models) # df_full = DataFrame(matrix_results, columns=["Task", "Model", "Trial", "Fit1", "Fit2", "Fit3"]) data = {'Task': matrix_results[:, 0], 'Model': matrix_results[:, 1], 'Trial': matrix_results[:, 2], 'Fit1': matrix_results[:, 3], 'Fit2': matrix_results[:, 4], 'Fit3': matrix_results[:, 5], } df_full = DataFrame(data) df_full["Task"] = to_numeric(df_full["Task"]) df_full["Trial"] = to_numeric(df_full["Trial"]) df_full["Fit1"] = to_numeric(df_full["Fit1"]) df_full["Fit2"] = to_numeric(df_full["Fit2"]) df_full["Fit3"] = to_numeric(df_full["Fit3"]) for n_task in OptExp.N_TASKS: performance_results = [] performance_results_mean = [] ## Find matrix results for each problem df_task = df_full[df_full["Task"] == n_task] matrix_task = df_task[['Fit1', 'Fit2', 'Fit3']].values hyper_point = max(matrix_task, axis=0) ## Find non-dominated matrix for each problem reference_fronts = zeros((1, 3)) dominated_list = find_dominates_list(matrix_task) for idx, value in enumerate(dominated_list): if value == 0: reference_fronts = vstack((reference_fronts, matrix_task[idx])) reference_fronts = reference_fronts[1:] ## For each model and each trial, calculate its performance metrics for model in models: er_list = zeros(OptExp.N_TRIALS) gd_list = zeros(OptExp.N_TRIALS) igd_list = zeros(OptExp.N_TRIALS) ste_list = zeros(OptExp.N_TRIALS) hv_list = zeros(OptExp.N_TRIALS) har_list = zeros(OptExp.N_TRIALS) for trial in range(OptExp.N_TRIALS): df_result = df_task[ (df_task["Model"] == model["name"]) & (df_task["Trial"] == trial) ] pareto_fronts = array(df_result.values[:, 3:], dtype=float) er = error_ratio(pareto_fronts, reference_fronts) gd = generational_distance(pareto_fronts, reference_fronts) igd = inverted_generational_distance(pareto_fronts, reference_fronts) ste = spacing_to_extent(pareto_fronts) hv = hyper_volume(pareto_fronts, reference_fronts, hyper_point, 100) har = hyper_area_ratio(pareto_fronts, reference_fronts, hyper_point, 100) performance_results.append([n_task, model["name"], trial, er, gd, igd, ste, hv, har]) er_list[trial] = er gd_list[trial] = gd igd_list[trial] = igd ste_list[trial] = ste hv_list[trial] = hv har_list[trial] = har er_min, er_max, er_mean, er_std, er_cv = min(er_list), max(er_list), mean(er_list), std(er_list), std(er_list)/mean(er_list) gd_min, gd_max, gd_mean, gd_std, gd_cv = min(gd_list), max(gd_list), mean(gd_list), std(gd_list), std(gd_list)/
mean(gd_list)
numpy.mean
from PIL import Image import numpy as np import cv2 def image_from_path(path, normalize=True): """ Create image from path :param path: path to image :param normalize: indication of whether or not to normalize image to 0-1 :return: 3d array representation of image """ image = np.array(Image.open(path)) image = image.astype("float64") if len(image.shape) == 2: _image = np.zeros(image.shape + (3,)) _image[:, :, 0] = image _image[:, :, 1] = image _image[:, :, 2] = image image = _image if normalize: return image / 255. return image def save_image(img, out_path, rescale=True): """ Save image to out_path :param img: 3d array representation of image :param out_path: path to save image to :param rescale: indication of whether or not image needs to be rescaled to 0-255 """ if rescale: img = img * 255. img = img.astype("uint8") img = Image.fromarray(img) img.save(out_path) def rgb_to_yuv(img): """ Convert image from RGB to YUV :param img: 3d array representation of image """ conversion_matrix = np.array([ [0.299, 0.587, 0.114], [-0.147, -0.289, 0.436], [0.615, -0.515, -0.100] ]) yuv_img = img @ conversion_matrix.T # Clip values to boundary yuv_img[:, :, 0] = yuv_img[:, :, 0].clip(0, 1) yuv_img[:, :, 1] = yuv_img[:, :, 1].clip(-0.5, 0.5) yuv_img[:, :, 2] = yuv_img[:, :, 2].clip(-0.5, 0.5) return yuv_img def yuv_to_rgb(img): """ Convert image from YUV to RGB :param img: 3d array representation of image """ conversion_matrix = np.array([ [1, 0, 1.14], [1, -0.395, -0.581], [1, 2.032, 0] ]) # Clip values to boundary return (img @ conversion_matrix.T).clip(0, 1) def get_neighbor_coords(channel_data, coord, radius=1, omit_center=False): """ Get set of coordinates in neighborhood around coord :param channel_data: channel data that neighborhoods are in :param coord: (row, col) at center of neighborhood :param radius: number of pixels on each side of coord in neighborhood :param omit_center: indication of whether or not coord should be omitted from neighborhood coords :return: set of (row, col) in neighborhood in channel_data """ # Compute bounds based on image size lower_bound1 = max(coord[0] - radius, 0) upper_bound1 = min(coord[0] + radius + 1, channel_data.shape[0]) lower_bound2 = max(coord[1] - radius, 0) upper_bound2 = min(coord[1] + radius + 1, channel_data.shape[1]) # Compute coordinates in computed bounds window_coords = np.array( np.meshgrid(
np.arange(lower_bound1, upper_bound1)
numpy.arange
from time import time import numpy as np import lptml import itertools import csv from sklearn import datasets from sklearn.decomposition import PCA from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import ShuffleSplit from sklearn.metrics import accuracy_score from sklearn.metrics import f1_score from sklearn.metrics import precision_score from sklearn.metrics import recall_score import pandas as pd import scipy.io as sio run_mlwga = False previous_solution = [] def split_pca_learn_metric(x, y, PCA_dim_by, repetitions, t_size, lptml_iterations, S, D, ut, lt, run_hadoop=False, num_machines=10, label_noise=0, rand_state=-1): experiment_results = {} global previous_solution d = len(x[0]) if rand_state < 0: ss = ShuffleSplit(test_size=1-t_size, n_splits=repetitions) else: ss = ShuffleSplit(test_size=1 - t_size, n_splits=repetitions, random_state=rand_state) for train_index, test_index in ss.split(x): x_train, x_test = x[train_index], x[test_index] y_train, y_test = y[train_index], y[test_index] # add label noise by re-sampling a fraction of the training labels if label_noise > 0: all_labels = np.unique(y_train) np.random.seed(rand_state) nss = ShuffleSplit(test_size=label_noise/100, n_splits=1, random_state=rand_state) for no_noise, yes_noise in nss.split(y_train): for i in yes_noise: y_train[i] = np.random.choice(np.setdiff1d(all_labels, y_train[i]), 1); np.random.seed(None) for reduce_dim_by in PCA_dim_by: print("Reducing dimension by", reduce_dim_by) dimensions = d - reduce_dim_by if reduce_dim_by > 0: pca = PCA(n_components=dimensions) x_pca_train = pca.fit(x_train).transform(x_train) x_pca_test = pca.fit(x_test).transform(x_test) else: x_pca_train = x_train x_pca_test = x_test if (ut == 0) and (lt == 0): distances = [] all_pairs = [] for pair_of_indexes in itertools.combinations(range(0, min(1000, len(x_pca_train))), 2): all_pairs.append(pair_of_indexes) distances.append(np.linalg.norm(x_pca_train[pair_of_indexes[0]] - x_pca_train[pair_of_indexes[1]])) u = np.percentile(distances, 10) l = np.percentile(distances, 90) else: u = ut l = lt previous_solution = [] # replace use of d by dim from here previous_t = 0 for target_iteration in lptml_iterations: t = target_iteration - previous_t previous_t = t print("Algorithm t=", lptml_iterations) if str(reduce_dim_by) not in experiment_results.keys(): experiment_results[str(reduce_dim_by)] = {str(target_iteration): []} else: if str(target_iteration) not in experiment_results[str(reduce_dim_by)].keys(): experiment_results[str(reduce_dim_by)][str(target_iteration)] = [] iteration_results = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] print('u', u, 'l', l) start_time = time() if run_mlwga: if len(S) > 0: sim = [] dis = [] # select those pairs in S & D that are in the training set for j in range(len(S)): if ((S[j][0] - 1) in train_index) and ((S[j][1] - 1) in train_index): # print("here", np.where(train_index == S[j][0])) sim.append([np.where(train_index == (S[j][0] - 1))[0][0], np.where(train_index == (S[j][1] - 1))[0][0]]) # print(S[j]) for j in range(len(D)): if ((D[j][0] - 1) in train_index) and ((D[j][1] - 1) in train_index): # print(train_index) dis.append([np.where(train_index == (D[j][0] - 1))[0][0], np.where(train_index == (D[j][1] - 1))[0][0]]) # print(D[j]) G = lptml.fit(x_pca_train, y_train, u, l, t, sim, dis, run_hadoop=run_hadoop, num_machines=num_machines, initial_solution=previous_solution) else: G = lptml.fit(x_pca_train, y_train, u, l, t, run_hadoop=run_hadoop, num_machines=num_machines, initial_solution=previous_solution, random_seed=rand_state) previous_solution = np.dot(np.transpose(G), G) else: G = np.identity(len(x_pca_train[1])) elapsed_time = time() - start_time print("elapsed time to get G", elapsed_time) # x_lptml = np.matmul(G, x.T).T print("what I got back was of type", type(G)) # x_lptml_train, x_lptml_test = x_lptml[train_index], x_lptml[test_index] try: x_lptml_train = np.matmul(G, np.transpose(x_pca_train)).T x_lptml_test = np.matmul(G, np.transpose(x_pca_test)).T except: print("continue") raise neigh_lptml = KNeighborsClassifier(n_neighbors=4, metric="euclidean") neigh_lptml.fit(x_lptml_train, np.ravel(y_train)) neigh = KNeighborsClassifier(n_neighbors=4, metric="euclidean") neigh.fit(x_pca_train, np.ravel(y_train)) y_prediction = neigh.predict(x_pca_test) y_lptml_prediction = neigh_lptml.predict(x_lptml_test) iteration_results[0] = accuracy_score(y_test, y_prediction) iteration_results[1] = accuracy_score(y_test, y_lptml_prediction) iteration_results[4] = precision_score(y_test, y_prediction, average="macro") iteration_results[5] = precision_score(y_test, y_lptml_prediction, average="macro") iteration_results[8] = recall_score(y_test, y_prediction, average="macro") iteration_results[9] = recall_score(y_test, y_lptml_prediction, average="macro") iteration_results[12] = f1_score(y_test, y_prediction, average="macro") iteration_results[13] = f1_score(y_test, y_lptml_prediction, average="macro") iteration_results[16] = lptml.initial_violation_count iteration_results[17] = lptml.max_best_solution_d + lptml.max_best_solution_s #violated constraints d_viol, s_viol = lptml.count_violated_constraints(x_pca_test, y_test, lptml.transformer(np.identity(dimensions)), u, l) iteration_results[18] = d_viol + s_viol d_viol, s_viol = lptml.count_violated_constraints(x_pca_test, y_test, G, u, l) iteration_results[19] = d_viol + s_viol iteration_results[20] = elapsed_time print(iteration_results) experiment_results[str(reduce_dim_by)][str(target_iteration)].append(iteration_results) return experiment_results def perform_experiment(x, y, number_of_folds, feat_count, PCA_dim_by, repeat_experiment, result_header, filename, lptml_iterations, S, D, ut, lt, run_hadoop=False, num_machines=10, label_noise=0, rand_state=-1): results_dict = split_pca_learn_metric(x, y, PCA_dim_by, repeat_experiment, number_of_folds, lptml_iterations, S, D, ut, lt, run_hadoop=run_hadoop, num_machines=num_machines, label_noise=label_noise, rand_state=rand_state) for pca in PCA_dim_by: for ite in lptml_iterations: final_results = ["", 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] results = np.array(results_dict[str(pca)][str(ite)]) if pca == 0: final_results[0] = result_header + " NOPCA" else: final_results[0] = result_header + " to " + str(feat_count - pca) final_results[0] += " t=" + str(ite) # Averages accuracy for Euclidean, lptml, LMNN, ITML final_results[1] = np.round(np.average(results[:, 0]), 2) final_results[2] = np.round(np.average(results[:, 1]), 2) # Std accuracy for Euclidean, lptml, LMNN, ITML final_results[3] = np.round(np.std(results[:, 0]), 2) final_results[4] = np.round(np.std(results[:, 1]), 2) # Averages precision for Euclidean, lptml, LMNN, ITML final_results[5] = np.round(np.average(results[:, 4]), 2) final_results[6] = np.round(np.average(results[:, 5]), 2) # Std precision for Euclidean, lptml, LMNN, ITML final_results[7] = np.round(np.std(results[:, 4]), 2) final_results[8] = np.round(np.std(results[:, 5]), 2) # Averages recall for Euclidean, lptml, LMNN, ITML final_results[9] = np.round(np.average(results[:, 8]), 2) final_results[10] = np.round(np.average(results[:, 9]), 2) # Std recall for Euclidean, lptml, LMNN, ITML final_results[11] = np.round(np.std(results[:, 8]), 2) final_results[12] = np.round(np.std(results[:, 9]), 2) # Averages F1 score for Euclidean, lptml, LMNN, ITML final_results[13] = np.round(np.average(results[:, 12]), 2) final_results[14] = np.round(
np.average(results[:, 13])
numpy.average
import numpy as np import cvxopt as co import matplotlib.pyplot as plt from tilitools.ssad_convex import ConvexSSAD from tilitools.utils_kernel import get_kernel if __name__ == '__main__': # example constants (training set size and splitting) k_type = 'rbf' # attention: this is the shape parameter of a Gaussian # which is 1/sigma^2 k_param = 2.4 N_pos = 10 N_neg = 10 N_unl = 10 # generate training labels Dy = np.zeros(N_pos+N_neg+N_unl, dtype=np.int) Dy[:N_pos] = 1 Dy[N_pos+N_unl:] = -1 # generate training data co.setseed(11) Dtrainp = co.normal(2,N_pos)*0.6 Dtrainu = co.normal(2,N_unl)*0.6 Dtrainn = co.normal(2,N_neg)*0.6 Dtrain21 = Dtrainn-1 Dtrain21[0,:] = Dtrainn[0,:]+1 Dtrain22 = -Dtrain21 # training data Dtrain = co.matrix([[Dtrainp], [Dtrainu], [Dtrainn+0.8]]) Dtrain =
np.array(Dtrain)
numpy.array
""" Utility functions for the validation scripts. """ from htof.parse import DataParser, HipparcosOriginalData, HipparcosRereductionDVDBook, HipparcosRereductionJavaTool from htof.fit import AstrometricFitter from htof.sky_path import parallactic_motion, earth_ephemeris from astropy import time from astropy.coordinates import Angle from astropy.table import Table from glob import glob import os import warnings import numpy as np def refit_hip_fromdata(data: DataParser, fit_degree, cntr_RA=Angle(0, unit='degree'), cntr_Dec=Angle(0, unit='degree'), use_parallax=False): data.calculate_inverse_covariance_matrices() # generate parallax motion jyear_epoch = time.Time(data.julian_day_epoch(), format='jd', scale='tcb').jyear # note that ra_motion and dec_motion are in degrees here. # generate sky path year_epochs = jyear_epoch - time.Time(1991.25, format='decimalyear', scale='tcb').jyear ra_motion, dec_motion = parallactic_motion(jyear_epoch, cntr_RA.degree, cntr_Dec.degree, 'degree', time.Time(1991.25, format='decimalyear', scale='tcb').jyear, ephemeris=earth_ephemeris) # Hipparcos was in a geostationary orbit. ra_resid = Angle(data.residuals.values * np.sin(data.scan_angle.values), unit='mas') dec_resid = Angle(data.residuals.values *
np.cos(data.scan_angle.values)
numpy.cos
from collections import deque import matplotlib.pyplot as plt import numpy as np import cv2 class Lane(): def __init__(self, nb_memory_items): self.nb_memory_items = nb_memory_items self.search_type = 'window' # x values of the last n fits of the line #x values for detected line pixels self.x = {'left': [], 'right': []} #y values for detected line pixels self.y = {'left': [], 'right': []} self.recent_xfitted = {'left': deque(maxlen=nb_memory_items), 'right':deque(maxlen=nb_memory_items)} # x values of the current fits of the line self.current_xfitted = {'left': [], 'right':[]} #average x values of the fitted line over the last n iterations self.best_xfitted = {'left': [], 'right': []} #polynomial coefficients of last n iterations self.recent_fit = {'left': deque(maxlen=nb_memory_items), 'right':deque(maxlen=nb_memory_items)} #polynomial coefficients averaged over the last n iterations self.best_fit = {'left': [], 'right':[]} #polynomial coefficients for the most recent fit self.current_fit = {'left': [], 'right':[]} # Status of the lines tells if they are valid self.line_valid = {'left': True, 'right': True} self.invalid_counter = {'left': 0, 'right': 0} self.search_margin = {'left': 65, 'right': 65} self.ploty = np.linspace(0, 719, 720) self.ploty2 = self.ploty**2 #radius of curvature of the line in some units self.radius_of_curvature = {'left': [], 'right':[]} self.average_radius_of_curvature = [] #distance in meters of vehicle center from the line self.vehicle_position = 0 self.xmeter_per_pixel = 3.7/700 self.ymeter_per_pixel = 30/720 # ++++++++++++++++++++++ N O T U S E D ++++++++++++++++++++++ # was the line detected in the last iteration? self.detected = False self.line_base_pos = None #difference in fit coefficients between last and new fits self.diffs = np.array([0,0,0], dtype='float') # ++++++++++++++++++++++ N O T U S E D ++++++++++++++++++++++ def _analyse_line_status(self, verbose=0): if len(self.recent_xfitted['left']) >= 1: last_radius = self.radius_of_curvature.copy() self._calculate_curvature_radius() for key in self.line_valid: self.line_valid[key] = (self.radius_of_curvature[key] > 150) # ((np.absolute(last_radius[key]-self.radius_of_curvature[key]) < 100) & if self.line_valid[key] == False: self.invalid_counter[key] += 1 else: self.invalid_counter[key] = 0 if self.invalid_counter[key] >= 2: self.search_type = 'window' if verbose==1: print("{0}:\t{1},\t valid[{2}],\t margin[{3}],\t counter[{4},\t #pxl[{5}],\tx[{6}]]".format(key, self.search_type, self.line_valid[key], self.search_margin[key], self.invalid_counter[key], len(self.x[key]), self.best_xfitted[key][-1])) if verbose == 1: print('\n') def _bounded_increase_search_margin(self, key): margin = self.search_margin[key] self.search_margin[key] = min((margin + 50), 200) def _bounded_decrease_search_margin(self, key): margin = self.search_margin[key] self.search_margin[key] = max((margin - 25), 65) def line_search(self, binary_warped, verbose=0): # Create an output image to draw on and visualize the result out_img =
np.dstack((binary_warped, binary_warped, binary_warped))
numpy.dstack
import numpy as np import torch import matplotlib.pyplot as plt from typing import Optional from torch.nn.utils import rnn as rnn_utils def batch_gather(sequence, indices): # type: (torch.Tensor, torch.Tensor) -> torch.Tensor """Batch gather from sequences. Arguments: sequence: A tensor of shape (batch_size, length, ...). indices: A tensor of shape (batch_size, num_indices). Returns: permuted_inputs: A tensor of shape (batch_size, num_indices, ...). """ indices = torch.stack([indices] * sequence.shape[-1], dim=-1) permuted_inputs = torch.gather(sequence, 1, indices) return permuted_inputs def batch_sequence_mask(lengths, max_len=None, dtype=torch.bool): # type: (torch.Tensor, Optional[int], Optional[torch.dtype]) -> torch.Tensor """Create a batch of sequence masks by valid lengths. Arguments: lengths: A `torch.int64` tensor of shape (batch_size,), the valid length of each example. max_len: An `int`, the maximum length to padding. Defaults to the maximum value of `lengths`. dtype: A `torch.dtype`, the output data type. Returns: mask: A binary tensor of shape (batch_size, max_len), true values for valid position. """ return (torch.arange(max_len or lengths.max())[None, :] < lengths[:, None]).to(dtype=dtype) def batch_reverse_sequence(sequences, lengths): indices = torch.arange(sequences.shape[-1], dtype=torch.int64) indices, lengths = torch.broadcast_tensors(indices[None, :], lengths[:, None]) gather_indices = torch.where( indices < lengths, lengths - indices - 1, indices) return torch.gather(sequences, 1, gather_indices) def batch_step_mask(masked, decoded): """Create a new mask by adding a decoded position to an old mask. Arguments: masked: The old mask of shape (batch_size, max_len). decoded: The decoded positions of shape (batch_size,). Returns: A new mask of shape (batch_size, max_len). """ decoded = decoded.unsqueeze(-1) return masked.scatter(-1, decoded, torch.zeros_like(decoded, dtype=masked.dtype)) def batch_steps_mask(steps, dtype=torch.bool): """Create a step mask by masking decoded position at each step. Arguments: steps: The index sequence of shape (batch_size, max_len). dtype: Output data type. Returns: A mask of shape (batch_size, max_len, max_len). """ batch_size, max_len = steps.size() masked = torch.ones(batch_size, max_len, dtype=dtype) masks = [masked] for i in range(max_len - 1): masked = batch_step_mask(masked, steps[:, i]) masks.append(masked) return torch.stack(masks, dim=1) def batch_journey(parameters, ending, lengths): # indices: starting zero at end mask = batch_sequence_mask(lengths, max_len=ending.shape[-1], dtype=parameters.dtype) ending = batch_gather(parameters, ending) beginning = ending.roll(1, dims=1) return ((ending - beginning).square().sum(-1) * mask).sqrt().sum(-1) def combine_masks(*masks, dtype=None): masks = torch.broadcast_tensors(*masks) mask = torch.ones_like(masks[0], dtype=torch.bool) for m in masks: mask = torch.logical_and(mask, m.to(dtype=torch.bool)) return mask.to(dtype=dtype or masks[0].dtype) def dynamic_rnn(rnn, inputs, lengths=None, hidden_state=None): if lengths is None: return rnn(inputs, hidden_state) packed_rnn_inputs = rnn_utils.pack_padded_sequence(inputs, lengths, enforce_sorted=False, batch_first=True) packed_rnn_outputs, hidden_state = rnn(packed_rnn_inputs, hidden_state) padded_outputs, _ = rnn_utils.pad_packed_sequence(packed_rnn_outputs, batch_first=True) return padded_outputs, hidden_state def stack_n(tensor, n, dim): return torch.stack([tensor] * n, dim=dim) def _get_numpy(maybe_tensor): if isinstance(maybe_tensor, torch.Tensor): if maybe_tensor.requires_grad: maybe_tensor = maybe_tensor.detach() return maybe_tensor.cpu().numpy() return np.array(maybe_tensor) def plot_solution(parameters, target, prediction): parameters, target, prediction = _get_numpy(parameters), _get_numpy(target), _get_numpy(prediction) target = np.concatenate([target, target[0:1]], axis=0) prediction =
np.concatenate([prediction, prediction[0:1]], axis=0)
numpy.concatenate
# coding: utf-8 from __future__ import print_function from __future__ import division import torch import torch.nn as nn import torch.nn.functional as F from libcity.model.abstract_model import AbstractModel from math import sin, cos, sqrt, atan2, radians import numpy as np def identity_loss(y_true, y_pred): return torch.mean(y_pred - 0 * y_true) class CARA1(nn.Module): def hard_sigmoid(self, x): x = torch.tensor(x / 6 + 0.5) x = F.threshold(-x, -1, -1) x = F.threshold(-x, 0, 0) return x def __init__(self, output_dim, input_dim, init='glorot_uniform', inner_init='orthogonal', **kwargs): super(CARA1, self).__init__() self.output_dim = output_dim self.init = init self.inner_init = inner_init self.activation = self.hard_sigmoid self.inner_activation = nn.Tanh() self.build(input_dim) def add_weight(self, shape, initializer): ts = torch.zeros(shape) if initializer == 'glorot_uniform': ts = nn.init.xavier_normal_(ts) elif initializer == 'orthogonal': ts = nn.init.orthogonal_(ts) return nn.Parameter(ts) def build(self, input_shape): # self.input_spec = [InputSpec(shape=input_shape)] self.input_dim = input_shape self.W_z = self.add_weight((self.input_dim, self.output_dim), initializer=self.init) self.U_z = self.add_weight((self.output_dim, self.output_dim), initializer=self.init) self.b_z = self.add_weight((self.output_dim,), initializer='zero') self.W_r = self.add_weight((self.input_dim, self.output_dim), initializer=self.init) self.U_r = self.add_weight((self.output_dim, self.output_dim), initializer=self.init) self.b_r = self.add_weight((self.output_dim,), initializer='zero') self.W_h = self.add_weight((self.input_dim, self.output_dim), initializer=self.init) self.U_h = self.add_weight((self.output_dim, self.output_dim), initializer=self.init) self.b_h = self.add_weight((self.output_dim,), initializer='zero') self.A_h = self.add_weight((self.output_dim, self.output_dim), initializer=self.init) self.A_u = self.add_weight((self.output_dim, self.output_dim), initializer=self.init) self.b_a_h = self.add_weight((self.output_dim,), initializer='zero') self.b_a_u = self.add_weight((self.output_dim,), initializer='zero') self.W_t = self.add_weight((self.input_dim, self.output_dim), initializer=self.init) self.U_t = self.add_weight((1, self.output_dim), initializer=self.init) self.b_t = self.add_weight((self.output_dim,), initializer='zero') self.W_g = self.add_weight((self.input_dim, self.output_dim), initializer=self.init) self.U_g = self.add_weight((1, self.output_dim), initializer=self.init) self.b_g = self.add_weight((self.output_dim,), initializer='zero') def preprocess_input(self, x): return x def forward(self, x): """ X : batch * timeLen * dims(有拓展) """ tlen = x.shape[1] output = torch.zeros((x.shape[0], self.output_dim)) for i in range(tlen): output = self.step(x[:, i, :], output) return output def step(self, x, states): """ 用于多批次同一时间 states为上一次多批次统一时间数据 """ h_tm1 = states # phi_t u = x[:, self.output_dim: 2 * self.output_dim] # delta_t t = x[:, 2 * self.output_dim: (2 * self.output_dim) + 1] # delta_g g = x[:, (2 * self.output_dim) + 1:] # phi_v x = x[:, :self.output_dim] t = self.inner_activation(torch.matmul(t, self.U_t)) g = self.inner_activation(torch.matmul(g, self.U_g)) # Time-based gate t1 = self.inner_activation(torch.matmul(x, self.W_t) + t + self.b_t) # Geo-based gate g1 = self.inner_activation(torch.matmul(x, self.W_g) + g + self.b_g) # Contextual Attention Gate a = self.inner_activation( torch.matmul(h_tm1, self.A_h) + torch.matmul(u, self.A_u) + self.b_a_h + self.b_a_u) x_z = torch.matmul(x, self.W_z) + self.b_z x_r = torch.matmul(x, self.W_r) + self.b_r x_h = torch.matmul(x, self.W_h) + self.b_h u_z_ = torch.matmul((1 - a) * u, self.W_z) + self.b_z u_r_ = torch.matmul((1 - a) * u, self.W_r) + self.b_r u_h_ = torch.matmul((1 - a) * u, self.W_h) + self.b_h u_z = torch.matmul(a * u, self.W_z) + self.b_z u_r = torch.matmul(a * u, self.W_r) + self.b_r u_h = torch.matmul(a * u, self.W_h) + self.b_h # update gate z = self.inner_activation(x_z + torch.matmul(h_tm1, self.U_z) + u_z) # reset gate r = self.inner_activation(x_r + torch.matmul(h_tm1, self.U_r) + u_r) # hidden state hh = self.activation(x_h + torch.matmul(r * t1 * g1 * h_tm1, self.U_h) + u_h) h = z * h_tm1 + (1 - z) * hh h = (1 + u_z_ + u_r_ + u_h_) * h return h # return h def bpr_triplet_loss(x): positive_item_latent, negative_item_latent = x reg = 0 loss = 1 - torch.log(torch.sigmoid( torch.sum(positive_item_latent, dim=-1, keepdim=True) - torch.sum(negative_item_latent, dim=-1, keepdim=True))) - reg return loss class Recommender(nn.Module): def __init__(self, num_users, num_items, num_times, latent_dim, maxvenue=5): super(Recommender, self).__init__() self.maxVenue = maxvenue self.latent_dim = latent_dim # num * maxVenue * dim self.U_Embedding = nn.Embedding(num_users, latent_dim) self.V_Embedding = nn.Embedding(num_items, latent_dim) self.T_Embedding = nn.Embedding(num_times, latent_dim) torch.nn.init.uniform_(self.U_Embedding.weight) torch.nn.init.uniform_(self.V_Embedding.weight) torch.nn.init.uniform_(self.T_Embedding.weight) self.rnn = nn.Sequential( CARA1(latent_dim, latent_dim, input_shape=(self.maxVenue, (self.latent_dim * 2) + 2,), unroll=True)) # latent_dim * 2 + 2 = v_embedding + t_embedding + time_gap + distance def forward(self, x): # INPUT = [self.user_input, self.time_input, self.gap_time_input, self.pos_distance_input, # self.neg_distance_input, self.checkins_input, # self.neg_checkins_input] # pass # User latent factor user_input = torch.tensor(x[0]) time_input = torch.tensor(x[1]) gap_time_input = torch.tensor(x[2], dtype=torch.float32) pos_distance_input = torch.tensor(x[3], dtype=torch.float32) neg_distance_input = torch.tensor(x[4], dtype=torch.float32) checkins_input = torch.tensor(x[5]) neg_checkins_input = torch.tensor(x[6]) self.u_latent = self.U_Embedding(user_input) self.t_latent = self.T_Embedding(time_input) h, w = gap_time_input.shape gap_time_input = gap_time_input.view(h, w, 1) rnn_input = torch.cat([self.V_Embedding(checkins_input), self.T_Embedding(time_input), gap_time_input], -1) neg_rnn_input = torch.cat([self.V_Embedding(neg_checkins_input), self.T_Embedding(time_input), gap_time_input], -1) h, w = pos_distance_input.shape pos_distance_input = pos_distance_input.view(h, w, 1) h, w = neg_distance_input.shape neg_distance_input = neg_distance_input.view(h, w, 1) rnn_input = torch.cat([rnn_input, pos_distance_input], -1) neg_rnn_input = torch.cat([neg_rnn_input, neg_distance_input], -1) self.checkins_emb = self.rnn(rnn_input) self.neg_checkins_emb = self.rnn(neg_rnn_input) pred = (self.checkins_emb * self.u_latent).sum(dim=1) neg_pred = (self.neg_checkins_emb * self.u_latent).sum(dim=1) return bpr_triplet_loss([pred, neg_pred]) def rank(self, uid, hist_venues, hist_times, hist_time_gap, hist_distances): # hist_venues = hist_venues + [candidate_venue] # hist_times = hist_times + [time] # hist_time_gap = hist_time_gap + [time_gap] # hist_distances = hist_distances + [distance] # u_latent = self.U_Embedding(torch.tensor(uid)) # v_latent = self.V_Embedding(torch.tensor(hist_venues)) # t_latent = self.T_Embedding(torch.tensor(hist_times)) u_latent = self.U_Embedding.weight[uid] v_latent = self.V_Embedding.weight[hist_venues.reshape(-1)].view(hist_venues.shape[0], hist_venues.shape[1], -1) t_latent = self.T_Embedding.weight[hist_times.reshape(-1)].view(hist_times.shape[0], hist_times.shape[1], -1) h, w = hist_time_gap.shape hist_time_gap = hist_time_gap.reshape(h, w, 1) h, w = hist_distances.shape hist_distances = hist_distances.reshape(h, w, 1) rnn_input = torch.cat([t_latent, torch.tensor(hist_time_gap, dtype=torch.float32)], dim=-1) rnn_input = torch.cat([rnn_input, torch.tensor(hist_distances, dtype=torch.float32)], dim=-1) rnn_input = torch.cat([v_latent, rnn_input], dim=-1) dynamic_latent = self.rnn(rnn_input) scores = torch.mul(dynamic_latent, u_latent).sum(1) # scores = np.dot(dynamic_latent, u_latent) return scores class CARA(AbstractModel): """rnn model with long-term history attention""" def __init__(self, config, data_feature): super(CARA, self).__init__(config, data_feature) self.loc_size = data_feature['loc_size'] self.tim_size = data_feature['tim_size'] self.uid_size = data_feature['uid_size'] self.poi_profile = data_feature['poi_profile'] self.id2locid = data_feature['id2locid'] self.id2loc = [] for i in range(self.loc_size - 1): self.id2loc.append(self.id2locid[str(i)]) self.id2loc.append(self.loc_size) self.id2loc = np.array(self.id2loc) self.coor = self.poi_profile['coordinates'].apply(eval) self.rec = Recommender(self.uid_size, self.loc_size, self.tim_size, 10) def get_time_interval(self, x): y = x[:, :-1] y = np.concatenate([x[:, 0, None], y], axis=1) return x - y def get_time_interval2(self, x): y = x[:-1] y = np.concatenate([x[0, None], y], axis=0) return x - y def get_pos_distance(self, x): x = np.array(x.tolist()) y = np.concatenate([x[:, 0, None, :], x[:, :-1, :]], axis=1) r = 6373.0 rx = np.radians(x) ry = np.radians(y) d = x - y a = np.sin(d[:, :, 0] / 2) ** 2 + np.cos(rx[:, :, 0]) * np.cos(ry[:, :, 0]) *
np.sin(d[:, :, 1] / 2)
numpy.sin
import numpy as np import datetime import pandas import os import glob import h5py import yaml from scipy import interpolate from ttools import utils, config from ttools.satellite import SATELLITES OMNI_COLUMNS = ( "rotation_number", "imf_id", "sw_id", "imf_n", "plasma_n", "b_mag", "b_vector_mag", "b_vector_lat_avg", "b_vector_lon_avg", "bx", "by_gse", "bz_gse", "by_gsm", "bz_gsm", "b_mag_std", "b_vector_mag_std", "bx_std", "by_std", "bz_std", "proton_temp", "proton_density", "plasma_speed", "plasma_lon_angle", "plasma_lat_angle", "na_np_ratio", "flow_pressure", "temp_std", "density_std", "speed_std", "phi_v_std", "theta_v_std", "na_np_ratio_std", "e_field", "plasma_beta", "alfven_mach_number", "kp", "r", "dst", "ae", "proton_flux_1", "proton_flux_2", "proton_flux_4", "proton_flux_10", "proton_flux_30", "proton_flux_60", "proton_flux_flag", "ap", "f107", "pcn", "al", "au", "magnetosonic_mach_number" ) def get_gm_index_kyoto(fn=None): if fn is None: fn = config.kp_file with open(fn, 'r') as f: text = f.readlines() ut_list = [] kp_list = [] ap_list = [] for line in text[1:]: day = datetime.datetime.strptime(line[:8], '%Y%m%d') dt = datetime.timedelta(hours=3) uts = np.array([(day + i * dt).timestamp() for i in range(8)], dtype=int) kp = [] for i in range(9, 25, 2): num = float(line[i]) sign = line[i + 1] if sign == '+': num += 1 / 3 elif sign == '-': num -= 1 / 3 kp.append(num) kp_sum = float(line[25:27]) sign = line[27] if sign == '+': kp_sum += 1 / 3 elif sign == '-': kp_sum -= 1 / 3 assert abs(kp_sum - sum(kp)) < .01 kp_list.append(kp) ap = [] for i in range(28, 52, 3): ap.append(float(line[i:i + 3])) ap = np.array(ap, dtype=int) Ap = float(line[52:55]) ut_list.append(uts) ap_list.append(ap) ut = np.concatenate(ut_list) ap = np.concatenate(ap_list) kp = np.concatenate(kp_list) return pandas.DataFrame({'kp': kp, 'ap': ap, 'ut': ut}, index=pandas.to_datetime(ut, unit='s')) def get_kp(times, fn=None): if fn is None: fn = config.kp_file data = get_gm_index_kyoto(fn) interpolator = interpolate.interp1d(data['ut'].values, data['kp'], kind='previous') return interpolator(times.astype('datetime64[s]').astype(float)) def get_omni_data(fn=None): if fn is None: fn = config.omni_file data = np.loadtxt(fn) year = (data[:, 0] - 1970).astype('datetime64[Y]') doy = (data[:, 1] - 1).astype('timedelta64[D]') hour = data[:, 2].astype('timedelta64[h]') datetimes = (year + doy + hour).astype('datetime64[s]') dtindex = pandas.DatetimeIndex(datetimes) df = pandas.DataFrame(data=data[:, 3:], index=dtindex, columns=OMNI_COLUMNS) for field in df: bad_val = df[field].max() bad_val_str = str(int(np.floor(bad_val))) if bad_val_str.count('9') == len(bad_val_str): mask = df[field] == bad_val df[field].loc[mask] = np.nan return df def get_borovsky_data(fn="E:\\borovsky_2020_data.txt"): data = np.loadtxt(fn, skiprows=1) year = (data[:, 1] - 1970).astype('datetime64[Y]') doy = (data[:, 2] - 1).astype('timedelta64[D]') hour = data[:, 3].astype('timedelta64[h]') datetimes = (year + doy + hour).astype('datetime64[s]') return datetimes.astype(int), data[:, 4:] def get_madrigal_data(start_date, end_date, data_dir=None): """Gets madrigal TEC and timestamps assuming regular sampling. Fills in missing time steps. Parameters ---------- start_date, end_date: np.datetime64 data_dir: str Returns ------- tec, times: numpy.ndarray """ if data_dir is None: data_dir = config.madrigal_dir dt = np.timedelta64(5, 'm') dt_sec = dt.astype('timedelta64[s]').astype(int) start_date = (np.ceil(start_date.astype('datetime64[s]').astype(int) / dt_sec) * dt_sec).astype('datetime64[s]') end_date = (np.ceil(end_date.astype('datetime64[s]').astype(int) / dt_sec) * dt_sec).astype('datetime64[s]') ref_times = np.arange(start_date, end_date, dt) ref_times_ut = ref_times.astype('datetime64[s]').astype(int) tec = np.ones((config.madrigal_lat.shape[0], config.madrigal_lon.shape[0], ref_times_ut.shape[0])) * np.nan file_dates = np.unique(ref_times.astype('datetime64[D]')) file_dates = utils.decompose_datetime64(file_dates) for i in range(file_dates.shape[0]): y = file_dates[i, 0] m = file_dates[i, 1] d = file_dates[i, 2] try: fn = glob.glob(os.path.join(data_dir, f"gps{y - 2000:02d}{m:02d}{d:02d}g.*.hdf5"))[-1] except IndexError: print(f"{y}-{m}-{d} madrigal file doesn't exist") continue t, ut, lat, lon = open_madrigal_file(fn) month_time_mask = np.in1d(ref_times_ut, ut) day_time_mask =
np.in1d(ut, ref_times_ut)
numpy.in1d
#%% # This script performs posterior inference for multiple operators # at a single aTc conc (by default, Oid, O1, O2 at 1ng/mL). import re #regex import warnings import dill from multiprocessing import Pool from git import Repo #for directory convenience import numpy as np from scipy.stats import nbinom as neg_binom from mpmath import hyp2f1 from scipy.special import gammaln import pandas as pd import emcee import srep def log_like_repressed(params, data_rep): """Conv wrapper for log likelihood for 2-state promoter w/ transcription bursts and repression. data_rep: a list of arrays, each of which is n x 2, of form data[:, 0] = SORTED unique mRNA counts data[:, 1] = frequency of each mRNA count Note the data pre-processing here, credit to Manuel for this observation: 'The likelihood asks for unique mRNA entries and their corresponding counts to speed up the process of computing the probability distribution. Instead of computing the probability of 3 mRNAs n times, it computes it once and multiplies the value by n.' This also reduces the size of the data arrays by ~10-fold, which reduces the time penalty of emcee's pickling to share the data within the multiprocessing Pool. """ k_burst, mean_burst, kR_on, *k_offs = params params_local = np.array([k_burst, mean_burst, kR_on, 0]) target = 0 for i, expt in enumerate(data_rep): max_m = expt[0].max() params_local[-1] = k_offs[i] # note log_probs contains values for ALL m < max_m, # not just those in the data set... log_probs = srep.models.log_prob_m_bursty_rep(max_m, *params_local) # ...so extract just the ones we want & * by their occurence target += np.sum(expt[1] * log_probs[expt[0]]) return target def log_like_constitutive(params, data_uv5): k_burst = params[0] mean_burst = params[1] # change vars for scipy's goofy parametrization p = (1 + mean_burst)**(-1) return np.sum(data_uv5[1] * neg_binom._logpmf(data_uv5[0], k_burst, p)) def log_prior(params): k_burst, mean_burst, kR_on, koff_Oid, koff_O1, koff_O2 = params # remember these params are log_10 of the actual values!! if (0.62 < k_burst < 0.8 and 0.4 < mean_burst < 0.64 and 0.1 < kR_on < 1.5 and -0.8 < koff_Oid < 0 and -0.5 < koff_O1 < 0.3 and 0.1 < koff_O2 < 1.2 ): return 0.0 return -np.inf def log_posterior(params, data_uv5, data_rep): """check prior and then farm out data to the respective likelihoods.""" lp = log_prior(params) if lp == -np.inf: return -np.inf # we're sampling in log space but liklihoods are written in linear space params = 10**params return (lp + log_like_constitutive(params, data_uv5) + log_like_repressed(params, data_rep)) #%% repo = Repo("./", search_parent_directories=True) # repo_rootdir holds the absolute path to the top-level of our repo repo_rootdir = repo.working_tree_dir expts = ("Oid_1ngmL", "O1_1ngmL", "O2_1ngmL") data_uv5, data_rep = srep.utils.condense_data(expts) #%% n_dim = 6 n_walkers = 18 n_burn = 1 n_steps = 100 # init walkers p0 =
np.zeros([n_walkers, n_dim])
numpy.zeros
import math import unittest import numpy as np from quasarnp.layers import (batch_normalization, conv1d, dense, flatten, linear, relu, sigmoid) class TestActivations(unittest.TestCase): def test_linear(self): # Test the liner activation for integers, positive and negative self.assertEqual(linear(0), 0) self.assertEqual(linear(1), 1) self.assertEqual(linear(-1), -1) # Test the linear activation for numpy arrays, both flat and 2d in_arr = np.arange(-10, 10) expected = np.arange(-10, 10) self.assertTrue(np.allclose(linear(in_arr), expected)) in_arr = np.reshape(in_arr, (-1, 5)) expected = np.reshape(expected, (-1, 5)) self.assertTrue(np.allclose(linear(in_arr), expected)) def test_relu(self): # Test the relu activation for integers, positive and negative self.assertEqual(relu(0), 0) self.assertEqual(relu(1), 1) self.assertEqual(relu(-1), 0) # Test the relu activation for numpy arrays, both flat and 2d in_arr = np.arange(-10, 10) expected = np.asarray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) self.assertTrue(np.allclose(relu(in_arr), expected)) in_arr = np.reshape(in_arr, (-1, 5)) expected = np.reshape(expected, (-1, 5)) self.assertTrue(np.allclose(relu(in_arr), expected)) def test_sigmoid(self): # Test the sigmoid activation for integers, positive and negative self.assertEqual(sigmoid(0), 0.5) self.assertEqual(sigmoid(1), 1 / (1 + 1 / math.e)) self.assertEqual(sigmoid(-1), 1 / (1 + math.e)) # Test the relu activation for numpy arrays, both flat and 2d in_arr = np.arange(-10, 10) expected = 1 / (1 + np.exp(-in_arr)) self.assertTrue(np.allclose(sigmoid(in_arr), expected)) in_arr = np.reshape(in_arr, (-1, 5)) expected = np.reshape(expected, (-1, 5)) self.assertTrue(np.allclose(sigmoid(in_arr), expected)) class TestLayers(unittest.TestCase): # For this test class we will assume that the activations are correct. # We test those separately up above anyway. def test_dense_weights(self): # This test has all weights set to 0, but nonzero/nonunity bias # This should mean the result is only the bias relu'd. in_weights = np.zeros((11, 5)) in_bias = np.arange(-2, 3) in_x = np.arange(-5, 6) observed = dense(in_x, in_weights, in_bias, relu) expected = [0, 0, 0, 1, 2] self.assertTrue(np.allclose(observed, expected)) # Setting the weights to 1 and ensuring the answer remains correct. # Since the input x array is symmetric the pre bias answer is still # zeros. in_weights = np.ones((11, 5)) observed = dense(in_x, in_weights, in_bias, relu) expected = [0, 0, 0, 1, 2] self.assertTrue(np.allclose(observed, expected)) def test_dense_bias(self): # This test has all biases set to 0, but nonzero/nonunity weights in_weights = [[1, 1, -5, -1, -1], [1, 2, -4, -1, -2], [1, 3, -3, -1, -3], [1, 4, -2, -1, -4], [1, 5, -1, -1, -5]] in_weights = np.asarray(in_weights) in_bias = np.zeros(5) in_x = np.arange(-2, 3) observed = dense(in_x, in_weights, in_bias, relu) expected = [0, 10, 10, 0, 0] self.assertTrue(np.allclose(observed, expected)) # Testing if we set the bias to 1 that the answer remains correct # NOTE: The last weights product equals -10 so adding the # 1 does not change the answer of the relu. in_bias = np.ones(5) observed = dense(in_x, in_weights, in_bias, relu) expected = [1, 11, 11, 1, 0] self.assertTrue(np.allclose(observed, expected)) # For testing flatten we need to test that the # array only flattens everything except the first dimension AND # that the flatten flattens in the correct order # We split the tests by dimensionality to help diagnose any problems. def test_flatten_2d(self): # Creates array that looks like this: # [1, 1, 1] # [2, 2, 2] # [3, 3, 3] column = np.asarray([1, 2, 3]) in_x = np.asarray([column] * 3).T # "Flatten" which does nothing here since we flatten higher dimensions observed = flatten(in_x) expected = in_x self.assertEqual(observed.shape, expected.shape) self.assertTrue(np.allclose(observed, expected)) def test_flatten_3d(self): # Creates the following 3d array: # [[[0 1], [2 3]],[[4 5],[6 7]]] in_x = np.arange(0, 2 * 2 * 2).reshape((2, 2, 2)) # Flatten and test observed = flatten(in_x) expected = np.asarray([[0, 1, 2, 3], [4, 5, 6, 7]]) self.assertEqual(observed.shape, expected.shape) self.assertTrue(np.allclose(observed, expected)) def test_flatten_4d(self): # Creates the following 4d array: # [[[[0 1], [2 3]], [[4 5], [6 7]]], # [[[8 9], [10 11]], [[12 13], [14 15]]]] in_x = np.arange(0, 2 * 2 * 2 * 2).reshape((2, 2, 2, 2)) # Flatten and test observed = flatten(in_x) expected = [[0, 1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14, 15]] expected = np.asarray(expected) self.assertEqual(observed.shape, expected.shape) self.assertTrue(np.allclose(observed, expected)) # This tests batchnormalizing a scalar def test_batch_normalization_scalar(self): eps = 1e-7 # To avoid divide by zero errors x = 3 mu = 2 var = 2 gamma = 1 beta = 0 # First test gamma = 1, beta = 0 so no scaling or offset observed = batch_normalization(x, mu, var, beta, gamma, eps) expected = 1 /
np.sqrt(2)
numpy.sqrt
import os import logging import numpy as np ''' @ Multifactorial Evolutionary Algorithm ''' def sbx_crossover(p1, p2, sbxdi): D = p1.shape[0] cf = np.empty([D]) u = np.random.rand(D) cf[u <= 0.5] = np.power((2 * u[u <= 0.5]), (1 / (sbxdi + 1))) cf[u > 0.5] = np.power((2 * (1 - u[u > 0.5])), (-1 / (sbxdi + 1))) c1 = 0.5 * ((1 + cf) * p1 + (1 - cf) * p2) c2 = 0.5 * ((1 + cf) * p2 + (1 - cf) * p1) c1 = np.clip(c1, 0, 1) c2 = np.clip(c2, 0, 1) return c1, c2 def mutate(p, pmdi): mp = float(1. / p.shape[0]) u = np.random.uniform(size=[p.shape[0]]) r = np.random.uniform(size=[p.shape[0]]) tmp = np.copy(p) for i in range(p.shape[0]): if r[i] < mp: if u[i] < 0.5: delta = (2*u[i]) ** (1/(1+pmdi)) - 1 tmp[i] = p[i] + delta * p[i] else: delta = 1 - (2 * (1 - u[i])) ** (1/(1+pmdi)) tmp[i] = p[i] + delta * (1 - p[i]) return tmp ''' @ other ultilities ''' def find_scalar_fitness(factorial_cost): return 1 / np.min(np.argsort(np.argsort(factorial_cost, axis=0), axis=0) + 1, axis=1) def get_best_individual(population, factorial_cost): K = factorial_cost.shape[1] p_bests = [] y_bests = [] for k in range(K): best_index =
np.argmax(factorial_cost[:, k])
numpy.argmax
# -*- encoding:utf-8 -*- import torch.nn.functional as F import torch.optim.lr_scheduler import numpy as np from uer.models.model import Model from uer.model_builder import build_model from uer.layers.layer_norm import LayerNorm from uer.utils.act_fun import gelu import torch.nn as nn from torch.autograd import Variable from matplotlib.pylab import * def orthonormal_initializer(output_size, input_size): """ adopted from <NAME> https://github.com/tdozat/Parser/blob/master/lib/linalg.py """ print(output_size, input_size) I = np.eye(output_size) lr = .1 eps = .05 / (output_size + input_size) success = False tries = 0 while not success and tries < 10: Q = np.random.randn(input_size, output_size) / np.sqrt(output_size) for i in range(100): QTQmI = Q.T.dot(Q) - I loss = np.sum(QTQmI ** 2 / 2) Q2 = Q ** 2 Q -= lr * Q.dot(QTQmI) / ( np.abs(Q2 + Q2.sum(axis=0, keepdims=True) + Q2.sum(axis=1, keepdims=True) - 1) + eps) if
np.max(Q)
numpy.max
# coding=utf-8 import sys sys.path.insert(0, '/home/chujie/PycharmProjects/amsoftmax_face_recognition_caffe/AM-Softmax-caffe/python') import caffe import cv2 import os import numpy as np import math import copy from numpy.linalg import inv, norm, lstsq from numpy.linalg import matrix_rank as rank of = 0 # 人脸对齐时多裁剪像素点 std_mean = 127.5 std_scale = 0.0078125 batchsize = 128 factor = 0.709 minisize = 30 # 检测人脸的最小值 # pnet pnet_stride = 2 pnet_cell_size = 12 pnet_thread = 0.95 # rnet rnet_thread = 0.95 # onet onet_thread = 0.95 def Align_sphereface(input_image, points, output_size=(96, 112)): image = copy.deepcopy(input_image) src = np.matrix([[points[0], points[2], points[4], points[6], points[8]], [points[1], points[3], points[5], points[7], points[9]], [1, 1, 1, 1, 1]]) dst = np.matrix([[30.2946, 65.5318, 48.0252, 33.5493, 62.7299], [51.6963, 51.5014, 71.7366, 92.3655, 92.2041]]) T = (src * src.T).I * src * dst.T img_affine = cv2.warpAffine(image, T.T, output_size) return img_affine def Align_seqface(input_image, points, output_size=(128, 128)): image = copy.deepcopy(input_image) eye_center_x = (points[0] + points[2]) * 0.5 eye_center_y = (points[1] + points[3]) * 0.5 mouse_center_x = (points[6] + points[8]) * 0.5 mouse_center_y = (points[7] + points[9]) * 0.5 rad_tan = 1.0 * (points[3] - points[1]) / (points[2] - points[0]) rad = math.atan(rad_tan) deg = np.rad2deg(rad) width = int(math.fabs(math.sin(rad)) * image.shape[0] + math.fabs(math.cos(rad)) * image.shape[1]) height = int(math.fabs(math.cos(rad)) * image.shape[0] + math.fabs(math.sin(rad)) * image.shape[1]) transformMat = cv2.getRotationMatrix2D((eye_center_x, eye_center_y), deg, 1.0) dst = cv2.warpAffine(image, transformMat, (width, height)) diff_x = mouse_center_x - eye_center_x diff_y = mouse_center_y - eye_center_y r_mouse_center_y = diff_y * float(math.cos(rad)) - diff_x * float(math.sin(rad)) + eye_center_y d = r_mouse_center_y - eye_center_y + 1 dx = int(d * 3 / 2.0) dy = int(d * 3 / 3.0) x0 = int(eye_center_x) - dx x0 = max(x0, 0) x1 = int(eye_center_x + (3 * d - dx)) - 1 x1 = min(x1, width - 1) y0 = int(eye_center_y) - dy y0 = max(y0, 0) y1 = int(eye_center_y + (3 * d - dy)) - 1 y1 = min(y1, height - 1) alignface = dst[y0:y1, x0:x1, :] alignface = cv2.resize(alignface, (128, 128)) return alignface def CalScale(width, height): scales = [] scale = 12.0 / minisize # 12.0/30 minWH = min(height, width) * scale while minWH >= 12.0: scales.append(scale) minWH *= factor scale *= factor return scales def BBoxRegression(results): for result in results: box = result['faceBox'] bbox_reg = result['bbox_reg'] w = box[2] - box[0] + 1 h = box[3] - box[1] + 1 box[0] += bbox_reg[0] * w box[1] += bbox_reg[1] * h box[2] += bbox_reg[2] * w box[3] += bbox_reg[3] * h return results def BBoxPad(results, width, height): for result in results: box = result['faceBox'] box[0] = round(max(box[0], 0.0)) box[1] = round(max(box[1], 0.0)) box[2] = round(min(box[2], width - 1.0)) box[3] = round(min(box[3], height - 1.0)) return results def BBoxPadSquare(results, width, height): for result in results: box = result['faceBox'] w = box[2] - box[0] + 1; h = box[3] - box[1] + 1; side = max(w, h) box[0] = round(max(box[0] + (w - side) * 0.5, 0)) box[1] = round(max(box[1] + (h - side) * 0.5, 0.)) box[2] = round(min(box[0] + side - 1.0, width - 1.0)) box[3] = round(min(box[1] + side - 1.0, height - 1.0)) return results def NMS(results, thresh, methodType): bboxes_nms = [] if len(results) == 0: return bboxes_nms else: results = sorted(results, key=lambda result: result['bbox_score'], reverse=True) flag = np.zeros_like(results) for index, result_i in enumerate(results): if flag[index] == 0: box_i = result_i['faceBox'] area1 = (box_i[2] - box_i[0] + 1) * (box_i[3] - box_i[1] + 1) bboxes_nms.append(result_i) flag[index] = 1 for j, result_j in enumerate(results): if flag[j] == 0: box_j = result_j['faceBox'] area_intersect = (min(box_i[2], box_j[2]) - max(box_i[0], box_j[0]) + 1) * \ (min(box_i[3], box_j[3]) - max(box_i[1], box_j[1]) + 1) if min(box_i[2], box_j[2]) - max(box_i[0], box_j[0]) < 0: area_intersect = 0.0 area2 = (box_j[2] - box_j[0] + 1) * (box_j[3] - box_j[1] + 1) iou = 0 if methodType == 'u': iou = (area_intersect) * 1.0 / (area1 + area2 - area_intersect) if methodType == 'm': iou = (area_intersect) * 1.0 / min(area1, area2) if iou > thresh: flag[j] = 1 return bboxes_nms def GenerateBBox(confidence, reg, scale, threshold): ch, hs, ws = confidence.shape results = [] for i in range(hs): for j in range(ws): if confidence[1][i][j] > threshold: result = {} box = [] box.append(j * pnet_stride / scale) # xmin box.append(i * pnet_stride / scale) # ymin box.append((j * pnet_stride + pnet_cell_size - 1.0) / scale) # xmax box.append((i * pnet_stride + pnet_cell_size - 1.0) / scale) # ymax result['faceBox'] = box b_reg = [] for k in range(reg.shape[0]): b_reg.append(reg[k][i][j]) result['bbox_reg'] = b_reg result['bbox_score'] = confidence[1][i][j] results.append(result) return results def GetResult_net12(pnet, image): image = (image.copy() - std_mean) * std_scale rows, cols, channels = image.shape scales = CalScale(cols, rows) results = [] for scale in scales: ws = int(math.ceil(cols * scale)) hs = int(math.ceil(rows * scale)) scale_img = cv2.resize(image, (ws, hs), cv2.INTER_CUBIC) tempimg = np.zeros((1, hs, ws, 3)) tempimg[0, :, :, :] = scale_img tempimg = tempimg.transpose(0, 3, 1, 2) pnet.blobs['data'].reshape(1, 3, hs, ws) pnet.blobs['data'].data[...] = tempimg pnet.forward() confidence = copy.deepcopy(pnet.blobs['prob1'].data[0]) reg = copy.deepcopy(pnet.blobs['conv4-2'].data[0]) result = GenerateBBox(confidence, reg, scale, pnet_thread) results.extend(result) res_boxes = NMS(results, 0.7, 'u') res_boxes = BBoxRegression(res_boxes) res_boxes = BBoxPadSquare(res_boxes, cols, rows) return res_boxes def GetResult_net24(rnet, res_boxes, image): image = (image.copy() - std_mean) * std_scale lenth = len(res_boxes) num = int(math.floor(lenth * 1.0 / batchsize)) rnet.blobs['data'].reshape(batchsize, 3, 24, 24) results = [] if len(res_boxes) == 0: return results for i in range(num): tempimg = np.zeros((batchsize, 24, 24, 3)) for j in range(batchsize): box = res_boxes[i * batchsize + j]['faceBox'] roi = copy.deepcopy(image[int(box[1]): int(box[3]), int(box[0]):int(box[2])]) scale_img = cv2.resize(roi, (24, 24)) tempimg[j, :, :, :] = scale_img tempimg = tempimg.transpose(0, 3, 1, 2) rnet.blobs['data'].data[...] = tempimg rnet.forward() confidence = copy.deepcopy(rnet.blobs['prob1'].data[...]) reg = copy.deepcopy(rnet.blobs['conv5-2'].data[...]) for j in range(batchsize): result = {} result['faceBox'] = res_boxes[i * batchsize + j]['faceBox'] b_reg = [] for k in range(reg.shape[1]): b_reg.append(reg[j][k]) result['bbox_reg'] = b_reg result['bbox_score'] = confidence[j][1] if confidence[j][1] > onet_thread: results.append(result) resnum = lenth - num * batchsize if resnum > 0: rnet.blobs['data'].reshape(resnum, 3, 24, 24) tempimg = np.zeros((resnum, 24, 24, 3)) for i in range(resnum): box = res_boxes[num * batchsize + i]['faceBox'] roi = copy.deepcopy(image[int(box[1]): int(box[3]), int(box[0]):int(box[2])]) scale_img = cv2.resize(roi, (24, 24)) tempimg[i, :, :, :] = scale_img tempimg = tempimg.transpose(0, 3, 1, 2) rnet.blobs['data'].data[...] = tempimg rnet.forward() confidence = copy.deepcopy(rnet.blobs['prob1'].data[...]) reg = copy.deepcopy(rnet.blobs['conv5-2'].data[...]) for i in range(resnum): result = {} result['faceBox'] = res_boxes[num * batchsize + i]['faceBox'] b_reg = [] for k in range(reg.shape[1]): b_reg.append(reg[i][k]) result['bbox_reg'] = b_reg result['bbox_score'] = confidence[i][1] if confidence[i][1] > rnet_thread: results.append(result) res_boxes = NMS(results, 0.7, 'u') res_boxes = BBoxRegression(res_boxes) res_boxes = BBoxPadSquare(res_boxes, image.shape[1], image.shape[0]) return res_boxes def GetResult_net48(onet, res_boxes, image): image = (image.copy() - std_mean) * std_scale lenth = len(res_boxes) num = int(math.floor(lenth * 1.0 / batchsize)) onet.blobs['data'].reshape(batchsize, 3, 48, 48) results = [] if len(res_boxes) == 0: return results for i in range(num): tempimg = np.zeros((batchsize, 48, 48, 3)) for j in range(batchsize): box = res_boxes[i * batchsize + j]['faceBox'] roi = copy.deepcopy(image[int(box[1]): int(box[3]), int(box[0]):int(box[2])]) scale_img = cv2.resize(roi, (48, 48)) tempimg[j, :, :, :] = scale_img tempimg = tempimg.transpose(0, 3, 1, 2) onet.blobs['data'].data[...] = tempimg onet.forward() confidence = copy.deepcopy(onet.blobs['prob1'].data[...]) reg = copy.deepcopy(onet.blobs['conv6-2'].data[...]) reg_landmark = copy.deepcopy(onet.blobs["conv6-3"].data[...]) for j in range(batchsize): result = {} result['faceBox'] = res_boxes[i * batchsize + j]['faceBox'] b_reg = [] for k in range(reg.shape[1]): b_reg.append(reg[j][k]) result['bbox_reg'] = b_reg result['bbox_score'] = confidence[j][1] w = result['faceBox'][2] - result['faceBox'][0] + 1 h = result['faceBox'][3] - result['faceBox'][1] + 1 l_reg = [] for l in range(5): l_reg.append(reg_landmark[j][2 * l] * w + result['faceBox'][0]) l_reg.append(reg_landmark[j][2 * l + 1] * h + result['faceBox'][1]) result['landmark_reg'] = l_reg if confidence[j][1] > onet_thread: results.append(result) resnum = lenth - num * batchsize if resnum > 0: onet.blobs['data'].reshape(resnum, 3, 48, 48) tempimg = np.zeros((resnum, 48, 48, 3)) for i in range(resnum): box = res_boxes[num * batchsize + i]['faceBox'] roi = copy.deepcopy(image[int(box[1]): int(box[3]), int(box[0]):int(box[2])].copy()) scale_img = cv2.resize(roi, (48, 48)) tempimg[i, :, :, :] = scale_img tempimg = tempimg.transpose(0, 3, 1, 2) onet.blobs['data'].data[...] = tempimg onet.forward() confidence = copy.deepcopy(onet.blobs['prob1'].data[...]) reg = copy.deepcopy(onet.blobs['conv6-2'].data[...]) reg_landmark = copy.deepcopy(onet.blobs["conv6-3"].data[...]) for i in range(resnum): result = {} result['faceBox'] = res_boxes[num * batchsize + i]['faceBox'] b_reg = [] for k in range(reg.shape[1]): b_reg.append(reg[i][k]) result['bbox_reg'] = b_reg result['bbox_score'] = confidence[i][1] w = result['faceBox'][2] - result['faceBox'][0] + 1 h = result['faceBox'][3] - result['faceBox'][1] + 1 l_reg = [] for k in range(int(reg_landmark.shape[1] / 2)): l_reg.append(reg_landmark[i][2 * k] * w + result['faceBox'][0]) l_reg.append(reg_landmark[i][2 * k + 1] * h + result['faceBox'][1]) result['landmark_reg'] = l_reg if confidence[i][1] > onet_thread: results.append(result) res_boxes = BBoxRegression(results) res_boxes = NMS(res_boxes, 0.7, 'm') res_boxes = BBoxPad(res_boxes, image.shape[1], image.shape[0]) return res_boxes def DetImage(pnet, rnet, onet, image, show=False): results = GetResult_net12(pnet, image) rnet_re = GetResult_net24(rnet, results, image) onet_re = GetResult_net48(onet, rnet_re, image) faceboxs = [] for index, result in enumerate(onet_re): facebox = {} facebox['box'] = result['faceBox'] facebox['landmark'] = result['landmark_reg'] faceboxs.append(facebox) if show: cv2.rectangle(image, (int(facebox['box'][0]), int(facebox['box'][1])), (int(facebox['box'][2]), int(facebox['box'][3])), (0, 0, 255), 1) for i in range(5): cv2.circle(image, (int(facebox['landmark'][2 * i]), int(facebox['landmark'][2 * i + 1])), 2, (55, 255, 155), -1) if show: cv2.imshow('', image) cv2.waitKey(0) return faceboxs def get_similarity_transform_for_cv2(src_pts, dst_pts, reflective=True): def tformfwd(trans, uv): uv = np.hstack((uv, np.ones((uv.shape[0], 1)))) xy = np.dot(uv, trans) xy = xy[:, 0:-1] return xy def tforminv(trans, uv): Tinv = inv(trans) xy = tformfwd(Tinv, uv) return xy def findNonreflectiveSimilarity(uv, xy, options=None): options = {'K': 2} K = options['K'] M = xy.shape[0] x = xy[:, 0].reshape((-1, 1)) # use reshape to keep a column vector y = xy[:, 1].reshape((-1, 1)) # use reshape to keep a column vector tmp1 = np.hstack((x, y, np.ones((M, 1)), np.zeros((M, 1)))) tmp2 = np.hstack((y, -x, np.zeros((M, 1)), np.ones((M, 1)))) X = np.vstack((tmp1, tmp2)) u = uv[:, 0].reshape((-1, 1)) # use reshape to keep a column vector v = uv[:, 1].reshape((-1, 1)) # use reshape to keep a column vector U = np.vstack((u, v)) if rank(X) >= 2 * K: r, _, _, _ = lstsq(X, U) r = np.squeeze(r) else: raise Exception('cp2tform:twoUniquePointsReq') sc = r[0] ss = r[1] tx = r[2] ty = r[3] Tinv = np.array([ [sc, -ss, 0], [ss, sc, 0], [tx, ty, 1] ]) T = inv(Tinv) T[:, 2] = np.array([0, 0, 1]) return T, Tinv def findSimilarity(uv, xy, options=None): options = {'K': 2} # Solve for trans1 trans1, trans1_inv = findNonreflectiveSimilarity(uv, xy, options) # Solve for trans2 # manually reflect the xy data across the Y-axis xyR = xy xyR[:, 0] = -1 * xyR[:, 0] trans2r, trans2r_inv = findNonreflectiveSimilarity(uv, xyR, options) # manually reflect the tform to undo the reflection done on xyR TreflectY = np.array([ [-1, 0, 0], [0, 1, 0], [0, 0, 1] ]) trans2 = np.dot(trans2r, TreflectY) # Figure out if trans1 or trans2 is better xy1 = tformfwd(trans1, uv) norm1 = norm(xy1 - xy) xy2 = tformfwd(trans2, uv) norm2 = norm(xy2 - xy) if norm1 <= norm2: return trans1, trans1_inv else: trans2_inv =
inv(trans2)
numpy.linalg.inv
# -*- coding: utf-8 -*- """ Created on Fri Nov 30 13:44:34 2018 @author: Moha-Thinkpad """ from tensorflow.keras import optimizers from tensorflow.keras.models import Model import datetime import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import tensorflow.keras import argparse import tensorflow as tf from tensorflow.keras import backend as K #cfg = K.tf.ConfigProto() #cfg.gpu_options.allow_growth = True #K.set_session(K.tf.Session(config=cfg)) #################################### ######################################################################## #################################### def custom_loss_seg (y_true, y_pred): #A = tensorflow.keras.losses.mean_squared_error(y_true, y_pred) B = tensorflow.keras.losses.mean_absolute_error(y_true, y_pred) return(B) from tensorflow.keras.layers import Lambda sum_dim_channel = Lambda(lambda xin: K.sum(xin, axis=3)) def lrelu(x): #from pix2pix code a=0.2 # adding these together creates the leak part and linear part # then cancels them out by subtracting/adding an absolute value term # leak: a*x/2 - a*abs(x)/2 # linear: x/2 + abs(x)/2 # this block looks like it has 2 inputs on the graph unless we do this x = tf.identity(x) return (0.5 * (1 + a)) * x + (0.5 * (1 - a)) * tf.abs(x) def lrelu_output_shape(input_shape): shape = list(input_shape) return tuple(shape) layer_lrelu=Lambda(lrelu, output_shape=lrelu_output_shape) def PreProcess(InputImages): #output=np.zeros(InputImages.shape,dtype=np.float) InputImages=InputImages.astype(np.float) for i in range(InputImages.shape[0]): try: InputImages[i,:,:,:]=InputImages[i,:,:,:]/np.max(InputImages[i,:,:,:]) # output[i,:,:,:] = (output[i,:,:,:]* 2)-1 except: InputImages[i,:,:]=InputImages[i,:,:]/np.max(InputImages[i,:,:]) # output[i,:,:] = (output[i,:,:]* 2) -1 return InputImages #################################### ######################################################################## #################################### parser = argparse.ArgumentParser() parser.add_argument("--mode", choices=["train", "test", "export"]) parser.add_argument("--input_dir", help="path to folder containing images") parser.add_argument("--target_dir", help="where to") parser.add_argument("--checkpoint", help="where to ") parser.add_argument("--output_dir", help="where to p") parser.add_argument("--landmarks", help=" -,-,-") parser.add_argument("--lr", help="adam learning rate") parser.add_argument("--ngf", type=int, default=64, help="number of generator filters in first conv layer") # export options a = parser.parse_args() a.batch_size=40 a.max_epochs_seg=1 a.lr_seg=0.0001 a.beta1=0.5 a.ngf=64 #a.seed=1 # a.mode="train" # a.input_dir='C:\\Users\\User\\Desktop\\Example_LoSoCo_Inputs_3_large_heatmaps/temp_train_png/' # a.target_dir='C:\\Users\\User\\Desktop\\Example_LoSoCo_Inputs_3_large_heatmaps/temp_train_lm/' # a.checkpoint='C:\\Users\\User\\Desktop\\Example_LoSoCo_Inputs_3_large_heatmaps/Models_lm/' # a.output_dir='C:\\Users\\User\\Desktop\\Example_LoSoCo_Inputs_3_large_heatmaps/Models_lm/' # a.landmarks='43,43,43' #a.mode="test" #a.batch_size=1 #a.input_dir='C:\\Users\\User\\Desktop\\Example_LoSoCo_Inputs_3_large_heatmaps/temp_test_png/' #a.target_dir='C:\\Users\\User\\Desktop\\Example_LoSoCo_Inputs_3_large_heatmaps/temp_test_lm/' #a.checkpoint='C:\\Users\\User\\Desktop\\Example_LoSoCo_Inputs_3_large_heatmaps/Models_lm/' #a.output_dir='C:\\Users\\User\\Desktop\\Example_LoSoCo_Inputs_3_large_heatmaps/Models_lm/' #a.landmarks='43,43,43' ######## ------------ Config #Ind_impo_landmarks_matlab=np.array([5, 6, 15,16,17,18,20,21,22,23,24,25,26,27,28,29,30,32,33,34,35,36,37,38,41]) #Ind_impo_landmarks_python=Ind_impo_landmarks_matlab-1 #Num_landmarks=25 # 33,23,16 - 29,15, - 30,20,26 - 5,18,21 - 44,17,41 - 28,22,34, - 27,43,37 StrLandmarks=a.landmarks StrLandmarks=StrLandmarks.split(",") Ind_impo_landmarks_matlab=np.array([0,0,0]) Ind_impo_landmarks_matlab[0]=int(StrLandmarks[0]) Ind_impo_landmarks_matlab[1]=int(StrLandmarks[1]) Ind_impo_landmarks_matlab[2]=int(StrLandmarks[2]) Ind_impo_landmarks_python=Ind_impo_landmarks_matlab-1 Num_landmarks=3 print('============================') print('============================') print(datetime.datetime.now()) print('============================') print('============================') #########----------------------DATA from os import listdir ImageFileNames=[] FileNames=listdir(a.input_dir) for names in FileNames: if names.endswith(".png"): ImageFileNames.append(names) #LMFileNames=listdir(a.target_dir) from skimage import io as ioSK from numpy import genfromtxt Images=np.zeros((len(ImageFileNames),256,256,3),dtype=np.uint8) #Images_seg=np.zeros((len(ImageFileNames),256,256),dtype=np.uint8) LandmarkLocations=np.zeros((len(ImageFileNames),2,44),dtype=np.uint8) for i in range(len(ImageFileNames)): Image = ioSK.imread(a.input_dir+'/'+ImageFileNames[i]) Images[i,:,:,:]=Image FileName=ImageFileNames[i] FileName=FileName[:-4] # Image = ioSK.imread(a.target_dir_seg+'/'+ImageFileNames[i]) # Images_seg[i,:,:]=Image Landmarks0 =
genfromtxt(a.target_dir+'/'+FileName+'.csv', delimiter=',')
numpy.genfromtxt
import numpy as np import os import requests from matplotlib import pyplot as plt from matplotlib import cm from lmfit.models import Model from sklearn.cluster import KMeans from shapely.geometry import Polygon from radio_beam.commonbeam import getMinVolEllipse from scipy import ndimage as ndi from scipy.spatial import distance from skimage import io from skimage.measure import EllipseModel from skimage.color import rgb2gray from skimage import filters, util from skimage.morphology import disk, skeletonize, ball from skimage.measure import approximate_polygon from skimage import transform from PIL import Image, ImageDraw, ImageFilter, ImageOps from sklearn.linear_model import LinearRegression from scipy import ndimage import copy import cv2 from scipy.spatial import ConvexHull import sys import logging import time import glob from logging import StreamHandler, Formatter from src.cfg import CfgAnglesNames, CfgBeamsNames, CfgDataset handler = StreamHandler(stream=sys.stdout) handler.setFormatter(Formatter(fmt='[%(asctime)s: %(levelname)s] %(message)s')) logger = logging.getLogger(__name__) logger.addHandler(handler) file_path = os.getcwd() + '/utils.py' class grainPreprocess(): @classmethod def imdivide(cls, image: np.ndarray, h: int, side: str) -> np.ndarray: """ :param image: ndarray (height,width,channels) :param h: int scalar :param side: str 'left' :return: ndarray (height,width/2,channels) """ # # возвращает левую или правую часть полученного изображения # height, width = image.shape sides = {'left': 0, 'right': 1} shapes = [(0, height - h, 0, width // 2), (0, height - h, width // 2, width)] shape = shapes[sides[side]] return image[shape[0]:shape[1], shape[2]:shape[3]] @classmethod def combine(cls, image: np.ndarray, h: int, k=0.5) -> np.ndarray: """ :param image: ndarray (height,width,channels) :param h: int scalar :param k: float scalar :return: ndarray (height,width/2,channels) """ # # накладывает левую и правые части изображения # если k=1, то на выходе будет левая часть изображения, если k=0, то будет правая часть # left_img = cls.imdivide(image, h, 'left') right_img = cls.imdivide(image, h, 'right') l = k r = 1 - l gray = np.array(left_img) * l gray += np.array(right_img) * r return gray.astype('uint8') @classmethod def do_otsu(cls, img: np.ndarray) -> np.ndarray: """ :param img: ndarray (height,width,channels) :return: ndarray (height,width), Boolean """ # # бинаризация отсу # global_thresh = filters.threshold_otsu(img) binary_global = img > global_thresh return binary_global.astype('uint8') @classmethod def image_preprocess(cls, image: np.ndarray) -> np.ndarray: """ :param image: ndarray (height,width,channels) :return: ndarray (height,width) """ # # комбинация медианного фильтра, биноризации и гражиента # у зерен значение пикселя - 0, у регионов связ. в-ва - 127,а у их границы - 254 # unsigned_image = util.img_as_ubyte(image) denoised = filters.rank.median(unsigned_image, ball(3)) binary = cls.do_otsu(denoised) grad = abs(filters.rank.gradient(binary, ball(1))) bin_grad = (1 - binary + grad) * 127 return bin_grad.astype(np.uint8) @classmethod def image_preprocess_kmeans(cls, image: np.ndarray, h=135, k=1, n_clusters=3, pos=1) -> np.ndarray: """ :param image: array (height,width,channels) :param h: int scalar :param k: float scalar :param n_clusters: int scalar :param pos: int scalar, cluster index :return: ndarray (height,width) """ # # выделение границ при помощи кластеризации # и выравнивание шума медианным фильтром # pos отвечает за выбор кластера, который будет отображен на возвращенном изображении # combined = cls.combine(image, h, k) clustered, colors = grainMorphology.kmeans_image(combined, n_clusters) cluster = clustered == colors[pos] cluster = np.array(cluster * 255, dtype='uint8') new_image = filters.median(cluster, disk(2)) return new_image @classmethod def read_preprocess_data(cls, images_dir, max_images_num_per_class=100, preprocess=False, save=False, crop_bottom=False, h=135, resize=True, resize_shape=None, save_name='all_images.npy'): folders_names = glob.glob(images_dir + '*') images_paths = [glob.glob(folder_name + '/*')[:max_images_num_per_class] for folder_name in folders_names] l = np.array(images_paths).flatten().shape[0] # Initial call to print 0% progress GrainLogs.printProgressBar(0, l, prefix='Progress:', suffix='Complete', length=50) preproc_images = [] start_time = time.time() step = 0 for i, images_list_paths in enumerate(images_paths): preproc_images.append([]) for image_path in images_list_paths: step += 1 image = io.imread(image_path).astype(np.uint8) # вырезает нижнюю полоску фотографии с линекой и тд if crop_bottom: image = grainPreprocess.combine(image, h) # ресайзит изображения if resize: if resize_shape is not None: image = transform.resize(image, resize_shape) else: print('No resize shape') # последовательно применяет фильтры (медианный, отсу, собель и тд) if preprocess: image = grainPreprocess.image_preprocess(image) end_time = time.time() eta = round((end_time - start_time) * (l - step), 1) GrainLogs.printProgressBar(step, l, eta=eta, prefix='Progress:', suffix='Complete', length=50) start_time = time.time() preproc_images[i].append(image) if save: np.save(save_name, preproc_images) return preproc_images @classmethod def tiff2jpg(cls, folder_path, start_name=0, stop_name=-4, new_folder_path='resized'): # # переводит из tiff 2^16 в jpg 2^8 бит # folders = os.listdir(folder_path) if not os.path.exists(new_folder_path): os.mkdir(new_folder_path) for folder in folders: if not os.path.exists(new_folder_path + '/' + folder): os.mkdir(new_folder_path + '/' + folder) for i, folder in enumerate(folders): images_names = os.listdir(folder_path + '/' + folder) for i, name in enumerate(images_names): if 'hdr' not in name: img = io.imread(folder_path + '/' + folder + '/' + name) img = (img / 255).astype('uint8') io.imsave(new_folder_path + '/' + folder + '/' + name[start_name:stop_name] + '.jpg', img) @classmethod def get_example_images(cls): ''' :return: ndarray [[img1],[img2]..] ''' # # скачивает из контейнера s3 по 1 снимку каждого образца # urls = CfgDataset.images_urls images = [] for url in urls: logger.warning(f'downloading {url}') file = requests.get(url, stream=True).raw img = np.asarray(Image.open(file)) images.append([img]) return np.array(images) class grainMorphology(): @classmethod def kmeans_image(cls, image, n_clusters=3): # # кластеризует при помощи kmeans # и возвращает изображение с нанесенными цветами кластеров # img = image.copy() size = img.shape img = img.reshape(-1, 1) model = KMeans(n_clusters=n_clusters) clusters = model.fit_predict(img) colors = [] for i in range(n_clusters): color = np.median(img[clusters == i]) # медианное значение пикселей у кластера img[clusters == i] = color colors.append(int(color)) img = img.reshape(size) colors.sort() return img, colors class grainFig(): @classmethod def line(cls, point1, point2): # # возвращает растровые координаты прямой между двумя точками # line = [] x1, y1 = point1[0], point1[1] x2, y2 = point2[0], point2[1] dx = x2 - x1 dy = y2 - y1 sign_x = 1 if dx > 0 else -1 if dx < 0 else 0 sign_y = 1 if dy > 0 else -1 if dy < 0 else 0 if dx < 0: dx = -dx if dy < 0: dy = -dy if dx > dy: pdx, pdy = sign_x, 0 es, el = dy, dx else: pdx, pdy = 0, sign_y es, el = dx, dy x, y = x1, y1 error, t = el / 2, 0 line.append((x, y)) while t < el: error -= es if error < 0: error += el x += sign_x y += sign_y else: x += pdx y += pdy t += 1 line.append((x, y)) return np.array(line).astype('int') @classmethod def rect(cls, point1, point2, r): # # возвращает растровые координаты прямоугольника ширины 2r, # построеного между двумя точками # x1, y1 = point1[0], point1[1] x2, y2 = point2[0], point2[1] l1, l2 = (x2 - x1), (y2 - y1) l_len = (l1 ** 2 + l2 ** 2) ** 0.5 l_len = int(l_len) a = (x1 - r * l2 / l_len), (y1 + r * l1 / l_len) b = (x1 + r * l2 / l_len), (y1 - r * l1 / l_len) side = cls.line(a, b) # a -> c lines = np.zeros((side.shape[0], l_len * 2, 2), dtype='int64') for i, left_point in enumerate(side): right_point = (left_point[0] + l1), (left_point[1] + l2) line_points = cls.line(left_point, right_point) for j, point in enumerate(line_points): lines[i, j] = point return lines class grainMark(): @classmethod def mark_corners_and_classes(cls, image, max_num=100000, sens=0.1, max_dist=1): # # НЕТ ГАРАНТИИ РАБОТЫ # corners = cv2.goodFeaturesToTrack(image, max_num, sens, max_dist) corners = np.int0(corners) x = copy.copy(corners[:, 0, 1]) y = copy.copy(corners[:, 0, 0]) corners[:, 0, 0], corners[:, 0, 1] = x, y classes = filters.rank.gradient(image, disk(1)) < 250 classes, num = ndi.label(classes) return corners, classes, num @classmethod def mean_pixel(cls, image, point1, point2, r): val2, num2 = cls.draw_rect(image, point2, point1, r) val = val1 + val2 num = num1 + num2 if num != 0 and val != 0: mean = (val / num) / 255 dist = distance.euclidean(point1, point2) else: mean = 1 dist = 1 return mean, dist @classmethod def get_row_contours(cls, image): """ :param image: ndarray (width, height,3) :return: list (N_contours,M_points,2) where ndarray (M_points,2) """ # # возвращает набор точек контуров # edges = cv2.Canny(image, 0, 255, L2gradient=False) # направление обхода контура по часовой стрелке contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) new_contours = [] for cnt in contours: new_contours.append(np.array(cnt).reshape((-1, 2))) return new_contours @classmethod def get_contours(cls, image, tol=3): """ :param tol: :param image: ndarray (width, height,3) :return: list (N_contours,M_points,2) where ndarray (M_points,2) """ # # уменьшение количества точек контура при помощи алгоритма Дугласа-Пекера # contours = cls.get_row_contours(image) new_contours = [] for j, cnt in enumerate(contours): if len(cnt) > 2: coords = approximate_polygon(cnt, tolerance=tol) new_contours.append(coords) else: continue return new_contours @classmethod def get_angles(cls, image, thr=5): # # считаем углы с направлением обхода контура против часовой стрелки, углы >180 градусов учитываются # approx = cls.get_contours(image, tol=4) # вычисление угла angles = [] angles_pos = [] for k, cnt in enumerate(approx): if len(cnt) > 2: for i, point in enumerate(cnt[:-1]): point1 = cnt[i - 1] point2 = cnt[i] point3 = cnt[i + 1] x1, y1 = point1[1], point1[0] x2, y2 = point2[1], point2[0] x3, y3 = point3[1], point3[0] # убирает контуры у границ if abs(x2 - image.shape[0] - 1) > thr and \ abs(y2 - image.shape[1] - 1) > thr and \ x2 > thr and y2 > thr: v1 = np.array((x1 - x2, y1 - y2)).reshape(1, 2) v2 = np.array((x3 - x2, y3 - y2)).reshape(1, 2) dot = np.dot(v1[0], v2[0]) dist1 = np.linalg.norm(v1[0]) dist2 = np.linalg.norm(v2[0]) cos = dot / (dist1 * dist2) v = np.concatenate([v1, v2]) det = np.linalg.det(v) if abs(cos) < 1: ang = int(np.arccos(cos) * 180 / np.pi) if det < 0: angles.append(ang) angles_pos.append([(x1, y1), (x2, y2), (x3, y3)]) else: angles.append(360 - ang) angles_pos.append([(x1, y1), (x2, y2), (x3, y3)]) else: if det < 0: angles.append(360) angles_pos.append([(x1, y1), (x2, y2), (x3, y3)]) else: angles.append(0) angles_pos.append([(x1, y1), (x2, y2), (x3, y3)]) return np.array(angles), angles_pos @classmethod def get_mvee_params(cls, image, tol=0.2, debug=False): """ :param image: :param tol: :return: ndarray (n_angles), radian """ # # возвращает полуоси и угол поворота фигуры minimal volume enclosing ellipsoid, # которая ограничивает исходные точки контура эллипсом # approx = grainMark.get_row_contours(image) a_beams = [] b_beams = [] angles = [] centroids = [] for i, cnt in enumerate(approx): if len(cnt) > 2: try: cnt = np.array(cnt) polygon = Polygon(cnt) x_centroid, y_centroid = polygon.centroid.coords[0] points = cnt - (x_centroid, y_centroid) x_norm, y_norm = points.mean(axis=0) points = (points - (x_norm, y_norm)) data = getMinVolEllipse(points, tol) xc, yc = data[0][0] a, b = data[1] sin = data[2][0][1] angle = -np.arcsin(sin) a_beams.append(a) b_beams.append(b) angles.append(angle) centroids.append([x_centroid + x_norm, y_centroid + y_norm]) except Exception: if debug: logger.warning(f'{file_path} error i={i}, singularity matrix error, no reason why', exc_info=debug) a_beams = np.array(a_beams, dtype='int32') b_beams = np.array(b_beams, dtype='int32') angles = np.array(angles, dtype='float32') centroids = np.array(centroids, dtype='int32') return a_beams, b_beams, angles, centroids @classmethod def skeletons_coords(cls, image): # # на вход подается бинаризованное изображение # создает массив индивидуальных скелетов # пикселю скелета дается класс, на координатах которого он находится # координаты класса определяются ndi.label # skeleton = np.array(skeletonize(image)) labels, classes_num = ndimage.label(image) bones = [[] for i in range(classes_num + 1)] for i in range(skeleton.shape[0]): for j in range(skeleton.shape[1]): if skeleton[i, j]: label = labels[i, j] bones[label].append((i, j)) return bones class grainShow(): @classmethod def img_show(cls, image, N=20, cmap=plt.cm.nipy_spectral): # # выводит изображение image # plt.figure(figsize=(N, N)) plt.axis('off') plt.imshow(image, cmap=cmap) plt.show() @classmethod def enclosing_ellipse_show(cls, image, pos=0, tolerance=0.2, N=15): # # рисует график точек многоугольника и описанного эллипса # a_beams, b_beams, angles, cetroids = grainMark.get_mvee_params(image, tolerance) approx = grainMark.get_row_contours(image) a = a_beams[pos] b = b_beams[pos] angle = angles[pos] print('полуось а ', a) print('полуось b ', b) print('угол поворота ', round(angle, 3), ' радиан') cnt = np.array(approx[pos]) xp = cnt[:, 0] yp = cnt[:, 1] xc = cetroids[pos, 0] yc = cetroids[pos, 1] x, y = grainStats.ellipse(a, b, angle) plt.figure(figsize=(N, N)) plt.plot(xp - xc, yp - yc) plt.scatter(0, 0) plt.plot(x, y) plt.show() class grainDraw(): @classmethod def draw_corners(cls, image, corners, color=255): # # НЕТ ГАРАНТИИ РАБОТЫ # image = copy.copy(image) for i in corners: x, y = i.ravel() cv2.circle(image, (x, y), 3, color, -1) return image @classmethod def draw_edges(cls, image, cnts, color=(50, 50, 50)): # # рисует на изображении линии по точкам контура cnts # линии в стиле x^1->x^2,x^2->x^3 и тд # new_image = copy.copy(image) im = Image.fromarray(np.uint8(cm.gist_earth(new_image) * 255)) draw = ImageDraw.Draw(im) for j, cnt in enumerate(cnts): if len(cnt) > 1: point = cnt[0] x1, y1 = point[1], point[0] r = 4 for i, point2 in enumerate(cnt): p2 = point2 x2, y2 = p2[1], p2[0] draw.ellipse((y2 - r, x2 - r, y2 + r, x2 + r), fill=color, width=5) draw.line((y1, x1, y2, x2), fill=(100, 100, 100), width=4) x1, y1 = x2, y2 else: continue img = np.array(im) return img @classmethod def draw_tree(cls, img, centres=False, leafs=False, nodes=False, bones=False): # # на вход подается биноризованное изображение # рисует на инвертированном изображении # скелет и точки центров, листьев, узлов и пикселей скелета # image = img.copy() / 255 skeleton = np.array(skeletonize(image)) * 255 im = 1 - image + skeleton im = Image.fromarray(np.uint8(cm.gist_earth(im) * 255)) draw = ImageDraw.Draw(im) if bones: for j, bone in enumerate(bones): for i, point in enumerate(bone): x2, y2 = point r = 1 draw.ellipse((y2 - r, x2 - r, y2 + r, x2 + r), fill=(89, 34, 0), width=5) if centres: for j, point in enumerate(centres): x2, y2 = point r = 2 draw.ellipse((y2 - r, x2 - r, y2 + r, x2 + r), fill=(255, 0, 0), width=5) if leafs: for j, leaf in enumerate(leafs): for i, point in enumerate(leaf): x2, y2 = point r = 2 draw.ellipse((y2 - r, x2 - r, y2 + r, x2 + r), fill=(0, 255, 0), width=5) if nodes: for j, node in enumerate(nodes): for i, point in enumerate(node): x2, y2 = point r = 2 draw.ellipse((y2 - r, x2 - r, y2 + r, x2 + r), fill=(0, 0, 255), width=10) return np.array(im) class grainStats(): @classmethod def kernel_points(cls, image, point, step=1): # # возвращает координаты пикселей матрицы, # центр которой это point # x, y = point coords = [] for xi in range(x - step, x + step + 1): for yi in range(y - step, y + step + 1): if xi < image.shape[0] and yi < image.shape[1]: coords.append((xi, yi)) return coords @classmethod def stats_preprocess(cls, array, step): # # приведение углов к кратости, например 0,step,2*step и тд # array_copy = array.copy() if step != 0: for i, a in enumerate(array_copy): while array_copy[i] % step != 0: array_copy[i] += 1 array_copy_set = np.sort(np.array(list(set(array_copy)))) dens_curve = [] for arr in array_copy_set: num = 0 for ar in array_copy: if arr == ar: num += 1 dens_curve.append(num) return np.array(array_copy), array_copy_set, np.array(dens_curve) else: print('step is 0, stats preprocess error') @classmethod def gaussian(cls, x, mu, sigma, amp=1): # # возвращает нормальную фунцию по заданным параметрам # return np.array((amp / (np.sqrt(2 * np.pi) * sigma)) * np.exp(-(x - mu) ** 2 / (2 * sigma ** 2))) @classmethod def gaussian_bimodal(cls, x, mu1, mu2, sigma1, sigma2, amp1=1, amp2=1): # # возвращает бимодальную нормальную фунцию по заданным параметрам # return cls.gaussian(x, mu1, sigma1, amp1) + cls.gaussian(x, mu2, sigma2, amp2) @classmethod def gaussian_termodal(cls, x, mu1, mu2, mu3, sigma1, sigma2, sigma3, amp1=1, amp2=1, amp3=1): # # возвращает термодальную нормальную фунцию по заданным параметрам # return cls.gaussian(x, mu1, sigma1, amp1) + cls.gaussian(x, mu2, sigma2, amp2) + cls.gaussian(x, mu3, sigma3, amp3) @classmethod def ellipse(cls, a, b, angle, xc=0, yc=0, num=50): # # возвращает координаты эллипса, построенного по заданным параметрам # по умолчанию центр (0,0) # угол в радианах, уменьшение угла обозначает поворот эллипса по часовой стрелке # xy = EllipseModel().predict_xy(np.linspace(0, 2 * np.pi, num), params=(xc, yc, a, b, angle)) return xy[:, 0], xy[:, 1] class grainApprox(): @classmethod def gaussian_fit(cls, x, y, mu=1, sigma=1, amp=1): # # аппроксимация заданных точек нормальной функцией # gmodel = Model(grainStats.gaussian) res = gmodel.fit(y, x=x, mu=mu, sigma=sigma, amp=amp) mu = res.params['mu'].value sigma = res.params['sigma'].value amp = res.params['amp'].value return mu, sigma, amp @classmethod def gaussian_fit_bimodal(cls, x, y, mu1=100, mu2=240, sigma1=30, sigma2=30, amp1=1, amp2=1): # # аппроксимация заданных точек бимодальной нормальной функцией # gmodel = Model(grainStats.gaussian_bimodal) res = gmodel.fit(y, x=x, mu1=mu1, mu2=mu2, sigma1=sigma1, sigma2=sigma2, amp1=amp1, amp2=amp2) mus = [res.params['mu1'].value, res.params['mu2'].value] sigmas = [res.params['sigma1'].value, res.params['sigma2'].value] amps = [res.params['amp1'].value, res.params['amp2'].value] return mus, sigmas, amps @classmethod def gaussian_fit_termodal(cls, x, y, mu1=10, mu2=100, mu3=240, sigma1=10, sigma2=30, sigma3=30, amp1=1, amp2=1, amp3=1): # # аппроксимация заданных точек термодальной нормальной функцией # gmodel = Model(grainStats.gaussian_termodal) res = gmodel.fit(y, x=x, mu1=mu1, mu2=mu2, mu3=mu3, sigma1=sigma1, sigma2=sigma2, sigma3=sigma3, amp1=amp1, amp2=amp2, amp3=amp3) mus = [res.params['mu1'].value, res.params['mu2'].value, res.params['mu3'].value] sigmas = [res.params['sigma1'].value, res.params['sigma2'].value, res.params['sigma3'].value] amps = [res.params['amp1'].value, res.params['amp2'].value, res.params['amp3'].value] return mus, sigmas, amps @classmethod def lin_regr_approx(cls, x, y): # # аппроксимация распределения линейной функцией # и создание графика по параметрам распределения # x_pred = np.linspace(x.min(axis=0), x.max(axis=0), 50) reg = LinearRegression().fit(x, y) y_pred = reg.predict(x_pred) k = reg.coef_[0][0] b = reg.predict([[0]])[0][0] angle = np.rad2deg(np.arctan(k)) score = reg.score(x, y) return (x_pred, y_pred), k, b, angle, score @classmethod def bimodal_gauss_approx(cls, x, y): # # аппроксимация распределения бимодальным гауссом # mus, sigmas, amps = cls.gaussian_fit_bimodal(x, y) x_gauss = np.arange(0, 361) y_gauss = grainStats.gaussian_bimodal(x_gauss, mus[0], mus[1], sigmas[0], sigmas[1], amps[0], amps[1]) return (x_gauss, y_gauss), mus, sigmas, amps class grainGenerate(): @classmethod def angles_legend(cls, images_amount, name, itype, step, mus, sigmas, amps, norm, ): # # создание легенды распределения углов # mu1 = round(mus[0], 2) sigma1 = round(sigmas[0], 2) amp1 = round(amps[0], 2) mu2 = round(mus[1], 2) sigma2 = round(sigmas[1], 2) amp2 = round(amps[1], 2) val = round(norm, 4) border = '--------------\n' total_number = '\n количество углов ' + str(val) images_number = '\n количество снимков ' + str(images_amount) text_angle = '\n шаг угла ' + str(step) + ' градусов' moda1 = '\n mu1 = ' + str(mu1) + ' sigma1 = ' + str(sigma1) + ' amp1 = ' + str(amp1) moda2 = '\n mu2 = ' + str(mu2) + ' sigma2 = ' + str(sigma2) + ' amp2 = ' + str(amp2) legend = border + name + ' ' + itype + total_number + images_number + text_angle + moda1 + moda2 return legend @classmethod def angles_approx_save(cls, folder, images, names, types, step, save=True): """ :param folder: str path to dir :param images: ndarray uint8 [[image1_class1,image2_class1,..],[image1_class2,image2_class2,..]..] :param names: list str [class_name1,class_name2,..] :param types: list str [class_type1,class_type2,..] :param step: scalar int [0,N] :param save: bool :return: ndarray uint8 (n_classes,n_samples, height, width) """ # # вывод распределения углов для всех фотографий одного образца # texts = [] xy_scatter = [] xy_gauss = [] xy_gauss_data = [] if not os.path.exists(folder): os.mkdir(folder) start_time = 0 progress_bar_step = 0 l = images.shape[0] * images.shape[1] GrainLogs.printProgressBar(0, l, prefix='Progress:', suffix='Complete', length=30) for i, images_list in enumerate(images): all_original_angles = [] for j, image in enumerate(images_list): original_angles, _ = grainMark.get_angles(image) end_time = time.time() progress_bar_step += 1 eta = round((end_time - start_time) * (l - 1 - progress_bar_step), 1) # print('eta: ', eta) # вывод времени не работает, пофиксить потом GrainLogs.printProgressBar(progress_bar_step, l, prefix='Progress:', suffix='Complete', length=30) start_time = time.time() for angle in original_angles: all_original_angles.append(angle) angles, angles_set, dens_curve = grainStats.stats_preprocess(all_original_angles, step) x = angles_set.astype(np.float64) y = dens_curve norm = np.sum(y) y = y / norm (x_gauss, y_gauss), mus, sigmas, amps = grainApprox.bimodal_gauss_approx(x, y) text = grainGenerate.angles_legend(len(images_list), names[i], types[i], step, mus, sigmas, amps, norm) xy_gauss.append((x_gauss, y_gauss)) xy_scatter.append((x, y)) xy_gauss_data.append(( (mus[0], sigmas[0], amps[0]), (mus[1], sigmas[1], amps[1]) )) texts.append(text) if save: np.save(f'{folder}/' + CfgAnglesNames.values + f'{step}.npy', np.array(xy_scatter, dtype=object)) np.save(f'{folder}/' + CfgAnglesNames.approx + f'{step}.npy', np.array(xy_gauss)) np.save(f'{folder}/' + CfgAnglesNames.approx_data + f'{step}.npy', np.array(xy_gauss_data)) np.save(f'{folder}/' + CfgAnglesNames.legend + f'{step}.npy', np.array(texts)) @classmethod def beams_legend(cls, name, itype, norm, k, angle, b, score, dist_step, dist_mean): # # создание легенды для распределения длин полуосей # border = '--------------' tp = '\n ' + name + ' тип ' + itype num = '\n регионы Co ' + str(norm) + ' шт' lin_k = '\n k наклона ' + str(round((k), 3)) + ' сдвиг b ' + str(round(b, 3)) lin_k_angle = '\n угол наклона $' + str(round(angle, 3)) + '^{\circ}$' acc = '\n точность ' + str(round(score, 2)) text_step = '\n шаг длины ' + str(dist_step) + '$ мкм$' mean_text = '\n средняя длина ' + str(round(dist_mean, 2)) legend = border + tp + lin_k + lin_k_angle + acc + num + text_step + mean_text return legend @classmethod def diametr_approx_save(cls, folder, images, names, types, step, pixel, start=2, end=-3, save=True, debug=False): # # вывод распределения длин а- и б- полуосей для разных образцов # texts = [] xy_scatter = [] xy_linear = [] xy_linear_data = [] l = images.shape[0] * images.shape[1] GrainLogs.printProgressBar(0, l, prefix='Progress:', suffix='Complete', length=30) progress_bar_step = 0 start_time = 0 angles = None for i, images_list in enumerate(images): all_a_beams = [] all_b_beams = [] for j, image in enumerate(images_list): a_beams, b_beams, angles, cetroids = grainMark.get_mvee_params(image, 0.2, debug=debug) progress_bar_step += 1 end_time = time.time() eta = round((end_time - start_time) * (l - 1 - progress_bar_step), 1) # print('eta: ', eta) # вывод времени не работает, пофиксить потом GrainLogs.printProgressBar(progress_bar_step, l, prefix='Progress:', suffix='Complete', length=30) start_time = time.time() for k in range(len(a_beams)): all_a_beams.append(a_beams[k]) all_b_beams.append(b_beams[k]) distances1, dist1_set, dens1_curve = grainStats.stats_preprocess(all_a_beams, step) distances2, dist2_set, dens2_curve = grainStats.stats_preprocess(all_b_beams, step) angles, angles_set, angles_dens_curve = grainStats.stats_preprocess(np.rad2deg(angles).astype('int32'), step=step) norm1 = round(
np.sum(dens1_curve)
numpy.sum
import math import numbers import numpy as np import pandas as pd import lmfit as lm from scipy.spatial.transform import Rotation import scipy.optimize as optimize import pypdt from .conversions import one_gev_c2_to_kg, one_kgm_s_to_mev_c, q_factor from scipy.constants import c cbar = c / 1.e9 cmmns = c / 1.e6 m_e = pypdt.get(11).mass*1000. q_e = -1 # fitting routine def fit_helix(track_data, B_data, m=m_e, q=q_e, rot=True): ''' track_data is 4 by N np.array, B_data is 3 by N where each row is track_data: [t, x, y, z] with units [s, m, m, m] B_data: [Bx, By, Bz] with units [T, T, T] (to work out of the box with emtracks.particle) ''' track_data = track_data.copy() # to not change track_data information track_data[0] = track_data[0]*1e9 # convert to ns track_data[1:] = track_data[1:]*1e3 # convert to mm # x0, y0 = track_data[1:3,0] # for phi0 estimate # translations: translate_vec = track_data[:,0].reshape(1, 4) track_data = track_data - np.repeat(translate_vec, track_data.shape[1], axis=0).T # Rotate so mean B vector is on z-axis B_mean = np.mean(B_data, axis=1) B = np.linalg.norm(B_mean) B_mean_T = np.linalg.norm(B_mean[:2]) # average transverse Bfield (original coords) # calculate rotation angles rot_theta = np.arctan2(B_mean_T, B_mean[2]) rot_phi = np.arctan2(B_mean[1], B_mean[0]) # create rotation function (+inverse) to align mean B with z axis rot_func = Rotation.from_euler('zy',
np.array([-rot_phi, -rot_theta])
numpy.array
""" This script is a demo script, showing how to use eslearn to training and testing a SVC model. Classifier: linear SVC Dimension reduction: PCA Feature selection: ReliefF """ import numpy as np import eslearn.machine_learning.classfication.pca_relieff_svc_cv as pca_relieff_svc # ============================================================================= # All inputs path_patients = r'D:\WorkStation_2018\Workstation_Old\WorkStation_2018-05_MVPA_insomnia_FCS\Degree\degree_gray_matter\Zdegree\Z_degree_patient\Weighted' # .nii format path_HC = r'D:\WorkStation_2018\Workstation_Old\WorkStation_2018-05_MVPA_insomnia_FCS\Degree\degree_gray_matter\Zdegree\Z_degree_control\Weighted' # .nii format path_mask = r'G:\Softer_DataProcessing\spm12\spm12\tpm\Reslice3_TPM_greaterThan0.2.nii' # mask file for filter image path_out = r'D:\WorkStation_2018\Workstation_Old\WorkStation_2018-05_MVPA_insomnia_FCS\Degree\degree_gray_matter\Zdegree' # directory for saving results # ============================================================================= clf = pca_relieff_svc.PcaReliffSvcCV( path_patients=path_patients, path_HC=path_HC, path_mask=path_mask, path_out=path_out, data_preprocess_method='MinMaxScaler', data_preprocess_level='group', num_of_kfold=5, # How many folds to perform cross validation (Default: 5-fold cross validation) is_dim_reduction=1, # Default is using PCA to reduce the dimension. components=0.75, is_feature_selection=False, # Whether perform feature selection( Default is using relief-based feature selection algorithms). n_features_to_select=0.99, # How many features to be selected. is_showfig_finally=True, # Whether show results figure finally. is_showfig_in_each_fold=False # Whether show results in each fold. ) results = clf.main_function() results = results.__dict__ print(f"mean accuracy = {np.mean(results['accuracy'])}") print(f"std of accuracy = {np.std(results['accuracy'])}") print(f"mean sensitivity = {np.mean(results['sensitivity'])}") print(f"std of sensitivity = {np.std(results['sensitivity'])}") print(f"mean specificity = {
np.mean(results['specificity'])
numpy.mean
# Copyright 2018- Onai (Onu Technology, Inc., San Jose, California) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is furnished # to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A # PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ Rounding """ from sklearn.cluster import KMeans import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as pp import numpy as np N = int(128000) N_BINS = 128 N_ROUNDS = 100 AMT = 10 ** 6 def generate_amts(): return np.random.randint(AMT, size=N) / AMT def cluster_amts(amts): setup = KMeans(n_clusters=N_BINS) clusters = setup.fit(amts.reshape(-1, 1)) centers = clusters.cluster_centers_.squeeze() plot_cents(centers) return ( clusters.cluster_centers_, clusters.labels_, get_cluster_sums(amts, clusters.labels_), ) def get_cluster_sums(amts, labels): result = {} for i in range(N_BINS): cluster_sum = amts[np.where(labels == i)[0]].sum() result[i] = (cluster_sum, np.where(labels == i)[0].shape[0]) return result def plot_cents(centers, round=0): pp.clf() pp.plot(centers, np.zeros_like(centers), "|") fig = pp.gcf() fig.set_size_inches(18.5, 10.5) pp.savefig("centers" + str(round) + ".png", dpi=100) def new_round(amts, clusters): """ choose some existing amts, reduce their amt (just halve for now), introduce new amts with the remainder """ # keep it equal for now n_picked = 100 picked_amts = np.random.randint(0, len(amts), size=n_picked) for amt_idx in picked_amts: new_amts, new_clusters = nuke_old_amt(amts, amt_idx, clusters) # new_amt = amts[amt_idx] - new_amts[amt_idx] new_amt = np.random.randint(AMT, AMT * 100, size=1).squeeze() amts, clusters = add_new_amt(new_amts, new_clusters, new_amt) return amts, clusters def nuke_old_amt(amts, amt_idx, clusters): """ """ old_amt = amts[amt_idx] new_amt = old_amt // 2 # get cluster id, update this cluster's center cur_cluster = clusters[1][amt_idx] cluster_center = clusters[0][cur_cluster] new_cluster = get_new_cluster(new_amt, clusters[0]) cluster_attrs = clusters[-1] cur_sum, cur_size = cluster_attrs[cur_cluster] new_sum = cur_sum - old_amt new_size = cur_size - 1 cluster_attrs[cur_cluster] = (new_sum, new_size) amts[amt_idx] = new_amt new_center = new_sum / new_size clusters[0][cur_cluster] = new_center clusters[1][amt_idx] = new_cluster return amts, (clusters[0], clusters[1], cluster_attrs) def add_new_amt(amts, clusters, new_amt): new_cluster = get_new_cluster(new_amt, clusters[0]) new_amts = np.append(amts, new_amt) new_labels = np.append(clusters[1], new_cluster) cluster_attrs = clusters[-1] new_size = cluster_attrs[new_cluster][1] + 1 new_sum = cluster_attrs[new_cluster][0] + new_amt cluster_attrs[new_cluster] = (new_sum, new_size) new_center = new_sum / new_size clusters[0][new_cluster] = new_center new_clusters = np.append(clusters[1], new_cluster) return new_amts, (clusters[0], new_clusters, cluster_attrs) def get_new_cluster(new_amt, centers): min_dist = AMT * 100 cl_id = -1 for i, center in enumerate(centers): if abs(center - new_amt) < min_dist: min_dist = abs(center - new_amt) cl_id = i return cl_id def metric(amts, clusters): cluster_amts =
np.zeros_like(amts)
numpy.zeros_like
import networkx as nx import numpy as np import utils as utils import sys import matplotlib.pyplot as plt def inputmaker(n): if n == 50: f = open("50.in", "w") elif n == 100: f = open("100.in", "w") elif n == 200: f = open("200.in", "w") f.write(str(n)) f.write("\n") f.write(str(int(n / 2))) f.write("\n") f.write(str(0)) for i in np.arange(1, n): f.write(" ") f.write(str(i)) f.write("\n") f.write(str(0)) for i in
np.arange(2, n, 2)
numpy.arange
import os import shutil import six import pytest import numpy as np from pyshac.config import hyperparameters as hp, data # compatible with both Python 2 and 3 try: FileNotFoundError except NameError: FileNotFoundError = IOError def deterministic_test(func): @six.wraps(func) def wrapper(*args, **kwargs): np.random.seed(0) output = func(*args, **kwargs) np.random.seed(None) return output return wrapper # wrapper function to clean up saved files def cleanup_dirs(func): @six.wraps(func) def wrapper(*args, **kwargs): output = func(*args, **kwargs) # remove temporary files if os.path.exists('shac/'): shutil.rmtree('shac/') if os.path.exists('custom/'): shutil.rmtree('custom/') return output return wrapper def get_hyperparameter_list(): h1 = hp.DiscreteHyperParameter('h1', [0, 1, 2]) h2 = hp.DiscreteHyperParameter('h2', [3, 4, 5, 6]) h3 = hp.UniformContinuousHyperParameter('h3', 7, 10) h4 = hp.DiscreteHyperParameter('h4', ['v1', 'v2']) return [h1, h2, h3, h4] def get_multi_parameter_list(): h1 = hp.MultiDiscreteHyperParameter('h1', [0, 1, 2], sample_count=2) h2 = hp.MultiDiscreteHyperParameter('h2', [3, 4, 5, 6], sample_count=3) h3 = hp.MultiUniformContinuousHyperParameter('h3', 7, 10, sample_count=5) h4 = hp.MultiDiscreteHyperParameter('h4', ['v1', 'v2'], sample_count=4) return [h1, h2, h3, h4] @cleanup_dirs def test_dataset_param_list(): params = get_hyperparameter_list() dataset = data.Dataset(params) assert isinstance(dataset._parameters, hp.HyperParameterList) dataset.set_parameters(params) assert isinstance(dataset._parameters, hp.HyperParameterList) h = hp.HyperParameterList(params) dataset.set_parameters(h) assert isinstance(dataset._parameters, hp.HyperParameterList) @cleanup_dirs def test_dataset_multi_param_list(): params = get_multi_parameter_list() dataset = data.Dataset(params) assert isinstance(dataset._parameters, hp.HyperParameterList) dataset.set_parameters(params) assert isinstance(dataset._parameters, hp.HyperParameterList) h = hp.HyperParameterList(params) dataset.set_parameters(h) assert isinstance(dataset._parameters, hp.HyperParameterList) @cleanup_dirs def test_dataset_basedir(): params = get_hyperparameter_list() h = hp.HyperParameterList(params) dataset = data.Dataset(h) assert os.path.exists(dataset.basedir) @cleanup_dirs def test_dataset_basedir_custom(): params = get_hyperparameter_list() h = hp.HyperParameterList(params) dataset = data.Dataset(h, basedir='custom') assert os.path.exists(dataset.basedir) assert not os.path.exists('shac') @cleanup_dirs def test_dataset_add_sample(): params = get_hyperparameter_list() h = hp.HyperParameterList(params) dataset = data.Dataset(h) samples = [(h.sample(), np.random.uniform()) for _ in range(5)] for sample in samples: dataset.add_sample(*sample) x, y = dataset.get_dataset() assert len(dataset) == 5 assert x.shape == (5, 4) assert y.shape == (5,) @cleanup_dirs def test_dataset_multi_add_sample(): params = get_multi_parameter_list() h = hp.HyperParameterList(params) dataset = data.Dataset(h) samples = [(h.sample(), np.random.uniform()) for _ in range(5)] for sample in samples: dataset.add_sample(*sample) x, y = dataset.get_dataset() assert len(dataset) == 5 assert x.shape == (5, 14) assert y.shape == (5,) @cleanup_dirs def test_set_dataset(): params = get_hyperparameter_list() h = hp.HyperParameterList(params) dataset = data.Dataset(h) # numpy arrays samples = [(np.array(h.sample()), np.random.uniform()) for _ in range(5)] x, y = zip(*samples) x = np.array(x) y = np.array(y) dataset.set_dataset(x, y) assert len(dataset) == 5 dataset.clear() # python arrays samples = [(h.sample(), float(np.random.uniform())) for _ in range(5)] x, y = zip(*samples) dataset.set_dataset(x, y) assert len(dataset) == 5 # None data with pytest.raises(TypeError): dataset.set_dataset(None, int(6)) with pytest.raises(TypeError): dataset.set_dataset([1, 2, 3], None) with pytest.raises(TypeError): dataset.set_dataset(None, None) @cleanup_dirs def test_multi_set_dataset(): params = get_multi_parameter_list() h = hp.HyperParameterList(params) dataset = data.Dataset(h) # numpy arrays samples = [(np.array(h.sample()), np.random.uniform()) for _ in range(5)] x, y = zip(*samples) x = np.array(x) y = np.array(y) dataset.set_dataset(x, y) assert len(dataset) == 5 dataset.clear() # python arrays samples = [(h.sample(), float(np.random.uniform())) for _ in range(5)] x, y = zip(*samples) dataset.set_dataset(x, y) assert len(dataset) == 5 # None data with pytest.raises(TypeError): dataset.set_dataset(None, int(6)) with pytest.raises(TypeError): dataset.set_dataset([1, 2, 3], None) with pytest.raises(TypeError): dataset.set_dataset(None, None) @cleanup_dirs @deterministic_test def test_dataset_get_best_parameters(): params = get_hyperparameter_list() h = hp.HyperParameterList(params) dataset = data.Dataset(h) with pytest.raises(ValueError): dataset.get_best_parameters(None) # Test with empty dataset assert dataset.get_best_parameters() is None samples = [(h.sample(), np.random.uniform()) for _ in range(5)] for sample in samples: dataset.add_sample(*sample) objective_values = [v for h, v in samples] min_index = np.argmin(objective_values) max_index = np.argmax(objective_values) max_hp = list(dataset.get_best_parameters(objective='max').values()) min_hp = list(dataset.get_best_parameters(objective='min').values()) assert max_hp == samples[max_index][0] assert min_hp == samples[min_index][0] @cleanup_dirs @deterministic_test def test_dataset_multi_get_best_parameters(): params = get_multi_parameter_list() h = hp.HyperParameterList(params) dataset = data.Dataset(h) with pytest.raises(ValueError): dataset.get_best_parameters(None) # Test with empty dataset assert dataset.get_best_parameters() is None samples = [(h.sample(), np.random.uniform()) for _ in range(5)] for sample in samples: dataset.add_sample(*sample) objective_values = [v for h, v in samples] min_index = np.argmin(objective_values) max_index = np.argmax(objective_values) max_hp = data.flatten_parameters(dataset.get_best_parameters(objective='max')) min_hp = data.flatten_parameters(dataset.get_best_parameters(objective='min')) assert max_hp == samples[max_index][0] assert min_hp == samples[min_index][0] @cleanup_dirs def test_dataset_parameters(): params = get_hyperparameter_list() h = hp.HyperParameterList(params) dataset = data.Dataset(h) assert len(params) == len(dataset.parameters) dataset.parameters = params assert len(params) == len(dataset.parameters) @cleanup_dirs def test_dataset_serialization_deserialization(): params = get_hyperparameter_list() h = hp.HyperParameterList(params) dataset = data.Dataset(h) samples = [(h.sample(), np.random.uniform()) for _ in range(5)] for sample in samples: dataset.add_sample(*sample) # serialization dataset.save_dataset() assert len(dataset) == 5 assert os.path.exists(dataset.data_path) assert os.path.exists(dataset.parameter_path) # deserialization dataset.clear() assert len(dataset) == 0 dataset.restore_dataset() assert len(dataset) == 5 assert os.path.exists(dataset.data_path) assert os.path.exists(dataset.parameter_path) # deserialization from class path = os.path.join('shac', 'datasets') dataset2 = data.Dataset.load_from_directory(path) assert dataset2.parameters is not None assert len(dataset2.X) == 5 assert len(dataset2.Y) == 5 assert len(dataset2) == 5 dataset3 = data.Dataset.load_from_directory() assert dataset3.parameters is not None assert len(dataset3.X) == 5 assert len(dataset3.Y) == 5 # serialization of empty get_dataset dataset = data.Dataset() with pytest.raises(FileNotFoundError): dataset.load_from_directory('null') with pytest.raises(ValueError): dataset.save_dataset() @cleanup_dirs def test_dataset_multi_serialization_deserialization(): params = get_multi_parameter_list() h = hp.HyperParameterList(params) dataset = data.Dataset(h) samples = [(h.sample(), np.random.uniform()) for _ in range(5)] for sample in samples: dataset.add_sample(*sample) # serialization dataset.save_dataset() assert len(dataset) == 5 assert os.path.exists(dataset.data_path) assert os.path.exists(dataset.parameter_path) # deserialization dataset.clear() assert len(dataset) == 0 dataset.restore_dataset() assert len(dataset) == 5 assert os.path.exists(dataset.data_path) assert os.path.exists(dataset.parameter_path) # deserialization from class path = os.path.join('shac', 'datasets') dataset2 = data.Dataset.load_from_directory(path) assert dataset2.parameters is not None assert len(dataset2.X) == 5 assert len(dataset2.Y) == 5 assert len(dataset2) == 5 dataset3 = data.Dataset.load_from_directory() assert dataset3.parameters is not None assert len(dataset3.X) == 5 assert len(dataset3.Y) == 5 # serialization of empty get_dataset dataset = data.Dataset() with pytest.raises(FileNotFoundError): dataset.load_from_directory('null') with pytest.raises(ValueError): dataset.save_dataset() @cleanup_dirs def test_dataset_serialization_deserialization_custom_basepath(): params = get_hyperparameter_list() h = hp.HyperParameterList(params) dataset = data.Dataset(h, basedir='custom') samples = [(h.sample(), np.random.uniform()) for _ in range(5)] for sample in samples: dataset.add_sample(*sample) # serialization dataset.save_dataset() assert len(dataset) == 5 assert os.path.exists(dataset.data_path) assert os.path.exists(dataset.parameter_path) # deserialization dataset.clear() assert len(dataset) == 0 dataset.restore_dataset() assert len(dataset) == 5 assert os.path.exists(dataset.data_path) assert os.path.exists(dataset.parameter_path) # deserialization from class path = os.path.join('custom', 'datasets') dataset2 = data.Dataset.load_from_directory(path) assert dataset2.parameters is not None assert len(dataset2.X) == 5 assert len(dataset2.Y) == 5 assert len(dataset2) == 5 dataset3 = data.Dataset.load_from_directory('custom') assert dataset3.parameters is not None assert len(dataset3.X) == 5 assert len(dataset3.Y) == 5 # serialization of empty get_dataset dataset = data.Dataset(basedir='custom') with pytest.raises(FileNotFoundError): dataset.load_from_directory('null') with pytest.raises(ValueError): dataset.save_dataset() @cleanup_dirs def test_dataset_serialization_deserialization_custom_param(): class MockDiscreteHyperParameter(hp.DiscreteHyperParameter): def __init__(self, name, values, seed=None): super(MockDiscreteHyperParameter, self).__init__(name, values, seed) # register the new hyper parameters hp.set_custom_parameter_class(MockDiscreteHyperParameter) params = get_hyperparameter_list() params.append(MockDiscreteHyperParameter('mock-param', ['x', 'y'])) h = hp.HyperParameterList(params, seed=0) dataset = data.Dataset(h) samples = [(h.sample(), np.random.uniform()) for _ in range(5)] for sample in samples: dataset.add_sample(*sample) # serialization dataset.save_dataset() assert len(dataset) == 5 assert os.path.exists(dataset.data_path) assert os.path.exists(dataset.parameter_path) # deserialization dataset.clear() assert len(dataset) == 0 dataset.restore_dataset() assert len(dataset) == 5 assert os.path.exists(dataset.data_path) assert os.path.exists(dataset.parameter_path) # deserialization from class path = os.path.join('shac', 'datasets') dataset2 = data.Dataset.load_from_directory(path) assert dataset2.parameters is not None assert len(dataset2.X) == 5 assert len(dataset2.Y) == 5 assert len(dataset2) == 5 assert 'mock-param' in dataset2.parameters.name_map.values() assert dataset2.parameters.num_choices == 5 dataset3 = data.Dataset.load_from_directory() assert dataset3.parameters is not None assert len(dataset3.X) == 5 assert len(dataset3.Y) == 5 assert 'mock-param' in dataset3.parameters.name_map.values() assert dataset3.parameters.num_choices == 5 # serialization of empty get_dataset dataset = data.Dataset() with pytest.raises(FileNotFoundError): dataset.load_from_directory('null') with pytest.raises(ValueError): dataset.save_dataset() @cleanup_dirs @deterministic_test def test_dataset_single_encoding_decoding(): params = get_hyperparameter_list() h = hp.HyperParameterList(params) dataset = data.Dataset(h) sample = (h.sample(), np.random.uniform()) dataset.add_sample(*sample) encoded_x, encoded_y = dataset.encode_dataset() y_values = [0.] assert encoded_x.shape == (1, 4) assert encoded_x.dtype == np.float64 assert encoded_y.shape == (1,) assert encoded_y.dtype == np.float64 assert np.allclose(y_values, encoded_y, rtol=1e-3) decoded_x = dataset.decode_dataset(encoded_x) assert decoded_x.shape == (1, 4) @cleanup_dirs @deterministic_test def test_dataset_single_multi_encoding_decoding(): params = get_multi_parameter_list() h = hp.HyperParameterList(params) dataset = data.Dataset(h) sample = (h.sample(), np.random.uniform()) dataset.add_sample(*sample) encoded_x, encoded_y = dataset.encode_dataset() y_values = [0.] assert encoded_x.shape == (1, 14) assert encoded_x.dtype == np.float64 assert encoded_y.shape == (1,) assert encoded_y.dtype == np.float64 assert np.allclose(y_values, encoded_y, rtol=1e-3) decoded_x = dataset.decode_dataset(encoded_x) assert decoded_x.shape == (1, 14) @cleanup_dirs @deterministic_test def test_dataset_single_encoding_decoding_min(): params = get_hyperparameter_list() h = hp.HyperParameterList(params) dataset = data.Dataset(h) sample = (h.sample(), np.random.uniform()) dataset.add_sample(*sample) encoded_x, encoded_y = dataset.encode_dataset(objective='min') y_values = [0.] assert encoded_x.shape == (1, 4) assert encoded_x.dtype == np.float64 assert encoded_y.shape == (1,) assert encoded_y.dtype == np.float64 assert np.allclose(y_values, encoded_y, rtol=1e-3) decoded_x = dataset.decode_dataset(encoded_x) assert decoded_x.shape == (1, 4) @cleanup_dirs @deterministic_test def test_dataset_single_multi_encoding_decoding_min(): params = get_multi_parameter_list() h = hp.HyperParameterList(params) dataset = data.Dataset(h) sample = (h.sample(), np.random.uniform()) dataset.add_sample(*sample) encoded_x, encoded_y = dataset.encode_dataset(objective='min') y_values = [0.] assert encoded_x.shape == (1, 14) assert encoded_x.dtype == np.float64 assert encoded_y.shape == (1,) assert encoded_y.dtype == np.float64 assert np.allclose(y_values, encoded_y, rtol=1e-3) decoded_x = dataset.decode_dataset(encoded_x) assert decoded_x.shape == (1, 14) @cleanup_dirs @deterministic_test def test_dataset_encoding_decoding(): params = get_hyperparameter_list() h = hp.HyperParameterList(params, seed=0) dataset = data.Dataset(h) samples = [(h.sample(), np.random.uniform()) for _ in range(5)] for sample in samples: dataset.add_sample(*sample) encoded_x, encoded_y = dataset.encode_dataset(objective='min') y_values = [0., 0., 0., 1., 1.] assert encoded_x.shape == (5, 4) assert encoded_x.dtype == np.float64 assert encoded_y.shape == (5,) assert encoded_y.dtype == np.float64 assert np.allclose(y_values, encoded_y, rtol=1e-3) decoded_x = dataset.decode_dataset(encoded_x) decoded_x2 = dataset.decode_dataset() assert decoded_x.shape == (5, 4) assert len(decoded_x) == len(decoded_x2) x, y = dataset.get_dataset() x_ = x[:, :3].astype('float') decoded_x_ = decoded_x[:, :3].astype('float') assert np.allclose(x_, decoded_x_, rtol=1e-3) samples2 = [(h.sample(), np.random.uniform()) for _ in range(5)] x, y = zip(*samples2) encoded_x, encoded_y = dataset.encode_dataset(x, y, objective='min') y_values = [0., 1., 0., 0., 1.] assert encoded_x.shape == (5, 4) assert encoded_x.dtype == np.float64 assert encoded_y.shape == (5,) assert encoded_y.dtype == np.float64 assert np.allclose(y_values, encoded_y, rtol=1e-3) @cleanup_dirs @deterministic_test def test_dataset_multi_encoding_decoding(): params = get_multi_parameter_list() h = hp.HyperParameterList(params, seed=0) dataset = data.Dataset(h) samples = [(h.sample(), np.random.uniform()) for _ in range(5)] for sample in samples: dataset.add_sample(*sample) encoded_x, encoded_y = dataset.encode_dataset(objective='min') y_values = [0., 0., 0., 1., 1.] assert encoded_x.shape == (5, 14) assert encoded_x.dtype == np.float64 assert encoded_y.shape == (5,) assert encoded_y.dtype == np.float64 assert np.allclose(y_values, encoded_y, rtol=1e-3) decoded_x = dataset.decode_dataset(encoded_x) decoded_x2 = dataset.decode_dataset() assert decoded_x.shape == (5, 14) assert len(decoded_x) == len(decoded_x2) x, y = dataset.get_dataset() x_ = x[:, :10].astype('float') decoded_x_ = decoded_x[:, :10].astype('float') assert np.allclose(x_, decoded_x_, rtol=1e-3) samples2 = [(h.sample(), np.random.uniform()) for _ in range(5)] x, y = zip(*samples2) encoded_x, encoded_y = dataset.encode_dataset(x, y, objective='min') y_values = [0., 1., 0., 0., 1.] assert encoded_x.shape == (5, 14) assert encoded_x.dtype == np.float64 assert encoded_y.shape == (5,) assert encoded_y.dtype == np.float64 assert np.allclose(y_values, encoded_y, rtol=1e-3) @cleanup_dirs @deterministic_test def test_dataset_encoding_decoding_min(): params = get_hyperparameter_list() h = hp.HyperParameterList(params, seed=0) dataset = data.Dataset(h) samples = [(h.sample(), np.random.uniform()) for _ in range(5)] for sample in samples: dataset.add_sample(*sample) encoded_x, encoded_y = dataset.encode_dataset(objective='min') y_values = [0., 0., 0., 1., 1.] assert encoded_x.shape == (5, 4) assert encoded_x.dtype == np.float64 assert encoded_y.shape == (5,) assert encoded_y.dtype == np.float64 assert np.allclose(y_values, encoded_y, rtol=1e-3) decoded_x = dataset.decode_dataset(encoded_x) assert decoded_x.shape == (5, 4) x, y = dataset.get_dataset() x_ = x[:, :3].astype('float') decoded_x_ = decoded_x[:, :3].astype('float') assert
np.allclose(x_, decoded_x_, rtol=1e-3)
numpy.allclose