prompt
stringlengths
19
879k
completion
stringlengths
3
53.8k
api
stringlengths
8
59
import numpy as np import time from field_ops import Engine n = 100 v = np.linspace(0, 1, n) x, y, z = np.meshgrid(v, v, v, indexing='ij') # setup simulation engine sim = Engine(x.shape) # allocate variables sim.allocate('c', [], 'both') sim.allocate('u', [3], 'both') sim.allocate('D', [3,3], 'both') sim.allocate('R', [3,3], float) sim.allocate('M', [3,3], float) sim.allocate('v', [3], float) sim.allocate('V', [3,3], float) sim.allocate('eye', [3,3], float) # set c to something D = sim.get('D') D[:] = np.random.rand(*D.shape) # instantiate processor pool sim.initialize_pool() # make eye actually be an identity eye = sim.get('eye') eye[0,0] = 1.0 eye[1,1] = 1.0 eye[2,2] = 1.0 # execute an einsum prod on D print('\n--- Testing einsum MAT MAT ---') instr = 'ij...,jk...->ik...' sim.einsum(instr, ['D','D'], 'R') st = time.time(); truth = np.einsum(instr,D,D); numpy_time = time.time()-st st = time.time(); sim.einsum(instr, ['D','D'], 'R'); sim_time = time.time()-st print('All close? ', np.allclose(truth, sim.get('R'))) print('... Einsum time (ms): {:0.1f}'.format(numpy_time*1000)) print('... Sim time (ms): {:0.1f}'.format(sim_time*1000)) # now make R be nicely conditioned sim.evaluate('R = 0.1*R + eye') # compute the eigendecomposition of R print('\n--- Testing eigendecomposition ---') R = sim.get('R') S = np.transpose(R, [2,3,4,0,1]) sim.reset_pool() st = time.time(); truth = np.linalg.eigh(S); numpy_time = time.time()-st st = time.time(); sim.eigh('R', 'v', 'V'); sim_time = time.time()-st tv = np.transpose(truth[0], [3,0,1,2]) tV = np.transpose(truth[1], [3,4,0,1,2]) print('... All close, values? ', np.allclose(tv, sim.get('v'))) print('... All close, vectors? ', np.allclose(tV, sim.get('V'))) print('... Eigh time (ms): {:0.1f}'.format(numpy_time*1000)) print('... Sim time (ms): {:0.1f}'.format(sim_time*1000)) # test eigendecomp on on-the-fly allocated variable print('\n--- Testing eigendecomposition on new variable of (2,2) size ---') variables = [ ['M2', [2,2], float], ['v2', [2], float], ['V2', [2,2], float], ] sim.allocate_many(variables) M2 = sim.get('M2') M2[:] = R[:2,:2] S = np.transpose(M2, [2,3,4,0,1]) # try to eigh this st = time.time(); truth =
np.linalg.eigh(S)
numpy.linalg.eigh
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for tensorflow.python.framework.sparse_tensor.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import parameterized import numpy as np from tensorflow.python.eager import context from tensorflow.python.eager import def_function from tensorflow.python.framework import dtypes from tensorflow.python.framework import errors from tensorflow.python.framework import ops from tensorflow.python.framework import sparse_tensor from tensorflow.python.framework import tensor_shape from tensorflow.python.framework import tensor_spec from tensorflow.python.framework import test_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import sparse_ops from tensorflow.python.platform import googletest class SparseTensorTest(test_util.TensorFlowTestCase): def testPythonConstruction(self): indices = [[1, 2], [2, 0], [3, 4]] values = [b"a", b"b", b"c"] shape = [4, 5] sp_value = sparse_tensor.SparseTensorValue(indices, values, shape) for sp in [ sparse_tensor.SparseTensor(indices, values, shape), sparse_tensor.SparseTensor.from_value(sp_value), sparse_tensor.SparseTensor.from_value( sparse_tensor.SparseTensor(indices, values, shape))]: self.assertEqual(sp.indices.dtype, dtypes.int64) self.assertEqual(sp.values.dtype, dtypes.string) self.assertEqual(sp.dense_shape.dtype, dtypes.int64) self.assertEqual(sp.get_shape(), (4, 5)) value = self.evaluate(sp) self.assertAllEqual(indices, value.indices) self.assertAllEqual(values, value.values) self.assertAllEqual(shape, value.dense_shape) sp_value = self.evaluate(sp) self.assertAllEqual(sp_value.indices, value.indices) self.assertAllEqual(sp_value.values, value.values) self.assertAllEqual(sp_value.dense_shape, value.dense_shape) def testShape(self): @def_function.function def test_fn(tensor): tensor = sparse_ops.sparse_transpose(tensor) self.assertEqual(tensor.shape.rank, 2) return tensor tensor = sparse_tensor.SparseTensor( indices=[[0, 0], [1, 2]], values=[1., 2], dense_shape=[3, 4]) test_fn(tensor) def testIsSparse(self): self.assertFalse(sparse_tensor.is_sparse(3)) self.assertFalse(sparse_tensor.is_sparse("foo")) self.assertFalse(sparse_tensor.is_sparse(np.array(3))) self.assertTrue( sparse_tensor.is_sparse(sparse_tensor.SparseTensor([[0]], [0], [1]))) self.assertTrue( sparse_tensor.is_sparse( sparse_tensor.SparseTensorValue([[0]], [0], [1]))) def testConsumers(self): with context.graph_mode(): sp = sparse_tensor.SparseTensor([[0, 0], [1, 2]], [1.0, 3.0], [3, 4]) w = ops.convert_to_tensor(np.ones([4, 1], np.float32)) out = sparse_ops.sparse_tensor_dense_matmul(sp, w) self.assertEqual(len(sp.consumers()), 1) self.assertEqual(sp.consumers()[0], out.op) dense = sparse_ops.sparse_tensor_to_dense(sp) self.assertEqual(len(sp.consumers()), 2) self.assertIn(dense.op, sp.consumers()) self.assertIn(out.op, sp.consumers()) def testWithValues(self): source = sparse_tensor.SparseTensor( indices=[[0, 0], [1, 2]], values=[1., 2], dense_shape=[3, 4]) new_tensor = source.with_values([5.0, 1.0]) self.assertAllEqual(new_tensor.indices, source.indices) self.assertAllEqual(new_tensor.values, [5.0, 1.0]) self.assertAllEqual(new_tensor.dense_shape, source.dense_shape) # ensure new value's shape is checked with self.assertRaises((errors.InvalidArgumentError, ValueError)): source.with_values([[5.0, 1.0]]) class ConvertToTensorOrSparseTensorTest(test_util.TensorFlowTestCase): def test_convert_dense(self): value = [42, 43] from_value = sparse_tensor.convert_to_tensor_or_sparse_tensor( value) self.assertAllEqual(value, self.evaluate(from_value)) def test_convert_sparse(self): indices = [[0, 1], [1, 0]] values = [42, 43] shape = [2, 2] sparse_tensor_value = sparse_tensor.SparseTensorValue( indices, values, shape) st = sparse_tensor.SparseTensor.from_value(sparse_tensor_value) from_value = self.evaluate( sparse_tensor.convert_to_tensor_or_sparse_tensor(sparse_tensor_value)) from_tensor = self.evaluate( sparse_tensor.convert_to_tensor_or_sparse_tensor(st)) for convertee in [from_value, from_tensor]: self.assertAllEqual(sparse_tensor_value.indices, convertee.indices) self.assertAllEqual(sparse_tensor_value.values, convertee.values) self.assertAllEqual( sparse_tensor_value.dense_shape, convertee.dense_shape) class SparseTensorShapeTest(test_util.TensorFlowTestCase): def test_simple(self): indices = [[0, 2]] values = [1] dense_shape = [5, 5] sp = sparse_tensor.SparseTensor(indices, values, dense_shape) self.assertIsInstance(sp.shape, tensor_shape.TensorShape) self.assertIsInstance(sp.dense_shape, ops.Tensor) self.assertEqual(sp.shape.as_list(), [5, 5]) def test_unknown_shape(self): @def_function.function def my_func(dense_shape): indices = [[0, 2]] values = [1] sp = sparse_tensor.SparseTensor(indices, values, dense_shape) self.assertEqual(sp.shape.as_list(), [None, None]) return sp my_func.get_concrete_function( dense_shape=tensor_spec.TensorSpec( dtype=dtypes.int64, shape=[2,])) def test_partial_shape(self): @def_function.function def my_func(x): indices = [[0, 2]] values = [1] y = ops.convert_to_tensor(3, dtype=dtypes.int64) dense_shape = [x, y] sp = sparse_tensor.SparseTensor(indices, values, dense_shape) self.assertEqual(sp.shape.as_list(), [None, 3]) return sp my_func.get_concrete_function( x=tensor_spec.TensorSpec(dtype=dtypes.int64, shape=[])) def test_neg_shape(self): indices = [[0, 2]] values = [1] dense_shape = [-1, 5] sp = sparse_tensor.SparseTensor(indices, values, dense_shape) self.assertEqual(sp.shape.as_list(), [None, 5]) def test_unknown_tensor_shape(self): @def_function.function def my_func(x): indices = [[0, 0]] values = [1] dense_shape = array_ops.shape(x) dense_shape = math_ops.cast(dense_shape, dtypes.int64) sp = sparse_tensor.SparseTensor(indices, values, dense_shape) self.assertEqual(sp.shape.as_list(), [None, None]) return sp my_func.get_concrete_function( x=tensor_spec.TensorSpec(dtype=dtypes.int64, shape=[None, None])) def test_unknown_rank(self): @def_function.function def my_func(dense_shape): indices = [[0, 0]] values = [1] sp = sparse_tensor.SparseTensor(indices, values, dense_shape) self.assertEqual(sp.shape.rank, None) return sp my_func.get_concrete_function( dense_shape=tensor_spec.TensorSpec(dtype=dtypes.int64, shape=[None])) @test_util.run_all_in_graph_and_eager_modes class SparseTensorSpecTest(test_util.TensorFlowTestCase, parameterized.TestCase): def assertAllTensorsEqual(self, list1, list2): self.assertLen(list1, len(list2)) for (t1, t2) in zip(list1, list2): self.assertAllEqual(t1, t2) def testConstruction(self): spec1 = sparse_tensor.SparseTensorSpec() self.assertEqual(spec1.shape.rank, None) self.assertEqual(spec1.dtype, dtypes.float32) spec2 = sparse_tensor.SparseTensorSpec([None, None], dtypes.string) self.assertEqual(spec2.shape.as_list(), [None, None]) self.assertEqual(spec2.dtype, dtypes.string) def testValueType(self): spec1 = sparse_tensor.SparseTensorSpec() self.assertEqual(spec1.value_type, sparse_tensor.SparseTensor) @parameterized.parameters([ (sparse_tensor.SparseTensorSpec(), (tensor_shape.TensorShape(None), dtypes.float32)), (sparse_tensor.SparseTensorSpec(shape=[5, None, None]), (tensor_shape.TensorShape([5, None, None]), dtypes.float32)), (sparse_tensor.SparseTensorSpec(dtype=dtypes.int32), (tensor_shape.TensorShape(None), dtypes.int32)), ]) # pyformat: disable def testSerialize(self, st_spec, expected): serialization = st_spec._serialize() # TensorShape has an unconventional definition of equality, so we can't use # assertEqual directly here. But repr() is deterministic and lossless for # the expected values, so we can use that instead. self.assertEqual(repr(serialization), repr(expected)) @parameterized.parameters([ (sparse_tensor.SparseTensorSpec(dtype=dtypes.string), [ tensor_spec.TensorSpec([None, None], dtypes.int64), tensor_spec.TensorSpec([None], dtypes.string), tensor_spec.TensorSpec([None], dtypes.int64) ]), (sparse_tensor.SparseTensorSpec(shape=[5, None, None]), [ tensor_spec.TensorSpec([None, 3], dtypes.int64), tensor_spec.TensorSpec([None], dtypes.float32), tensor_spec.TensorSpec([3], dtypes.int64) ]), ]) def testComponentSpecs(self, st_spec, expected): self.assertEqual(st_spec._component_specs, expected) @parameterized.parameters([ { "st_spec": sparse_tensor.SparseTensorSpec(), "indices": [[0, 1], [10, 8]], "values": [3.0, 5.0], "dense_shape": [100, 100] }, { "st_spec": sparse_tensor.SparseTensorSpec([100, None, None]), "indices": [[0, 1, 3], [10, 8, 2]], "values": [3.0, 5.0], "dense_shape": [100, 20, 20] }, ]) def testToFromComponents(self, st_spec, indices, values, dense_shape): st = sparse_tensor.SparseTensor(indices, values, dense_shape) actual_components = st_spec._to_components(st) self.assertAllTensorsEqual(actual_components, [indices, values, dense_shape]) st_reconstructed = st_spec._from_components(actual_components) self.assertAllEqual(st.indices, st_reconstructed.indices) self.assertAllEqual(st.values, st_reconstructed.values) self.assertAllEqual(st.dense_shape, st_reconstructed.dense_shape) @test_util.run_v1_only("SparseTensorValue is deprecated in v2") def testFromNumpyComponents(self): indices =
np.array([[0], [8]])
numpy.array
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))
numpy.ones
import numpy as np import torch import sys sys.path.append('..') sys.path.append('../acd/util') sys.path.append('../acd/scores') import cd import score_funcs import pickle as pkl import warnings warnings.filterwarnings("ignore") def test_sst(device='cpu'): # load the model and data sys.path.append('../dsets/sst') from dsets.sst.model import LSTMSentiment sst_pkl = pkl.load(open('../dsets/sst/sst_vocab.pkl', 'rb')) model = torch.load('../dsets/sst/sst.model', map_location=device) model.device = device # text and label sentence = ['a', 'great', 'ensemble', 'cast', 'ca', 'n\'t', 'lift', 'this', 'heartfelt', 'enterprise', 'out', 'of', 'the', 'familiar', '.'] # note this is a real example from the dataset def batch_from_str_list(s): # form class to hold data class B: text = torch.zeros(1).to(device) batch = B() nums = np.expand_dims(np.array([sst_pkl['stoi'][x] for x in s]).transpose(), axis=1) batch.text = torch.LongTensor(nums).to(device) #cuda() return batch # prepare inputs batch = batch_from_str_list(sentence) preds = model(batch).data.cpu().numpy()[0] # predict # check that full sentence = prediction preds = preds - model.hidden_to_label.bias.detach().numpy() cd_score, irrel_scores = cd.cd_text(batch, model, start=0, stop=len(sentence), return_irrel_scores=True) assert(np.allclose(cd_score, preds, atol=1e-2)) assert(np.allclose(irrel_scores, irrel_scores * 0, atol=1e-2)) # check that rel + irrel = prediction for another subset cd_score, irrel_scores = cd.cd_text(batch, model, start=3, stop=len(sentence), return_irrel_scores=True) assert(
np.allclose(cd_score + irrel_scores, preds, atol=1e-2)
numpy.allclose
""" Functions for handling observations of SFR package output. """ import os import numpy as np import pandas as pd import geopandas as gpd from shapely.geometry import Polygon from gisutils import shp2df try: import flopy fm = flopy.modflow except: flopy = False from .gis import get_shapefile_crs, project from .fileio import read_tables from .routing import get_next_id_in_subset def add_observations(sfrdata, data, flowline_routing=None, obstype=None, sfrlines_shapefile=None, rno_column_in_sfrlines='rno', x_location_column=None, y_location_column=None, line_id_column=None, rno_column=None, obstype_column=None, obsname_column='site_no'): """Add SFR observations to the observations DataFrame attribute of an sfrdata instance. Observations can by located on the SFR network by specifying reach number directly (rno_column), by x, y location (x_column_in_data and y_column in data), or by specifying the source hydrography lines that they are located on (line_id_column). Parameters ---------- sfrdata : sfrmaker.SFRData instance SFRData instance with reach_data table attribute. To add observations from x, y coordinates, the reach_data table must have a geometry column with LineStrings representing each reach, or an sfrlines_shapefile is required. Reach numbers are assumed to be in an 'rno' column. data : DataFrame, path to csv file, or list of DataFrames or file paths Table with information on the observation sites to be located. Must have either reach numbers (rno_column), line_ids (line_id_column), or x and y locations (x_column_in_data and y_column_in_data). obstype : str or list-like (optional) Type(s) of observation to record, for MODFLOW-6 (default 'downstream-flow'; see MODFLOW-6 IO documentation for more details). Alternatively, observation types can be specified by row in data, using the obstype_column_in_data argument. x_location_column : str (optional) Column in data with site x-coordinates (in same CRS as SFR network). y_location_column : str (optional) Column in data with site y-coordinates (in same CRS as SFR network). sfrlines_shapefile : str (optional) Shapefile version of SFRdata.reach_data. Only needed if SFRdata.reach_data doesn't have LineString geometries for the reaches. rno_column_in_sfrlines : str (optional) Column in sfrlines with reach numbers for matching lines with reaches in sfrdata, or reach numbers assigned to observation sites. (default 'rno') line_id_column : str Column in data matching observation sites to line_ids in the source hydrography data. rno_column : str Column in data matching observation sites to reach numbers in the SFR network. flowline_routing : dict Optional dictionary of routing for source hydrography. Only needed if locating by line_id, and SFR network is a subset of the full source hydrography (i.e. some lines were dropped in the creation of the SFR packge, or if the sites are inflow points corresponding to lines outside of the model perimeter). In this case, observation points referenced to line_ids that are missing from the SFR network are placed at the first reach corresponding to the next downstream line_id that is represented in the SFR network. obstype_column : str (optional) Column in data with MODFLOW-6 observation types. For adding observations of different types. If obstype and obstype_column_in_data are none, the default of 'downstream-flow' will be used. obsname_column : str Column in data with unique identifier (e.g. site number or name) for observation sites. Notes ----- Sites located by line_id (source hydrography) will be assigned to the last reach in the segment corresponding to the line_id. Locating by x, y or reach number is more accurate. """ sfrd = sfrdata reach_data = sfrdata.reach_data.copy() # allow input via a list of tables or single table data = read_tables(data, dtype={obsname_column: object})#, dtype={obsname_column: object}) # need a special case if allowing obsname_column to also be identifier if obsname_column == rno_column: obsname_column = f'obsnamecol_{obsname_column}' data[obsname_column] = data[rno_column].astype(object) elif obsname_column == line_id_column: obsname_column = f'obsnamecol_{obsname_column}' data[obsname_column] = data[line_id_column].astype(object) else: data[obsname_column] = data[obsname_column].astype(object) assert data[obsname_column].dtype == np.object # read reach geometries from a shapefile if sfrlines_shapefile is not None: sfrlines = shp2df(sfrlines_shapefile) geoms = dict(zip(sfrlines[rno_column_in_sfrlines], sfrlines['geometry'])) reach_data['geometry'] = [geoms[rno] for rno in reach_data['rno']] # if no reach number is provided msg = "Observation sites need reach number, (x,y) coordinates, or source hydrography IDs" if rno_column not in data.columns: rno_column = 'rno' # get reach numbers by x, y location of sites if x_location_column in data.columns and y_location_column in data.columns: locs = locate_sites(data, reach_data, x_column_in_data=x_location_column, y_column_in_data=y_location_column, reach_id_col='rno', # reach number column in reach_data site_number_col=obsname_column ) data[rno_column] = locs['rno'] # get reach number from site locations in source hydrography (line_ids) elif line_id_column in data.columns: # map NHDPlus COMIDs to reach numbers if flowline_routing is None: line_id = dict(zip(reach_data.iseg, reach_data.line_id)) sfr_routing = sfrdata.segment_routing.copy() # routing for source hydrography flowline_routing = {line_id.get(k, 0): line_id.get(v, 0) for k, v in sfr_routing.items()} # get the last reach in each segment r1 = reach_data.sort_values(by=['iseg', 'ireach'], axis=0).groupby('iseg').last() line_id_rno_mapping = dict(zip(r1['line_id'], r1['rno'])) line_ids = get_next_id_in_subset(r1.line_id, flowline_routing, data[line_id_column]) data[rno_column] = [line_id_rno_mapping[lid] for lid in line_ids] else: raise ValueError(msg) # create observations dataframe obsdata = pd.DataFrame(columns=sfrd.observations.columns) # remove duplicate locations data = data.groupby(rno_column).first().reset_index() obsdata['rno'] = data[rno_column] # segment and reach info iseg_ireach = dict(list(zip(reach_data.rno, zip(reach_data.iseg, reach_data.ireach)))) obsdata['iseg'] = [iseg_ireach[rno][0] for rno in obsdata.rno] obsdata['ireach'] = [iseg_ireach[rno][1] for rno in obsdata.rno] for col in ['rno', 'iseg', 'ireach']: obsdata[col] = obsdata[col].astype(int) if obstype is not None: if isinstance(obstype, str): obsdata['obstype'] = obstype obsdata['obsname'] = data[obsname_column].astype(str) else: obstypes = obstype dfs = [] for obstype in obstypes: df = obsdata.copy() df['obstype'] = obstype obsnme_suffix = obstype.split('-')[-1] df['obsname'] = [f"{obsnme}-{obsnme_suffix}" for obsnme in data[obsname_column].astype(str)] dfs.append(df) obsdata = pd.concat(dfs) elif obstype_column in data.columns: obsdata['obstype'] = data[obstype_column] # check if base observation names (with just site info) are unique # if not, formulate name based on type as well site_names = data[obsname_column].astype(str) if len(set(site_names)) < len(data): obsname_suffixes = [obstype.split('-')[-1] for obstype in obsdata['obstype']] obsdata['obsname'] = [f"{obsnme}-{obsnme_suffix}" for obsnme, obsnme_suffix in zip(site_names, obsname_suffixes)] else: obsdata['obsname'] = site_names else: obsdata['obstype'] = 'downstream-flow' obsdata['obsname'] = data[obsname_column].astype(str) return obsdata def get_closest_reach(x, y, sfrlines, rno_column='rno'): """Get the SFR reach number closest to a point feature. Parameters ---------- x : scalar or list of scalars x-coordinate(s) of point feature(s) y : scalar or list of scalars y-coordinate(s) or point feature(s) sfrlines: dataframe DataFrame containing a geometry column with SFR line arcs, and a column rno_column with unique numbers for each reach. rno_column: str Column with unique number for each reach. default "rno" threshold : numeric Distance threshold (in CRS units). Only return reaches within this distance. Returns ------- rno : int or list of ints Reach numbers for reaches closest to each location defined by x, y. """ scalar = False if np.isscalar(x): scalar = True x = [x] if np.isscalar(y): y = [y] geoms = sfrlines.geometry.values rno = sfrlines[rno_column].values allX = [] # all x coordinates in sfrlines allY = [] # all y coordinates in sfrlines all_rno = [] # reach number for each x, y point in sfrlines for i, g in enumerate(geoms): if 'Multi' not in g.type: g = [g] for part in g: gx, gy = part.coords.xy allX += gx allY += gy all_rno += [rno[i]]*len(gx) allX = np.array(allX) allY =
np.array(allY)
numpy.array
import numpy as np from munch import unmunchify from tensorboardX import SummaryWriter from stable_baselines3.common.monitor import Monitor class CoordMonitor(Monitor): REQUEST_KEYS = ['accepts', 'requests', 'num_invalid', 'num_rejects', 'no_egress_route', 'no_extension', 'skipped_on_arrival'] ACCEPTED_KEYS = ['cum_service_length', 'cum_route_hops', 'cum_datarate', 'cum_max_latency', 'cum_resd_latency'] ACCEPTED_VALS = ['mean_service_len', 'mean_hops', 'mean_datarate', 'mean_latency', 'mean_resd_latency'] def __init__(self, episode, tag, env, filename=None, allow_early_resets=True, reset_keywords=(), infor_keywords=()): super().__init__(env, None, allow_early_resets, reset_keywords, infor_keywords) self.writer = SummaryWriter(filename) self.episode = episode self.tag = tag self.reset() def close(self): self.writer.flush() self.writer.close() super().close() def reset(self, **kwargs): self.c_util, self.m_util, self.d_util = [], [], [] return super().reset(**kwargs) def step(self, action): obs, reward, done, info = super().step(action) for service in range(len(self.env.services)): logs = unmunchify(self.env.info[service]) for key in self.REQUEST_KEYS: scalar = logs[key] / self.env.num_requests tag = f'{self.tag}/{service}/{key}' self.writer.add_scalar(tag, scalar, self.episode) accepts = logs['accepts'] if logs['accepts'] > 0 else np.inf for key in self.ACCEPTED_KEYS: scalar = logs[key] / accepts tag = f'{self.tag}/{service}/{key}' self.writer.add_scalar(tag, scalar, self.episode) self.update_utilization() return obs, reward, done, info def update_utilization(self): nodes = self.env.net.nodes cutil = [1 - self.env.computing[n] / self.env.net.nodes[n]['compute'] for n in nodes] mutil = [1 - self.env.memory[n] / self.env.net.nodes[n]['memory'] for n in nodes] cutil =
np.mean(cutil)
numpy.mean
# -*- coding: utf-8 -*- """ implementation of the gamut mapping described in Report ITU-R BT.2407 Annex2. """ # import standard libraries import os # import third-party libraries import numpy as np from multiprocessing import Pool, cpu_count, Array from colour import RGB_to_XYZ, XYZ_to_Lab, Lab_to_XYZ, XYZ_to_RGB,\ RGB_COLOURSPACES # import my libraries from bt2407_parameters import get_chroma_map_lut_name,\ get_gamut_boundary_lut_name import color_space as cs from cielab import bilinear_interpolation from bt2407_parameters import GAMUT_BOUNDARY_LUT_LUMINANCE_SAMPLE,\ GAMUT_BOUNDARY_LUT_HUE_SAMPLE, get_l_cusp_name, get_focal_name from make_bt2047_luts import calc_value_from_hue_1dlut, load_cusp_focal_lut,\ calc_chroma_map_degree2 # information __author__ = '<NAME>' __copyright__ = 'Copyright (C) 2019 - <NAME>' __license__ = 'New BSD License - https://opensource.org/licenses/BSD-3-Clause' __maintainer__ = '<NAME>' __email__ = 'toru.ver.11 at-sign gmail.com' __all__ = [] def merge_lightness_mapping( hd_data_l, st_degree_l, chroma_map_l, lightness_map_l, chroma_map_c, lightness_map_c): """ L_Focalベース, C_Focalベースの結果をマージする。 具体的には、入力の hd_data_l の degree に対して、 L_Focal の開始 degree よりも大きい場合は L_Focal の結果を、 それ意外は C_Focal の結果を使うようにしている。 Parameters ---------- hd_data_l : array_like L_focal ベースの hue-degree のデータ st_degree_l : array_like chroma mapping 用の hue-degree 2DLUT の各HUEに対する 開始 degree の入ったデータ chroma_map_l : array_like L_Focal ベースで Lightness Mapping したあとの Chroma値 lightness_map_l : array_like L_Focal ベースで Lightness Mapping したあとの Lightness値 chroma_map_c : array_like C_Focal ベースで Lightness Mapping したあとの Chroma値 lightness_map_c : array_like C_Focal ベースで Lightness Mapping したあとの Lightness値 """ # 出力用バッファ用意 chroma_out = np.zeros_like(chroma_map_l) lightness_out = np.zeros_like(lightness_map_l) # 上側・下側のデータを後で抜き出すためのindexを計算 st_degree_l_intp = calc_value_from_hue_1dlut( hd_data_l[..., 0], st_degree_l) upper_area_idx = (hd_data_l[..., 1] >= st_degree_l_intp) lower_area_idx = np.logical_not(upper_area_idx) # L_focal と C_focal の結果をマージ chroma_out[upper_area_idx] = chroma_map_l[upper_area_idx] lightness_out[upper_area_idx] = lightness_map_l[upper_area_idx] chroma_out[lower_area_idx] = chroma_map_c[lower_area_idx] lightness_out[lower_area_idx] = lightness_map_c[lower_area_idx] return chroma_out, lightness_out def eliminate_inner_gamut_data_l_focal( dst_distance, src_chroma, src_lightness, l_focal): """ 元々の Gamut の範囲内のデータは Lightness Mapping を しないように元のデータに戻す。 実は Lightness Mapping では Gamutの範囲内外もすべて Gamut の境界線上にマッピングしてしまっている(分岐を減らすため)。 当然、Mapping が不要なデータは戻すべきであり、本関数ではその処理を行う。 ここでは Luminance Mapping の前後での Focal からの distance を 比較している。前述の通り、Luminance Mapping では Gamut の内外を問わず 全て Gamut の境界線上にマッピングしている。したがって、 `src_distance <= dst_distance` の配列のデータを元に戻せば良い。 Parameters ---------- dst_distance : array_like distance from L_focal after luminance mapping. src_chroma : array_like chroma value before luminance mapping. lightness : array_like lightness value before luminance mapping. """ src_distance = calc_distance_from_l_focal( src_chroma, src_lightness, l_focal) restore_idx_l = (src_distance <= dst_distance) dst_distance[restore_idx_l] = src_distance[restore_idx_l] def eliminate_inner_gamut_data_c_focal( dst_distance, src_chroma, src_lightness, c_focal): """ 元々の Gamut の範囲内のデータは Lightness Mapping を しないように元のデータに戻す。 実は Lightness Mapping では Gamutの範囲内外もすべて Gamut の境界線上にマッピングしてしまっている(分岐を減らすため)。 当然、Mapping が不要なデータは戻すべきであり、本関数ではその処理を行う。 ここでは Luminance Mapping の前後での Focal からの distance を 比較している。前述の通り、Luminance Mapping では Gamut の内外を問わず 全て Gamut の境界線上にマッピングしている。したがって、 `src_distance > dst_distance` の配列のデータを元に戻せば良い。 Parameters ---------- dst_distance : array_like distance from L_focal after luminance mapping. src_chroma : array_like chroma value before luminance mapping. lightness : array_like lightness value before luminance mapping. """ src_distance = calc_distance_from_c_focal( src_chroma, src_lightness, c_focal) restore_idx_c = (src_distance > dst_distance) dst_distance[restore_idx_c] = src_distance[restore_idx_c] def interpolate_chroma_map_lut(cmap_hd_lut, degree_min, degree_max, data_hd): """ Chroma Mapping の LUT が任意の Input に 対応できるように補間をする。 LUTは Hue-Degree の2次元LUTである。 これを Bilinear補間する。 cmap_hd_lut: array_like Hue, Degree に対応する Chroma値が入っているLUT。 degree_min: array_like cmap_hd_lut の 各 h_idx に対する degree の 開始角度(degree_min)、終了角度(degree_max) が 入っている。 print(degree_min[h_idx]) ==> 0.4pi みたいなイメージ data_hd: array_like(shape is (N, 2)) data_hd[..., 0]: Hue Value data_hd[..., 1]: Degree """ # 補間に利用するLUTのIndexを算出 hue_data = data_hd[..., 0] degree_data = data_hd[..., 1] hue_sample_num = GAMUT_BOUNDARY_LUT_HUE_SAMPLE hue_index_max = hue_sample_num - 1 degree_sample_num = GAMUT_BOUNDARY_LUT_HUE_SAMPLE degree_index_max = degree_sample_num - 1 # 1. h_idx h_idx_float = hue_data / (2 * np.pi) * (hue_index_max) h_idx_low = np.int16(h_idx_float) h_idx_high = h_idx_low + 1 h_idx_low = np.clip(h_idx_low, 0, hue_index_max) h_idx_high = np.clip(h_idx_high, 0, hue_index_max) degree_lmin = degree_min[h_idx_low] degree_lmax = degree_max[h_idx_low] degree_hmin = degree_min[h_idx_high] degree_hmax = degree_max[h_idx_high] # 2. d_idx d_idx_l_float = (degree_data - degree_lmin)\ / (degree_lmax - degree_lmin) * degree_index_max d_idx_l_float = np.clip(d_idx_l_float, 0, degree_index_max) d_idx_ll = np.int16(d_idx_l_float) d_idx_lh = d_idx_ll + 1 d_idx_h_float = (degree_data - degree_hmin)\ / (degree_hmax - degree_hmin) * degree_index_max d_idx_h_float = np.clip(d_idx_h_float, 0, degree_index_max) d_idx_hl = np.int16(d_idx_h_float) d_idx_hh = d_idx_hl + 1 d_idx_ll = np.clip(d_idx_ll, 0, degree_index_max) d_idx_lh = np.clip(d_idx_lh, 0, degree_index_max) d_idx_hl = np.clip(d_idx_hl, 0, degree_index_max) d_idx_hh = np.clip(d_idx_hh, 0, degree_index_max) # 3. r_low, r_high r_low = d_idx_lh - d_idx_l_float r_high = d_idx_hh - d_idx_h_float # 4. interpolation in degree derection intp_d_low = r_low * cmap_hd_lut[h_idx_low, d_idx_ll]\ + (1 - r_low) * cmap_hd_lut[h_idx_low, d_idx_lh] intp_d_high = r_high * cmap_hd_lut[h_idx_high, d_idx_hl]\ + (1 - r_high) * cmap_hd_lut[h_idx_high, d_idx_hh] # 6. final_r final_r = h_idx_high - h_idx_float # 7. interpolation in hue direction intp_data = final_r * intp_d_low + (1 - final_r) * intp_d_high return intp_data def calc_distance_from_l_focal(chroma, lightness, l_focal): """ L_Focal から 引数で指定した Chroma-Lightness までの距離を求める。 """ distance = ((chroma) ** 2 + (lightness - l_focal) ** 2) ** 0.5 return distance def calc_distance_from_c_focal(chroma, lightness, c_focal): """ C_Focal から 引数で指定した Chroma-Lightness までの距離を求める。 """ distance = ((chroma - c_focal) ** 2 + (lightness) ** 2) ** 0.5 return distance def calc_degree_from_cl_data_using_l_focal(cl_data, l_focal): """ chroma-lightness のデータから degree を計算 """ chroma = cl_data[..., 0] lightness = cl_data[..., 1] # chroma == 0 は -np.pi/2 or np.pi/2 になる degree = np.where( chroma != 0, np.arctan((lightness - l_focal) / chroma), (np.pi / 2) * np.sign(lightness - l_focal) ) return degree def calc_degree_from_cl_data_using_c_focal(cl_data, c_focal): """ chroma-lightness のデータから degree を計算 """ chroma = cl_data[..., 0] lightness = cl_data[..., 1] return np.arctan(lightness / (chroma - c_focal)) + np.pi def calc_cusp_lut(lh_lut): """ Gamut Boundary の Lightness-Hue の LUTから Cusp の (Lightness, Chroma) 情報が入った LUT を作る。 Parameters ---------- lh_lut : array_like Gamut Bondary の lh_lut[L_idx, H_idx] = Chroma 的なやつ。 Returns ------- array_like H_idx を入れると Lightness, Chroma が得られる LUT。 retun_val[h_idx, 0] => Lightness retun_val[h_idx, 1] => Chroma 的な。 """ cusp_chroma = np.max(lh_lut, axis=0) cusp_chroma_idx = np.argmax(lh_lut, axis=0) cusp_lightness = cusp_chroma_idx / (lh_lut.shape[0] - 1) * 100 return np.dstack((cusp_lightness, cusp_chroma))[0] def get_chroma_lightness_val_specfic_hue( hue=30/360*2*np.pi, lh_lut_name=get_gamut_boundary_lut_name(cs.BT709)): """ Gamut Boundary の LUT から 任意の HUE の Chroma-Lighenss を得る。 以下のコマンドで 横軸 Chroma、縦軸 Lightness の平面が書ける。 ``` plt.plot(retun_vall[..., 0], retun_vall[..., 1]) plt.show() ``` """ lh_lut = np.load(lh_lut_name) lstar = np.linspace(0, 100, lh_lut.shape[0]) hue_list = np.ones((lh_lut.shape[1])) * hue lh = np.dstack([lstar, hue_list]) chroma = bilinear_interpolation(lh, lh_lut) return np.dstack((chroma, lstar))[0] def calc_chroma_lightness_using_length_from_l_focal( distance, degree, l_focal): """ L_Focal からの距離(distance)から chroma, lightness 値を 三角関数の計算で算出する。 Parameters ---------- distance : array_like Chroma-Lightness 平面における L_focal からの距離の配列。 例えば Lightness Mapping 後の距離が入ってたりする。 degree : array_like L_focal からの角度。Chroma軸が0°である。 l_focal : array_like l_focal の配列。Lightness の値のリスト。 Returns ------ chroma : array_like Chroma値 lightness : array_like Lightness値 """ chroma = distance * np.cos(degree) lightness = distance * np.sin(degree) + l_focal return chroma, lightness def calc_chroma_lightness_using_length_from_c_focal( distance, degree, c_focal): """ C_Focal からの距離(distance)から chroma, lightness 値を 三角関数の計算で算出する。 Parameters ---------- distance : array_like Chroma-Lightness 平面における C_focal からの距離の配列。 例えば Lightness Mapping 後の距離が入ってたりする。 degree : array_like C_focal からの角度。Chroma軸が0°である。 c_focal : array_like c_focal の配列。Chroma の値のリスト。 Returns ------ chroma : array_like Chroma値 lightness : array_like Lightness値 """ chroma = distance * np.cos(degree) + c_focal lightness = distance * np.sin(degree) return chroma, lightness def calc_hue_from_ab(aa, bb): """ CIELAB空間で a, b の値から HUE を計算する。 出力の値域は [0, 2pi) である。 Examples -------- >>> aa=np.array([1.0, 0.5, 0.0, -0.5, -1.0, -0.5, 0.0, 0.5, 0.99])*np.pi, >>> bb=np.array([0.0, 0.5, 1.0, 0.5, 0.0, -0.5, -1.0, -0.5, -0.001])*np.pi >>> hue = calc_hue_from_ab(aa, bb) [0. 45. 90. 135. 180. 225. 270. 315. 359.94212549] """ hue = np.where(aa != 0, np.arctan(bb/aa), np.pi/2*np.sign(bb)) add_pi_idx = (aa < 0) & (bb >= 0) sub_pi_idx = (aa < 0) & (bb < 0) hue[add_pi_idx] = hue[add_pi_idx] + np.pi hue[sub_pi_idx] = hue[sub_pi_idx] - np.pi hue[hue < 0] = hue[hue < 0] + 2 * np.pi return hue def calc_hue_degree_data_from_rgb( rgb_linear, l_focal_lut, c_focal_lut, outer_color_space_name=cs.BT2020): """ Lightness Mapping に使用する Hue-Degree 形式に変換する。 """ large_xyz = RGB_to_XYZ( rgb_linear, cs.D65, cs.D65, RGB_COLOURSPACES[outer_color_space_name].RGB_to_XYZ_matrix) lab = XYZ_to_Lab(large_xyz) lightness = lab[..., 0] aa = lab[..., 1] bb = lab[..., 2] hue = calc_hue_from_ab(aa, bb) chroma = ((aa ** 2) + (bb ** 2)) ** 0.5 # _debug_plot_ab_plane(rgb_linear, hue, chroma) cl_data = np.dstack((chroma, lightness))[0] degree_l = calc_degree_from_cl_data_using_l_focal( cl_data=cl_data, l_focal=calc_value_from_hue_1dlut(hue, l_focal_lut)) degree_c = calc_degree_from_cl_data_using_c_focal( cl_data=cl_data, c_focal=calc_value_from_hue_1dlut(hue, c_focal_lut)) hd_data_l = np.dstack((hue, degree_l))[0] hd_data_c =
np.dstack((hue, degree_c))
numpy.dstack
# -*- coding: utf-8 -*- """ Created on Thu Feb 20 21:52:42 2020 @author: wany105 """ import ShareFunction as sf class PTinter1(object): """Establish one type of the Power-Transportation Interdependency: Power Provides Electricity to Transportation Signals """ def __init__(self, network1, network2, name, color): self.name = name ##Network2 depends on Network1, flow moves from network1 to network2 self.network1 = network1 self.network2 = network2 self.c = color def distadj(self): """Calculate the distance matrix for two networks distance matrix D: network1.Nnum \times network2.Nnum D[i, j] represents the distance between node i in network1 and node j in network2 """ import numpy as np self.D = np.zeros([self.network1.Nnum, self.network2.Nnum]) for i in range(self.network1.Nnum): for j in range(self.network2.Nnum): node1 = np.array([self.network1.Nx[i], self.network1.Ny[i]]) node2 = np.array([self.network2.Nx[j], self.network2.Ny[j]]) self.D[i, j] = sf.dist(node1, node2)/1000 def dependadj(self, DepenNum): """Define the adjacent matrix for the interdependency A of dimension network1.Nnum*network2.Nnum A[i, j] = 1: there is an arc from node i in network1 to node j in network2, flow can move from node j in network2 to network1 A[i ,j] = 0: there is no arc currently DepenNum[j]: The number of nodes in network1 that node j relies on """ import math import numpy as np self.adj = np.zeros([self.network1.Nnum, self.network2.Nnum]) for i in range(self.network2.Nnum): Index = sf.sortget(list(self.D[:, i]), DepenNum[i]) self.adj[Index, i] = 1 def loadnetwork1(self, psignal): """Calculate the flow going into each vertex in network1 based on the need of each vertex in network2 """ import numpy as np self.network2.powersignal(psignal) self.network1.dadj = np.zeros(self.network1.Nnum) for i in range(self.network2.Nnum): index = sf.indexget(self.adj[:, i], 1) temp = self.network2.psignal[i]/len(index) #Assumption: the energy required is divided evenly self.network1.dadj[index] += temp self.flowadj() return self.network1.dadj def flowadj(self): """Set up the flow matrix for the interdependency link flow[i, j] denotes the flow along the interdependency link from node i in network1 to node j in network2 """ import numpy as np self.flow =
np.zeros([self.network1.Nnum, self.network2.Nnum])
numpy.zeros
import numpy as np from scipy.stats import random_correlation, norm, expon from scipy.linalg import svdvals import warnings warnings.filterwarnings("error") from collections import defaultdict def get_mae(x_imp, x_true, x_obs=None): """ gets Mean Absolute Error (MAE) between x_imp and x_true """ x_imp = np.asarray(x_imp) x_true = np.asarray(x_true) if x_obs is not None: x_obs = np.asarray(x_obs) loc = np.isnan(x_obs) & (~np.isnan(x_true)) else: loc = ~np.isnan(x_true) diff = x_imp[loc] - x_true[loc] return np.mean(np.abs(diff)) def get_rmse(x_imp, x_true, x_obs = None, relative=False): """ gets Root Mean Squared Error (RMSE) or Normalized Root Mean Squared Error (NRMSE) between x_imp and x_true Parameters ---------- x_imp : array-like of shape (nsamples, nfeatures) Imputed complete matrix x_true : array-like of shape (nsamples, nfeatures) True matrix. Can be incomplete x_obs : array-like of shape (nsamples, nfeatures) or None Observed incomplete matrix. The evaluation entries are those observed in x_true but not in x_obs If None, evaluation entries are those observed in x_true. relative : bool, default=False Return NRMSE if True and RMSE if False """ x_imp = np.asarray(x_imp) x_true = np.asarray(x_true) if x_obs is not None: x_obs = np.asarray(x_obs) loc = np.isnan(x_obs) & (~np.isnan(x_true)) else: loc = ~np.isnan(x_true) diff = x_imp[loc] - x_true[loc] #mse = np.mean(diff**2.0, axis=0) mse = np.mean(np.power(diff, 2)) rmse = np.sqrt(mse) if not relative: return rmse else: # RMSE of zero-imputation norm = np.sqrt(np.mean(np.power(x_true[loc],2))) return rmse/norm def get_smae(x_imp, x_true, x_obs, baseline=None, per_type=False, var_types = {'cont':list(range(5)), 'ord':list(range(5, 10)), 'bin':list(range(10, 15))}): """ gets Scaled Mean Absolute Error (SMAE) between x_imp and x_true """ x_imp = np.asarray(x_imp) x_true = np.asarray(x_true) x_obs = np.asarray(x_obs) p = x_obs.shape[1] # the first column records the imputation error of x_imp, # while the second column records the imputation error of baseline error = np.zeros((p,2)) # iterate over columns/variables for i, col in enumerate(x_obs.T): test = np.bitwise_and(~np.isnan(x_true[:,i]), np.isnan(col)) # skip the column if there is no evaluation entry if np.sum(test) == 0: error[i,0] = np.nan error[i,1] = np.nan print(f'There is no entry to be evaluated in variable {i}.') continue base_imp = np.median(col[~np.isnan(col)]) if baseline is None else baseline[i] x_true_col = x_true[test,i] x_imp_col = x_imp[test,i] diff = np.abs(x_imp_col - x_true_col) base_diff = np.abs(base_imp - x_true_col) error[i,0] = np.sum(diff) error[i,1] = np.sum(base_diff) if per_type: scaled_diffs = {} for name, val in var_types.items(): try: scaled_diffs[name] = np.sum(error[val,0])/np.sum(error[val,1]) except RuntimeWarning: print(f'Baseline imputation achieves zero imputation error in some variable.') raise else: try: scaled_diffs = error[:,0] / error[:,1] except RuntimeWarning: print(f'Baseline imputation achieves zero imputation error in some variable.') raise return scaled_diffs def batch_iterable(X, batch_size=40): ''' Generator which returns a mini-batch view of X. ''' n = X.shape[0] start = 0 while start < n: end = min(start + batch_size, n) yield X[start:end] start = end def get_smae_batch(x_imp, x_true, x_obs, batch_size = 40, baseline=None, per_type=False, var_types = {'cont':list(range(5)), 'ord':list(range(5, 10)), 'bin':list(range(10, 15))}): ''' Compute SMAE in the unit of a mini-batch ''' x_imp = np.asarray(x_imp) x_true = np.asarray(x_true) x_obs = np.asarray(x_obs) result = defaultdict(list) if per_type else [] baseline = np.nanmedian(x_obs,0) if baseline is None else baseline for imp, true, obs in zip(batch_iterable(x_imp,batch_size), batch_iterable(x_true,batch_size), batch_iterable(x_obs,batch_size)): scaled_diffs = get_smae(imp, true, obs, baseline=baseline, per_type=per_type) if per_type: for name, val in scaled_diffs.items(): result[name].append(val) else: result.append(scaled_diffs) return result def get_scaled_error(sigma_imp, sigma): """ gets a scaled error between matrices |simga - sigma_imp|_F^2 / |sigma|_F^2 """ return np.linalg.norm(sigma - sigma_imp) / np.linalg.norm(sigma) def grassman_dist(A,B): U1, d1, _ = np.linalg.svd(A, full_matrices = False) U2, d2, _ = np.linalg.svd(B, full_matrices = False) d = svdvals(np.dot(U1.T, U2)) theta = np.arccos(d) return np.linalg.norm(theta),
np.linalg.norm(d1-d2)
numpy.linalg.norm
# TODO maybe handle conversions using scipy # img_as_float # Convert to 64-bit floating point. # img_as_ubyte # Convert to 8-bit uint. # img_as_uint # Convert to 16-bit uint. # img_as_int # Convert to 16-bit int. # TODO allow add or remove ROIs --> create IJ compatible ROIs... --> in a way that is simpler than the crop I was proposing --> think about how to implement that # logging from epyseg.tools.logger import TA_logger logger = TA_logger() # logging_level=TA_logger.DEBUG import random import os import read_lif # read Leica .lif files (requires numexpr) from builtins import super, int import warnings import skimage from skimage import io from PIL import Image import tifffile # open Zeiss .tif and .lsm files import czifile # open .czi spim files import glob from skimage.transform import rescale from skimage.util import img_as_ubyte import scipy.signal # convolution of images import numpy as np import json from PyQt5.QtGui import QImage, QColor # allows for qimage creation from natsort import natsorted # sort strings as humans would do import xml.etree.ElementTree as ET # to handle xml metadata of images import base64 import io import matplotlib.pyplot as plt import traceback from skimage.morphology import white_tophat, black_tophat, disk from skimage.morphology import square, ball, diamond, octahedron, rectangle # for future development # np = None # try: # np = __import__('cupy') # 3d accelerated numpy # except: # np = __import__('numpy') def RGB_to_int24(RGBimg): RGB24 = (RGBimg[..., 0].astype(np.uint32) << 16) | (RGBimg[..., 1].astype(np.uint32) << 8) | RGBimg[..., 2].astype( np.uint32) return RGB24 def int24_to_RGB(RGB24): RGBimg =
np.zeros(shape=(*RGB24.shape, 3), dtype=np.uint8)
numpy.zeros
# This module has been generated automatically from space group information # obtained from the Computational Crystallography Toolbox # """ Space groups This module contains a list of all the 230 space groups that can occur in a crystal. The variable space_groups contains a dictionary that maps space group numbers and space group names to the corresponding space group objects. .. moduleauthor:: <NAME> <<EMAIL>> """ #----------------------------------------------------------------------------- # Copyright (C) 2013 The Mosaic Development Team # # Distributed under the terms of the BSD License. The full license is in # the file LICENSE.txt, distributed as part of this software. #----------------------------------------------------------------------------- import numpy as N class SpaceGroup(object): """ Space group All possible space group objects are created in this module. Other modules should access these objects through the dictionary space_groups rather than create their own space group objects. """ def __init__(self, number, symbol, transformations): """ :param number: the number assigned to the space group by international convention :type number: int :param symbol: the Hermann-Mauguin space-group symbol as used in PDB and mmCIF files :type symbol: str :param transformations: a list of space group transformations, each consisting of a tuple of three integer arrays (rot, tn, td), where rot is the rotation matrix and tn/td are the numerator and denominator of the translation vector. The transformations are defined in fractional coordinates. :type transformations: list """ self.number = number self.symbol = symbol self.transformations = transformations self.transposed_rotations = N.array([N.transpose(t[0]) for t in transformations]) self.phase_factors = N.exp(N.array([(-2j*N.pi*t[1])/t[2] for t in transformations])) def __repr__(self): return "SpaceGroup(%d, %s)" % (self.number, repr(self.symbol)) def __len__(self): """ :return: the number of space group transformations :rtype: int """ return len(self.transformations) def symmetryEquivalentMillerIndices(self, hkl): """ :param hkl: a set of Miller indices :type hkl: Scientific.N.array_type :return: a tuple (miller_indices, phase_factor) of two arrays of length equal to the number of space group transformations. miller_indices contains the Miller indices of each reflection equivalent by symmetry to the reflection hkl (including hkl itself as the first element). phase_factor contains the phase factors that must be applied to the structure factor of reflection hkl to obtain the structure factor of the symmetry equivalent reflection. :rtype: tuple """ hkls = N.dot(self.transposed_rotations, hkl) p = N.multiply.reduce(self.phase_factors**hkl, -1) return hkls, p space_groups = {} transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(1, 'P 1', transformations) space_groups[1] = sg space_groups['P 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(2, 'P -1', transformations) space_groups[2] = sg space_groups['P -1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(3, 'P 1 2 1', transformations) space_groups[3] = sg space_groups['P 1 2 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(4, 'P 1 21 1', transformations) space_groups[4] = sg space_groups['P 1 21 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(5, 'C 1 2 1', transformations) space_groups[5] = sg space_groups['C 1 2 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(6, 'P 1 m 1', transformations) space_groups[6] = sg space_groups['P 1 m 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(7, 'P 1 c 1', transformations) space_groups[7] = sg space_groups['P 1 c 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(8, 'C 1 m 1', transformations) space_groups[8] = sg space_groups['C 1 m 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(9, 'C 1 c 1', transformations) space_groups[9] = sg space_groups['C 1 c 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(10, 'P 1 2/m 1', transformations) space_groups[10] = sg space_groups['P 1 2/m 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(11, 'P 1 21/m 1', transformations) space_groups[11] = sg space_groups['P 1 21/m 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(12, 'C 1 2/m 1', transformations) space_groups[12] = sg space_groups['C 1 2/m 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(13, 'P 1 2/c 1', transformations) space_groups[13] = sg space_groups['P 1 2/c 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(14, 'P 1 21/c 1', transformations) space_groups[14] = sg space_groups['P 1 21/c 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(15, 'C 1 2/c 1', transformations) space_groups[15] = sg space_groups['C 1 2/c 1'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(16, 'P 2 2 2', transformations) space_groups[16] = sg space_groups['P 2 2 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(17, 'P 2 2 21', transformations) space_groups[17] = sg space_groups['P 2 2 21'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(18, 'P 21 21 2', transformations) space_groups[18] = sg space_groups['P 21 21 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(19, 'P 21 21 21', transformations) space_groups[19] = sg space_groups['P 21 21 21'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(20, 'C 2 2 21', transformations) space_groups[20] = sg space_groups['C 2 2 21'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(21, 'C 2 2 2', transformations) space_groups[21] = sg space_groups['C 2 2 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(22, 'F 2 2 2', transformations) space_groups[22] = sg space_groups['F 2 2 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(23, 'I 2 2 2', transformations) space_groups[23] = sg space_groups['I 2 2 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(24, 'I 21 21 21', transformations) space_groups[24] = sg space_groups['I 21 21 21'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(25, 'P m m 2', transformations) space_groups[25] = sg space_groups['P m m 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(26, 'P m c 21', transformations) space_groups[26] = sg space_groups['P m c 21'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(27, 'P c c 2', transformations) space_groups[27] = sg space_groups['P c c 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(28, 'P m a 2', transformations) space_groups[28] = sg space_groups['P m a 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(29, 'P c a 21', transformations) space_groups[29] = sg space_groups['P c a 21'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(30, 'P n c 2', transformations) space_groups[30] = sg space_groups['P n c 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(31, 'P m n 21', transformations) space_groups[31] = sg space_groups['P m n 21'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(32, 'P b a 2', transformations) space_groups[32] = sg space_groups['P b a 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(33, 'P n a 21', transformations) space_groups[33] = sg space_groups['P n a 21'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(34, 'P n n 2', transformations) space_groups[34] = sg space_groups['P n n 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(35, 'C m m 2', transformations) space_groups[35] = sg space_groups['C m m 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(36, 'C m c 21', transformations) space_groups[36] = sg space_groups['C m c 21'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(37, 'C c c 2', transformations) space_groups[37] = sg space_groups['C c c 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(38, 'A m m 2', transformations) space_groups[38] = sg space_groups['A m m 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(39, 'A b m 2', transformations) space_groups[39] = sg space_groups['A b m 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(40, 'A m a 2', transformations) space_groups[40] = sg space_groups['A m a 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(41, 'A b a 2', transformations) space_groups[41] = sg space_groups['A b a 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(42, 'F m m 2', transformations) space_groups[42] = sg space_groups['F m m 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,3,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,3,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([3,1,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([3,1,3]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([3,3,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([3,3,1]) trans_den = N.array([4,4,4]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(43, 'F d d 2', transformations) space_groups[43] = sg space_groups['F d d 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(44, 'I m m 2', transformations) space_groups[44] = sg space_groups['I m m 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(45, 'I b a 2', transformations) space_groups[45] = sg space_groups['I b a 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(46, 'I m a 2', transformations) space_groups[46] = sg space_groups['I m a 2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(47, 'P m m m', transformations) space_groups[47] = sg space_groups['P m m m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(48, 'P n n n :2', transformations) space_groups[48] = sg space_groups['P n n n :2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(49, 'P c c m', transformations) space_groups[49] = sg space_groups['P c c m'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,0]) trans_den = N.array([1,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(50, 'P b a n :2', transformations) space_groups[50] = sg space_groups['P b a n :2'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(51, 'P m m a', transformations) space_groups[51] = sg space_groups['P m m a'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,1,1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,-1,-1]) trans_den = N.array([1,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,-1]) trans_den = N.array([2,2,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(52, 'P n n a', transformations) space_groups[52] = sg space_groups['P n n a'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(53, 'P m n a', transformations) space_groups[53] = sg space_groups['P m n a'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,0,1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,0,-1]) trans_den = N.array([2,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,-1]) trans_den = N.array([1,1,2]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([-1,0,0]) trans_den = N.array([2,1,1]) transformations.append((rot, trans_num, trans_den)) sg = SpaceGroup(54, 'P c c a', transformations) space_groups[54] = sg space_groups['P c c a'] = sg transformations = [] rot = N.array([1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([1,1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,-1,0,0,0,-1]) rot.shape = (3, 3) trans_num = N.array([0,0,0]) trans_den = N.array([1,1,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([-1,0,0,0,1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,-1,0,0,0,1]) rot.shape = (3, 3) trans_num = N.array([-1,-1,0]) trans_den = N.array([2,2,1]) transformations.append((rot, trans_num, trans_den)) rot = N.array([1,0,0,0,1,0,0,0,-1]) rot.shape = (3, 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])
numpy.array
import numpy as np import os import random import cv2 def load_imgpath_labels(filename, labels_num=1, shuffle=True): imgpath=[] labels=[] with open(os.path.join(filename)) as f: lines_list = f.readlines() if shuffle: random.shuffle(lines_list) for lines in lines_list: line = lines.rstrip().split(',') label = None if labels_num == 1: label = int(line[1]) else: for i in range(labels_num): label.append(int(line[i+1])) imgpath.append(line[0]) labels.append(label) return np.array(imgpath), np.array(labels) def get_input_img(filename, input_size=32): img = cv2.imread(filename) img = cv2.resize(img, (input_size, input_size)) img = np.array(img, dtype=np.float32) img = np.reshape(img, -1) return img def fer_generator(data_file, batch_size=64): filenames, labels = load_imgpath_labels(data_file) file_num = len(filenames) def get_epoch(): rng_state = np.random.get_state() np.random.shuffle(filenames) np.random.set_state(rng_state) np.random.shuffle(labels) max_num = file_num - (file_num % batch_size) for i in range(0, max_num, batch_size): batch_x = [] batch_y = [] for j in range(batch_size): img = get_input_img(filenames[i + j]) label = labels[i + j] batch_x.append(img) batch_y.append(label) batch_x = np.array(batch_x, dtype=np.float32) batch_y =
np.array(batch_y)
numpy.array
""" Compare preformance of methods within certain running time. Author(s): <NAME> (<EMAIL>) """ import argparse import os import itertools import numpy as np import matplotlib.pyplot as plt plt.rcParams.update({'font.size': 18}) if __name__ == "__main__": # Arguments parser = argparse.ArgumentParser(description='Optimize') parser.add_argument('--n_runs', type=int, default=10, help='number of runs') parser.add_argument('--n_eval', type=int, default=500, help='number of evaluations per run') args = parser.parse_args() n_runs = args.n_runs n_eval = args.n_eval ''' Call optimization ''' for latent_dim in [2, 4, 6, 8, 10]: if not os.path.exists('./results_opt/gan_bo_refine_{}_10/opt_history.npy'.format(latent_dim)) or not os.path.exists('./results_opt/gan_bo_refine_{}_10/opt_airfoil.npy'.format(latent_dim)): os.system('python optimize_gan_bo_refine.py {} 10 --n_runs={} --n_eval={}'.format(latent_dim, args.n_runs, args.n_eval)) if not os.path.exists('./results_opt/gan_bo_8_0/opt_history.npy') or not os.path.exists('./results_opt/gan_bo_8_0/opt_airfoil.npy'): os.system('python optimize_gan_bo.py 8 0 --n_runs={} --n_eval={}'.format(args.n_runs, args.n_eval)) if not os.path.exists('./results_opt/gan_bo_refine_8_20/opt_history.npy') or not os.path.exists('./results_opt/gan_bo_refine_8_20/opt_airfoil.npy'): os.system('python optimize_gan_bo_refine.py 8 20 --n_runs={} --n_eval={}'.format(args.n_runs, args.n_eval)) for latent_dim in [2, 4, 6, 8, 10]: if not os.path.exists('./results_opt/gan_bo_{}_10/opt_history.npy'.format(latent_dim)) or not os.path.exists('./results_opt/gan_bo_{}_10/opt_airfoil.npy'.format(latent_dim)): os.system('python optimize_gan_bo.py {} 10 --n_runs={} --n_eval={}'.format(latent_dim, args.n_runs, args.n_eval)) for dim in [6, 8, 10, 12]: if not os.path.exists('./results_opt/generic_bo_{}/opt_history.npy'.format(dim)) or not os.path.exists('./results_opt/generic_bo_{}/opt_airfoil.npy'.format(dim)): os.system('python optimize_generic_bo.py {} --n_runs={} --n_eval={}'.format(dim, args.n_runs, args.n_eval)) if not os.path.exists('./results_opt/generic_ga_8/opt_history.npy') or not os.path.exists('./results_opt/generic_ga_8/opt_airfoil.npy'): os.system('python optimize_generic_ga.py 8 --n_runs={} --n_eval={}'.format(args.n_runs, args.n_eval)) for dim in [8, 9, 10]: if not os.path.exists('./results_opt/svd_bo_{}/opt_history.npy'.format(dim)) or not os.path.exists('./results_opt/svd_bo_{}/opt_airfoil.npy'.format(dim)): os.system('python optimize_svd_bo.py {} --n_runs={} --n_eval={}'.format(dim, args.n_runs, args.n_eval)) if not os.path.exists('./results_opt/svd_ga_9/opt_history.npy') or not os.path.exists('./results_opt/svd_ga_9/opt_airfoil.npy'): os.system('python optimize_svd_ga.py 9 --n_runs={} --n_eval={}'.format(args.n_runs, args.n_eval)) if not os.path.exists('./results_opt/nurbs_bo/opt_history.npy') or not os.path.exists('./results_opt/nurbs_bo/opt_airfoil.npy'): os.system('python optimize_nurbs_bo.py --n_runs={} --n_eval={}'.format(args.n_runs, args.n_eval)) if not os.path.exists('./results_opt/nurbs_ga/opt_history.npy') or not os.path.exists('./results_opt/nurbs_ga/opt_airfoil.npy'): os.system('python optimize_nurbs_ga.py --n_runs={} --n_eval={}'.format(args.n_runs, args.n_eval)) if not os.path.exists('./results_opt/ffd_bo/opt_history.npy') or not os.path.exists('./results_opt/ffd_bo/opt_airfoil.npy'): os.system('python optimize_ffd_bo.py --n_runs={} --n_eval={}'.format(args.n_runs, args.n_eval)) if not os.path.exists('./results_opt/ffd_ga/opt_history.npy') or not os.path.exists('./results_opt/ffd_ga/opt_airfoil.npy'): os.system('python optimize_ffd_ga.py --n_runs={} --n_eval={}'.format(args.n_runs, args.n_eval)) ''' Plot history ''' gan_bo_2_10_hist = np.load('results_opt/gan_bo_2_10/opt_history.npy') gan_bo_4_10_hist = np.load('results_opt/gan_bo_4_10/opt_history.npy') gan_bo_6_10_hist = np.load('results_opt/gan_bo_6_10/opt_history.npy') gan_bo_8_10_hist = np.load('results_opt/gan_bo_8_10/opt_history.npy') gan_bo_10_10_hist = np.load('results_opt/gan_bo_10_10/opt_history.npy') gan_bo_refine_2_10_hist = np.load('results_opt/gan_bo_refine_2_10/opt_history.npy') gan_bo_refine_4_10_hist = np.load('results_opt/gan_bo_refine_4_10/opt_history.npy') gan_bo_refine_6_10_hist = np.load('results_opt/gan_bo_refine_6_10/opt_history.npy') gan_bo_refine_8_10_hist = np.load('results_opt/gan_bo_refine_8_10/opt_history.npy') gan_bo_refine_10_10_hist = np.load('results_opt/gan_bo_refine_10_10/opt_history.npy') gan_bo_8_0_hist = np.load('results_opt/gan_bo_8_0/opt_history.npy') gan_bo_refine_8_20_hist = np.load('results_opt/gan_bo_refine_8_20/opt_history.npy') generic_bo_6_hist = np.load('results_opt/generic_bo_6/opt_history.npy') generic_bo_8_hist = np.load('results_opt/generic_bo_8/opt_history.npy') generic_bo_10_hist = np.load('results_opt/generic_bo_10/opt_history.npy') generic_bo_12_hist = np.load('results_opt/generic_bo_12/opt_history.npy') generic_ga_8_hist = np.load('results_opt/generic_ga_8/opt_history.npy') svd_bo_8_hist = np.load('results_opt/svd_bo_8/opt_history.npy') svd_bo_9_hist = np.load('results_opt/svd_bo_9/opt_history.npy') svd_bo_10_hist = np.load('results_opt/svd_bo_10/opt_history.npy') svd_ga_9_hist = np.load('results_opt/svd_ga_9/opt_history.npy') nurbs_bo_hist = np.load('results_opt/nurbs_bo/opt_history.npy') nurbs_ga_hist = np.load('results_opt/nurbs_ga/opt_history.npy') ffd_bo_hist = np.load('results_opt/ffd_bo/opt_history.npy') ffd_ga_hist = np.load('results_opt/ffd_ga/opt_history.npy') mean_gan_bo_2_10_hist = np.mean(gan_bo_2_10_hist, axis=0) std_gan_bo_2_10_hist = np.std(gan_bo_2_10_hist, axis=0) mean_gan_bo_4_10_hist = np.mean(gan_bo_4_10_hist, axis=0) std_gan_bo_4_10_hist = np.std(gan_bo_4_10_hist, axis=0) mean_gan_bo_6_10_hist = np.mean(gan_bo_6_10_hist, axis=0) std_gan_bo_6_10_hist = np.std(gan_bo_6_10_hist, axis=0) mean_gan_bo_8_10_hist = np.mean(gan_bo_8_10_hist, axis=0) std_gan_bo_8_10_hist = np.std(gan_bo_8_10_hist, axis=0) mean_gan_bo_10_10_hist = np.mean(gan_bo_10_10_hist, axis=0) std_gan_bo_10_10_hist = np.std(gan_bo_10_10_hist, axis=0) mean_gan_bo_refine_2_10_hist = np.mean(gan_bo_refine_2_10_hist, axis=0) std_gan_bo_refine_2_10_hist = np.std(gan_bo_refine_2_10_hist, axis=0) mean_gan_bo_refine_4_10_hist = np.mean(gan_bo_refine_4_10_hist, axis=0) std_gan_bo_refine_4_10_hist = np.std(gan_bo_refine_4_10_hist, axis=0) mean_gan_bo_refine_6_10_hist = np.mean(gan_bo_refine_6_10_hist, axis=0) std_gan_bo_refine_6_10_hist = np.std(gan_bo_refine_6_10_hist, axis=0) mean_gan_bo_refine_8_10_hist = np.mean(gan_bo_refine_8_10_hist, axis=0) std_gan_bo_refine_8_10_hist = np.std(gan_bo_refine_8_10_hist, axis=0) mean_gan_bo_refine_10_10_hist = np.mean(gan_bo_refine_10_10_hist, axis=0) std_gan_bo_refine_10_10_hist = np.std(gan_bo_refine_10_10_hist, axis=0) mean_gan_bo_8_0_hist = np.mean(gan_bo_8_0_hist, axis=0) std_gan_bo_8_0_hist = np.std(gan_bo_8_0_hist, axis=0) mean_gan_bo_refine_8_20_hist = np.mean(gan_bo_refine_8_20_hist, axis=0) std_gan_bo_refine_8_20_hist = np.std(gan_bo_refine_8_20_hist, axis=0) mean_generic_bo_6_hist = np.mean(generic_bo_6_hist, axis=0) std_generic_bo_6_hist = np.std(generic_bo_6_hist, axis=0) mean_generic_bo_8_hist = np.mean(generic_bo_8_hist, axis=0) std_generic_bo_8_hist = np.std(generic_bo_8_hist, axis=0) mean_generic_bo_10_hist = np.mean(generic_bo_10_hist, axis=0) std_generic_bo_10_hist = np.std(generic_bo_10_hist, axis=0) mean_generic_bo_12_hist = np.mean(generic_bo_12_hist, axis=0) std_generic_bo_12_hist = np.std(generic_bo_12_hist, axis=0) mean_generic_ga_8_hist = np.mean(generic_ga_8_hist, axis=0) std_generic_ga_8_hist = np.std(generic_ga_8_hist, axis=0) mean_svd_bo_8_hist = np.mean(svd_bo_8_hist, axis=0) std_svd_bo_8_hist = np.std(svd_bo_8_hist, axis=0) mean_svd_bo_9_hist = np.mean(svd_bo_9_hist, axis=0) std_svd_bo_9_hist = np.std(svd_bo_9_hist, axis=0) mean_svd_bo_10_hist = np.mean(svd_bo_10_hist, axis=0) std_svd_bo_10_hist = np.std(svd_bo_10_hist, axis=0) mean_svd_ga_9_hist = np.mean(svd_ga_9_hist, axis=0) std_svd_ga_9_hist = np.std(svd_ga_9_hist, axis=0) mean_nurbs_bo_hist = np.mean(nurbs_bo_hist, axis=0) std_nurbs_bo_hist = np.std(nurbs_bo_hist, axis=0) mean_nurbs_ga_hist = np.mean(nurbs_ga_hist, axis=0) std_nurbs_ga_hist = np.std(nurbs_ga_hist, axis=0) mean_ffd_bo_hist = np.mean(ffd_bo_hist, axis=0) std_ffd_bo_hist = np.std(ffd_bo_hist, axis=0) mean_ffd_ga_hist = np.mean(ffd_ga_hist, axis=0) std_ffd_ga_hist = np.std(ffd_ga_hist, axis=0) linestyles = ['-', '--', ':', '-.', (0, (5,1,1,1,1,1)), (0, (1,4))] lss = itertools.cycle(linestyles) iters = np.arange(n_eval+1, dtype=int) diff_2 = gan_bo_refine_2_10_hist - gan_bo_2_10_hist mean_diff_2 = np.mean(diff_2, axis=0) std_diff_2 = np.std(diff_2, axis=0) diff_4 = gan_bo_refine_4_10_hist - gan_bo_4_10_hist mean_diff_4 = np.mean(diff_4, axis=0) std_diff_4 = np.std(diff_4, axis=0) diff_6 = gan_bo_refine_6_10_hist - gan_bo_6_10_hist mean_diff_6 =
np.mean(diff_6, axis=0)
numpy.mean
############################################ ## Title: IBM Domain-Specific Compiler ## ## Author: <NAME>, <NAME>,## ## <NAME> ## ## Date: 03/19/2020 ######################## import numpy as np from qiskit import qiskit_code from rigetti import rigetti_code ### This code assumes qubits are labeled 0,1,2,...,N and connected in that order ### lineList = [line.rstrip('\n') for line in open("advance_gates.txt")] count = len(lineList) #Read the gate in right vector form # G = Gate type # TH = Angle of rotation ! if no angle rotation then TH = 0 # TH2 = 2nd angle of rotation (used in U2 and U3 gates) # TH3 = 3rd angle of rotation (used in U3 gates) # AC1 = qubit on which action is happening # AC2 = qubit on which controlled action is happening G = ["" for x in range(count)] G = list(G) AC1 = np.zeros(shape=(count),dtype=np.int) AC2 = np.zeros(shape=(count),dtype=np.int) TH = np.zeros(shape=(count)) for i in range (0,count): G[i] = 0 TH[i] = 0 AC1[i] = 0 AC2[i] = 0 if lineList[i][0:1] == "H": G[i]="H" TH[i] = 0 AC1[i] = lineList[i][2:3] AC2[i] = 0 if lineList[i][0:2] == "RZ": G[i] = "RZ" TH[i] = lineList[i][lineList[i].find("(")+1:lineList[i].find(")")] AC1[i] = lineList[i][-1] AC2[i] = 0 if lineList[i][0:4] == "CNOT": G[i] = "CNOT" TH[i] = 0 AC1[i] = lineList[i][5:6] AC2[i] = lineList[i][7:8] if lineList[i][0:7] == "MEASURE": G[i] = "MEASURE" TH[i] = 0 AC1[i] = 0 AC2[i] =0 nqubits = max(max(AC1),max(AC2)) #Omit last and second-to-last CNOT for each qubit for qub in range(0,nqubits+1): i=-1 count=0 while count<=1 and i>=-int(len(G)): if G[i] == "CNOT" and AC1[i]==qub and AC2[i]==qub+1: del G[i] TH=np.delete(TH,i) AC1=np.delete(AC1,i) AC2=np.delete(AC2,i) count=count+1 i=i-1 #Omit last RZ for each qubit for qub in range(0,nqubits+1): i=-1 while i>=-int(len(G)): if G[i] == "H" and AC1[i]==qub: break if G[i] == "RZ" and AC1[i]==qub: G[i] = "NULL" break i=i-1 #Use CNOT (0,1) -> H(0) H(1) CNOT(1,0) H(0) H(1) i=0 while G[i] != "MEASURE": if G[i]=="CNOT" and (G[i+1]=="H" and G[i+2]=="H" and AC1[i+1]==AC1[i] and AC1[i+2]==AC2[i])==False: G[i]="H" flag1=int(AC1[i]) flag2=int(AC2[i]) AC2[i]=0 G.insert(i,"H") TH=np.insert(TH,i,0) AC1=np.insert(AC1,i,flag2) AC2=np.insert(AC2,i,0) G.insert(i,"CNOT") TH=np.insert(TH,i,0) AC1=np.insert(AC1,i,flag2) AC2=np.insert(AC2,i,flag1) G.insert(i,"H") TH=np.insert(TH,i,0) AC1=np.insert(AC1,i,flag1) AC2=np.insert(AC2,i,0) G.insert(i,"H") TH=np.insert(TH,i,0) AC1=np.insert(AC1,i,flag2) AC2=np.insert(AC2,i,0) i=i+1 #Rearrange circuits to put successive Hadamard gates in order i=0 while G[i] != "MEASURE": if G[i]=="H": flag=AC1[i] j=i+1 boolean=0 while G[j] != "MEASURE" and boolean ==0: if AC1[j]==flag and G[j] == "H": boolean=1 del G[j] TH=
np.delete(TH,j)
numpy.delete
import numpy as np from numpy.random import Generator from scipy.signal import butter, filtfilt # # from src import float_service as fs, float_service_dev_utils as fsdu, globals as g import src.float_service as fs import src.float_service_utils as fsdu # def test_low_pass_filter_input(): # # TODO: FIX test. processed_input and input cannot be compared the way it is being done # """ # Should choose a selection of data, benchmark some measures, clean it, and compare benchmarks to new measures. # Examples of measures: # - Std deviation from some type of mean value # - Std dev from a polynomial regression of parts of the data # - Std dev from a smoothed line using something else than the Butterfield filter # - Decided to use scipy.interpolate.UnivariateSpline # # TODO: Consider using other metrics than standard deviation from a regression line. For instance, another metric # could be used to ensure that the processing doesn't smooth the data too much. # """ # print('----clean_data_test()----') # path = 'data/bestumkilen_04-23_timestamped_input.hdf5' # f_id = '39202020ff06230d' # n_rows = 10000 # # # In order to use the Butterfield filter, some values should be set up before-hand # sampling_rate = 104.0 # nyquist_freq = sampling_rate / 2 # cutoff_rate = 0.1 # low_b, low_a = butter(int(1 / (cutoff_rate * sampling_rate) * nyquist_freq + 0.5), # cutoff_rate, # btype='lowpass', # output='ba') # # # Alternative regression/smoothing/mean methods # def _butterfield_filter(y: np.ndarray): # interval = 26 # out = y.copy() # ii = 0 # while (ii+1)*interval <= len(y): # out[ii * interval: (ii + 1) * interval] = np.array(filtfilt(low_b, # low_a, # y[ii * interval: (ii + 1) * interval])) # ii += 1 # # return out # # def _polynomial_regression(x: np.ndarray, y: np.ndarray, deg: int, dof: int = 0): # """ # This method uses numpy.polyfit() to produce polynomials of some degree for individual bursts of the sensor # input. # It returns an entire column of data after having produced all the burst polynomials. # """ # interval = 26 # out = y.copy() # ii = 0 # while (ii+1)*interval <= len(x): # # np.polyfit() returns the coefficients of an n-degree polynomial # try: # z = np.polyfit(x=x[ii*interval: (ii+1)*interval], y=y[ii*interval: (ii+1)*interval], deg=deg) # # np.poly1d() returns a polynomial mapping from these coefficients # polynomial = np.poly1d(z) # # polynomial is used to convert each burst to the resulting values # out[ii * interval: (ii + 1) * interval] = polynomial(x[ii * interval: (ii + 1) * interval]) # except np.linalg.LinAlgError as lae: # print(f'\npolyfit() failed for dof {dof}, at interval [{ii*interval}, {(ii+1)*interval}].\n' # f'The given interval was not used.') # print(lae.__str__()) # ii += 1 # return out # # def _neighbor_mean(y: np.ndarray, padding: int = 1): # """ # Use some number of neighboring data points to predict every data point in the series (except for the same # number of beginning and end points). # :param y: Time series of data # :param padding: Number of data points used on both side of the mid point to calculate its value # """ # out = np.zeros_like(y) # for ii in range(padding): # out[ii] = y[ii] # # Could be optimised to use a lesser numnber of data points to predict edge points, but this isn't # # noticeable in the long run # out[-ii-1] = y[-ii-1] # for ii in range(padding, len(y)-padding): # out[ii] = (np.sum(y[ii-padding:ii]) + np.sum(y[ii+1:ii+padding+1]))/(2*padding) # # return out # ########################################################################################### # # def _std_of_arrays(y1: np.ndarray, y2: np.ndarray): # """ # Measure the standard deviation between not an array and it's mean, but between two arrays. # """ # differences = y2-y1 # sqr_diff = np.power(differences, 2) # sum_sqr_diff = np.sum(sqr_diff) # mean_sum_sqr_diff = sum_sqr_diff/len(y1) # return np.sqrt(mean_sum_sqr_diff) # # # Test begins # # # Create process, fill buffers of requested size # sis = fsdu.ProcessSimulator(data_path=path, data_rows_total=n_rows, buffer_size=n_rows, dev_mode=True) # # # Focusing on data from a single sensor # sensor_id = f_id # # # Process data (including preprocessing) # sis.all_bursts_single_sensor(sensor_id=sensor_id) # # # Save raw and processed input # input_raw = sis.float_services[sensor_id].input # input_cleaned = sis.float_services[sensor_id].processed_input # # # Until timestamps are provided, we use indices as x-values: # x_indices = np.arange(0, len(input_raw), step=1, dtype=int) # # # For each of the 6 degrees of freedom, measure std of both raw and cleaned data, compared to their respective # # results from the other regression/smoothing/mean methods # raw_data_deviation = np.zeros([5, 4], dtype=float) # clean_data_deviation = np.zeros_like(raw_data_deviation) # for i in range(5): # # Apply each method, save information on standard deviations # poly_reg_line = _polynomial_regression(x=x_indices, y=input_raw[:, i], deg=3, dof=i) # raw_data_deviation[i, 0] = _std_of_arrays(y1=poly_reg_line, y2=input_raw[:, i]) # # uni_line = _univariate_spline(x=x, y=input_raw[:, i], smoothing_factor=0.003) # # raw_data_deviation[i, 1] = _std_of_arrays(y1=uni_line, y2=input_raw[:, i]) # mean_line_1 = _neighbor_mean(y=input_raw[:, i], padding=1) # raw_data_deviation[i, 1] = _std_of_arrays(y1=mean_line_1, y2=input_raw[:, i]) # mean_line_2 = _neighbor_mean(y=input_raw[:, i], padding=2) # raw_data_deviation[i, 2] = _std_of_arrays(y1=mean_line_2, y2=input_raw[:, i]) # butterfield_line = _butterfield_filter(y=input_raw[:, i]) # raw_data_deviation[i, 3] = _std_of_arrays(y1=butterfield_line, y2=input_raw[:, i]) # # # Do the same thing using cleaned data # cleaned_poly_reg_line = _polynomial_regression(x=x_indices, y=input_cleaned[:, i], deg=3, dof=i) # clean_data_deviation[i, 0] = _std_of_arrays(y1=cleaned_poly_reg_line, y2=input_cleaned[:, i]) # # cleaned_uni_line = _univariate_spline(x=x, y=input_cleaned[:, i], smoothing_factor=0.003) # # clean_data_deviation[i, 1] = _std_of_arrays(y1=cleaned_uni_line, y2=input_cleaned[:, i]) # cleaned_mean_line_1 = _neighbor_mean(y=input_cleaned[:, i], padding=1) # clean_data_deviation[i, 1] = _std_of_arrays(y1=cleaned_mean_line_1, y2=input_cleaned[:, i]) # cleaned_mean_line_2 = _neighbor_mean(y=input_cleaned[:, i], padding=2) # clean_data_deviation[i, 2] = _std_of_arrays(y1=cleaned_mean_line_2, y2=input_cleaned[:, i]) # cleaned_butterfield_line = _butterfield_filter(y=input_cleaned[:, i]) # clean_data_deviation[i, 3] = _std_of_arrays(y1=cleaned_butterfield_line, y2=input_cleaned[:, i]) # # data_cleaning_tests = 0 # dc_tests_passed = 0 # # Inspect the standard deviation of every metric # # num_2_dof = {0: 'accX', 1: 'accY', 2: 'accZ', 3: 'gyroX', 4: 'gyroY', 5: 'gyroZ'} # num_2_func = {0: 'polynomial', 1: 'univariate', 2: 'neighbourAverage1', 3: 'neighborAverage2'} # # err_msg = '' # for i in range(np.shape(raw_data_deviation)[0]): # for j in range(np.shape(raw_data_deviation)[1]): # data_cleaning_tests += 1 # if raw_data_deviation[i, j] <= clean_data_deviation[i, j]: # err_msg += f'{num_2_dof[i]}: {num_2_func[j]}, ' # else: # dc_tests_passed += 1 # # print(err_msg) # print('----clean_data_test() ended----\n') # assert dc_tests_passed == data_cleaning_tests # # self.fail_messages.append(f'{self.tc[2]}FAILED{self.tc[0]}\n' + # # err_msg + f'\n{dc_tests_passed}/{data_cleaning_tests} passed.\n' # # f'If some of the univariate tests fail, there might still' # # f' be no problem at all.\n' # # f'NB test is broken as of 12. jan 2021.\n') # # else: # # self.n_passed += 1 # # self.passed_messages.append(f'{self.tc[1]}PASSED{self.tc[0]}\n' # # 'clean_data_test()\n' # # f'{dc_tests_passed}/{data_cleaning_tests} tests passed.\n') def test_nan_handling(): print('----nan_smoothing_test()----') err_msg = '' n_tests = 0 n_passed = 0 data_size = 1000 name = 'Copernicus' # 1. Testing for whether or not the burst is discarded # 1.1 All data is NaN mock_input = np.zeros([data_size, 6], dtype=float) output = np.zeros([data_size, 3], dtype=float) float_service = fs.FloatService(name=name, input=mock_input, output=output) mock_input[:] = float('nan') float_service.nan_handling(start=0, end=data_size) n_tests += 1 if not float_service.burst_is_discarded: err_msg += f'- 1.1 Burst not properly discarded\n' else: n_passed += 1 # 1.2 Slightly more data than threshold is NaN mock_input = np.zeros([data_size, 6], dtype=float) output = np.zeros([data_size, 3], dtype=float) float_service = fs.FloatService(name=name, input=mock_input, output=output) n_nan = int(float_service.discard_burst_nan_threshold * data_size + 1) mock_input[0:n_nan, :] = float('nan') float_service.nan_handling(start=0, end=data_size) n_tests += 1 if not float_service.burst_is_discarded: err_msg += f'- 1.2 Burst not properly discarded\n' else: n_passed += 1 # 2. The correct number of NaN-values in a burst n_tests += 1 if not float_service.nan_in_burst == n_nan: err_msg += f'- 2. Wrong number of NaN values found\n' \ f' Found = {float_service.nan_in_burst}, correct = {n_nan}\n' else: n_passed += 1 # 3. Clean dataset mock_input = np.zeros([data_size, 6], dtype=float) output = np.zeros([data_size, 3], dtype=float) float_service = fs.FloatService(name=name, input=mock_input, output=output) float_service.nan_handling(start=0, end=data_size) n_tests += 1 if not float_service.nan_in_burst == 0: err_msg += f'- 2. Wrong number of NaN values found\n' \ f' Found = {float_service.nan_in_burst}, correct = {n_nan}\n' else: n_passed += 1 print(err_msg) print('----nan_handling_test() ended----\n') assert n_passed == n_tests def test_set_processed_data_nan(): """ This test sets up a mock input data set with some values being NaN values. It checks whether the NaN values have been converted to non-NaN values in output and processed input. """ print('----nan_smoothing_test()----') err_msg = '' n_tests = 0 n_passed = 0 data_size = 1000 name = 'Copernicus' mock_input = np.zeros([data_size, 6], dtype=float) output = np.zeros([data_size, 3], dtype=float) # Every n-th entry in the input is set to NaN nan_step = 3 for i in range(0, data_size, nan_step): mock_input[i, :] = float('nan') mock_input[-1, :] = float('nan') # Every 3rd entry from index 1 is set to 1.0 for i in range(1, data_size, nan_step): mock_input[i, :] = 1.0 float_service = fs.FloatService(name=name, input=mock_input, output=output) # Apply NaN smoothing for i in range(6): float_service.set_processed_acc_input_nan(start=0, end=data_size) float_service.set_processed_gyro_input_nan(start=0, end=data_size) # Check that input is not overwritten n_tests += 1 passed = True for i in range(0, data_size, nan_step): if not np.all(np.isnan(mock_input[i])): err_msg += f'- 1.1 Input overwritten\n' passed = False break if passed: n_passed += 1 # Check that output is not NaN n_tests += 1 if np.any(np.isnan(output)): err_msg += f'- 1.2 NaN in output\n' else: n_passed += 1 # Check that processed input is not NaN n_tests += 1 if np.any(np.isnan(float_service.processed_input)): err_msg += f'- 1.3 NaN in processed input' else: n_passed += 1 print(err_msg) print('----nan_smoothing_test() ended----\n') assert n_passed == n_tests def test_discard_burst(): print('----discard_burst_test()----') data_size = 1000 burst_size = 100 name = 'Copernicus' err_msg = '' n_tests = 0 n_passed = 0 # 1. All data is NaN mock_input = np.zeros(shape=[data_size, 6], dtype=float) mock_input[:] = float('nan') output = np.zeros(shape=[data_size, 3], dtype=float) float_service = fs.FloatService(name=name, input=mock_input, output=output) fs.n_rows = data_size for i in range(data_size//burst_size): float_service.process(number_of_rows=burst_size) # Check that input is not overwritten n_tests += 1 if not np.all(np.isnan(mock_input)): err_msg += f'- 1.1 Input overwritten\n' else: n_passed += 1 # Check that output is not NaN n_tests += 1 if np.any(np.isnan(output)): err_msg += f'- 1.2 NaN in output\n' else: n_passed += 1 # Check that processed input is not NaN n_tests += 1 if np.any(np.isnan(float_service.processed_input)): err_msg += f'- 1.3 NaN in processed input' else: n_passed += 1 print(err_msg) print('----discard_burst_test() ended----\n') assert n_passed == n_tests def test_adjust_pos_and_vel_dampening_factors(): print('----adjust_pos_and_vel_dampening_factors_test()----') data_size = 100 mock_input = np.zeros(shape=[data_size, 6], dtype=float) output = np.zeros(shape=[data_size, 3], dtype=float) name = 'Copernicus' float_service = fs.FloatService(name=name, input=mock_input, output=output, dev_mode=True) # Set dampening factors to max float_service.vel_dampening_factor = float_service.vel_dampening_factor_big float_service.pos_dampening_factor = float_service.pos_dampening_factor_big vdf = float_service.vel_dampening_factor pdf = float_service.pos_dampening_factor for i in range(data_size-1): float_service.process(number_of_rows=1) assert vdf >= float_service.vel_dampening_factor assert pdf >= float_service.pos_dampening_factor vdf = float_service.vel_dampening_factor pdf = float_service.pos_dampening_factor print('----adjust_pos_and_vel_dampening_factors_test() ended----\n') def test_boost_dampeners(): print('----boost_dampeners_test()----') data_size = 100 mock_input = np.zeros(shape=[data_size, 6], dtype=float) output = np.zeros(shape=[data_size, 3], dtype=float) name = 'Copernicus' err_msg = '' passed = True # 1. Setting dampening factors to custom value float_service = fs.FloatService(name=name, input=mock_input, output=output) vdf = float_service.vel_dampening_factor pdf = float_service.pos_dampening_factor float_service.boost_dampeners(vel_dampening_factor=2*vdf, pos_dampening_factor=2*pdf) if vdf > float_service.vel_dampening_factor\ or pdf > float_service.pos_dampening_factor: passed = False err_msg += '\n- 1. Custom value dampening factor' # 2. Setting dampening factors to default value float_service = fs.FloatService(name=name, input=mock_input, output=output) float_service.boost_dampeners() if not(float_service.vel_dampening_factor_big == float_service.vel_dampening_factor and float_service.pos_dampening_factor_big == float_service.pos_dampening_factor): passed = False err_msg += '\n- 2. Default value dampening factor' print(err_msg) print('----boost_dampeners_test() ended----\n') assert passed def test_set_position_average_weights(): print('----set_position_average_weights_test()----') data_size = 100 sensor_input = np.zeros(shape=[data_size, 6]) sensor_output = np.zeros(shape=[data_size, 3]) name = 'copernicus' float_service = fs.FloatService(name=name, input=sensor_input, output=sensor_output, dev_mode=True) pos_mean_window_len = float_service.n_points_for_pos_mean assert pos_mean_window_len == len(float_service.vert_pos_average_weights) new_pos_mean_window_len = 350 float_service.n_points_for_pos_mean = new_pos_mean_window_len float_service.set_position_average_weights() assert new_pos_mean_window_len == len(float_service.vert_pos_average_weights) print('----set_position_average_weights_test() ended----\n') def test_kalman_project_state(): """ This test is written with prototype 2 in mind, where the y-axis is flipped, as well as all gyro values. """ print('----kalman_project_state_test()----') kalman_project_state_tests = 0 kalman_project_state_tests_passed = 0 err_msg = '' data_size = 100 fs.n_rows = data_size # 1 - Still, horizontal sensor kalman_project_state_tests += 1 sensor_name = 'copernicus_01' input_buffers = np.zeros(shape=[fs.n_rows, 6], dtype=float) output_buffers = np.zeros(shape=[fs.n_rows, 3], dtype=float) float_service = fs.FloatService(name=sensor_name, input=input_buffers, output=output_buffers, dev_mode=True) # Turn off gyroscope mean adjustment float_service.points_between_gyro_bias_update = np.inf # Mock input manipulation float_service.input[:, 2] = 1.0 float_service.process(number_of_rows=data_size) passed = True for i in range(len(float_service.output)): # This test expects the acceleration induced angles to be 0.0 if float_service.dev_gyro_state[i, 0] != 0.0 \ or float_service.dev_gyro_state[i, 1] != 0.0: err_msg += '- 1. Still, horizontal sensor\n' passed = False break if passed: kalman_project_state_tests_passed += 1 # 2 - Constant angular velocity, single axis kalman_project_state_tests += 1 sensor_name = 'copernicus_02' input_buffers = np.zeros(shape=[fs.n_rows, 6], dtype=float) output_buffers = np.zeros(shape=[fs.n_rows, 3], dtype=float) float_service = fs.FloatService(name=sensor_name, input=input_buffers, output=output_buffers, dev_mode=True) # Turn off gyroscope mean adjustment float_service.points_between_gyro_bias_update = np.inf # Mock input manipulation input_burst = np.zeros(shape=[data_size, 6], dtype=float) # Constant angular velocity of 1 deg/s around the x-axis # Gyro data flipped input_burst[:, 3] = - 1.0 float_service.points_between_gyro_bias_update = np.inf passed = True for i in range(len(float_service.output)-1): # Check that the next gyro induced state has a greater x-angle than the last if float_service.dev_gyro_state[i+1, 0] < \ float_service.dev_gyro_state[i, 0]: err_msg += '- 2. Constant angular velocity, single axis\n' passed = False break if passed: kalman_project_state_tests_passed += 1 print(err_msg) print('----kalman_project_state_test() ended----\n') assert kalman_project_state_tests_passed == kalman_project_state_tests def test_kalman_z(): """ This test is written with prototype 2 in mind, where the y-axis is flipped, as well as all gyro values. """ print('----kalman_z_test()----') kalman_z_tests = 0 kalman_z_passed = 0 err_msg = '' data_size = 100 # These timestamps are used for nothing except in producing mock input, # and does not influence sampling rate etc timestamps = np.linspace(0.0, 10, data_size) # 1 - Still, horizontal sensor kalman_z_tests += 1 sensor_name = 'copernicus_01' fs.n_rows = data_size input_buffers = np.zeros(shape=[fs.n_rows, 6], dtype=float) output_buffers = np.zeros(shape=[fs.n_rows, 3], dtype=float) float_service = fs.FloatService(name=sensor_name, input=input_buffers, output=output_buffers, dev_mode=True) # Turn off acceleration mean adjustment float_service.points_between_acc_bias_update = np.inf # Mock input manipulation float_service.input[:, 2] = 1.0 float_service.process(number_of_rows=data_size) passed = True for i in range(len(float_service.output)): # This test expects the acceleration induced angles to be 0.0 if float_service.dev_acc_state[i, 0] != 0.0 \ or float_service.dev_acc_state[i, 1] != 0.0: err_msg += '- 1. Still, horizontal sensor\n' passed = False break if passed: kalman_z_passed += 1 # 2 - Moving sensor kalman_z_tests += 1 sensor_name = 'copernicus_02' fs.n_rows = data_size input_buffers = np.zeros(shape=[fs.n_rows, 6], dtype=float) output_buffers = np.zeros(shape=[fs.n_rows, 3], dtype=float) fs.n_rows = data_size float_service = fs.FloatService(name=sensor_name, input=input_buffers, output=output_buffers, dev_mode=True) # Turn off acceleration mean adjustment float_service.points_between_acc_bias_update = np.inf # Make sure the Kalman filter is activated at every data row float_service.rows_per_kalman_use = 1 # Mock input manipulation float_service.input[:, 0] = np.sin(timestamps) # Y-axis flipped float_service.input[:, 1] = - np.cos(timestamps) float_service.process(number_of_rows=data_size) passed = True for i in range(len(float_service.output)): # This test expects the absolute value of the acceleration tests to if abs(float_service.input[i, 0]) > abs(float_service.input[i, 1]) and \ abs(float_service.dev_acc_state[i, 0]) > \ abs(float_service.dev_acc_state[i, 1]): err_msg += '- 2.1 Moving sensor, absolute value\n' passed = False print(i) break if passed: kalman_z_passed += 1 print(err_msg) print('----kalman_z_test() ended----\n') assert kalman_z_passed == kalman_z_tests def test_get_corrected_angle(): pi = np.pi input_angles = [0.0, 0.25 * pi, 0.5 * pi, 0.75 * pi, pi, 1.25 * pi, 1.5 * pi, 1.75 * pi, 2.0 * pi, 2.25 * pi, 3.25 * pi, -0.25 * pi, -0.5 * pi, -0.75 * pi, -pi, -1.25 * pi, -1.5 * pi, -1.75 * pi, -2.0 * pi, -2.25 * pi, -3.25 * pi] output_angles = [0.0, 0.25 * pi, 0.5 * pi, 0.75 * pi, pi, -0.75 * pi, -0.5 * pi, -0.25 * pi, 0.0, 0.25 * pi, -0.75 * pi, -0.25 * pi, -0.5 * pi, -0.75 * pi, -pi, 0.75 * pi, 0.5 * pi, 0.25 * pi, 0.0, -0.25 * pi, 0.75 * pi] for i in range(len(input_angles)): assert abs(fs.FloatService.get_corrected_angle(input_angles[i]) - output_angles[i]) < 0.00001 def test_rotate_system(): """ System is represented as three unit vectors emerging from origo, denoting the three axes of the system: [x, y, z] = [[x_X, y_X, z_X], [x_Y, y_Y, z_Y], [x_Z, y_Z, z_Z]] Where x, y, z are 3x1 the axes of the inner system, represented by coordinates from the outer system, X, Y, Z, Such that x_Y is the outer Y-coordinate of the inner x-axis. Since the rotate_system() method is the only method that will ever access the rotation_matrix() method, this is probably actually more of a test to see whether the rotation matrix correctly rotates the axes of the system. Tests that may be used: - No rotation: Simply testing that the system is conserved if there is no rotation. - Elemental rotations: Rotations along single axes to see if the vectors of the affected axes end up correctly placed. - Linked rotations: Rotate a system around one axis, and then another one, to ensure the matrix rotates the system intrinsically (along the axes of the inner system, or sensor) and not extrinsically (along the axes of the outer system). - Small multi-axis rotations: Rotate a system using angles from more than one axis. Do small, realistic steps and verify that the system rotates correctly. Look at angles between original and new axes, for instance. This could be expanded to ensure that the same minor rotation done twice provides the same result. # TODO: Write expansion of small multi-axis rotation tests - Angles between axes: Since the entire system is to be rotated as one, rigid body, the orthogonality of the three axes must be kept true. Tiny anomalies are acceptable due to float point accuracy. - Linked rotation error: The error arising from many linked rotations should be measured in order to know how often to adjust for this by for instance checking for axis orthogonality """ # Rotation specific methods def _check_for_ndarray_element_similarity(m1: np.ndarray, m2: np.ndarray, threshold: float = 0.00001): """ Helper method for rotate_system_test() """ if np.shape(m1) != np.shape(m2): return False for i in range(np.shape(m1)[0]): for j in range(np.shape(m2)[1]): if abs(m1[i, j] - m2[i, j]) > threshold: return False return True def _check_system_coordinate_movement_directions(m1: np.ndarray, m2: np.ndarray, diffs: list, threshold: float = 0.00001): """ Helper method for rotate_system_test(). :param m1: The system before a minor rotation is applied. :param m2: The resulting system after the rotation. :param diffs: A list of assumptions regarding the relationship between pairs of coordinates. If a diffs-element equals -1, check that the resulting coordinate is of a smaller value than the original one. If the diffs-element equals 1, check the opposite. If 0 (which I doubt will be tested for in reality with rotation around more than one axis) check that the two coordinates are within the threshold of each other. NB: This list is written row-wise from the two ndarrays. :param threshold: Only used for cases where two coordinates are assumed equal to each other. """ for i in range(np.shape(m1)[0]): for j in range(np.shape(m1)[1]): if diffs[i * np.shape(m1)[0] + j] == -1: if m2[i, j] > m1[i, j]: print(f'Wrong assumption on negative movement in {i, j}') return False if diffs[i * np.shape(m1)[0] + j] == 1: if m2[i, j] < m1[i, j]: print(f'Wrong assumption on positive movement in {i, j}') return False if diffs[i * np.shape(m1)[0] + j] == 0: if abs(m2[i, j] - m1[i, j]) > threshold: return False return True def _angle(v1, v2): return np.arccos((v1[0] * v2[0] + v1[1] * v2[1] + v1[2] * v2[2] / (np.sqrt(v1[0] ** 2 + v1[1] ** 2 + v1[2] ** 2) * np.sqrt(v2[0] ** 2 + v2[1] ** 2 + v2[2] ** 2)))) def _check_orthogonal_axes(system: np.ndarray, threshold: float = 0.0001): """ Helper method for rotate_system_test(). Control whether the angles between the axes are within some threshold of 90 degrees. """ v1 = system[:, 0] v2 = system[:, 1] v3 = system[:, 2] if abs(_angle(v1, v2) - 0.5 * np.pi) > threshold: return False if abs(_angle(v1, v3) - 0.5 * np.pi) > threshold: return False if abs(_angle(v2, v3) - 0.5 * np.pi) > threshold: return False return True def _stats_from_skewed_system(sys_1: np.ndarray, sys_2: np.ndarray): """ Used for observing the error that stems from multiple roundtrip rotations. """ # Measure individual coordinate drift of each axis max_coordinate_drift = np.max(np.abs(sys_2.flatten() - sys_1.flatten())) mean_coordinate_drift = np.mean(np.abs(sys_2.flatten() - sys_1.flatten())) # Measure angles between original axes and resulting axes angles = np.zeros([3], dtype=float) for i in 0, 1, 2: angles[i] = _angle(sys_1[:, i], sys_2[:, i]) max_angular_drift =
np.max(angles)
numpy.max
""" detalied balance calculation of many junction devices Copyright 2017 <NAME>, Toyota Technological Institute Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import numpy as np import copy from .illumination import Illumination from .fom import voc from .ivsolver import calculate_j01, \ gen_rec_iv_with_rs_by_newton, solve_mj_iv, \ calculate_j01_from_qe, gen_rec_iv_by_rad_eta, solve_ms_mj_iv from .fom import max_power from .photocurrent import gen_step_qe, calc_jsc, calc_jsc_from_eg import scipy.constants as sc from pypvcell.spectrum import Spectrum def set_subcell_spectrum(input_ill, subcell_eg, subcell_filter): subcell_ill = list() for layer_num, _ in enumerate(subcell_eg): tmp_ill = copy.deepcopy(input_ill) filter_set = list() for filter_index in range(layer_num): filter_set.append(subcell_filter[filter_index]) ill = tmp_ill.attenuation(filter_set) subcell_ill.append(ill) return subcell_ill def rad_to_voc(rad_eta, qe, max_voltage=1.9,spectrum="AM1.5g"): """ Calculate Voc from given radiative efficiency numerically :param rad_eta: radiative efficiency (in ratio) :param qe: quantum efficiency :type qe: Spectrum :param max_voltage: the maximum voltage of the dark-IV, the default value is 1.9. A safe way is set it to the value of the band gap :return: the calculated Voc """ assert isinstance(qe, Spectrum) test_voltage = np.linspace(-0.5, max_voltage, num=300) j01_t = calculate_j01_from_qe(qe) # j02_t = calculate_j02_from_rad_eff(j01_t, rad_eta, test_voltage, 300, n2=2) v_top, i_top = gen_rec_iv_by_rad_eta(j01_t, rad_eta, 1, 300, 1e10, test_voltage) top_voc = extract_voc(v_top, i_top, qe,spectrum=spectrum) return top_voc def rad_to_voc_fast(rad_eta, qe, spectrum="AM1.5g", T=300): """ Calculate Voc from given radiative efficiency analytically :param rad_eta: radiative efficiency (in ratio) :param qe: quantum efficiency :type qe: Spectrum :param max_voltage: the maximum voltage of the dark-IV, the default value is 1.9. A safe way is set it to the value of the band gap :return: the calculated Voc """ assert isinstance(qe, Spectrum) j01_t = calculate_j01_from_qe(qe, T=T) # j02_t = calculate_j02_from_rad_eff(j01_t, rad_eta, test_voltage, 300, n2=2) jsc = calc_jsc(input_illumination=Illumination(spectrum), qe=qe) voc = np.log(rad_eta * jsc / j01_t) * (sc.k * T / sc.e) return voc def extract_voc(voltage, current, qe, spectrum="AM1.5g"): """ Calculate Voc from given dark I-V :param voltage: voltage array of dark I-V :param current: current array of dark I-V :param qe: quantum efficiency, a spectrum_base instance :param spectrum: can be "AM1.5g", "AM1.5d" :return: the calculated Voc """ # TODO: assign concentration, or use Illumination() class as input input_ill = Illumination(spectrum=spectrum,concentration=1) jsc = calc_jsc(input_ill, qe=qe) gen_current = current - jsc return voc(voltage, gen_current) def calc_ere(qe, voc, T=300, ill=Illumination("AM1.5g"), verbose=0): """ Calculate external radiative efficiency based on Martin Green's paper [1] <NAME>, “Radiative efficiency of state-of-the-art photovoltaic cells,” Prog. Photovolt: Res. Appl., vol. 20, no. 4, pp. 472–476, Sep. 2011. :param qe: input EQE, a spectrum_base object :param voc: Voc of the test cell :param T: test tempearture of the cell, default is 300 K :param ill: illumination object, default is AM1.5d@1x :return: the calculated value of ERE """ jsc = calc_jsc(ill, qe) if verbose>0: print(jsc) jd = calculate_j01_from_qe(qe, lead_term=None) ere = np.exp(sc.e * voc / (sc.k * T)) * jd / jsc/(3.5**2*2) #ere = np.exp(sc.e * voc / (sc.k * T)) * jd / jsc return ere def calc_1j_eta(eg,qe,r_eta,cell_temperature=300, n_c=3.5,n_s=1, concentration=1, spectrum="AM1.5g", j01_method="qe"): """ Calculate the 1J efficiency from given band gap and qe values :param eg: The band gap of material :param qe: A single value. We assume flat, step-like QE. :param r_eta: Radiative efficiency :param cell_temperature: default to 300K :param n_c: the refractive index of the semiconductor material, default is 3.5 :param n_s: the refractiv index of surrouding material, default is 1 :param concentration: default value is 1 :param spectrum: default value is "AM1.5g" :return: the calculated efficiency """ volt = np.linspace(-0.5, eg, num=300) qe_spec = gen_step_qe(eg, qe) ill = Illumination(spectrum=spectrum, concentration=concentration) if j01_method=="qe": j01 = calculate_j01_from_qe(qe_spec, n_c=n_c, n_s=n_s) jsc = calc_jsc(ill, qe_spec) elif j01_method=="eg": j01=calculate_j01(eg,temperature=cell_temperature,n1=1,n_c=n_c,n_s=n_s) jsc=calc_jsc_from_eg(ill,eg) volt,current=gen_rec_iv_by_rad_eta(j01,r_eta,1,cell_temperature,1e15,voltage=volt,jsc=jsc) return max_power(volt,current)/ill.total_power() def calc_mj_eta(subcell_eg, subcell_qe, subcell_rad_eff, cell_temperature, concentration=1, rs=0, replace_iv=None, replace_qe=None, verbose=0, spectrum="AM1.5g", n_s=1, mj="2T"): """ :param subcell_eg: :param subcell_qe: :param subcell_rad_eff: :param cell_temperature: :param concentration: :param rs: :param replace_iv: :param replace_qe: :param verbose: :param spectrum: :param n_s: :param mj: "2T" for two terminal device. "MS" for multi-terminal mechanical stack. :return: """ subcell_eg = np.array(subcell_eg) subcell_qe = np.array(subcell_qe) subcell_rad_eff = np.array(subcell_rad_eff) subcell_voltage =
np.linspace(-0.5, 1.9, num=300)
numpy.linspace
# Copyright (c) MONAI Consortium # 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 os import unittest import numpy as np from monai.transforms import LoadImage from monai.utils import set_determinism from parameterized import parameterized from monailabel.scribbles.infer import HistogramBasedGraphCut from monailabel.scribbles.transforms import ( AddBackgroundScribblesFromROId, ApplyGraphCutOptimisationd, InteractiveSegmentationTransform, MakeISegUnaryd, MakeLikelihoodFromScribblesHistogramd, SoftenProbSoftmax, WriteLogits, ) from monailabel.transform.writer import Writer set_determinism(seed=123) def generate_synthetic_binary_segmentation(height, width, num_circles=10, r_min=10, r_max=100, random_state=None): # function based on: # https://github.com/Project-MONAI/MONAI/blob/dev/monai/data/synthetic.py if r_min > r_max: raise ValueError("r_min cannot be greater than r_max") min_size = min(height, width) if 2 * r_max > min_size: raise ValueError("2 * r_max cannot be greater than min side") rs: np.random.RandomState = np.random.random.__self__ if random_state is None else random_state mask = np.zeros((height, width), dtype=bool) for _ in range(num_circles): x = rs.randint(r_max, width - r_max) y = rs.randint(r_max, height - r_max) r = rs.randint(r_min, r_max) spy, spx = np.ogrid[-x : width - x, -y : height - y] circle = (spx * spx + spy * spy) <= r * r mask[circle] = True return mask def add_salt_and_pepper_noise(data, p=0.05): if p <= 0: return data original_dtype = data.dtype random_image_data = np.random.choice([0, 1], p=[p, 1 - p], size=data.shape) return (data.astype(np.float32) * random_image_data).astype(original_dtype) def generate_label_with_noise(height, width, label_key="label", noisy_key="noisy", pred_key="pred", num_slices=1): label = generate_synthetic_binary_segmentation(height, width, num_circles=10, r_min=10, r_max=50) noisy_invert = ~add_salt_and_pepper_noise( generate_synthetic_binary_segmentation(height, width, num_circles=10, r_min=10, r_max=50), p=0.7 ) noisy = label & noisy_invert label = np.expand_dims(label, axis=0).astype(np.float32) noisy = np.expand_dims(noisy, axis=0).astype(np.float32) if num_slices >= 1: if num_slices != 1: label = np.expand_dims(label, axis=0) noisy = np.expand_dims(noisy, axis=0) tmp_list = [] for _ in range(num_slices): tmp_list.append(label) label = np.concatenate(tmp_list, axis=1) tmp_list = [] for _ in range(num_slices): tmp_list.append(noisy) noisy = np.concatenate(tmp_list, axis=1) else: raise ValueError(f"unrecognised num_slices selected [{num_slices}]") pred = label label = np.concatenate([1 - label, label], axis=0) return {label_key: label, noisy_key: noisy, pred_key: pred} HEIGHT = 128 WIDTH = 128 NUM_SLICES = 32 # generate 2d noisy data two_dim_data = generate_label_with_noise( height=HEIGHT, width=WIDTH, label_key="prob", noisy_key="image", pred_key="target", num_slices=1 ) # generate 3d noisy data three_dim_data = generate_label_with_noise( height=HEIGHT, width=WIDTH, label_key="prob", noisy_key="image", pred_key="target", num_slices=NUM_SLICES ) TEST_CASE_OPTIM_TX = [ # 2D case ( {"unary": "prob", "pairwise": "image"}, {"prob": two_dim_data["prob"], "image": two_dim_data["image"]}, {"target": two_dim_data["target"]}, (1, HEIGHT, WIDTH), ), # 3D case ( {"unary": "prob", "pairwise": "image"}, {"prob": three_dim_data["prob"], "image": three_dim_data["image"]}, {"target": three_dim_data["target"]}, (1, NUM_SLICES, HEIGHT, WIDTH), ), ] TEST_CASE_ISEG_OPTIM_TX = [ # 2D case ( { "image": "image", "logits": "prob", "scribbles": "scribbles", "scribbles_bg_label": 2, "scribbles_fg_label": 3, }, {"image": two_dim_data["image"], "prob": two_dim_data["prob"], "scribbles": two_dim_data["prob"][[1], ...] + 2}, {"target": two_dim_data["target"]}, (1, HEIGHT, WIDTH), ), # 3D case ( { "image": "image", "logits": "prob", "scribbles": "scribbles", "scribbles_bg_label": 2, "scribbles_fg_label": 3, }, { "image": three_dim_data["image"], "prob": three_dim_data["prob"], "scribbles": three_dim_data["prob"][[1], ...] + 2, }, {"target": three_dim_data["target"]}, (1, NUM_SLICES, HEIGHT, WIDTH), ), ] TEST_CASE_MAKE_ISEG_UNARY_TX = [ # 2D case ( { "image": "image", "logits": "prob", "scribbles": "scribbles", "scribbles_bg_label": 2, "scribbles_fg_label": 3, }, {"image": two_dim_data["image"], "prob": two_dim_data["prob"], "scribbles": two_dim_data["prob"][[1], ...] + 2}, {"target": two_dim_data["prob"]}, (2, HEIGHT, WIDTH), ), # 3D case ( { "image": "image", "logits": "prob", "scribbles": "scribbles", "scribbles_bg_label": 2, "scribbles_fg_label": 3, }, { "image": three_dim_data["image"], "prob": three_dim_data["prob"], "scribbles": three_dim_data["prob"][[1], ...] + 2, }, {"target": three_dim_data["prob"]}, (2, NUM_SLICES, HEIGHT, WIDTH), ), ] TEST_CASE_MAKE_LIKE_HIST_TX = [ # 2D case ( {"image": "image", "scribbles": "scribbles", "scribbles_bg_label": 2, "scribbles_fg_label": 3}, {"image": two_dim_data["target"], "scribbles": two_dim_data["prob"][[1], ...] + 2}, {"target": two_dim_data["prob"]}, (2, HEIGHT, WIDTH), ), # 3D case ( {"image": "image", "scribbles": "scribbles", "scribbles_bg_label": 2, "scribbles_fg_label": 3}, {"image": three_dim_data["target"], "scribbles": three_dim_data["prob"][[1], ...] + 2}, {"target": three_dim_data["prob"]}, (2, NUM_SLICES, HEIGHT, WIDTH), ), ] TEST_CASE_ADD_BG_ROI = [ ( {"scribbles": "scribbles", "roi_key": "roi", "scribbles_bg_label": 2, "scribbles_fg_label": 3}, { "scribbles": np.zeros((1, NUM_SLICES, HEIGHT, WIDTH), dtype=np.float32), "roi": [ NUM_SLICES // 2 - 4, NUM_SLICES // 2 + 4, HEIGHT // 2 - 8, HEIGHT // 2 + 8, WIDTH // 2 - 16, WIDTH // 2 + 16, ], }, (1, NUM_SLICES, HEIGHT, WIDTH), ), ] TEST_CASE_HISTOGRAM_GRAPHCUT = [ # 2D case ( { "image": np.squeeze(two_dim_data["image"]), "label": np.squeeze(two_dim_data["prob"][[1], ...] + 2), "image_meta_dict": {"affine": np.identity(4)}, "label_meta_dict": {"affine": np.identity(4)}, }, (1, HEIGHT, WIDTH), ), # 3D case ( { "image": np.squeeze(three_dim_data["image"]), "label": np.squeeze(three_dim_data["prob"][[1], ...] + 2), "image_meta_dict": {"affine": np.identity(5)}, "label_meta_dict": {"affine":
np.identity(5)
numpy.identity
import ynet from util import * from singa.layer import Conv2D, Activation, MaxPooling2D, AvgPooling2D, Flatten, Slice, LRN from singa import initializer from singa import layer from singa import loss from singa import tensor import cPickle as pickle import logging import os import numpy as np from numpy.core.umath_tests import inner1d import scipy.spatial from tqdm import trange import time logger = logging.getLogger(__name__) class L2Norm(ynet.L2Norm): def forward(self, is_train, x): norm = np.sqrt(
np.sum(x**2, axis=1)
numpy.sum
"""Utility functions for processing images""" import cv2 import itertools import math import numpy as np import os import sys from scipy.ndimage.interpolation import zoom from skimage.transform import resize import micro_dl.utils.aux_utils as aux_utils import micro_dl.utils.normalize as normalize def im_bit_convert(im, bit=16, norm=False, limit=[]): im = im.astype(np.float32, copy=False) # convert to float32 without making a copy to save memory if norm: if not limit: # scale each image individually based on its min and max limit = [np.nanmin(im[:]),
np.nanmax(im[:])
numpy.nanmax
import numpy as np from sklearn.linear_model import Lasso, Ridge from sklearn.preprocessing import scale from math import floor class LinearRegression: """ Regression class which uses sklearn. Includes functions to solve: * Ordinary Least Squares (OLS). * Ridge regression. * Lasso regression. Parameters ---------- X : array, shape(N x p) Design matrix. y : array, shape (N, ) Y-data points. Attributes ---------- X : array, shape(N x p) Design matrix. y : array, shape (N, ) Y-data points. X_temp : array, shape(N x p) Copy of X. y_temp : array, shape (N, ) Copy of y. p : int Number of features. beta : array, shape(p, ) Weights after fit. Examples -------- model = Regression(X, y) model.ols_fit(svd=True) y_pred = model.predict(X) MSE_kfold, R2 = model.k_fold_cross_validation(10, "ols", svd=True) MSE_train = model.mean_squared_error(y, y_pred) """ def __init__(self, X, y): # store all of X, y self.X = X self.y = y # copies of X, y (NB: these are used in ols/ridge/lasso), convenient # for the k-fold cross validation self.X_temp = X self.y_temp = y self.p = None def update_X(self, X): self.X = X self.X_temp = X return None def update_y(self, y): self.y = y self.y_temp = y return None def svd_inv(self, A): """Invert matrix A by using Singular Value Decomposition""" U, D, VT = np.linalg.svd(A) return VT.T @ np.linalg.inv(np.diag(D)) @ U.T def ols_fit(self, svd=False): """ Find the coefficients of beta: An array of shape (p, 1), where p is the number of features. Beta is calculated using the X, y attributes of the instance. Parameter --------- svd : bool If True, (X^T X) is inverted by using SVD. """ XTX = self.X_temp.T @ self.X_temp if svd: XTX_inv = self.svd_inv(XTX) else: XTX_inv = np.linalg.inv(XTX) self.beta = XTX_inv @ self.X_temp.T @ self.y_temp self.p = self.beta.shape[0] return None def ridge_fit(self, alpha=1e-6): """ Find the coefficients of beta: An array of shape (p, 1), where p is the number of features. Beta is calculated using the X, y attributes of the instance. Parameter --------- alpha : float Hyperparameter for the Ridge regression """ model = Ridge(alpha=alpha, normalize=True) model.fit(self.X_temp,self.y_temp) p = self.X_temp.shape[1] self.beta = np.transpose(model.coef_) self.beta[0] = model.intercept_ self.p = self.beta.shape[0] return None def lasso_fit(self, alpha=1e-6): """ Find the coefficients of beta: An array of shape (p, 1), where p is the number of features. Beta is calculated using the X, y attributes of the instance. Parameter --------- alpha : float Hyperparameter for the LASSO regression. """ model = Lasso(alpha=alpha, normalize=True, tol=0.05, max_iter=2500) model.fit(self.X_temp,self.y_temp) p = self.X_temp.shape[1] self.beta = np.transpose(model.coef_) self.beta[0] = model.intercept_ self.p = self.beta.shape[0] return None def predict(self, X): """ This method can only be called after ols/ridge/lasso_regression() has been called. It will predict y, given X. Parameter --------- X : array, shape(N, p) Matrix to provide prediction for. Returns ------- y_pred : array, shape(N, ) Prediction. """ if self.p: if X.shape[1] != self.p: raise ValueError(f"Model has produced a beta with {self.p} features" + f" and X in predict(X) has {X.shape[1]} columns.") y_pred = X @ self.beta return y_pred else: print("Warning, cannot predict because nothing has been fitted yet!" + " Try using ols_fit(), ridge_fit() or lasso_fit() first.") def mean_squared_error(self, y, y_pred): """Evaluate the mean squared error for y, y_pred""" mse =
np.mean((y - y_pred)**2)
numpy.mean
import numpy as np from scipy.stats import gmean TRADING_DAYS_IN_YEAR = 252 MONTHS_IN_YEAR = 12 QUARTERS_IN_YEAR = 4 def compute_returns(prices): return prices.pct_change().dropna() def compute_compound_return(returns): """ Compound a stream of returns :param returns: vector of returns :return: the compounded return """ # This implementation uses sum instead of prod and is faster than: (returns + 1).prod() - 1 return np.expm1(np.log1p(returns).sum()) def annualized_return(r, periods_in_year): """ Annualize a periodic return :param r: the periods return :param periods_in_year: periods in year when return is awarded :return: the annualized return """ return (1 + r) ** periods_in_year - 1 def annualized_monthly_return(r): return annualized_return(r, MONTHS_IN_YEAR) def annualized_quarterly_return(r): return annualized_return(r, QUARTERS_IN_YEAR) def annualized_daily_return(r): return annualized_return(r, TRADING_DAYS_IN_YEAR) def annualize_returns(returns, periods_in_year): """ Annualizes a set of returns :param returns: the vector of returns :param periods_in_year: periods in year that returns are awarded """ return (returns + 1).prod() ** (periods_in_year / len(returns)) - 1 def annualize_volatility(returns, periods_in_year): return returns.std()*
np.sqrt(periods_in_year)
numpy.sqrt
# flake8: noqa """ Grayscale BM3D denoising demo file, based on <NAME>, <NAME>, <NAME>, 2019. Exact Transform-Domain Noise Variance for Collaborative Filtering of Stationary Correlated Noise. In IEEE International Conference on Image Processing (ICIP), pp. 185-189 """ import numpy import numpy as np import matplotlib.pyplot as plt from bm3d import bm3d from aydin.features.fast.fast_features import FastFeatureGenerator from aydin.io.datasets import camera, cropped_newyork, newyork, characters, pollen from aydin.it.fgr import ImageTranslatorFGR from aydin.regression.cb import CBRegressor from aydin.regression.lgbm import LGBMRegressor from aydin.util.bm3d.experiment_funcs import ( get_experiment_noise, get_psnr, get_cropped_psnr, ) def main(): # Load noise-free image y = np.array(characters()) / 255 # Possible noise types to be generated 'gw', 'g1', 'g2', 'g3', 'g4', 'g1w', # 'g2w', 'g3w', 'g4w'. noise_type = 'gw' noise_var = 0.2 # Noise variance seed = 0 # seed for pseudorandom noise realization # Generate noise with given PSD noise, psd, kernel = get_experiment_noise(noise_type, noise_var, seed, y.shape) # N.B.: For the sake of simulating a more realistic acquisition scenario, # the generated noise is *not* circulant. Therefore there is a slight # discrepancy between PSD and the actual PSD computed from infinitely many # realizations of this noise with different seeds. # Generate noisy image corrupted by additive spatially correlated noise # with noise power spectrum PSD z = np.atleast_3d(y) + np.atleast_3d(noise) # Call BM3D With the default settings. y_est = bm3d(z, psd) # To include refiltering: # y_est = bm3d(z, psd, 'refilter') # For other settings, use BM3DProfile. # profile = BM3DProfile(); # equivalent to profile = BM3DProfile('np'); # profile.gamma = 6; # redefine value of gamma parameter # y_est = bm3d(z, psd, profile); # Note: For white noise, you may instead of the PSD # also pass a standard deviation # y_est = bm3d(z, sqrt(noise_var)); # Ignore values outside range for display (or plt gives an error for multichannel input) y_est = np.minimum(np.maximum(y_est, 0), 1) z_rang = np.minimum(np.maximum(z, 0), 1) plt.title("y, z, y_est") plt.imshow(np.concatenate((y,
np.squeeze(z_rang)
numpy.squeeze
#!/usr/bin/env python """ @package ion_functions.qc_functions @file ion_functions/qc_functions.py @author <NAME> @brief Module containing QC functions ported from matlab samples in DPS documents """ from ion_functions.qc.qc_extensions import stuckvalues, spikevalues, gradientvalues, ntp_to_month import time import numpy as np import numexpr as ne from scipy.interpolate import LinearNDInterpolator from ion_functions import utils from ion_functions.utils import fill_value # try to load the OOI logging module, using default Python logging module if # unavailable try: from ooi.logging import log except ImportError: import logging log = logging.getLogger('ion-functions') def is_fill(arr): return np.atleast_1d(arr)[-1] == -9999. # Not the normal fill value, it's hardcoded to the QC params def is_none(arr): return arr is None or (np.atleast_1d(arr)[-1] == None) def dataqc_globalrangetest_minmax(dat, dat_min, dat_max, strict_validation=False): ''' Python wrapper for dataqc_globalrangetest Combines the min/max arguments into list for dataqc_globalrangetest ''' if is_none(dat_min) or is_none(dat_max) or is_fill(dat_min) or is_fill(dat_max): out = np.empty(dat.shape, dtype=np.int8) out.fill(-99) return out return dataqc_globalrangetest(dat, [np.atleast_1d(dat_min)[-1], np.atleast_1d(dat_max)[-1]], strict_validation=strict_validation) def dataqc_globalrangetest(dat, datlim, strict_validation=False): """ Description: Data quality control algorithm testing if measurements fall into a user-defined valid range. Returns 1 for presumably good data and 0 for data presumed bad. Implemented by: 2010-07-28: DPS authored by <NAME>. Example code provided for Matlab. 2013-04-06: <NAME>. Initial python implementation. 2013-05-30: <NAME>. Performance improvements by adding strict_validation flag. Usage: qcflag = dataqc_globalrangetest(dat, datlim, strict_validation) where qcflag = Boolean, 0 if value is outside range, else = 1. dat = Input dataset, any scalar or vector. Must be numeric and real. datlim = Two-element vector with the minimum and maximum values considered to be valid. strict_validation = Flag (default is False) to assert testing of input types (e.g. isreal, isnumeric) References: OOI (2012). Data Product Specification for Global Range Test. Document Control Number 1341-10004. https://alfresco.oceanobservatories.org (See: Company Home >> OOI >> Controlled >> 1000 System Level >> 1341-10004_Data_Product_SPEC_GLBLRNG_OOI.pdf) """ dat = np.atleast_1d(dat) datlim = np.atleast_1d(datlim) if strict_validation: if not utils.isnumeric(dat).all(): raise ValueError('\'dat\' must be numeric') if not utils.isreal(dat).all(): raise ValueError('\'dat\' must be real') if not utils.isnumeric(datlim).all(): raise ValueError('\'datlim\' must be numeric') if not utils.isreal(datlim).all(): raise ValueError('\'datlim\' must be real') if len(datlim) < 2: # Must have at least 2 elements raise ValueError('\'datlim\' must have at least 2 elements') return (datlim.min() <= dat) & (dat <= datlim.max()).astype('int8') def dataqc_localrangetest_wrapper(dat, datlim, datlimz, dims, pval_callback): if is_none(datlim) or np.all(np.atleast_1d(datlim).flatten() == -9999): out = np.empty(dat.shape, dtype=np.int8) out.fill(-99) return out if is_none(datlimz) or np.all(np.atleast_1d(datlim).flatten() == -9999): out = np.empty(dat.shape, dtype=np.int8) out.fill(-99) return out if is_none(dims): out = np.empty(dat.shape, dtype=np.int8) out.fill(-99) return out if is_none(pval_callback): out = np.empty(dat.shape, dtype=np.int8) out.fill(-99) return out z = [] for dim in dims: if dim == 'month': # Convert time vector to vector of months v = pval_callback('time') v = np.asanyarray(v, dtype=np.float) v = ntp_to_month(v) z.append(v) else: # Fetch the dimension from the callback method v = pval_callback(dim) z.append(v) if len(dims)>1: z = np.column_stack(z) else: z = z[0] datlimz = datlimz[:,0] return dataqc_localrangetest(dat, z, datlim, datlimz) def dataqc_localrangetest(dat, z, datlim, datlimz, strict_validation=False): """ Description: Data quality control algorithm testing if measurements fall into a user-defined valid range. This range is not constant but varies with measurement location. Returns 1 for presumably good data and 0 for data presumed bad. Implemented by: 2012-07-17: DPS authored by <NAME>. Example code provided for Matlab. 2013-04-06: <NAME>. Initial python implementation. Usage: qcflag = dataqc_localrangetest(dat, z, datlim, datlimz) where qcflag = Boolean, 0 if value is outside range, else = 1. dat = input data set, a numeric real scalar or column vector. z = location of measurement dat. must have same # of rows as dat and same # of columns as datlimz datlim = two column array with the minimum (column 1) and maximum (column 2) values considered valid. datlimz = array with the locations where datlim is given. must have same # of rows as datlim and same # of columns as z. References: OOI (2012). Data Product Specification for Local Range Test. Document Control Number 1341-10005. https://alfresco.oceanobservatories.org/ (See: Company Home >> OOI >> Controlled >> 1000 System Level >> 1341-10005_Data_Product_SPEC_LOCLRNG_OOI.pdf) """ if strict_validation: # check if dat and datlim are matrices if not utils.isvector(dat): raise ValueError('\'dat\' must be a matrix') if not utils.ismatrix(datlim): raise ValueError('\'datlim\' must be a matrix') # check if all inputs are numeric and real for k, arg in {'dat': dat, 'z': z, 'datlim': datlim, 'datlimz': datlimz}.iteritems(): if not utils.isnumeric(arg).all(): raise ValueError('\'{0}\' must be numeric'.format(k)) if not utils.isreal(arg).all(): raise ValueError('\'{0}\' must be real'.format(k)) if len(datlim.shape) == 3 and datlim.shape[0] == 1: datlim = datlim.reshape(datlim.shape[1:]) if len(datlimz.shape) == 3 and datlimz.shape[0] == 1: datlimz = datlimz.reshape(datlimz.shape[1:]) # test size and shape of the input arrays datlimz and datlim, setting test # variables. array_size = datlimz.shape if len(array_size) == 1: numlim = array_size[0] ndim = 1 else: numlim = array_size[0] ndim = array_size[1] array_size = datlim.shape tmp1 = array_size[0] tmp2 = array_size[1] if tmp1 != numlim: raise ValueError('\'datlim\' and \'datlimz\' must ' 'have the same number of rows.') if tmp2 != 2: raise ValueError('\'datlim\' must be structured as 2-D array ' 'with exactly 2 columns and 1 through N rows.') # test the size and shape of the z input array array_size = z.shape if len(array_size) == 1: num = array_size[0] tmp2 = 1 else: num = array_size[0] tmp2 = array_size[1] if tmp2 != ndim: raise ValueError('\'z\' must have the same number of columns ' 'as \'datlimz\'.') if num != dat.size: raise ValueError('Len of \'dat\' must match number of ' 'rows in \'z\'') # test datlim, values in column 2 must be greater than those in column 1 if not all(datlim[:, 1] > datlim[:, 0]): raise ValueError('Second column values of \'datlim\' should be ' 'greater than first column values.') # calculate the upper and lower limits for the data set if ndim == 1: # determine the lower limits using linear interpolation lim1 = np.interp(z, datlimz, datlim[:, 0], left=np.nan, right=np.nan) # determine the upper limits using linear interpolation lim2 = np.interp(z, datlimz, datlim[:, 1], left=np.nan, right=np.nan) else: # Compute Delaunay Triangulation and use linear interpolation to # determine the N-dimensional lower limits F = LinearNDInterpolator(datlimz, datlim[:, 0].reshape(numlim, 1)) lim1 = F(z).reshape(dat.size) # Compute Delaunay Triangulation and use linear interpolation to # determine the N-dimensional upper limits F = LinearNDInterpolator(datlimz, datlim[:, 1].reshape(numlim, 1)) lim2 = F(z).reshape(dat.size) # replace NaNs from above interpolations ff = (np.isnan(lim1)) | (np.isnan(lim2)) lim1[ff] = np.max(datlim[:, 1]) lim2[ff] = np.min(datlim[:, 0]) # compute the qcflags qcflag = (dat >= lim1) & (dat <= lim2) return qcflag.astype('int8') def dataqc_spiketest_wrapper(dat, acc, N, L, strict_validation=False): if is_none(acc) or is_fill(acc) or is_none(N) or is_fill(N) or is_none(L) or is_fill(L): out = np.empty(dat.shape, dtype=np.int8) out.fill(-99) return out return dataqc_spiketest(dat, np.atleast_1d(acc)[-1], np.atleast_1d(N)[-1], np.atleast_1d(L)[-1], strict_validation=strict_validation) def dataqc_spiketest(dat, acc, N=5, L=5, strict_validation=False): """ Description: Data quality control algorithm testing a time series for spikes. Returns 1 for presumably good data and 0 for data presumed bad. The time series is divided into windows of len L (an odd integer number). Then, window by window, each value is compared to its (L-1) neighboring values: a range R of these (L-1) values is computed (max. minus min.), and replaced with the measurement accuracy ACC if ACC>R. A value is presumed to be good, i.e. no spike, if it deviates from the mean of the (L-1) peers by less than a multiple of the range, N*max(R,ACC). Further than (L-1)/2 values from the start or end points, the peer values are symmetrically before and after the test value. Within that range of the start and end, the peers are the first/last L values (without the test value itself). The purpose of ACC is to restrict spike detection to deviations exceeding a minimum threshold value (N*ACC) even if the data have little variability. Use ACC=0 to disable this behavior. Implemented by: 2012-07-28: DPS authored by <NAME>. Example code provided for Matlab. 2013-04-06: <NAME>. Initial python implementation. 2013-05-30: <NAME>. Performance optimizations. Usage: qcflag = dataqc_spiketest(dat, acc, N, L) where qcflag = Boolean, 0 if value is outside range, else = 1. dat = input data set, a numeric, real vector. acc = Accuracy of any input measurement. N = (optional, defaults to 5) Range multiplier, cf. above L = (optional, defaults to 5) Window len, cf. above References: OOI (2012). Data Product Specification for Spike Test. Document Control Number 1341-10006. https://alfresco.oceanobservatories.org/ (See: Company Home >> OOI >> Controlled >> 1000 System Level >> 1341-10006_Data_Product_SPEC_SPKETST_OOI.pdf) """ dat = np.atleast_1d(dat) if strict_validation: if not utils.isnumeric(dat).all(): raise ValueError('\'dat\' must be numeric') if not utils.isreal(dat).all(): raise ValueError('\'dat\' must be real') if not utils.isvector(dat): raise ValueError('\'dat\' must be a vector') for k, arg in {'acc': acc, 'N': N, 'L': L}.iteritems(): if not utils.isnumeric(arg).all(): raise ValueError('\'{0}\' must be numeric'.format(k)) if not utils.isreal(arg).all(): raise ValueError('\'{0}\' must be real'.format(k)) dat = np.asanyarray(dat, dtype=np.float) out = spikevalues(dat, L, N, acc) return out def dataqc_polytrendtest_wrapper(dat, t, ord_n, nstd, strict_validation=False): if is_none(ord_n) or is_fill(ord_n) or is_none(nstd) or is_fill(ord_n): out =
np.empty(dat.shape, dtype=np.int8)
numpy.empty
import logging logging.basicConfig() logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) logger.info("Loaded " + __name__) import cv2 import requests from base64 import b64encode, b64decode import json import time import numpy as np from numpy.linalg import norm class recognizerClient(): def __init__(self,config={}): logger.info("initialized with config -{}".format(config)) endpoint=config.get("endpoint","http://localhost") apiPort=config.get("apiPort",8020) mlPort=config.get("mlPort",6500) api_version=config.get("api_version","api/v1") service=config.get("service","recognition") api_key=config.get("api_key","00000000-0000-0000-0000-000000000002") maxFailedAttempts=config.get("maxFailedAttempts",5000) matchThreshold=config.get("matchThreshold",0.6) self.matchThreshold=matchThreshold self.baseurl="{}:{}".format(endpoint,apiPort) self.recogUrl="{}/{}/{}".format(self.baseurl,api_version,service) self.mlUrl="{}:{}".format(endpoint,mlPort) self.headers = {"x-api-key": api_key} self.api_version='api/v1/recognition' self.failedAttempts=0 self.maxFailedAttempts=maxFailedAttempts self.get_similarity_coeffs() def recognize(self,image,filename='test',max_limit=5,det_threshold=0.5,plugins='calculator',types='image'): url="{}/{}?prediction_count={}&det_prob_threshold={}&face_plugins={}".format(self.recogUrl,'recognize',max_limit,det_threshold,plugins) try: if types != 'file': encoded= cv2.imencode(".jpg", image)[1].tostring() else: encoded=image files = {'file': ('image.jpg', encoded, 'image/jpeg', {'Expires': '0'})} logger.info("url-{}".format(url)) response = requests.post(url,headers=self.headers,files=files,timeout=60) response.raise_for_status() dets= response.json()["result"] logger.info(dets) return dets except Exception as e: message="" try: resp=response.json() message=resp["message"] except: pass logger.info("Error in recognition call-{},message-{}".format(str(e),message)) return [] def createArtefact(self,artefactId,images,types='image'): url ="{}/{}?subject={}".format(self.recogUrl,'faces',artefactId) success =0 for image in images: message="" try: if types != 'file': encoded= cv2.imencode(".jpg", image)[1].tostring() else: encoded=image encoded= cv2.imencode(".jpg", image)[1].tostring() files = {'file': ('image.jpg', encoded, 'image/jpeg', {'Expires': '0'})} response = requests.post(url,headers=self.headers,files=files,timeout=60) response.raise_for_status() success+=1 subject=response.json()['subject'] imid=response.json()['image_id'] logger.info("successfully created subject-{} with image id-{}".format(subject,imid)) except Exception as e: try: resp=response.json() message=resp["message"] except: pass logger.info("Error in creating subject-{}-{},message-{}".format(artefactId,str(e),message)) if success>0: return True else: return False def getArtefacts(self): url="{}/{}".format(self.recogUrl,'faces') message="" try: response = requests.get(url,headers=self.headers) response.raise_for_status() return response.json()['faces'] except Exception as e: try: resp=response.json() message=resp["message"] except: pass logger.info("Error in getting subjects -{},message-{}".format(str(e),message)) return [] def deleteArtefact(self,artefactId): url="{}/{}?subject={}".format(self.recogUrl,'faces',artefactId) message="" try: response = requests.request("DELETE", url,headers=self.headers) response.raise_for_status() logger.info("Successful in deleting subject{}".format(artefactId)) return True except Exception as e: try: resp=response.json() message=resp["message"] except: pass logger.info("Error in deleting subject{} -{},message-{}".format(artefactId,str(e),message)) return False def face_encodings(self,image,types='image'): url="{}/{}?face_plugins=calculator".format(self.mlUrl,'find_faces') message="" if types != 'file': encoded= cv2.imencode(".jpg", image)[1].tostring() else: encoded=image files = {'file': ('image.jpg', encoded, 'image/jpeg', {'Expires': '0'})} logger.info("url-{}".format(url)) try: response = requests.post(url,headers=self.headers,files=files,timeout=60) response.raise_for_status() embedding=(response.json()['result'][0]['embedding']) norm_factor=norm(embedding) npEmbedding=np.array(embedding/norm_factor) return [npEmbedding] except Exception as e: try: resp=response.json() message=resp["message"] except: pass logger.info("Error in getting encoding -{},message-{}".format(str(e),message)) return None def get_similarity_coeffs(self): url ="{}/status".format(self.mlUrl) message="" try: response = requests.get(url,headers=self.headers,timeout=60) response.raise_for_status() self.coeffs=response.json()["similarity_coefficients"] logger.info("success getting coeffs-{}".format(self.coeffs)) except Exception as e: try: resp=response.json() message=resp["message"] except: pass logger.info("Error in getting subjects -{},message-{}".format(str(e),message)) raise Exception (str(e)) def face_distance(self,encodings,encodingToMatch): if len(encodings) == 0: return np.empty((0)) dist= norm(encodings-encodingToMatch,axis=1) similarity=(np.tanh((self.coeffs[0]-dist) * self.coeffs[1]) + 1) / 2 #logger.info("similarity matrix-{}".format(similarity)) return 1- similarity def face_similarity(self,encodings,encodingToMatch): if len(encodings) == 0: return np.empty((0)) dist= norm(encodings-encodingToMatch,axis=1) similarity=(
np.tanh((self.coeffs[0]-dist) * self.coeffs[1])
numpy.tanh
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Analysis of fire seasons. For the purpose of these analyses, burned area at each location is relative to the maximum burned are observed at that location. This allows the use of a single unitless threshold throughout. The start & end months of the fire seasons and their variation are analysed temporally and spatially. A varying threshold is used to determine when fires are significant in order to avoid small, anomalous fire events from influencing the final estimate. A mask that allows selecting fire season months only may be calculated as well. """ import logging import os from copy import deepcopy import matplotlib as mpl import numpy as np from joblib import Parallel, delayed from scipy.ndimage import label from tqdm import tqdm from ..cache import get_memory from ..data import * from ..logging_config import enable_logging from .plotting import * __all__ = ("thres_fire_season_stats",) logger = logging.getLogger(__name__) memory = get_memory("fire_season") def get_fire_season( ba_data, thres, climatology=True, quiet=True, return_mask=False, return_fraction=False, ): """Determine the fire season from burned area data. The mask is respected by returning masked arrays that contain the original mask. The fire seasons are organised into clusters - contiguous blocks of 'significant' burned area (see `thres`). Args: ba_data (numpy.ma.core.MaskedArray): Burned area data. The time-coordinate (first axis) should have a length that is an integer multiple of 12. thres (float): Threshold [0, 1]. Defines when normalised burned area (divided by maximum) is significant. climatology (bool): If True, treat the data as a climatology by allowing wrap-around of burned area clusters around the beginning and end of the time coordinate. quiet (bool): If True, suppress progress meter. return_mask (bool): If True, return a boolean numpy array representing the significant fire clusters. return_fraction (bool): If True, return an array containing the fraction of times above the threshold which are contained within the main cluster. Returns: indices, season_start, season_end, season_duration: Description of the fire season at each location given by `indices`. Examples: >>> import numpy as np >>> data_shape = (12, 4, 3) >>> data = np.ma.MaskedArray(np.zeros(data_shape), mask=np.zeros(data_shape)) >>> data.mask[:, :, -1] = True >>> data[[0, -1], 0, 0] = 1 >>> data[[-2, -1], 0, 1] = 1 >>> data[[0, 1], 1, 0] = 1 >>> data[0, 1, 1] = 1 >>> data[:, 2, 0] = 1 >>> data[-1, 2, 1] = 1 >>> data[[0, 4, 5, 6], 3, 0] = 1 >>> data[[0, 4, 5, 6, -1], 3, 1] = 1 >>> out = get_fire_season(data, 0.5, return_mask=True) >>> for i, j in zip(*np.where(~out[0].mask)): ... print( ... (i, j), f"{out[0][i, j]:>2d} {out[1][i, j]:>2d} {out[2][i, j]:>2d}" ... ) (0, 0) 11 0 2 (0, 1) 10 11 2 (1, 0) 0 1 2 (1, 1) 0 0 1 (2, 0) 0 11 12 (2, 1) 11 11 1 (3, 0) 4 6 3 (3, 1) 4 6 3 >>> mask = np.zeros(data_shape, dtype=np.bool_) >>> mask[[0, -1], 0, 0] = 1 >>> mask[[-2, -1], 0, 1] = 1 >>> mask[[0, 1], 1, 0] = 1 >>> mask[0, 1, 1] = 1 >>> mask[:, 2, 0] = 1 >>> mask[-1, 2, 1] = 1 >>> mask[[4, 5, 6], 3, 0] = 1 >>> mask[[4, 5, 6], 3, 1] = 1 >>> np.all(mask == out[3]) True """ # Make sure the proper number of months are given. assert ba_data.shape[0] % 12 == 0, "Need an integer multiple of 12 months." # Make a copy of the mask initially, because certain operations may change this # later on. orig_mask = deepcopy(ba_data.mask) def null_func(x, *args, **kwargs): return x if return_mask: season_mask = np.zeros(ba_data.shape, dtype=np.bool_) # Normalise burned areas, dividing by the maximum burned area for each location. ba_data /= np.max(ba_data, axis=0) # Find significant samples. ba_data = ba_data > thres # Define the structure such that only elements touching in the time-axis are # counted as part of the same cluster. # TODO: Modify this to take into account spatial connectivity as well? # Eg. a cluster may be contained past points of no burning due to adjacent # pixels burning during the gaps. structure = np.zeros((3, 3, 3), dtype=np.int64) structure[:, 1, 1] = 1 # Scipy `label` does not take the mask into account, so set masked elements to # boolean False in the input. ba_data[ba_data.mask] = False ba_data.mask = orig_mask # NOTE: Iterate like `range(1, n_clusters + 1)` for cluster indices. clusters, n_clusters = label(ba_data, structure=structure) # The data mask is used the determine where calculations should take place - # locations which are always masked are never considered. indices = np.where(np.any(~orig_mask, axis=0) & np.any(clusters, axis=0)) starts = [] ends = [] sizes = [] if return_fraction: fractions = [] equal_cluster_errors = 0 if climatology: # Iterate only over relevant areas. for xy in tqdm(zip(*indices), total=len(indices[0]), disable=quiet): cluster = clusters[(slice(None),) + tuple(xy)] assert np.any(cluster) size = 0 main_cluster_index = None for cluster_index in set(np.unique(cluster)) - {0}: new_size = np.sum(cluster == cluster_index) if new_size > size: size = new_size main_cluster_index = cluster_index # To handle wrap-around, first determine where this is relevant - only # where there is a cluster both at the beginning and the end. # Also ignore the case where there is only one complete cluster since that # is not a wrap-around case. potential_wrap = False if np.logical_and(cluster[0], cluster[-1]) and not all( edge_index == main_cluster_index for edge_index in (cluster[0], cluster[-1]) ): wrap_size = sum( np.sum(cluster == cluster_index) for cluster_index in (cluster[0], cluster[-1]) ) if wrap_size == size: equal_cluster_errors += 1 logger.debug("Equal cluster sizes detected. Ignoring both.") continue if wrap_size > size: potential_wrap = True size = wrap_size cluster_selection = np.logical_or( cluster == cluster[0], cluster == cluster[-1] ) selected_indices = np.where(cluster_selection)[0] # In the case of the wrap-around, stick to the convention that the # 'last' index is the start and vice versa, to maintain a # contiguous cluster across the wrap. # The 'start' is the first occurrence of the final cluster. start = np.where(cluster == cluster[-1])[0][0] # The 'end' is the last occurrence of the initial cluster. end = np.where(cluster == cluster[0])[0][-1] if not potential_wrap: # If we are this point, then wrapping is not significant. cluster_selection = cluster == main_cluster_index selected_indices = np.where(cluster_selection)[0] start = selected_indices[0] end = selected_indices[-1] starts.append(start) ends.append(end) sizes.append(size) if return_mask: season_mask[(slice(None),) + tuple(xy)] = cluster_selection if return_fraction: fractions.append(size / np.sum(cluster > 0)) if equal_cluster_errors: logger.warning( f"{equal_cluster_errors} equal cluster size(s) detected and ignored." ) else: raise NotImplementedError("Check back later.") start_arr = np.ma.MaskedArray( np.zeros(ba_data.shape[1:], dtype=np.int64), mask=True ) end_arr =
np.zeros_like(start_arr)
numpy.zeros_like
import ctypes import numpy as np import pytest from psyneulink.core import llvm as pnlvm from llvmlite import ir DIM_X = 1000 DIM_Y = 2000 u = np.random.rand(DIM_X, DIM_Y) v = np.random.rand(DIM_X, DIM_Y) vector = np.random.rand(DIM_X) trans_vector = np.random.rand(DIM_Y) scalar = np.random.rand() llvm_mat_res = np.random.rand(DIM_X, DIM_Y) llvm_vec_res = np.random.rand(DIM_Y) llvm_tvec_res = np.random.rand(DIM_X) mat_add_res = np.add(u,v) mat_sub_res = np.subtract(u,v) mat_mul_res = np.multiply(u, v) dot_res = np.dot(vector, u) trans_dot_res = np.dot(trans_vector, u.transpose()) mat_sadd_res = np.add(u, scalar) mat_smul_res = np.multiply(u, scalar) ct_u = u.ctypes.data_as(ctypes.POINTER(ctypes.c_double)) ct_v = v.ctypes.data_as(ctypes.POINTER(ctypes.c_double)) ct_vec = vector.ctypes.data_as(ctypes.POINTER(ctypes.c_double)) ct_tvec = trans_vector.ctypes.data_as(ctypes.POINTER(ctypes.c_double)) ct_mat_res = llvm_mat_res.ctypes.data_as(ctypes.POINTER(ctypes.c_double)) ct_vec_res = llvm_vec_res.ctypes.data_as(ctypes.POINTER(ctypes.c_double)) ct_tvec_res = llvm_tvec_res.ctypes.data_as(ctypes.POINTER(ctypes.c_double)) @pytest.mark.benchmark(group="Hadamard") @pytest.mark.parametrize("op, builtin, result", [ (np.add, "__pnl_builtin_mat_add", mat_add_res), (np.subtract, "__pnl_builtin_mat_sub", mat_sub_res), (np.multiply, "__pnl_builtin_mat_hadamard", mat_mul_res), ], ids=["ADD", "SUB", "MUL"]) @pytest.mark.parametrize("mode", ['Python', pytest.param('LLVM', marks=pytest.mark.llvm)]) def test_mat_hadamard(benchmark, op, builtin, result, mode): if mode == 'Python': res = benchmark(op, u, v) elif mode == 'LLVM': llvm_fun = pnlvm.LLVMBinaryFunction.get(builtin) benchmark(llvm_fun, ct_u, ct_v, DIM_X, DIM_Y, ct_mat_res) res = llvm_mat_res assert np.allclose(res, result) @pytest.mark.benchmark(group="Scalar") @pytest.mark.parametrize("op, builtin, result", [ (np.add, "__pnl_builtin_mat_scalar_add", mat_sadd_res), (np.multiply, "__pnl_builtin_mat_scalar_mult", mat_smul_res), ], ids=["ADD", "MUL"]) @pytest.mark.parametrize("mode", ['Python', pytest.param('LLVM', marks=pytest.mark.llvm)]) def test_mat_scalar(benchmark, op, builtin, result, mode): if mode == 'Python': res = benchmark(op, u, scalar) elif mode == 'LLVM': llvm_fun = pnlvm.LLVMBinaryFunction.get(builtin) benchmark(llvm_fun, ct_u, scalar, DIM_X, DIM_Y, ct_mat_res) res = llvm_mat_res assert np.allclose(res, result) @pytest.mark.benchmark(group="Dot") def test_dot_numpy(benchmark): numpy_res = benchmark(np.dot, vector, u) assert
np.allclose(numpy_res, dot_res)
numpy.allclose
#------------------------------------------Single Rectangle dection-------------------------------------------# ## Adapted from https://github.com/jrieke/shape-detection by <NAME> # Import libraries: import numpy as np import matplotlib.pyplot as plt import matplotlib import time import os # Import tensorflow to use GPUs on keras: import tensorflow as tf # Set keras with GPUs import keras config = tf.ConfigProto( device_count = {'GPU': 1 , 'CPU': 12} ) sess = tf.Session(config=config) keras.backend.set_session(sess) # Import keras tools: from keras.models import Sequential from keras.layers import Dense, Activation, Dropout from keras.optimizers import SGD # Create images with random rectangles and bounding boxes: num_imgs = 50000 img_size = 8 min_object_size = 1 max_object_size = 4 num_objects = 1 bboxes = np.zeros((num_imgs, num_objects, 4)) imgs = np.zeros((num_imgs, img_size, img_size)) # set background to # Generating random images and bounding boxes: for i_img in range(num_imgs): for i_object in range(num_objects): w, h = np.random.randint(min_object_size, max_object_size, size=2) # bbox width (w) and height (h) x = np.random.randint(0, img_size - w) # bbox x lower left corner coordinate y = np.random.randint(0, img_size - h) # bbox y lower left corner coordinate imgs[i_img, x:x+w, y:y+h] = 1. # set rectangle to 1 bboxes[i_img, i_object] = [x, y, w, h] # store coordinates # Lets plot one example of generated image: i = 0 plt.imshow(imgs[i].T, cmap='Greys', interpolation='none', origin='lower', extent=[0, img_size, 0, img_size]) for bbox in bboxes[i]: plt.gca().add_patch(matplotlib.patches.Rectangle((bbox[0], bbox[1]), bbox[2], bbox[3], ec='r', fc='none')) ## Obs: # - The transpose was done for using properly both plt functions # - extent is the size of the image # - ec is the color of the border of the bounding box # - fc is to avoid any coloured background of the bounding box # Display plot: # plt.show() # Reshape (stack rows horizontally) and normalize the image data to mean 0 and std 1: X = (imgs.reshape(num_imgs, -1) - np.mean(imgs)) / np.std(imgs) X.shape, np.mean(X), np.std(X) # Normalize x, y, w, h by img_size, so that all values are between 0 and 1: # Important: Do not shift to negative values (e.g. by setting to mean 0) #----------- because the IOU calculation needs positive w and h y = bboxes.reshape(num_imgs, -1) / img_size y.shape, np.mean(y), np.std(y) # Split training and test: i = int(0.8 * num_imgs) train_X = X[:i] test_X = X[i:] train_y = y[:i] test_y = y[i:] test_imgs = imgs[i:] test_bboxes = bboxes[i:] # Build the model: model = Sequential([Dense(200, input_dim=X.shape[-1]), Activation('relu'), Dropout(0.2), Dense(y.shape[-1])]) model.compile('adadelta', 'mse') # Fit the model: tic = time.time() model.fit(train_X, train_y,nb_epoch=30, validation_data=(test_X, test_y), verbose=2) toc = time.time() - tic print(toc) # Predict bounding boxes on the test images: pred_y = model.predict(test_X) pred_bboxes = pred_y * img_size pred_bboxes = pred_bboxes.reshape(len(pred_bboxes), num_objects, -1) pred_bboxes.shape # Function to define the intersection over the union of the bounding boxes pair: def IOU(bbox1, bbox2): '''Calculate overlap between two bounding boxes [x, y, w, h] as the area of intersection over the area of unity''' x1, y1, w1, h1 = bbox1[0], bbox1[1], bbox1[2], bbox1[3] x2, y2, w2, h2 = bbox2[0], bbox2[1], bbox2[2], bbox2[3] w_I = min(x1 + w1, x2 + w2) - max(x1, x2) h_I = min(y1 + h1, y2 + h2) - max(y1, y2) if w_I <= 0 or h_I <= 0: # no overlap return 0 else: I = w_I * h_I U = w1 * h1 + w2 * h2 - I return I / U # Show a few images and predicted bounding boxes from the test dataset. os.chdir('/workdir/jp2476/repo/diversity-proj/files') plt.figure(figsize=(12, 3)) for i_subplot in range(1, 5): plt.subplot(1, 4, i_subplot) i = np.random.randint(len(test_imgs)) plt.imshow(test_imgs[i].T, cmap='Greys', interpolation='none', origin='lower', extent=[0, img_size, 0, img_size]) for pred_bbox, train_bbox in zip(pred_bboxes[i], test_bboxes[i]): plt.gca().add_patch(matplotlib.patches.Rectangle((pred_bbox[0], pred_bbox[1]), pred_bbox[2], pred_bbox[3], ec='r', fc='none')) plt.annotate('IOU: {:.2f}'.format(IOU(pred_bbox, train_bbox)), (pred_bbox[0], pred_bbox[1]+pred_bbox[3]+0.2), color='r') # plt.savefig("simple_detection.pdf", dpi=150) # plt.savefig("simple_detection.png", dpi=150) plt.show() plt.clf() # Calculate the mean IOU (overlap) between the predicted and expected bounding boxes on the test dataset: summed_IOU = 0. for pred_bbox, test_bbox in zip(pred_bboxes.reshape(-1, 4), test_bboxes.reshape(-1, 4)): summed_IOU += IOU(pred_bbox, test_bbox) mean_IOU = summed_IOU / len(pred_bboxes) mean_IOU #-------------------------------------------Two Rectangle dection---------------------------------------------# ## Adapted from https://github.com/jrieke/shape-detection by <NAME> # Import libraries: import numpy as np import matplotlib.pyplot as plt import matplotlib import time import os # Import tensorflow to use GPUs on keras: import tensorflow as tf # Set keras with GPUs import keras config = tf.ConfigProto( device_count = {'GPU': 1 , 'CPU': 12} ) sess = tf.Session(config=config) keras.backend.set_session(sess) # Import keras tools: from keras.models import Sequential from keras.layers import Dense, Activation, Dropout from keras.optimizers import SGD # Create images with random rectangles and bounding boxes: num_imgs = 50000 # Image parameters for simulation: img_size = 8 min_rect_size = 1 max_rect_size = 4 num_objects = 2 # Initialize objects: bboxes = np.zeros((num_imgs, num_objects, 4)) imgs = np.zeros((num_imgs, img_size, img_size)) # Generate images and bounding boxes: for i_img in range(num_imgs): for i_object in range(num_objects): w, h = np.random.randint(min_rect_size, max_rect_size, size=2) x = np.random.randint(0, img_size - w) y = np.random.randint(0, img_size - h) imgs[i_img, x:x+w, y:y+h] = 1. bboxes[i_img, i_object] = [x, y, w, h] # Get shapes: imgs.shape, bboxes.shape # Plot one example of generated images: i = 0 plt.imshow(imgs[i].T, cmap='Greys', interpolation='none', origin='lower', extent=[0, img_size, 0, img_size]) for bbox in bboxes[i]: plt.gca().add_patch(matplotlib.patches.Rectangle((bbox[0], bbox[1]), bbox[2], bbox[3], ec='r', fc='none')) # plt.show() # Reshape and normalize the data to mean 0 and std 1: X = (imgs.reshape(num_imgs, -1) - np.mean(imgs)) / np.std(imgs) X.shape, np.mean(X), np.std(X) # Normalize x, y, w, h by img_size, so that all values are between 0 and 1: # Important: Do not shift to negative values (e.g. by setting to mean 0), #---------- because the IOU calculation needs positive w and h y = bboxes.reshape(num_imgs, -1) / img_size y.shape, np.mean(y), np.std(y) # Function to define the intersection over the union of the bounding boxes pair: def IOU(bbox1, bbox2): '''Calculate overlap between two bounding boxes [x, y, w, h] as the area of intersection over the area of unity''' x1, y1, w1, h1 = bbox1[0], bbox1[1], bbox1[2], bbox1[3] x2, y2, w2, h2 = bbox2[0], bbox2[1], bbox2[2], bbox2[3] w_I = min(x1 + w1, x2 + w2) - max(x1, x2) h_I = min(y1 + h1, y2 + h2) - max(y1, y2) if w_I <= 0 or h_I <= 0: # no overlap return 0 else: I = w_I * h_I U = w1 * h1 + w2 * h2 - I return I / U # Split training and test. i = int(0.8 * num_imgs) train_X = X[:i] test_X = X[i:] train_y = y[:i] test_y = y[i:] test_imgs = imgs[i:] test_bboxes = bboxes[i:] # Build the model. from keras.models import Sequential from keras.layers import Dense, Activation, Dropout from keras.optimizers import SGD model = Sequential([ Dense(256, input_dim=X.shape[-1]), Activation('relu'), Dropout(0.4), Dense(y.shape[-1]) ]) model.compile('adadelta', 'mse') # Flip bboxes during training: # Note: The validation loss is always quite big here because we don't flip the bounding boxes for #------ the validation data # Define the distance between the two bounding boxes: def distance(bbox1, bbox2): return np.sqrt(np.sum(np.square(bbox1[:2] - bbox2[:2]))) # Parameters to fit the model: num_epochs = 50 flipped = np.zeros((len(train_y), num_epochs)) ious_epoch = np.zeros((len(train_y), num_epochs)) dists_epoch = np.zeros((len(train_y), num_epochs)) mses_epoch = np.zeros((len(train_y), num_epochs)) # Training the model: for epoch in range(num_epochs): # Print the current epoch: print('Epoch', epoch) # Fit the model: model.fit(train_X, train_y, nb_epoch=1, validation_data=(test_X, test_y), verbose=2) # Get the output from the neural net: hat_y = model.predict(train_X) for i, (hat_bboxes, train_bboxes) in enumerate(zip(hat_y, train_y)): # Flip the training data: flipped_train_bboxes = np.concatenate([train_bboxes[4:], train_bboxes[:4]]) # Compute the mean-squared error for non-flipped and flipped data points: mse = np.mean(np.square(hat_bboxes - train_bboxes)) mse_flipped = np.mean(np.square(hat_bboxes - flipped_train_bboxes)) # Compute the IOU for each variation: iou = IOU(hat_bboxes[:4], train_bboxes[:4]) + IOU(hat_bboxes[4:], train_bboxes[4:]) iou_flipped = IOU(hat_bboxes[:4], flipped_train_bboxes[:4]) + IOU(hat_bboxes[4:], flipped_train_bboxes[4:]) # Compute the distance for each variation: dist = distance(hat_bboxes[:4], train_bboxes[:4]) + distance(hat_bboxes[4:], train_bboxes[4:]) dist_flipped = distance(hat_bboxes[:4], flipped_train_bboxes[:4]) + distance(hat_bboxes[4:], flipped_train_bboxes[4:]) # Store stats: if mse_flipped < mse: # you can also use iou or dist here train_y[i] = flipped_train_bboxes flipped[i, epoch] = 1 mses_epoch[i, epoch] = mse_flipped ious_epoch[i, epoch] = iou_flipped / 2. dists_epoch[i, epoch] = dist_flipped / 2. else: mses_epoch[i, epoch] = mse ious_epoch[i, epoch] = iou / 2. dists_epoch[i, epoch] = dist / 2. print('Flipped {} training samples ({} %)'.format(np.sum(flipped[:, epoch]), np.mean(flipped[:, epoch]) * 100.)) print('Mean IOU: {}'.format(np.mean(ious_epoch[:, epoch]))) print('Mean dist: {}'.format(
np.mean(dists_epoch[:, epoch])
numpy.mean
from __future__ import print_function import open3d as o3d # open3d needs to be imported before other packages! import argparse import os import random import numpy as np import torch import torch.nn.parallel import torch.utils.data from model.VAE import VAE from dataset.dataset import RIODatasetSceneGraph, collate_fn_vaegan, collate_fn_vaegan_points from helpers.util import bool_flag, batch_torch_denormalize_box_params from helpers.metrics import validate_constrains, validate_constrains_changes, estimate_angular_std from helpers.visualize_graph import run as vis_graph from helpers.visualize_scene import render import helpers.retrieval as retrieval from model.atlasnet import AE_AtlasNet import extension.dist_chamfer as ext chamfer = ext.chamferDist() import json parser = argparse.ArgumentParser() parser.add_argument('--num_points', type=int, default=1024, help='number of points in the shape') parser.add_argument('--dataset', required=False, type=str, default="./GT", help="dataset path") parser.add_argument('--dataset_3RScan', type=str, default='', help="dataset path of 3RScan") parser.add_argument('--label_file', required=False, type=str, default='labels.instances.align.annotated.ply', help="label file name") parser.add_argument('--with_points', type=bool_flag, default=False, help="if false, only predicts layout") parser.add_argument('--with_feats', type=bool_flag, default=True, help="Load Feats directly instead of points.") parser.add_argument('--manipulate', default=True, type=bool_flag) parser.add_argument('--path2atlas', default="./experiments/model_36.pth", type=str) parser.add_argument('--exp', default='./experiments/layout_test', help='experiment name') parser.add_argument('--epoch', type=str, default='100', help='saved epoch') parser.add_argument('--recompute_stats', type=bool_flag, default=False, help='Recomputes statistics of evaluated networks') parser.add_argument('--evaluate_diversity', type=bool_flag, default=False, help='Computes diversity based on multiple predictions') parser.add_argument('--visualize', default=False, type=bool_flag) parser.add_argument('--export_3d', default=False, type=bool_flag, help='Export the generated shapes and boxes in json files for future use') args = parser.parse_args() def evaluate(): print(torch.__version__) random.seed(48) torch.manual_seed(48) argsJson = os.path.join(args.exp, 'args.json') assert os.path.exists(argsJson), 'Could not find args.json for experiment {}'.format(args.exp) with open(argsJson) as j: modelArgs = json.load(j) saved_model = torch.load(args.path2atlas) point_ae = AE_AtlasNet(num_points=1024, bottleneck_size=128, nb_primitives=25) point_ae.load_state_dict(saved_model, strict=True) if torch.cuda.is_available(): point_ae = point_ae.cuda() test_dataset_rels_changes = RIODatasetSceneGraph( root=args.dataset, atlas=point_ae, path2atlas=args.path2atlas, root_3rscan=args.dataset_3RScan, label_file=args.label_file, split='val_scans', npoints=args.num_points, data_augmentation=False, use_points=args.with_points, use_scene_rels=modelArgs['use_scene_rels'], vae_baseline=modelArgs['network_type']=='sln', with_changes=True, eval=True, eval_type='relationship', with_feats=args.with_feats, recompute_feats=False, use_rio27=modelArgs['rio27'], use_canonical=modelArgs['use_canonical'], large=modelArgs['large'], use_splits=modelArgs['use_splits'], crop_floor=modelArgs['crop_floor'] if 'crop_floor' in modelArgs.keys() else False, center_scene_to_floor=modelArgs['crop_floor'] if 'crop_floor' in modelArgs.keys() else False) test_dataset_addition_changes = RIODatasetSceneGraph( root=args.dataset, atlas=point_ae, path2atlas=args.path2atlas, root_3rscan=args.dataset_3RScan, label_file=args.label_file, split='val_scans', npoints=args.num_points, data_augmentation=False, use_points=args.with_points, use_scene_rels=modelArgs['use_scene_rels'], vae_baseline=modelArgs['network_type']=='sln', with_changes=True, eval=True, eval_type='addition', with_feats=args.with_feats, use_rio27=modelArgs['rio27'], use_canonical=modelArgs['use_canonical'], large=modelArgs['large'], use_splits=modelArgs['use_splits'], crop_floor=modelArgs['crop_floor'] if 'crop_floor' in modelArgs.keys() else False, center_scene_to_floor=modelArgs['crop_floor'] if 'crop_floor' in modelArgs.keys() else False) # used to collect train statistics stats_dataset = RIODatasetSceneGraph( root=args.dataset, atlas=point_ae, path2atlas=args.path2atlas, root_3rscan=args.dataset_3RScan, label_file=args.label_file, npoints=args.num_points, split='train_scans', use_points=args.with_points, use_scene_rels=modelArgs['use_scene_rels'], with_changes=False, vae_baseline=modelArgs['network_type']=='sln', eval=False, with_feats=args.with_feats, use_rio27=modelArgs['rio27'], use_canonical=modelArgs['use_canonical'], large=modelArgs['large'], use_splits=modelArgs['use_splits'], crop_floor=modelArgs['crop_floor'] if 'crop_floor' in modelArgs.keys() else False, center_scene_to_floor=modelArgs['crop_floor'] if 'crop_floor' in modelArgs.keys() else False) test_dataset_no_changes = RIODatasetSceneGraph( root=args.dataset, atlas=point_ae, path2atlas=args.path2atlas, root_3rscan=args.dataset_3RScan, label_file=args.label_file, split='val_scans', npoints=args.num_points, data_augmentation=False, use_points=args.with_points, use_scene_rels=modelArgs['use_scene_rels'], vae_baseline=modelArgs['network_type']=='sln', with_changes=False, eval=True, with_feats=args.with_feats, use_rio27=modelArgs['rio27'], use_canonical=modelArgs['use_canonical'], large=modelArgs['large'], use_splits=modelArgs['use_splits'], crop_floor=modelArgs['crop_floor'] if 'crop_floor' in modelArgs.keys() else False, center_scene_to_floor=modelArgs['crop_floor'] if 'crop_floor' in modelArgs.keys() else False) if args.with_points: collate_fn = collate_fn_vaegan_points else: collate_fn = collate_fn_vaegan test_dataloader_rels_changes = torch.utils.data.DataLoader( test_dataset_rels_changes, batch_size=1, collate_fn=collate_fn, shuffle=False, num_workers=0) test_dataloader_add_changes = torch.utils.data.DataLoader( test_dataset_addition_changes, batch_size=1, collate_fn=collate_fn, shuffle=False, num_workers=0) # dataloader to collect train data statistics stats_dataloader = torch.utils.data.DataLoader( stats_dataset, batch_size=1, collate_fn=collate_fn, shuffle=False, num_workers=0) test_dataloader_no_changes = torch.utils.data.DataLoader( test_dataset_no_changes, batch_size=1, collate_fn=collate_fn, shuffle=False, num_workers=0) modeltype_ = modelArgs['network_type'] replacelatent_ = modelArgs['replace_latent'] if 'replace_latent' in modelArgs else None with_changes_ = modelArgs['with_changes'] if 'with_changes' in modelArgs else None model = VAE(type=modeltype_, vocab=test_dataset_no_changes.vocab, replace_latent=replacelatent_, with_changes=with_changes_, residual=modelArgs['residual'], gconv_pooling=modelArgs['pooling'], with_angles=modelArgs['with_angles']) model.load_networks(exp=args.exp, epoch=args.epoch) if torch.cuda.is_available(): model = model.cuda() model = model.eval() point_ae = point_ae.eval() model.compute_statistics(exp=args.exp, epoch=args.epoch, stats_dataloader=stats_dataloader, force=args.recompute_stats) cat2objs = None if model.type_ == 'sln': # prepare data for retrieval for the 3d-sln baseline rel_json_file = stats_dataset.root + '/relationships_merged_train_clean.json' cat2objs = retrieval.read_box_json(rel_json_file, stats_dataset.box_json_file) def reseed(): np.random.seed(47) torch.manual_seed(47) random.seed(47) print('\nEditing Mode - Additions') reseed() validate_constrains_loop_w_changes(test_dataloader_add_changes, model, with_diversity=args.evaluate_diversity, atlas=point_ae, with_angles=modelArgs['with_angles'], cat2objs=cat2objs) reseed() print('\nEditing Mode - Relationship changes') validate_constrains_loop_w_changes(test_dataloader_rels_changes, model, with_diversity=args.evaluate_diversity, atlas=point_ae, with_angles=modelArgs['with_angles'], cat2objs=cat2objs) reseed() print('\nGeneration Mode') validate_constrains_loop(test_dataloader_no_changes, model, with_diversity=args.evaluate_diversity, with_angles=modelArgs['with_angles'], vocab=test_dataset_no_changes.vocab, point_classes_idx=test_dataset_no_changes.point_classes_idx, point_ae=point_ae, export_3d=args.export_3d, cat2objs=cat2objs, datasize='large' if modelArgs['large'] else 'small') def validate_constrains_loop_w_changes(testdataloader, model, with_diversity=True, atlas=None, with_angles=False, num_samples=10, cat2objs=None): if with_diversity and num_samples < 2: raise ValueError('Diversity requires at least two runs (i.e. num_samples > 1).') accuracy = {} accuracy_unchanged = {} accuracy_in_orig_graph = {} for k in ['left', 'right', 'front', 'behind', 'smaller', 'bigger', 'lower', 'higher', 'same', 'total']: accuracy_in_orig_graph[k] = [] accuracy_unchanged[k] = [] accuracy[k] = [] all_diversity_boxes = [] all_diversity_angles = [] all_diversity_chamfer = [] for i, data in enumerate(testdataloader, 0): try: enc_objs, enc_triples, enc_tight_boxes, enc_objs_to_scene, enc_triples_to_scene = data['encoder']['objs'], \ data['encoder']['tripltes'], \ data['encoder']['boxes'], \ data['encoder']['obj_to_scene'], \ data['encoder'][ 'tiple_to_scene'] if 'feats' in data['encoder']: encoded_enc_points = data['encoder']['feats'] encoded_enc_points = encoded_enc_points.float().cuda() if 'points' in data['encoder']: enc_points = data['encoder']['points'] enc_points = enc_points.cuda() with torch.no_grad(): encoded_enc_points = atlas.encoder(enc_points.transpose(2,1).contiguous()) dec_objs, dec_triples, dec_tight_boxes, dec_objs_to_scene, dec_triples_to_scene = data['decoder']['objs'], \ data['decoder']['tripltes'], \ data['decoder']['boxes'], \ data['decoder']['obj_to_scene'], \ data['decoder']['tiple_to_scene'] missing_nodes = data['missing_nodes'] manipulated_nodes = data['manipulated_nodes'] except Exception as e: # skipping scene continue enc_objs, enc_triples, enc_tight_boxes = enc_objs.cuda(), enc_triples.cuda(), enc_tight_boxes.cuda() dec_objs, dec_triples, dec_tight_boxes = dec_objs.cuda(), dec_triples.cuda(), dec_tight_boxes.cuda() model = model.eval() all_pred_boxes = [] enc_boxes = enc_tight_boxes[:, :6] enc_angles = enc_tight_boxes[:, 6].long() - 1 enc_angles = torch.where(enc_angles > 0, enc_angles, torch.zeros_like(enc_angles)) enc_angles = torch.where(enc_angles < 24, enc_angles, torch.zeros_like(enc_angles)) attributes = None with torch.no_grad(): (z_box, _), (z_shape, _) = model.encode_box_and_shape(enc_objs, enc_triples, encoded_enc_points, enc_boxes, enc_angles, attributes) if args.manipulate: boxes_pred, points_pred, keep = model.decoder_with_changes_boxes_and_shape(z_box, z_shape, dec_objs, dec_triples, attributes, missing_nodes, manipulated_nodes, atlas) if with_angles: boxes_pred, angles_pred = boxes_pred else: boxes_pred, angles_pred, points_pred, keep = model.decoder_with_additions_boxes_and_shape(z_box, z_shape, dec_objs, dec_triples, attributes, missing_nodes, manipulated_nodes, atlas) if with_angles and angles_pred is None: boxes_pred, angles_pred = boxes_pred if with_diversity: # Run multiple times to obtain diversity # Only when a node was added or manipulated we run the diversity computation if len(missing_nodes) > 0 or len(manipulated_nodes) > 0: # Diversity results for this dataset sample boxes_diversity_sample, shapes_sample, angle_diversity_sample, diversity_retrieval_ids_sample = [], [], [], [] for sample in range(num_samples): # Generated changes diversity_angles = None if args.manipulate: diversity_boxes, diversity_points, diversity_keep = model.decoder_with_changes_boxes_and_shape( z_box, z_shape, dec_objs, dec_triples, attributes, missing_nodes, manipulated_nodes, atlas) else: diversity_boxes, diversity_angles, diversity_points, diversity_keep = model.decoder_with_additions_boxes_and_shape( z_box, z_shape, dec_objs, dec_triples, attributes, missing_nodes, manipulated_nodes, atlas) if with_angles and diversity_angles is None: diversity_boxes, diversity_angles = diversity_boxes if model.type_ == 'sln': dec_objs_filtered = dec_objs[diversity_keep[:,0] == 0] diversity_boxes_filtered = diversity_boxes[diversity_keep[:,0] == 0] dec_objs_filtered = dec_objs_filtered.reshape((-1, 1)) diversity_boxes = diversity_boxes.reshape((-1, 6)) diversity_points_retrieved, diversity_retrieval_ids_ivd = retrieval.rio_retrieve( dec_objs_filtered, diversity_boxes_filtered, testdataloader.dataset.vocab, cat2objs, testdataloader.dataset.root_3rscan, skip_scene_node=False, return_retrieval_id=True) diversity_points = torch.zeros((len(dec_objs), 1024, 3)) diversity_points[diversity_keep[:,0] == 0] = diversity_points_retrieved diversity_retrieval_ids = [''] * len(dec_objs) diversity_retrieval_ids_ivd = diversity_retrieval_ids_ivd.tolist() for i in range(len(dec_objs)): if diversity_keep[i, 0].cpu().numpy() == 0: diversity_retrieval_ids[i] = diversity_retrieval_ids_ivd.pop(0) diversity_retrieval_ids = np.asarray(diversity_retrieval_ids, dtype=np.str_) # Computing shape diversity on canonical and normalized shapes normalized_points = [] filtered_diversity_retrieval_ids = [] for ins_id, obj_id in enumerate(dec_objs): if obj_id != 0 and obj_id in testdataloader.dataset.point_classes_idx: # We only care for manipulated nodes if diversity_keep[ins_id, 0] == 1: continue points = diversity_points[ins_id] if type(points) is torch.Tensor: points = points.cpu().numpy() if points is None: continue # Normalizing shapes points = torch.from_numpy(normalize(points)) if torch.cuda.is_available(): points = points.cuda() normalized_points.append(points) if model.type_ == 'sln': filtered_diversity_retrieval_ids.append(diversity_retrieval_ids[ins_id]) # We use keep to filter changed nodes boxes_diversity_sample.append(diversity_boxes[diversity_keep[:, 0] == 0]) if with_angles: # We use keep to filter changed nodes angle_diversity_sample.append(np.expand_dims(np.argmax(diversity_angles[diversity_keep[:, 0] == 0].cpu().numpy(), 1), 1) / 24. * 360.) if len(normalized_points) > 0: shapes_sample.append(torch.stack(normalized_points)) # keep has already been applied for points if model.type_ == 'sln': diversity_retrieval_ids_sample.append(np.stack(filtered_diversity_retrieval_ids)) # keep has already been applied for points # Compute standard deviation for box for this sample if len(boxes_diversity_sample) > 0: boxes_diversity_sample = torch.stack(boxes_diversity_sample, 1) bs = boxes_diversity_sample.shape[0] if model.type_ != 'sln': boxes_diversity_sample = batch_torch_denormalize_box_params(boxes_diversity_sample.reshape([-1, 6])).reshape([bs, -1, 6]) all_diversity_boxes += torch.std(boxes_diversity_sample, dim=1).cpu().numpy().tolist() # Compute standard deviation for angle for this sample if len(angle_diversity_sample) > 0: angle_diversity_sample = np.stack(angle_diversity_sample, 1) all_diversity_angles += [estimate_angular_std(d[:,0]) for d in angle_diversity_sample] # Compute chamfer distances for shapes for this sample if len(shapes_sample) > 0: if len(diversity_retrieval_ids_sample) > 0: diversity_retrieval_ids_sample = np.stack(diversity_retrieval_ids_sample, 1) shapes_sample = torch.stack(shapes_sample, 1) for shapes_id in range(len(shapes_sample)): # Taking a single predicted shape shapes = shapes_sample[shapes_id] if len(diversity_retrieval_ids_sample) > 0: # To avoid that retrieval the object ids like 0,1,0,1,0 gives high error # We sort them to measure how often different objects are retrieved 0,0,0,1,1 diversity_retrieval_ids = diversity_retrieval_ids_sample[shapes_id] sorted_idx = diversity_retrieval_ids.argsort() shapes = shapes[sorted_idx] sequence_diversity = [] # Iterating through its multiple runs for shape_sequence_id in range(len(shapes) - 1): # Compute chamfer with the next shape in its sequences dist1, dist2 = chamfer(shapes[shape_sequence_id:shape_sequence_id + 1].float(), shapes[shape_sequence_id + 1:shape_sequence_id + 2].float()) chamfer_dist = torch.mean(dist1) + torch.mean(dist2) # Save the distance sequence_diversity += [chamfer_dist.cpu().numpy().tolist()] all_diversity_chamfer.append(np.mean(sequence_diversity)) bp = [] for i in range(len(keep)): if keep[i] == 0: bp.append(boxes_pred[i].cpu().detach()) else: bp.append(dec_tight_boxes[i,:6].cpu().detach()) all_pred_boxes.append(boxes_pred.cpu().detach()) # compute relationship constraints accuracy through simple geometric rules accuracy = validate_constrains_changes(dec_triples, boxes_pred, dec_tight_boxes, keep, model.vocab, accuracy, with_norm=model.type_ != 'sln') accuracy_in_orig_graph = validate_constrains_changes(dec_triples, torch.stack(bp, 0), dec_tight_boxes, keep, model.vocab, accuracy_in_orig_graph, with_norm=model.type_ != 'sln') accuracy_unchanged = validate_constrains(dec_triples, boxes_pred, dec_tight_boxes, keep, model.vocab, accuracy_unchanged, with_norm=model.type_ != 'sln') if with_diversity: print("DIVERSITY:") print("\tShape (Avg. Chamfer Distance) = %f" % (np.mean(all_diversity_chamfer))) print("\tBox (Std. metric size and location) = %f, %f" % ( np.mean(np.mean(all_diversity_boxes, axis=0)[:3]), np.mean(np.mean(all_diversity_boxes, axis=0)[3:]))) print("\tAngle (Std.) %s = %f" % (k, np.mean(all_diversity_angles))) keys = list(accuracy.keys()) for dic, typ in [(accuracy, "changed nodes"), (accuracy_unchanged, 'unchanged nodes'), (accuracy_in_orig_graph, 'changed nodes placed in original graph')]: # NOTE 'changed nodes placed in original graph' are the results reported in the paper! # The unchanged nodes are kept from the original scene, and the accuracy in the new nodes is computed with # respect to these original nodes print('{} & {:.2f} & {:.2f} & {:.2f} & {:.2f} &{:.2f} & {:.2f}'.format(typ, np.mean([np.mean(dic[keys[0]]), np.mean(dic[keys[1]])]), np.mean([np.mean(dic[keys[2]]), np.mean(dic[keys[3]])]), np.mean([np.mean(dic[keys[4]]), np.mean(dic[keys[5]])]), np.mean([np.mean(dic[keys[6]]), np.mean(dic[keys[7]])]), np.mean(dic[keys[8]]), np.mean(dic[keys[9]]))) print('means of mean: {:.2f}'.format(np.mean([np.mean([np.mean(dic[keys[0]]), np.mean(dic[keys[1]])]), np.mean([np.mean(dic[keys[2]]), np.mean(dic[keys[3]])]), np.mean([np.mean(dic[keys[4]]), np.mean(dic[keys[5]])]), np.mean([np.mean(dic[keys[6]]), np.mean(dic[keys[7]])]), np.mean(dic[keys[8]])]))) def validate_constrains_loop(testdataloader, model, with_diversity=True, with_angles=False, vocab=None, point_classes_idx=None, point_ae=None, export_3d=False, cat2objs=None, datasize='large', num_samples=10): if with_diversity and num_samples < 2: raise ValueError('Diversity requires at least two runs (i.e. num_samples > 1).') accuracy = {} for k in ['left', 'right', 'front', 'behind', 'smaller', 'bigger', 'lower', 'higher', 'same', 'total']: # compute validation for these relation categories accuracy[k] = [] all_diversity_boxes = [] all_diversity_angles = [] all_diversity_chamfer = [] all_pred_shapes_exp = {} # for export all_pred_boxes_exp = {} for i, data in enumerate(testdataloader, 0): try: dec_objs, dec_triples = data['decoder']['objs'], data['decoder']['tripltes'] instances = data['instance_id'][0] scan = data['scan_id'][0] split = data['split_id'][0] except Exception as e: continue dec_objs, dec_triples = dec_objs.cuda(), dec_triples.cuda() all_pred_boxes = [] with torch.no_grad(): boxes_pred, shapes_pred = model.sample_box_and_shape(point_classes_idx, point_ae, dec_objs, dec_triples, attributes=None) if with_angles: boxes_pred, angles_pred = boxes_pred angles_pred = torch.argmax(angles_pred, dim=1, keepdim=True) * 15.0 else: angles_pred = None if model.type_ != 'sln': shapes_pred, shape_enc_pred = shapes_pred if model.type_ != 'sln': boxes_pred_den = batch_torch_denormalize_box_params(boxes_pred) else: boxes_pred_den = boxes_pred if export_3d: if with_angles: boxes_pred_exp = torch.cat([boxes_pred_den.float(), angles_pred.view(-1,1).float()], 1).detach().cpu().numpy().tolist() else: boxes_pred_exp = boxes_pred_den.detach().cpu().numpy().tolist() if model.type_ != 'sln': # save point encodings shapes_pred_exp = shape_enc_pred.detach().cpu().numpy().tolist() else: # 3d-sln baseline does not generate shapes # save object labels to use for retrieval instead shapes_pred_exp = dec_objs.view(-1,1).detach().cpu().numpy().tolist() for i in range(len(shapes_pred_exp)): if dec_objs[i] not in testdataloader.dataset.point_classes_idx: shapes_pred_exp[i] = [] shapes_pred_exp = list(shapes_pred_exp) if scan not in all_pred_shapes_exp: all_pred_boxes_exp[scan] = {} all_pred_shapes_exp[scan] = {} if split not in all_pred_shapes_exp[scan]: all_pred_boxes_exp[scan][split] = {} all_pred_shapes_exp[scan][split] = {} all_pred_boxes_exp[scan][split]['objs'] = list(instances) all_pred_shapes_exp[scan][split]['objs'] = list(instances) for i in range(len(dec_objs) - 1): all_pred_boxes_exp[scan][split][instances[i]] = list(boxes_pred_exp[i]) all_pred_shapes_exp[scan][split][instances[i]] = list(shapes_pred_exp[i]) if args.visualize: # scene graph visualization. saves a picture of each graph to the outfolder colormap = vis_graph(use_sampled_graphs=False, scan_id=scan, split=str(split), data_path=args.dataset, outfolder=args.exp + "/vis_graphs/") colors = [] # convert colors to expected format def hex_to_rgb(hex): hex = hex.lstrip('#') hlen = len(hex) return tuple(int(hex[i:i+hlen//3], 16) for i in range(0, hlen, hlen//3)) for i in instances: h = colormap[str(i)] rgb = hex_to_rgb(h) colors.append(rgb) colors = np.asarray(colors) / 255. # layout and shape visualization through open3d render(boxes_pred_den, angles_pred, classes=vocab['object_idx_to_name'], render_type='points', classed_idx=dec_objs, shapes_pred=shapes_pred.cpu().detach(), colors=colors, render_boxes=True) all_pred_boxes.append(boxes_pred_den.cpu().detach()) if with_diversity: # Run multiple times to obtain diversities # Diversity results for this dataset sample boxes_diversity_sample, shapes_sample, angle_diversity_sample, diversity_retrieval_ids_sample = [], [], [], [] for sample in range(num_samples): diversity_boxes, diversity_points = model.sample_box_and_shape(point_classes_idx, point_ae, dec_objs, dec_triples, attributes=None) if with_angles: diversity_boxes, diversity_angles = diversity_boxes if model.type_ == 'sln': diversity_points, diversity_retrieval_ids = retrieval.rio_retrieve( dec_objs, diversity_boxes, vocab, cat2objs, testdataloader.dataset.root_3rscan, return_retrieval_id=True) else: diversity_points = diversity_points[0] # Computing shape diversity on canonical and normalized shapes normalized_points = [] filtered_diversity_retrieval_ids = [] for ins_id, obj_id in enumerate(dec_objs): if obj_id != 0 and obj_id in testdataloader.dataset.point_classes_idx: points = diversity_points[ins_id] if type(points) is torch.Tensor: points = points.cpu().numpy() if points is None: continue # Normalizing shapes points = torch.from_numpy(normalize(points)) if torch.cuda.is_available(): points = points.cuda() normalized_points.append(points) if model.type_ == 'sln': filtered_diversity_retrieval_ids.append(diversity_retrieval_ids[ins_id]) # We use keep to filter changed nodes boxes_diversity_sample.append(diversity_boxes) if with_angles: # We use keep to filter changed nodes angle_diversity_sample.append(np.expand_dims(np.argmax(diversity_angles.cpu().numpy(), 1), 1) / 24. * 360.) if len(normalized_points) > 0: shapes_sample.append(torch.stack(normalized_points)) # keep has already been aplied for points if model.type_ == 'sln': diversity_retrieval_ids_sample.append(np.stack(filtered_diversity_retrieval_ids)) # Compute standard deviation for box for this sample if len(boxes_diversity_sample) > 0: boxes_diversity_sample = torch.stack(boxes_diversity_sample, 1) bs = boxes_diversity_sample.shape[0] if model.type_ != 'sln': boxes_diversity_sample = batch_torch_denormalize_box_params(boxes_diversity_sample.reshape([-1, 6])).reshape([bs, -1, 6]) all_diversity_boxes += torch.std(boxes_diversity_sample, dim=1).cpu().numpy().tolist() # Compute standard deviation for angle for this sample if len(angle_diversity_sample) > 0: angle_diversity_sample = np.stack(angle_diversity_sample, 1) all_diversity_angles += [estimate_angular_std(d[:,0]) for d in angle_diversity_sample] # Compute chamfer distances for shapes for this sample if len(shapes_sample) > 0: shapes_sample = torch.stack(shapes_sample, 1) for shapes_id in range(len(shapes_sample)): # Taking a single predicted shape shapes = shapes_sample[shapes_id] if len(diversity_retrieval_ids_sample) > 0: # To avoid that retrieval the object ids like 0,1,0,1,0 gives high error # We sort them to measure how often different objects are retrieved 0,0,0,1,1 diversity_retrieval_ids = diversity_retrieval_ids_sample[shapes_id] sorted_idx = diversity_retrieval_ids.argsort() shapes = shapes[sorted_idx] sequence_diversity = [] # Iterating through its multiple runs for shape_sequence_id in range(len(shapes) - 1): # Compute chamfer with the next shape in its sequences dist1, dist2 = chamfer(shapes[shape_sequence_id:shape_sequence_id + 1].float(), shapes[shape_sequence_id + 1:shape_sequence_id + 2].float()) chamfer_dist = torch.mean(dist1) + torch.mean(dist2) # Save the distance sequence_diversity += [chamfer_dist.cpu().numpy().tolist()] if len(sequence_diversity) > 0: # check if sequence has shapes all_diversity_chamfer.append(np.mean(sequence_diversity)) # compute constraints accuracy through simple geometric rules accuracy = validate_constrains(dec_triples, boxes_pred, None, None, model.vocab, accuracy, with_norm=model.type_ != 'sln') if export_3d: # export box and shape predictions for future evaluation result_path = os.path.join(args.exp, 'results') if not os.path.exists(result_path): # Create a new directory for results os.makedirs(result_path) shape_filename = os.path.join(result_path, 'shapes_' + ('large' if datasize else 'small') + '.json') box_filename = os.path.join(result_path, 'boxes_' + ('large' if datasize else 'small') + '.json') json.dump(all_pred_boxes_exp, open(box_filename, 'w')) # 'dis_nomani_boxes_large.json' json.dump(all_pred_shapes_exp, open(shape_filename, 'w')) if with_diversity: print("DIVERSITY:") print("\tShape (Avg. Chamfer Distance) = %f" % (np.mean(all_diversity_chamfer))) print("\tBox (Std. metric size and location) = %f, %f" % ( np.mean(np.mean(all_diversity_boxes, axis=0)[:3]), np.mean(np.mean(all_diversity_boxes, axis=0)[3:]))) print("\tAngle (Std.) %s = %f" % (k, np.mean(all_diversity_angles))) keys = list(accuracy.keys()) for dic, typ in [(accuracy, "acc")]: print('{} & {:.2f} & {:.2f} & {:.2f} & {:.2f} &{:.2f} & {:.2f}'.format(typ, np.mean([np.mean(dic[keys[0]]), np.mean(dic[keys[1]])]), np.mean([np.mean(dic[keys[2]]), np.mean(dic[keys[3]])]), np.mean([np.mean(dic[keys[4]]), np.mean(dic[keys[5]])]), np.mean([
np.mean(dic[keys[6]])
numpy.mean
import numpy as np from scipy.ndimage.interpolation import rotate from scipy.interpolate import interp2d def annulusMask(width, r_in, r_out = None, width_x = None, cen_y = None, cen_x = None): """Creat a width*width all-0 mask; for r_in <= r <= r_out, 1. If r_out = 0, it means you are not constraining r_out, i.e., if r >= r_int, all ones. Default is a square mask centering at the center. Input: width: number of rows, a.k.a., width_y; width_x: number of columns. Default is None, i.e., width_x = width; r_in: where 1 starts; r_out: where 1 ends. Default is None, i.e., r_out = +infinity; cen_y: center of the annulus in y-direction. Default is None, i.e., cen_y = (width-1)/2.0; cen_x: center of the annulus in x-direction. Default is None, i.e., cen_x = (width_x-1)/2.0; Output: result. """ if width_x is None: width_x = width if cen_y is None: cen_y = (width-1)/2.0 if cen_x is None: cen_x = (width_x-1)/2.0 result = np.zeros((width, width_x)) r_in = np.max([0, r_in]) for i in range(width): for j in range(width_x): if r_out is None: if (i - cen_y)**2 + (j - cen_x)**2 >= r_in**2: result[i, j] = 1 else: if (i - cen_y)**2 + (j - cen_x)**2 >= r_in**2 and (i - cen_y)**2 + (j - cen_x)**2 <= r_out**2: result[i, j] = 1 return result def addplanet(image, planet, orientat = None, starflux = 1, radius = None, angle = None, contrast=1, exptime=1, planetOnly = False, x_planet = None, y_planet = None, surroundingReplace = None): """ Add a fake planet or image to ONE image of the star, "angle" is from north to east. Input: image: image of star, orientat: ORIENTAT keyword, starflux: total flux of the star, planet: image of fake planet, radius: seperation between the star and the planet, angle: angle of the planet on y-axis (deg E of N), contrast: contrast, exptime: exposure time planetOnly: only output the planet? x_planet, y_planet: you can add the Cartesian coordinates directly -- this will overwrite the radius and angle info if you have already. surroundingReplace: number. If given, the surroundings of the planet (i.e., the star except the planet) will be replaced with this value.""" #star centerx = (image.shape[1]-1)/2.0 centery = (image.shape[0]-1)/2.0 #planet nan_flag = 0 #flag of whether are there nan's in the planet array if np.sum(np.isnan(planet)) != 0: nan_flag = 1 planet_nans = np.zeros(planet.shape) #array to store the nan valuse in the planet planet_nans[np.where(np.isnan(planet))] = 1 #Find the nan's in the planet, then use this mask to exclude the nan region in the last step. palnet_nans_added = addplanet(np.zeros(image.shape), planet = planet_nans) palnet_nans_added[palnet_nans_added <= 0.9] = 0 palnet_nans_added[palnet_nans_added != 0] = 1 planet[np.where(np.isnan(planet))] = 0 #now the nan's in the planet are replaced with 0's. if x_planet is None: if radius is not None: x_planet = round(radius*np.cos(np.deg2rad(-orientat+angle+90)) + centerx, 2) else: x_planet = (image.shape[1]-1)/2.0 #default is put in the center. if y_planet is None: if radius is not None: y_planet = round(radius*np.sin(np.deg2rad(-orientat+angle+90)) + centery, 2) else: y_planet = (image.shape[0]-1)/2.0 x_range = np.arange(-(planet.shape[1]-1)/2.0+x_planet, -(planet.shape[1]-1)/2.0+x_planet + planet.shape[1] - 0.001, 1) y_range = np.arange(-(planet.shape[0]-1)/2.0++y_planet, -(planet.shape[0]-1)/2.0+y_planet + planet.shape[0] - 0.001, 1) planetfunc = interp2d(x_range, y_range, planet, kind='cubic') #Interpolation Part, (x_planet,y_planet) is maximum planetonly = np.zeros(image.shape) #This image contains only the planet x_range = np.arange( max(0, round(min(x_range)), 0), min(image.shape[1]-1, round(max(x_range), 0)) + 1 , 1) y_range = np.arange( max(0, round(min(y_range)), 0), min(image.shape[0]-1, round(max(y_range), 0)) + 1 , 1) if surroundingReplace is not None: planetonly[:,:] = surroundingReplace planetonly[int(min(y_range)):int(max(y_range))+1, int(min(x_range)):int(max(x_range))+1] = planetfunc(x_range, y_range)*starflux*contrast*exptime if nan_flag == 1: planetonly[np.where(palnet_nans_added == 1)] = np.nan if planetOnly or surroundingReplace is not None: return planetonly return planetonly+image def cutImage(image, halfSize, x_cen = None, y_cen = None, halfSizeX = None, halfSizeY = None, mask = None, relative_shift = False, dx = None, dy = None): """Cut the given image""" image = np.copy(image) if x_cen is None: x_cen = (image.shape[1] - 1)/2.0 if y_cen is None: y_cen = (image.shape[0] - 1)/2.0 if halfSizeX is None: halfSizeX = halfSize if halfSizeY is None: halfSizeY = halfSize if relative_shift == True: if dx is not None: x_cen += dx if dy is not None: y_cen += dy if mask is None: mask = np.ones(image.shape) mask[np.where(mask < 0.9)] = 0 mask[np.where(mask != 0)] = 1 maskNaN = np.ones(image.shape) #In case there are NaN's in the image maskNaN[np.isnan(image)] = 0 mask *= maskNaN image[np.isnan(image)] = 0 image_interp = interp2d(np.arange(image.shape[1]), np.arange(image.shape[0]), image) mask_interp = interp2d(np.arange(image.shape[1]), np.arange(image.shape[0]), mask) newImage = np.zeros((int(2*halfSizeY+1), int(2*halfSizeX+1))) x_range = np.round(np.arange(x_cen - halfSizeX, x_cen + halfSizeX + 0.1, 1), decimals = 2) y_range = np.round(np.arange(y_cen - halfSizeY, y_cen + halfSizeY + 0.1, 1), decimals = 2) newImage = image_interp(x_range, y_range) maskInterped = mask_interp(x_range, y_range) #Interpolate the image and mask maskInterped[np.where(maskInterped < 0.9)] = 0 maskInterped[np.where(maskInterped == 0)] = np.nan return newImage*maskInterped def bin_data(data, bin_size = 3, data_type = 'data', bin_method = 'average', mask_thresh = 0.9): """Bin the data with a bin_size*bin_size box. If the data_type is `data`, then a simple addition is performed, if it is an `uncertainty` map, then the square root of the squared sums are returned. if it is a `mask` (binary: 0 and 1), then the value that are smaller <= mask_thresh are treated as 0, and 1 otherwise The bin_method can be assigned with 'average' or 'sum': if 'sum', the raw binned data will be returned; if 'average', the raw binned data will be divided by bin_size^2 then returned. If your data is already in unit of /arcsec^2, please use this option. """ if data_type == 'uncertainty': data = data**2 if len(data.shape) == 3: # a cube result = np.array([bin_data(data[i], bin_size = bin_size, data_type = data_type, bin_method = bin_method) for i in range(data.shape[0])]) return result total_size = np.ceil(data.shape[0] / bin_size) * bin_size half_size = (total_size - 1)/2.0 data_extended = cutImage(data, halfSize=half_size) data_extended[np.isnan(data_extended)] = 0 bin_matrix = np.zeros((int(total_size), int(total_size//bin_size))) for i in range(int(total_size//bin_size)): bin_matrix[bin_size*i:bin_size*(i+1), i] = 1 data_binned = np.dot(bin_matrix.T, np.dot(data_extended, bin_matrix)) if bin_method == 'sum': if data_type == 'uncertainty': return np.sqrt(data_binned) elif data_type == 'mask': raise Exception('Please use `average` for the bin_method option for a mask!') elif bin_method == 'average': if data_type == 'data': data_binned /= bin_size**2 elif data_type == 'uncertainty': data_binned = np.sqrt(data_binned) data_binned/= bin_size**2 #the extra power of 2 is because the raw data is squared for the uncertainty map elif data_type == 'mask': data_binned[np.where(data_binned <= mask_thresh)] = 0 data_binned[np.where(data_binned != 0)] = 1 return data_binned def rotateImage(cube, mask = None, angle = None, reshape = False, new_width = None, new_height = None, thresh = 0.9, maskedNaN = False, outputMask = True, instrument = None): """Rotate an image with 1 mask and 1 angle.""" cube0 = np.copy(cube) cube0[np.where(np.isnan(cube0))] = 0 #1. Prepare the Cube and Mask if reshape: if new_width is None and new_height is None: new_width = int(np.sqrt(np.sum(np.asarray(cube.shape)**2))) new_height = new_width cube = np.zeros((new_height, new_width)) cube += addplanet(cube, planet = cube0, surroundingReplace = np.nan, planetOnly = True) #Replace the surroundings of extended cube with NaN's -- this is used to generate a mask if no mask is provided. if mask is not None: mask0 = np.copy(mask) mask = np.zeros(cube.shape) mask += addplanet(cube, planet = mask0, surroundingReplace = 0, planetOnly = True) mask[np.where(mask < thresh)] = 0 mask[np.where(mask != 0)] = 1 else: mask = np.ones(cube.shape) mask[np.where(np.isnan(cube))] = 0 cube[np.where(np.isnan(cube))] = 0 else: if mask is None: mask = np.ones(cube.shape) mask[np.where(np.isnan(cube))] = 0 cube = cube0 else: mask2 = np.ones(mask.shape) mask2[np.isnan(mask)] = 0 mask2[np.where(mask == 0)] = 0 mask = np.copy(mask2) cube = cube0 #2. Rotate if angle is None: angle = 0 if instrument == "GPI": angle -= 66.5 #IFS rotation result = rotate(cube, angle, reshape = False) rotatedMask = rotate(mask, angle, reshape = False) rotatedMask[np.where(rotatedMask < thresh)] = 0 rotatedMask[np.where(rotatedMask != 0)] = 1 result *= rotatedMask if maskedNaN: result[np.where(rotatedMask == 0)] = np.nan if instrument == "GPI": result = np.fliplr(result) rotatedMask = np.fliplr(rotatedMask) if outputMask: return result, rotatedMask else: return result def rotateCube(cube, mask = None, angle = None, reshape = False, new_width = None, new_height = None, thresh = 0.9, maskedNaN = False, outputMask = True, instrument = None): """Rotation function for a cube. ======= Input: cube (2- or 3-D array): either an image or an image cube mask (2- or 3-D array): either a mask or a mask cube angle (float number or 1-D array): either an angle or an angle array reshape (boolean): change the size? If yes, new_width (integer): new width of the output (can be larger or smaller than before) new_height (integer): new height of the output (can be larger or smaller then before) thresh (float, 0 to 1): if the mask is smaller than 0.9 then it will be regarded as 0 maskedNaN (boolean): put the masked pixels as NaN value? outputMask (boolean): output the rotated mask(s)? Output: first one: results second one: rotatedMasks (only when outputMask == True) ======== Example: results, masks = rotateCube(data, mask= mask, angle=-angles, maskedNaN= True, reshape=True) """ # print("Rotating a cube...") cube0 = np.copy(cube) # cube0[np.where(np.isnan(cube0))] = 0 mask0 = np.copy(mask) if mask is None: mask0 = None angle0 = np.copy(angle) if (angle is None) or (np.asarray(angle).shape == ()): angle = [angle] angle = np.asarray(angle) if len(cube0.shape) == 2: # print("\tJust one input image, look easy.") #single image if len(angle) != 1: # print("\t\tBut with multiple angles, start working...") #multiple angles if (mask is None) or (len(mask.shape) == 2): # print("\t\t\t Just one input mask (or none), duplicating to make a mask cube.") #if single mask, then make multiple masks mask = np.asarray([mask0] * len(angle)) #calculation if outputMask: #need rotated masks # print("\t\t\t\t Rotating...") for i in range(len(angle)): results_temp, rotatedMask_temp = rotateImage(cube, mask = mask[i], angle = angle[i], reshape = reshape, new_width = new_width, new_height = new_height, thresh = thresh, maskedNaN = maskedNaN, outputMask = outputMask, instrument = instrument) if i == 0: results = np.zeros((mask.shape[0], ) + results_temp.shape) rotatedMasks = np.zeros(results.shape) results[i] = results_temp rotatedMasks[i] = rotatedMask_temp # print("\t\t\t\t\t Done. Returning.") return results, rotatedMasks else: #don't need rotated masks # print("\t\t\t\t Rotating...") for i in range(len(angle)): # print(i, cube.shape, mask, angle[i]) results_temp = rotateImage(cube, mask = mask[i], angle = angle[i], reshape = reshape, new_width = new_width, new_height = new_height, thresh = thresh, maskedNaN = maskedNaN, outputMask = outputMask, instrument = instrument) if i == 0: results = np.zeros((mask.shape[0], ) + results_temp.shape) results[i] = results_temp # print("\t\t\t\t\t Done. Returning.") return results else: # print("\t\tAnd just one angle, looks easier..") if (mask is None) or (len(mask.shape) == 2): # print("\t\t\t Yeah and there is only one mask or no mask. Hooray!") if outputMask: pass # print("\t\t\t\t Returning results and rotated masks.") else: pass # print("\t\t\t\t Returning results.") return rotateImage(cube, mask = mask, angle = angle[0], reshape = reshape, new_width = new_width, new_height = new_height, thresh = thresh, maskedNaN = maskedNaN, outputMask = outputMask, instrument = instrument) else: # print("\t\t\t Hmmmmm, several masks, working on that...") if outputMask: for i in range(mask.shape[0]): results_temp, rotatedMask_temp = rotateImage(cube, mask = mask[i], angle = angle[0], reshape = reshape, new_width = new_width, new_height = new_height, thresh = thresh, maskedNaN = maskedNaN, outputMask = outputMask, instrument = instrument) if i == 0: results = np.zeros((mask.shape[0], ) + results_temp.shape) rotatedMasks =
np.zeros(results.shape)
numpy.zeros
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Feb 27 13:31:50 2019 @author: farismismar """ import math from gym import spaces from gym.utils import seeding import numpy as np from numpy import linalg as LA # An attempt to follow # https://github.com/openai/gym/blob/master/gym/envs/classic_control/cartpole.py # Environment parameters # cell radius # UE movement speed # BS max tx power # BS antenna # UE noise figure # Center frequency # Transmit antenna isotropic gain # Antenna heights # Shadow fading margin # Number of ULA antenna elements # Oversampling factor class radio_environment: ''' Observation: Type: Box(6 or 8) Num Observation Min Max 0 User1 server X -r r 1 User1 server Y -r r 2 User2 server X isd-r isd+r 3 User2 server Y -r r 4 Serving BS Power 5 40W 5 Neighbor BS power 5 40W 6 BF codebook index for Serving 0 M-1 7 BF codebook index for Neighbor 0 M-1 ''' def __init__(self, seed): self.M_ULA = 4 self.cell_radius = 150 # in meters. self.inter_site_distance = 3 * self.cell_radius / 2. self.num_users = 30 # number of users. self.gamma_0 = 5 # beamforming constant SINR. self.min_sinr = -3 # in dB self.sinr_target = self.gamma_0 + 10*np.log10(self.M_ULA) # in dB. self.max_tx_power = 40 # in Watts self.max_tx_power_interference = 40 # in Watts self.f_c = 28e9 # Hz self.G_ant_no_beamforming = 11 # dBi self.prob_LOS = 0.8 # Probability of LOS transmission self.num_actions = 16 self.step_count = 0 # which step # Where are the base stations? self.x_bs_1, self.y_bs_1 = 0, 0 self.x_bs_2, self.y_bs_2 = self.inter_site_distance, 0 # for Beamforming self.use_beamforming = True self.k_oversample = 1 # oversampling factor self.Np = 4 # from 3 to 5 for mmWave self.F = np.zeros( [self.M_ULA, self.k_oversample*self.M_ULA], dtype=complex) self.theta_n = math.pi * \ np.arange(start=0., stop=1., step=1. / (self.k_oversample*self.M_ULA)) # Beamforming codebook F for n in np.arange(self.k_oversample*self.M_ULA): f_n = self._compute_bf_vector(self.theta_n[n]) self.F[:, n] = f_n self.f_n_bs1 = None # The index in the codebook for serving BS self.f_n_bs2 = None # The index in the codebook for interfering BS # for Reinforcement Learning self.reward_min = -20 self.reward_max = 100 bounds_lower = np.array([ -self.cell_radius, -self.cell_radius, self.inter_site_distance-self.cell_radius, -self.cell_radius, 1, 1, 0, 0]) bounds_upper = np.array([ self.cell_radius, self.cell_radius, self.inter_site_distance+self.cell_radius, self.cell_radius, self.max_tx_power, self.max_tx_power_interference, self.k_oversample*self.M_ULA - 1, self.k_oversample*self.M_ULA - 1]) self.action_space = spaces.Discrete( self.num_actions) # action size is here # spaces.Discrete(2) # state size is here self.observation_space = spaces.Box( bounds_lower, bounds_upper, dtype=np.float32) self.seed(seed=seed) self.state = None # self.steps_beyond_done = None self.received_sinr_dB = None self.serving_transmit_power_dB = None self.interfering_transmit_power_dB = None def seed(self, seed=None): self.np_random, seed = seeding.np_random(seed) return [seed] def reset(self, seed): # Initialize f_n of both cells self.np_random, seed = seeding.np_random(seed) self.f_n_bs1 = self.np_random.randint(self.M_ULA) self.f_n_bs2 = self.np_random.randint(self.M_ULA) self.state = [self.np_random.uniform(low=-self.cell_radius, high=self.cell_radius), self.np_random.uniform( low=-self.cell_radius, high=self.cell_radius), self.np_random.uniform( low=self.inter_site_distance-self.cell_radius, high=self.inter_site_distance+self.cell_radius), self.np_random.uniform( low=-self.cell_radius, high=self.cell_radius), self.np_random.uniform(low=1, high=self.max_tx_power/2), self.np_random.uniform( low=1, high=self.max_tx_power_interference/2), self.f_n_bs1, self.f_n_bs2 ] self.step_count = 0 return np.array(self.state) def step(self, action): # assert self.action_space.contains(action), # "%r (%s) invalid"%(action, type(action)) state = self.state reward = 0 x_ue_1, y_ue_1, x_ue_2, y_ue_2, \ pt_serving, pt_interferer, f_n_bs1, f_n_bs2 = state # based on the action make your call # only once a period, perform BF # The action is derived from a decimal interpretation ################################################################ # log_2 M (serving) # log_2 M (interferer) # S # O # ################################################################ if (action != -1): # optimal # int('0b0100101',2) power_command_l = action & 0b0001 # 1 power up, 0 power down # 1 power up, 0 power down power_command_b = (action & 0b0010) >> 1 bf_selection_l = (action & 0b0100) >> 2 # 1 step up, 0 step down bf_selection_b = (action & 0b1000) >> 3 self.step_count += 1 if (power_command_l == 0): pt_serving *= 10**(-0.03/10.) else: pt_serving *= 10**(0.03/10.) if (power_command_b == 0): pt_interferer *= 10**(-0.03/10.) else: pt_interferer *= 10**(0.03/10.) if (bf_selection_l == 1): f_n_bs1 = (f_n_bs1 + 1) % self.k_oversample*self.M_ULA else: f_n_bs1 = (f_n_bs1 - 1) % self.k_oversample*self.M_ULA if (bf_selection_b == 1): f_n_bs2 = (f_n_bs2 + 1) % self.k_oversample*self.M_ULA else: f_n_bs2 = (f_n_bs2 - 1) % self.k_oversample*self.M_ULA elif (action > self.num_actions - 1): print('WARNING: Invalid action played!') reward = 0 return [], 0, False, True # move the UEs at a speed of v, in a random direction v = 2 # km/h. v *= 5./18 # in m/sec theta_1, theta_2 = self.np_random.uniform( low=-math.pi, high=math.pi, size=2) dx_1 = v * math.cos(theta_1) dy_1 = v * math.sin(theta_1) dx_2 = v * math.cos(theta_2) dy_2 = v * math.sin(theta_2) # Move UE 1 x_ue_1 += dx_1 y_ue_1 += dy_1 # Move UE 2 x_ue_2 += dx_2 y_ue_2 += dy_2 # Update the beamforming codebook index self.f_n_bs1 = f_n_bs1 self.f_n_bs2 = f_n_bs2 received_power, interference_power, received_sinr = self._compute_rf( x_ue_1, y_ue_1, pt_serving, pt_interferer, is_ue_2=False) received_power_ue2, interference_power_ue2, \ received_ue2_sinr = self._compute_rf( x_ue_2, y_ue_2, pt_serving, pt_interferer, is_ue_2=True) # keep track of quantities... self.received_sinr_dB = received_sinr self.received_ue2_sinr_dB = received_ue2_sinr self.serving_transmit_power_dBm = 10*np.log10(pt_serving*1e3) self.interfering_transmit_power_dBm = 10*np.log10(pt_interferer*1e3) # Did we find a FEASIBLE NON-DEGENERATE solution? done = (pt_serving <= self.max_tx_power) and (pt_serving >= 0) and \ (pt_interferer <= self.max_tx_power_interference) and \ (pt_interferer >= 0) and (received_sinr >= self.min_sinr) and \ (received_ue2_sinr >= self.min_sinr) and \ (received_sinr >= self.sinr_target) and \ (received_ue2_sinr >= self.sinr_target) abort = (pt_serving > self.max_tx_power) or \ (pt_interferer > self.max_tx_power_interference) or \ (received_sinr < self.min_sinr) or \ (received_ue2_sinr < self.min_sinr) or \ (received_sinr > 70) or (received_ue2_sinr > 70) # or (received_sinr < 10) or (received_ue2_sinr < 10) # print('{:.2f} dB | {:.2f} dB | {:.2f} W | {:.2f} W '.format( # received_sinr, received_ue2_sinr, pt_serving, pt_interferer), end='') # print('Done: {}'.format(done)) # print('UE moved to ({0:0.3f},{1:0.3f}) # and their received SINR became {2:0.3f} dB.'.format( # x,y,received_sinr)) # the reward reward = received_sinr + received_ue2_sinr # Update the state. self.state = (x_ue_1, y_ue_1, x_ue_2, y_ue_2, pt_serving, pt_interferer, f_n_bs1, f_n_bs2) if abort is True: done = False reward = self.reward_min elif done: reward += self.reward_max # print(done, (received_sinr >= self.sinr_target) , # (pt_serving <= self.max_tx_power) , (pt_serving >= 0) , \ # (pt_interferer <= self.max_tx_power_interference) , # (pt_interferer >= 0) , (received_ue2_sinr >= self.sinr_target)) if action == -1: # for optimal return np.array(self.state), reward, False, False return np.array(self.state), reward, done, abort def _compute_bf_vector(self, theta): c = 3e8 # speed of light wavelength = c / self.f_c d = wavelength / 2. # antenna spacing k = 2. * math.pi / wavelength exponent = 1j * k * d * math.cos(theta) * np.arange(self.M_ULA) f = 1. / math.sqrt(self.M_ULA) * np.exp(exponent) # Test the norm square... is it equal to unity? YES. # norm_f_sq = LA.norm(f, ord=2) ** 2 # print(norm_f_sq) return f def _compute_channel(self, x_ue, y_ue, x_bs, y_bs): # Np is the number of paths p PLE_L = 2 PLE_N = 4 G_ant = 3 # dBi for beamforming mmWave antennas # Override the antenna gain if no beamforming if self.use_beamforming is False: G_ant = self.G_ant_no_beamforming # theta is the steering angle. Sampled iid from unif(0,pi). theta = np.random.uniform(low=0, high=math.pi, size=self.Np) is_mmWave = (self.f_c > 25e9) if is_mmWave: path_loss_LOS = 10 ** (self._path_loss_mmWave(x_ue, y_ue, PLE_L, x_bs, y_bs) / 10.) path_loss_NLOS = 10 ** (self._path_loss_mmWave(x_ue, y_ue, PLE_N, x_bs, y_bs) / 10.) else: path_loss_LOS = 10 ** (self._path_loss_sub6(x_ue, y_ue, x_bs, y_bs) / 10.) path_loss_NLOS = 10 ** (self._path_loss_sub6(x_ue, y_ue, x_bs, y_bs) / 10.) # Bernoulli for p alpha = np.zeros(self.Np, dtype=complex) p = np.random.binomial(1, self.prob_LOS) if (p == 1): self.Np = 1 alpha[0] = 1. / math.sqrt(path_loss_LOS) else: # just changed alpha to be complex in the case of NLOS alpha = (np.random.normal(size=self.Np) + 1j * np.random.normal(size=self.Np)) \ / math.sqrt(path_loss_NLOS) rho = 1. * 10 ** (G_ant / 10.) # initialize the channel as a complex variable. h = np.zeros(self.M_ULA, dtype=complex) for p in np.arange(self.Np): a_theta = self._compute_bf_vector(theta[p]) # scalar multiplication into a vector h += alpha[p] / rho * a_theta.T h *= math.sqrt(self.M_ULA) # print ('Warning: channel gain is {} dB.'.format( # 10*np.log10(LA.norm(h, ord=2)))) return h def _compute_rf(self, x_ue, y_ue, pt_bs1, pt_bs2, is_ue_2=False): T = 290 # Kelvins B = 15000 # Hz k_Boltzmann = 1.38e-23 noise_power = k_Boltzmann*T*B # this is in Watts if is_ue_2 is False: # Without loss of generality, the base station is at the origin # The interfering base station is x = cell_radius, y = 0 x_bs_1, y_bs_1 = self.x_bs_1, self.y_bs_1 x_bs_2, y_bs_2 = self.x_bs_2, self.y_bs_2 # Now the channel h, which is a vector in beamforming. # This computes the channel for user # in serving BS from the serving BS. h_1 = self._compute_channel(x_ue, y_ue, x_bs=x_bs_1, y_bs=y_bs_1) # This computes the channel for user # in serving BS from the interfering BS. h_2 = self._compute_channel(x_ue, y_ue, x_bs=x_bs_2, y_bs=y_bs_2) # if this is not beamforming, there is no precoder: if (self.use_beamforming): received_power = pt_bs1 * \ abs(np.dot(h_1.conj(), self.F[:, self.f_n_bs1])) ** 2 interference_power = pt_bs2 * \ abs(np.dot(h_2.conj(), self.F[:, self.f_n_bs2])) ** 2 else: # the gain is ||h||^2 received_power = pt_bs1 * LA.norm(h_1, ord=2) ** 2 interference_power = pt_bs2 * LA.norm(h_2, ord=2) ** 2 else: x_bs_1, y_bs_1 = self.x_bs_1, self.y_bs_1 x_bs_2, y_bs_2 = self.x_bs_2, self.y_bs_2 # Now the channel h, which is a vector in beamforming. # This computes the channel for user # in serving BS from the serving BS. h_1 = self._compute_channel(x_ue, y_ue, x_bs=x_bs_2, y_bs=y_bs_2) # This computes the channel for user # in serving BS from the interfering BS. h_2 = self._compute_channel(x_ue, y_ue, x_bs=x_bs_1, y_bs=y_bs_1) # if this is not beamforming, there is no precoder: if (self.use_beamforming): received_power = pt_bs2 * \ abs(np.dot(h_1.conj(), self.F[:, self.f_n_bs2])) ** 2 interference_power = pt_bs1 * \ abs(np.dot(h_2.conj(), self.F[:, self.f_n_bs1])) ** 2 else: # the gain is ||h||^2 received_power = pt_bs2 * LA.norm(h_1, ord=2) ** 2 interference_power = pt_bs1 * LA.norm(h_2, ord=2) ** 2 interference_plus_noise_power = interference_power + noise_power received_sinr = 10 * \ np.log10(received_power / interference_plus_noise_power) return [received_power, interference_power, received_sinr] # https://ieeexplore-ieee-org.ezproxy.lib.utexas.edu/stamp/ # stamp.jsp?tp=&arnumber=7522613 def _path_loss_mmWave(self, x, y, PLE, x_bs=0, y_bs=0): # These are the parameters for f = 28000 MHz. c = 3e8 # speed of light wavelength = c / self.f_c A = 0.0671 Nr = self.M_ULA sigma_sf = 9.1 # PLE = 3.812 d = math.sqrt((x - x_bs)**2 + (y - y_bs)**2) # in meters fspl = 10 * np.log10(((4*math.pi*d) / wavelength) ** 2) pl = fspl + 10 * np.log10(d ** PLE) * (1 - A*
np.log2(Nr)
numpy.log2
import numpy as np import scipy from scipy.linalg import expm from numpy.linalg import matrix_power from scipy.signal import resample from .cov_util import (calc_cov_from_cross_cov_mats, calc_cross_cov_mats_from_cov, calc_cross_cov_mats_from_data, calc_pi_from_cov) def gen_gp_cov(kernel, T, N): """Generates a T*N-by-T*N covariance matrix for a spatiotemporal Gaussian process (2D Gaussian random field) with a provided kernel. Parameters ---------- T : int Number of time-steps. N : int Number of spatial steps. kernel : function Should be of the form kernel = K(t1, t2, x1, x2). The kernel can choose to imlement temporal or spatial stationarity, however this is not enfored. Returns ------- C : np.ndarray, shape (T*N, T*N) Covariance matrix for the Gaussian process. Time is the "outer" variable and space is the "inner" variable. """ t1, t2, x1, x2 = np.arange(T), np.arange(T), np.arange(N), np.arange(N) t1, t2, x1, x2 = np.meshgrid(t1, t2, x1, x2, indexing="ij") C = kernel(t1, t2, x1, x2) C = C.swapaxes(1, 2).reshape(T * N, T * N) return C def calc_pi_for_gp(kernel, T_pi, N): """Calculates the predictive information in a spatiotemporal Gaussian process with a given kernel. Parameters ---------- T : int Length of temporal windows accross which to compute mutual information. N : int Number of spatial steps in teh Gaussian process. kernel : function Should be of the form kernel = K(t1, t2, x1, x2). The kernel can choose to imlement temporal or spatial stationarity, however this is not enfored. Returns ------- PI : float (Temporal) predictive information in the Gaussian process. """ cov_2_T_pi = gen_gp_cov(kernel, 2 * T_pi, N) cov_T_pi = cov_2_T_pi[:T_pi * N, :T_pi * N] sgn_T, logdet_T = np.linalg.slogdet(cov_T_pi) sgn_2T, logdet_2T = np.linalg.slogdet(cov_2_T_pi) PI = logdet_T - 0.5 * logdet_2T return PI def gen_gp_kernel(kernel_type, spatial_scale, temporal_scale, local_noise=0.): """Generates a specified type of Kernel for a spatiotemporal Gaussian process. Parameters ---------- kernel_type : string 'squared_exp' or 'exp' spatial_scale : float Spatial autocorrelation scale. temporal_scale : float Temporal autocorrelation scale. Returns ------- K : function Kernel of the form K(t1, t2, x1, x2). """ def squared_exp(t1, t2, x1, x2): rval = np.exp(-(t1 - t2)**2 / temporal_scale**2 - (x1 - x2)**2 / spatial_scale**2) if local_noise > 0.: local_mask = np.logical_and(np.equal(t1, t2), np.equal(x1, x2)) rval += local_noise * local_mask return rval def exp(t1, t2, x1, x2): rval = np.exp(-np.abs(t1 - t2) / temporal_scale - np.abs(x1 - x2) / spatial_scale) if local_noise > 0.: local_mask = np.logical_and(np.equal(t1, t2), np.equal(x1, x2)) rval += local_noise * local_mask return rval def switch(t1, t2, x1, x2): mask = abs(t1 - t2) >= temporal_scale ex = exp(t1, t2, x1, x2) sq = squared_exp(t1, t2, x1, x2) rval = mask * ex + (1. - mask) * sq if local_noise > 0.: local_mask = np.logical_and(np.equal(t1, t2), np.equal(x1, x2)) rval += local_noise * local_mask return rval if kernel_type == "squared_exp": K = squared_exp elif kernel_type == "exp": K = exp elif kernel_type == "switch": K = switch return K def sample_gp(T, N, kernel, num_to_concat=1): """Draw a sample from a spatiotemporal Gaussian process. Parameters ---------- T : int Length in time of sample. N : int Size in space of sample. kernel : function Kernel of the form K(t1, t2, x1, x2). num_to_concat : int Number of samples of lenght T to concatenate before returning the result. Returns ------- sample : np.ndarray, size (T*num_to_concat, N) Sample from the Gaussian process. """ t1, t2, x1, x2 = np.arange(T), np.arange(T), np.arange(N), np.arange(N) t1, t2, x1, x2 = np.meshgrid(t1, t2, x1, x2, indexing="ij") C = kernel(t1, t2, x1, x2) C = C.swapaxes(1, 2).reshape(T * N, T * N) sample = np.concatenate(np.random.multivariate_normal(mean=np.zeros(C.shape[0]), cov=C, size=num_to_concat)) sample = sample.reshape(T * num_to_concat, N) return sample def embed_gp(T, N, d, kernel, noise_cov, T_pi, num_to_concat=1): """Embed a d-dimensional Gaussian process into N-dimensional space, then add (potentially) spatially structured white noise. Parameters ---------- T : int Length in time. N : int Ambient dimension. d : int Gaussian process dimension. kernel : function Kernel of the form K(t1, t2, x1, x2). noise_cov : np.ndarray, shape (N, N) Covariance matrix from which to sampel Gaussian noise to add to each time point in an iid fashion. num_to_concat : int Number of samples of lenght T to concatenate before returning the result. Returns ------- X : np.ndarray, size (T*num_to_concat, N) Embedding of GP into high-dimensional space, plus noise. """ # Latent dynamics Y = sample_gp(T, d, kernel, num_to_concat) # Random orthogonal embedding matrix U U = scipy.stats.ortho_group.rvs(N)[:, :d] # Data matrix X X =
np.dot(Y, U.T)
numpy.dot
""" Collection of functions used for the stitching. IMPORTANT: The identification of the organization of the fovs in the composite image can be simplified if the (0,0) coords of the stage/camera will be set to the same position for all machine used in the analysis. In our case we started running experiments with the coords not adjusted so the position of (0,0) is different for all the machine that are used to generate the data. """ from typing import * import logging import shutil import copy import itertools import math import pickle import zarr import sys import operator import numpy as np import pandas as pd from matplotlib import pyplot as plt from itertools import groupby from pathlib import Path from sklearn.neighbors import NearestNeighbors import sklearn.linear_model as linmod from skimage.feature import register_translation from skimage import measure from scipy.optimize import minimize from pynndescent import NNDescent from pysmFISH.logger_utils import selected_logger from pysmFISH.fovs_registration import create_fake_image from pysmFISH.data_models import Dataset from pysmFISH import io class organize_square_tiles(): """Class designed to determine the tile organization and identify the coords of the overlapping regions between the tiles. IMPORTANT: The normalize_coords method should be adjusted according to the setup of the microscope. """ def __init__(self, experiment_fpath:str,dataset: pd.DataFrame, metadata:Dict,round_num:int): """Class initialization Args: experiment_fpath (str): Path to the experiment to process dataset (pd.DataFrame): Properties of the images of the experiment metadata (Dict): Metadata describing the experiment round_num (int): Reference acquisition round number """ self.logger = selected_logger() self.experiment_fpath = Path(experiment_fpath) self.dataset = dataset self.metadata = metadata self.round_num = round_num self.experiment_name = self.metadata['experiment_name'] self.stitching_channel = self.metadata['stitching_channel'] self.overlapping_percentage = int(self.metadata['overlapping_percentage']) / 100 self.pixel_size = self.metadata['pixel_microns'] self.img_width = self.metadata['img_width'] self.img_height = self.metadata['img_height'] logging.getLogger('matplotlib.font_manager').disabled = True if self.img_width == self.img_height: self.img_size = self.img_width else: self.logger.error(f'the images to stitch are not square') sys.exit(f'the images to stitch are not square') def extract_microscope_coords(self): """Method to extract images coords in the stage reference system""" selected = self.dataset.loc[self.dataset.round_num == self.round_num, ['round_num','fov_num','fov_acquisition_coords_x','fov_acquisition_coords_y']] selected.drop_duplicates(subset=['fov_num'],inplace=True) selected.sort_values(by='fov_num', ascending=True, inplace=True) self.x_coords = selected.loc[:,'fov_acquisition_coords_x'].to_numpy() self.y_coords = selected.loc[:,'fov_acquisition_coords_y'].to_numpy() def normalize_coords(self): """ Normalize the coords according to how the stage/camera are set. This function must be modified according to the stage/camera setup. ROBOFISH1 has stage with x increasing left-> right and y top->bottom ------> (x) | | V (y) ROBOFISH2 has stage with x increasing right-> left and y top->bottom (x) <------ | | V (y) ROBOFISH3 has stage with x increasing left-> right and y bottom->top ^ (y) | | ------> (x) Axis modifications steps: (1) The reference system will be first converted to image style: ------> (x) | | V (y) This step will cause a change in the position of the reference corner for each fov. After image acquisition the reference corner is top-left however after converting the axis direction to image-style the reference corner will change postion: ROBOFISH1: top-left --> top-left ROBOFISH2: top-left --> top-right ROBOFISH3: top-left --> bottom-left (2) The coords will be translated to (0,0) (3) then to matrix (python) notation ------> (columns) | | V (rows) """ # port the coords to image type coords if self.metadata['machine'] == 'ROBOFISH2': self.x_coords = - self.x_coords self.reference_corner_fov_position = 'top-right' elif self.metadata['machine'] == 'ROBOFISH3': self.x_coords = - self.x_coords self.y_coords = - self.y_coords self.reference_corner_fov_position = 'bottom-left' elif self.metadata['machine'] == 'ROBOFISH1': self.reference_corner_fov_position = 'top-left' elif self.metadata['machine'] == 'NOT_DEFINED': self.logger.error(f'Need to define the specs for stitching NOT_DEFINED machine') sys.exit(f'Need to define the specs for stitching NOT_DEFINED machine') else: self.logger.error(f'define the right machine used to collected the data') sys.exit(f'define the right machine used to collected the data') # shift the coords to reference point (0,0) # consider that we get the top-right corner of the image as well y_min = np.amin(self.y_coords) x_min = np.amin(self.x_coords) x_max = np.amax(self.x_coords) y_max = np.amax(self.y_coords) # Put the coords to zero if x_min >=0 : self.x_coords = self.x_coords - x_min else: self.x_coords = self.x_coords + np.abs(x_min) if y_min>0: self.y_coords = self.y_coords - y_min else: self.y_coords = self.y_coords + np.abs(y_min) # if x_max >=0 : # self.x_coords = self.x_coords - x_min # else: # self.x_coords = self.x_coords + np.abs(x_min) # if y_max>0: # self.y_coords = self.y_coords - y_min # else: # self.y_coords = self.y_coords + np.abs(y_min) # change the coords from x,y to r,c adjusted_coords = np.zeros([self.x_coords.shape[0],2]) adjusted_coords[:,0] = self.y_coords adjusted_coords[:,1] = self.x_coords # move coords to pxl space self.tile_corners_coords_pxl = adjusted_coords / self.pixel_size # def save_graph_original_coords(self): # to correct because I already converted the coords to image # # Turn interactive plotting off # saving_fpath = self.experiment_fpath / 'output_figures' / 'microscope_space_tiles_organization.png' # plt.ioff() # # Create image type axes # labels = [str(nr) for nr in np.arange(self.x_coords.shape[0])] # fig = plt.figure(figsize=(20,10)) # plt.plot(self.x_coords,self.y_coords,'or') # for label, x, y in zip(labels, self.x_coords,self.y_coords): # plt.annotate( # label, # xy=(x,y), xytext=(-2, 2), # textcoords='offset points', ha='center', va='bottom',fontsize=12) # plt.tight_layout() # plt.savefig(saving_fpath) def save_graph_image_space_coords(self): """Method used to save the organization of the tiles """ # Turn interactive plotting off saving_fpath = self.experiment_fpath / 'output_figures' / 'image_space_tiles_organization.png' plt.ioff() # Create image type axes labels = [str(nr) for nr in np.arange(self.tile_corners_coords_pxl.shape[0])] fig = plt.figure(figsize=(20,10)) plt.gca().invert_yaxis() plt.plot(self.tile_corners_coords_pxl[:,1],self.tile_corners_coords_pxl[:,0],'or') for label, x, y in zip(labels, self.tile_corners_coords_pxl[:,1],self.tile_corners_coords_pxl[:,0]): plt.annotate( label, xy=(x,y), xytext=(-2, 2), textcoords='offset points', ha='center', va='bottom',fontsize=12) plt.tight_layout() plt.savefig(saving_fpath) def identify_adjacent_tiles(self): """Method that use Nearest neighbors to identify the beighbouring tiles """ shift_percent_tolerance = 0.05 searching_radius = self.img_size - (self.img_size*self.overlapping_percentage) + (self.img_size*shift_percent_tolerance) nn = NearestNeighbors(n_neighbors=5,radius=searching_radius, metric='euclidean') nn.fit(self.tile_corners_coords_pxl) self.dists, self.indices = nn.kneighbors(self.tile_corners_coords_pxl, return_distance=True) def determine_overlapping_regions(self): """Method used to calculate the coords of the overlapping regions between the tiles. """ # remember that overlapping region can be an empty dictionary self.overlapping_regions = {} self.overlapping_order ={} for idx in np.arange(self.indices.shape[0]): self.overlapping_regions[idx] = {} self.overlapping_order[idx] = {} for idx in np.arange(self.indices.shape[0]): # Determine the indices that identify the correct adjacent processing_indices = self.indices[idx,:] processing_dists = self.dists[idx,:] ref_tile = processing_indices[0] self.overlapping_regions[ref_tile] = {} self.overlapping_order[ref_tile] = {} trimmed_indices = processing_indices[1:] trimmed_dists = processing_dists[1:] idx_adj = np.where(trimmed_dists < self.img_size) adj_tiles_id = trimmed_indices[idx_adj] adj_cpls = [(ref_tile, adj_tile) for adj_tile in adj_tiles_id] # remove pairs that are already selected only_new_cpls = [cpl for cpl in adj_cpls if (cpl[1],cpl[0]) not in self.overlapping_regions[cpl[1]].keys()] # only_new_cpls = [cpl for cpl in adj_cpls] if self.reference_corner_fov_position == 'top-left': for cpl in only_new_cpls: tile1_r_coords = self.tile_corners_coords_pxl[cpl[0]][0] tile2_r_coords = self.tile_corners_coords_pxl[cpl[1]][0] tile1_c_coords = self.tile_corners_coords_pxl[cpl[0]][1] tile2_c_coords = self.tile_corners_coords_pxl[cpl[1]][1] if tile1_r_coords > tile2_r_coords: r_tl = tile1_r_coords r_br = tile2_r_coords + self.img_height row_order = ('bottom','top') else: r_tl = tile2_r_coords r_br = tile1_r_coords + self.img_height row_order = ('top','bottom') if tile1_c_coords > tile2_c_coords: c_tl = tile1_c_coords c_br = tile2_c_coords + self.img_width col_order = ('right','left') else: c_tl = tile2_c_coords c_br = tile1_c_coords + self.img_width col_order = ('left','right') self.overlapping_regions[ref_tile][cpl] = [r_tl, r_br, c_tl, c_br] self.overlapping_order[ref_tile][cpl] = {'row_order':row_order,'column_order':col_order} elif self.reference_corner_fov_position == 'top-right': for cpl in only_new_cpls: tile1_r_coords = self.tile_corners_coords_pxl[cpl[0]][0] tile2_r_coords = self.tile_corners_coords_pxl[cpl[1]][0] tile1_c_coords = self.tile_corners_coords_pxl[cpl[0]][1] tile2_c_coords = self.tile_corners_coords_pxl[cpl[1]][1] if tile1_r_coords > tile2_r_coords: r_tl = tile1_r_coords r_br = tile2_r_coords + self.img_height row_order = ('bottom','top') else: r_tl = tile2_r_coords r_br = tile1_r_coords + self.img_height row_order = ('top','bottom') if tile1_c_coords > tile2_c_coords: c_tl = tile1_c_coords - self.img_width c_br = tile2_c_coords col_order = ('right','left') else: c_tl = tile2_c_coords - self.img_width c_br = tile1_c_coords col_order = ('left','right') self.overlapping_regions[ref_tile][cpl] = [r_tl, r_br, c_tl, c_br] self.overlapping_order[ref_tile][cpl] = {'row_order':row_order,'column_order':col_order} elif self.reference_corner_fov_position == 'bottom-left': for cpl in only_new_cpls: tile1_r_coords = self.tile_corners_coords_pxl[cpl[0]][0] tile2_r_coords = self.tile_corners_coords_pxl[cpl[1]][0] tile1_c_coords = self.tile_corners_coords_pxl[cpl[0]][1] tile2_c_coords = self.tile_corners_coords_pxl[cpl[1]][1] if tile1_r_coords > tile2_r_coords: r_tl = tile1_r_coords - self.img_height r_br = tile2_r_coords row_order = ('bottom','top') else: r_tl = tile2_r_coords - self.img_height r_br = tile1_r_coords row_order = ('top','bottom') if tile1_c_coords > tile2_c_coords: c_tl = tile1_c_coords c_br = tile2_c_coords + self.img_width col_order = ('right','left') else: c_tl = tile2_c_coords c_br = tile1_c_coords + self.img_width col_order = ('left','right') self.overlapping_regions[ref_tile][cpl] = [r_tl, r_br, c_tl, c_br] self.overlapping_order[ref_tile][cpl] = {'row_order':row_order,'column_order':col_order} def run_tiles_organization(self): """Method used to run all the methods """ self.extract_microscope_coords() # self.save_graph_original_coords() self.normalize_coords() self.save_graph_image_space_coords() self.identify_adjacent_tiles() self.determine_overlapping_regions() fname = self.experiment_fpath / 'results' / 'microscope_tile_corners_coords_pxl.npy' np.save(fname,self.tile_corners_coords_pxl) class organize_square_tiles_old_room(): """ Class used to identify the orgabnization of the tiles before the reorganization of the Robofish room of April 2021 when Robofish3 was assembled. """ def __init__(self, experiment_fpath:str,dataset, metadata:Dict,round_num:int): """ round_num = int reference channel """ self.logger = selected_logger() self.experiment_fpath = Path(experiment_fpath) self.dataset = dataset self.metadata = metadata self.round_num = round_num self.experiment_name = self.metadata['experiment_name'] self.stitching_channel = self.metadata['stitching_channel'] self.overlapping_percentage = int(self.metadata['overlapping_percentage']) / 100 self.pixel_size = self.metadata['pixel_microns'] self.img_width = self.metadata['img_width'] self.img_height = self.metadata['img_height'] logging.getLogger('matplotlib.font_manager').disabled = True if self.img_width == self.img_height: self.img_size = self.img_width else: self.logger.error(f'the images to stitch are not square') sys.exit(f'the images to stitch are not square') def extract_microscope_coords(self): selected = self.dataset.loc[self.dataset.round_num == self.round_num, ['round_num','fov_num','fov_acquisition_coords_x','fov_acquisition_coords_y']] selected.drop_duplicates(subset=['fov_num'],inplace=True) selected.sort_values(by='fov_num', ascending=True, inplace=True) self.x_coords = selected.loc[:,'fov_acquisition_coords_x'].to_numpy() self.y_coords = selected.loc[:,'fov_acquisition_coords_y'].to_numpy() def normalize_coords(self): if self.metadata['machine'] == 'ROBOFISH2': # RobofishII has stage with reference point # in the center (0,0) # consider that we get the top-right corner of the image as well self.reference_corner_fov_position = 'old-room-robofish2' # Not sure (i don't remember) # consider that we get the top-right corner of the image as well y_min = np.amin(self.y_coords) x_min = np.amin(self.x_coords) x_max = np.amax(self.x_coords) y_max = np.amax(self.y_coords) # Put the coords to zero if x_max >=0 : self.x_coords = self.x_coords - x_min else: self.x_coords = self.x_coords + np.abs(x_min) if y_max>0: self.y_coords = self.y_coords - y_min else: self.y_coords = self.y_coords + np.abs(y_min) # flip y_axis self.y_coords = self.y_coords - self.y_coords.max() self.y_coords = - self.y_coords # change the coords from x,y to r,c adjusted_coords = np.zeros([self.x_coords.shape[0],2]) adjusted_coords[:,0] = self.y_coords adjusted_coords[:,1] = self.x_coords elif self.metadata['machine'] == 'ROBOFISH1': # The current system has stage ref coords top-left self.reference_corner_fov_position = 'top-left' # Normalize to (0,0) still BOTTOM-RIGHT y_min = np.amin(self.y_coords) x_min = np.amin(self.x_coords) self.x_coords = self.x_coords - x_min self.y_coords = self.y_coords - y_min # flip axis to move (0,0) on TOP-LEF self.x_coords = self.x_coords - self.x_coords.max() self.x_coords = - self.x_coords self.y_coords = self.y_coords - self.y_coords.max() self.y_coords = - self.y_coords # change the coords from x,y to r,c adjusted_coords = np.zeros([self.x_coords.shape[0],2]) adjusted_coords[:,0] = self.y_coords adjusted_coords[:,1] = self.x_coords elif self.metadata['machine'] == 'NOT_DEFINED': self.logger.error(f'Need to define the specs for stitching NOT_DEFINED machine') sys.exit(f'Need to define the specs for stitching NOT_DEFINED machine') else: self.logger.error(f'define the right machine used to collected the data') sys.exit(f'define the right machine used to collected the data') self.tile_corners_coords_pxl = adjusted_coords / self.pixel_size def save_graph_original_coords(self): # Turn interactive plotting off saving_fpath = self.experiment_fpath / 'output_figures' / 'microscope_space_tiles_organization.png' plt.ioff() # Create image type axes labels = [str(nr) for nr in
np.arange(self.x_coords.shape[0])
numpy.arange
import numpy as np from gym.envs.mujoco import mujoco_env from meta_mb.meta_envs.base import RandomEnv from gym import utils import os import pickle class BlueEnv(RandomEnv, utils.EzPickle): def __init__(self, arm='right', log_rand=0, actions=None): utils.EzPickle.__init__(**locals()) assert arm in ['left', 'right'] xml_file = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'assets', 'blue_' + arm + '_v2.xml') self.actions = {} self.goal = np.zeros((3,)) self._arm = arm self.iters = 0 if actions is not None: self.actions = actions self.path_len = 0 self.max_path_len = len(actions) max_torques = np.array([5, 5, 4, 4, 3, 2, 2]) self._low = -max_torques self._high = max_torques RandomEnv.__init__(self, log_rand, xml_file, 20) def _get_obs(self): return np.concatenate([ self.sim.data.qpos.flat, self.sim.data.qvel.flat[:-3], self.get_body_com("right_gripper_link"), self.ee_position - self.goal ]) def step(self, act): if self.iters==0: action =
np.array([0.52, -3.2, 1.2, -3.5])
numpy.array
# Copyright 2017 Battelle Energy Alliance, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # 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. """ Created on Dec. 20, 2018 @author: wangc module for Convolutional neural network (CNN) """ #for future compatibility with Python 3-------------------------------------------------------------- from __future__ import division, print_function, unicode_literals, absolute_import #End compatibility block for Python 3---------------------------------------------------------------- #External Modules------------------------------------------------------------------------------------ import numpy as np ###### #Internal Modules------------------------------------------------------------------------------------ from .KerasClassifier import KerasClassifier #Internal Modules End-------------------------------------------------------------------------------- class KerasConvNetClassifier(KerasClassifier): """ Convolutional neural network (CNN) classifier constructed using Keras API in TensorFlow """ def __init__(self, **kwargs): """ A constructor that will appropriately intialize a supervised learning object @ In, kwargs, dict, an arbitrary dictionary of keywords and values @ Out, None """ super().__init__(**kwargs) self.printTag = 'KerasConvNetClassifier' self.allowedLayers = self.basicLayers + self.kerasROMDict['kerasConvNetLayersList'] + self.kerasROMDict['kerasPoolingLayersList'] def _preprocessInputs(self,featureVals): """ Perform input feature values before sending to ROM prediction @ In, featureVals, numpy.array, i.e. [shapeFeatureValue,numFeatures], values of features @ Out, featureVals, numpy.array, predicted values """ shape = featureVals.shape if len(shape) == 2: featureVals =
np.reshape(featureVals,(1, shape[0], shape[1]))
numpy.reshape
import anndata import multiprocessing as mp import numpy as np import os import pandas as pd import pytest import rpy2.robjects.packages import rpy2.robjects.pandas2ri import scipy.sparse as ss import scipy.stats as st import scmodes import scmodes.benchmark.gof from .fixtures import test_data ashr = rpy2.robjects.packages.importr('ashr') rpy2.robjects.pandas2ri.activate() def test__gof(): np.random.seed(0) mu = 10 px = st.poisson(mu=mu) x = px.rvs(size=100) d, p = scmodes.benchmark.gof._gof(x, cdf=px.cdf, pmf=px.pmf) assert d >= 0 assert 0 <= p <= 1 def test__rpp(): np.random.seed(0) mu = 10 px = st.poisson(mu=mu) x = px.rvs(size=100) F = px.cdf(x - 1) f = px.pmf(x) vals = scmodes.benchmark.gof._rpp(F, f) assert vals.shape == x.shape def test_gof_point(test_data): x = test_data res = scmodes.benchmark.gof_point(x) assert res.shape[0] == x.shape[1] assert np.isfinite(res['stat']).all() assert np.isfinite(res['p']).all() def test_gamma_cdf(): np.random.seed(0) x = st.nbinom(n=10, p=.1).rvs(size=100) Fx = scmodes.benchmark.gof._zig_cdf(x, size=1, log_mu=-5, log_phi=-1) assert Fx.shape == x.shape assert np.isfinite(Fx).all() assert (Fx >= 0).all() assert (Fx <= 1).all() def test_zig_cdf(): np.random.seed(0) x = st.nbinom(n=10, p=.1).rvs(size=100) Fx = scmodes.benchmark.gof._zig_cdf(x, size=1, log_mu=-5, log_phi=-1, logodds=-3) assert Fx.shape == x.shape assert (Fx >= 0).all() assert (Fx <= 1).all() def test_zig_pmf_cdf(): x = np.arange(50) import scmodes.benchmark.gof size = 1000 log_mu=-5 log_phi=-1 logodds=-1 Fx = scmodes.benchmark.gof._zig_cdf(x, size=size, log_mu=log_mu, log_phi=log_phi, logodds=logodds) Fx_1 = scmodes.benchmark.gof._zig_cdf(x - 1, size=size, log_mu=log_mu, log_phi=log_phi, logodds=logodds) fx = scmodes.benchmark.gof._zig_pmf(x, size=size, log_mu=log_mu, log_phi=log_phi, logodds=logodds) assert
np.isclose(Fx - Fx_1, fx)
numpy.isclose
''' Functions to generate the set of endpoints for the time series benchmark on the HiRID database''' import glob import logging import math import os import os.path import pickle import random import sys import lightgbm as lgbm import numpy as np import pandas as pd import skfda.preprocessing.smoothing.kernel_smoothers as skks import skfda.representation.grid as skgrid import sklearn.linear_model as sklm import sklearn.metrics as skmetrics import sklearn.preprocessing as skpproc def load_pickle(fpath): ''' Given a file path pointing to a pickle file, yields the object pickled in this file''' with open(fpath,'rb') as fp: return pickle.load(fp) SUPPOX_TO_FIO2={ 0: 21, 1: 26, 2: 34, 3: 39, 4: 45, 5: 49, 6: 54, 7: 57, 8: 58, 9: 63, 10: 66, 11: 67, 12: 69, 13: 70, 14: 73, 15: 75 } def mix_real_est_pao2(pao2_col, pao2_meas_cnt, pao2_est_arr, bandwidth=None): ''' Mix real PaO2 measurement and PaO2 estimates using a Gaussian kernel''' final_pao2_arr=np.copy(pao2_est_arr) sq_scale=57**2 # 1 hour has mass 1/3 approximately for idx in range(final_pao2_arr.size): meas_ref=pao2_meas_cnt[idx] real_val=None real_val_dist=None # Search forward and backward with priority giving to backward if equi-distant for sidx in range(48): if not idx-sidx<0 and pao2_meas_cnt[idx-sidx]<meas_ref: real_val=pao2_col[idx-sidx+1] real_val_dist=5*sidx break elif not idx+sidx>=final_pao2_arr.size and pao2_meas_cnt[idx+sidx]>meas_ref: real_val=pao2_col[idx+sidx] real_val_dist=5*sidx break if real_val is not None: alpha_mj=math.exp(-real_val_dist**2/sq_scale) alpha_ej=1-alpha_mj final_pao2_arr[idx]=alpha_mj*real_val+alpha_ej*pao2_est_arr[idx] return final_pao2_arr def perf_regression_model(X_list, y_list, aux_list, configs=None): ''' Initial test of a regression model to estimate the current Pao2 based on 6 features of the past. Also pass FiO2 to calculate resulting mistakes in the P/F ratio''' logging.info("Testing regression model for PaO2...") # Partition the data into 3 sets and run SGD regressor X_train=X_list[:int(0.6*len(X_list))] X_train=np.vstack(X_train) y_train=np.concatenate(y_list[:int(0.6*len(y_list))]) X_val=X_list[int(0.6*len(X_list)):int(0.8*len(X_list))] X_val=np.vstack(X_val) y_val=np.concatenate(y_list[int(0.6*len(y_list)):int(0.8*len(y_list))]) X_test=X_list[int(0.8*len(X_list)):] X_test=np.vstack(X_test) y_test=np.concatenate(y_list[int(0.8*len(y_list)):]) fio2_test=np.concatenate(aux_list[int(0.8*len(aux_list)):]) if configs["sur_model_type"]=="linear": scaler=skpproc.StandardScaler() X_train_std=scaler.fit_transform(X_train) X_val_std=scaler.transform(X_val) X_test_std=scaler.transform(X_test) if configs["sur_model_type"]=="linear": alpha_cands=[0.0001,0.001,0.01,0.1,1.0] elif configs["sur_model_type"]=="lgbm": alpha_cands=[32] best_alpha=None best_score=np.inf # Search for the best model on the validation set for alpha in alpha_cands: logging.info("Testing alpha: {}".format(alpha)) if configs["sur_model_type"]=="linear": lmodel_cand=sklm.SGDRegressor(alpha=alpha, random_state=2021) elif configs["sur_model_type"]=="lgbm": lmodel_cand=lgbm.LGBMRegressor(num_leaves=alpha, learning_rate=0.05, n_estimators=1000, random_state=2021) if configs["sur_model_type"]=="linear": lmodel_cand.fit(X_train_std,y_train) elif configs["sur_model_type"]=="lgbm": lmodel_cand.fit(X_train_std,y_train, eval_set=(X_val_std,y_val), early_stopping_rounds=20, eval_metric="mae") pred_y_val=lmodel_cand.predict(X_val_std) mae_val=np.median(np.absolute(y_val-pred_y_val)) if mae_val<best_score: best_score=mae_val best_alpha=alpha lmodel=sklm.SGDRegressor(alpha=best_alpha,random_state=2021) lmodel.fit(X_train_std,y_train) pred_y_test=lmodel.predict(X_test_std) pred_pf_ratio_test=pred_y_test/fio2_test true_pf_ratio_test=y_test/fio2_test mae_test=skmetrics.mean_absolute_error(y_test, pred_y_test) logging.info("Mean absolute error in test set: {:.3f}".format(mae_test)) def percentile_smooth(signal_col, percentile, win_scope_mins): ''' Window percentile smoother, where percentile is in the interval [0,100]''' out_arr=np.zeros_like(signal_col) mins_per_window=5 search_range=int(win_scope_mins/mins_per_window/2) for jdx in range(out_arr.size): search_arr=signal_col[max(0,jdx-search_range):min(out_arr.size,jdx+search_range)] out_arr[jdx]=np.percentile(search_arr,percentile) return out_arr def subsample_blocked(val_arr, meas_arr=None, ss_ratio=None, block_length=None, normal_value=None): ''' Subsample blocked with ratio and block length''' val_arr_out=np.copy(val_arr) meas_arr_out=np.copy(meas_arr) meas_idxs=[] n_meas=0 for idx in range(meas_arr.size): if meas_arr[idx]>n_meas: meas_idxs.append(idx) n_meas+=1 if len(meas_idxs)==0: return (val_arr_out, meas_arr_out) meas_select=int((1-ss_ratio)*len(meas_idxs)) begin_select=meas_select//block_length feas_begins=[meas_idxs[idx] for idx in np.arange(0,len(meas_idxs),block_length)] sel_meas_begins=sorted(random.sample(feas_begins, begin_select)) sel_meas_delete=[] for begin in sel_meas_begins: for add_idx in range(block_length): sel_meas_delete.append(begin+add_idx) # Rewrite the measuremnent array with deleted indices for midx,meas_idx in enumerate(meas_idxs): prev_cnt=0 if meas_idx==0 else meas_arr_out[meas_idx-1] revised_cnt=prev_cnt if meas_idx in sel_meas_delete else prev_cnt+1 if midx<len(meas_idxs)-1: for rewrite_idx in range(meas_idx,meas_idxs[midx+1]): meas_arr_out[rewrite_idx]=revised_cnt else: for rewrite_idx in range(meas_idx,len(meas_arr_out)): meas_arr_out[rewrite_idx]=revised_cnt # Rewrite the value array with deleted indices, with assuming forward filling for midx,meas_idx in enumerate(meas_idxs): prev_val=normal_value if meas_idx==0 else val_arr_out[meas_idx-1] cur_val=val_arr_out[meas_idx] revised_value=prev_val if meas_idx in sel_meas_delete else cur_val if midx<len(meas_idxs)-1: for rewrite_idx in range(meas_idx,meas_idxs[midx+1]): val_arr_out[rewrite_idx]=revised_value else: for rewrite_idx in range(meas_idx,len(meas_arr_out)): val_arr_out[rewrite_idx]=revised_value return (val_arr_out, meas_arr_out) def subsample_individual(val_arr, meas_arr=None, ss_ratio=None, normal_value=None): ''' Subsample individual measurements completely randomly with random choice''' val_arr_out=np.copy(val_arr) meas_arr_out=np.copy(meas_arr) meas_idxs=[] n_meas=0 for idx in range(meas_arr.size): if meas_arr[idx]>n_meas: meas_idxs.append(idx) n_meas+=1 if len(meas_idxs)==0: return (val_arr_out, meas_arr_out) meas_select=int((1-ss_ratio)*len(meas_idxs)) sel_meas_delete=sorted(random.sample(meas_idxs, meas_select)) # Rewrite the measuremnent array with deleted indices for midx,meas_idx in enumerate(meas_idxs): prev_cnt=0 if meas_idx==0 else meas_arr_out[meas_idx-1] revised_cnt=prev_cnt if meas_idx in sel_meas_delete else prev_cnt+1 if midx<len(meas_idxs)-1: for rewrite_idx in range(meas_idx,meas_idxs[midx+1]): meas_arr_out[rewrite_idx]=revised_cnt else: for rewrite_idx in range(meas_idx,len(meas_arr_out)): meas_arr_out[rewrite_idx]=revised_cnt # Rewrite the value array with deleted indices, with assuming forward filling for midx,meas_idx in enumerate(meas_idxs): prev_val=normal_value if meas_idx==0 else val_arr_out[meas_idx-1] cur_val=val_arr_out[meas_idx] revised_value=prev_val if meas_idx in sel_meas_delete else cur_val if midx<len(meas_idxs)-1: for rewrite_idx in range(meas_idx,meas_idxs[midx+1]): val_arr_out[rewrite_idx]=revised_value else: for rewrite_idx in range(meas_idx,len(meas_arr_out)): val_arr_out[rewrite_idx]=revised_value return (val_arr_out, meas_arr_out) def merge_short_vent_gaps(vent_status_arr, short_gap_hours): ''' Merge short gaps in the ventilation status array''' in_gap=False gap_length=0 before_gap_status=np.nan for idx in range(len(vent_status_arr)): cur_state=vent_status_arr[idx] if in_gap and (cur_state==0.0 or np.isnan(cur_state)): gap_length+=5 elif not in_gap and (cur_state==0.0 or np.isnan(cur_state)): if idx>0: before_gap_status=vent_status_arr[idx-1] in_gap=True in_gap_idx=idx gap_length=5 elif in_gap and cur_state==1.0: in_gap=False after_gap_status=cur_state if gap_length/60.<=short_gap_hours: vent_status_arr[in_gap_idx:idx]=1.0 return vent_status_arr def kernel_smooth_arr(input_arr, bandwidth=None): ''' Kernel smooth an input array with a Nadaraya-Watson kernel smoother''' output_arr=np.copy(input_arr) fin_arr=output_arr[np.isfinite(output_arr)] time_axis=5*np.arange(len(output_arr)) fin_time=time_axis[np.isfinite(output_arr)] # Return the unsmoothed array if fewer than 2 observations if fin_arr.size<2: return output_arr smoother=skks.NadarayaWatsonSmoother(smoothing_parameter=bandwidth) fgrid=skgrid.FDataGrid([fin_arr], fin_time) fd_smoothed=smoother.fit_transform(fgrid) output_smoothed=fd_smoothed.data_matrix.flatten() output_arr[np.isfinite(output_arr)]=output_smoothed return output_arr def delete_short_vent_events(vent_status_arr, short_event_hours): ''' Delete short events in the ventilation status array''' in_event=False event_length=0 for idx in range(len(vent_status_arr)): cur_state=vent_status_arr[idx] if in_event and cur_state==1.0: event_length+=5 if not in_event and cur_state==1.0: in_event=True event_length=5 event_start_idx=idx if in_event and (cur_state==0.0 or np.isnan(cur_state)): in_event=False if event_length/60.<short_event_hours: vent_status_arr[event_start_idx:idx]=0.0 return vent_status_arr def ellis(x_orig): ''' ELLIS model converting SpO2 in 100 % units into a PaO2 ABGA estimate''' x_orig[np.isnan(x_orig)]=98 # Normal value assumption x=x_orig/100 x[x==1]=0.999 exp_base = (11700/((1/x)-1)) exp_sqrbracket = np.sqrt(pow(50,3)+(exp_base**2)) exp_first = np.cbrt(exp_base + exp_sqrbracket) exp_second = np.cbrt(exp_base - exp_sqrbracket) exp_full = exp_first + exp_second return exp_full def correct_left_edge_vent(vent_status_arr, etco2_meas_cnt, etco2_col): ''' Corrects the left edge of the ventilation status array, to pin-point the exact conditions''' on_left_edge=False in_event=False # Correct left ventilation edges of the ventilation zone for idx in range(len(vent_status_arr)): if vent_status_arr[idx]==1.0 and not in_event: in_event=True on_left_edge=True if on_left_edge and in_event: if vent_status_arr[idx]==0.0: in_event=False on_left_edge=False elif (idx==0 and etco2_meas_cnt[idx]>0 or etco2_meas_cnt[idx]-etco2_meas_cnt[idx-1]>=1) and etco2_col[idx]>0.5: on_left_edge=False else: vent_status_arr[idx]=0.0 return vent_status_arr def delete_small_continuous_blocks(event_arr,block_threshold=None): ''' Given an event array, deletes small contiguous blocks that are sandwiched between two other blocks, one of which is longer, they both have the same label. For the moment we delete blocks smaller than 30 minutes. Note this requires only a linear pass over the array''' block_list=[] active_block=None # Build a block list for jdx in range(event_arr.size): new_block=event_arr[jdx] # Start a new block at the beginning if active_block is None: active_block=new_block left_block_idx=jdx # Change to a new block elif not active_block==new_block: block_list.append((active_block,left_block_idx,jdx-1)) left_block_idx=jdx active_block=new_block # Same last block unconditionally if jdx==event_arr.size-1: block_list.append((new_block,left_block_idx,jdx)) # Merge blocks while True: all_clean=True for bidx, block in enumerate(block_list): block_label,lidx,ridx=block block_len=ridx-lidx+1 # Candidate for merging if block_len<=block_threshold: if len(block_list)==1: all_clean=True break # Only right block elif bidx==0: next_block=block_list[bidx+1] nb_label,nb_lidx,nb_ridx=next_block nb_len=nb_ridx-nb_lidx+1 # Merge blocks if nb_len>block_len and nb_len>block_threshold: block_list[bidx]=(nb_label,lidx,nb_ridx) block_list.remove(next_block) all_clean=False break # Only left block elif bidx==len(block_list)-1: prev_block=block_list[bidx-1] pb_label,pb_lidx,pb_ridx=prev_block pb_len=pb_ridx-pb_lidx+1 if pb_len>block_len and pb_len>block_threshold: block_list[bidx]=(pb_label,pb_lidx,ridx) block_list.remove(prev_block) all_clean=False break # Interior block else: prev_block=block_list[bidx-1] next_block=block_list[bidx+1] pb_label,pb_lidx,pb_ridx=prev_block nb_label,nb_lidx,nb_ridx=next_block pb_len=pb_ridx-pb_lidx+1 nb_len=nb_ridx-nb_lidx+1 if pb_label==nb_label and (pb_len>block_threshold or nb_len>block_threshold): block_list[bidx]=(pb_label,pb_lidx,nb_ridx) block_list.remove(prev_block) block_list.remove(next_block) all_clean=False break # Traversed block list with no actions required if all_clean: break # Now back-translate the block list to the list out_arr=np.copy(event_arr) for blabel,lidx,ridx in block_list: out_arr[lidx:ridx+1]=blabel # Additionally build an array where the two arrays are different diff_arr=(out_arr!=event_arr).astype(np.bool) return (out_arr,diff_arr) def collect_regression_data(spo2_col, spo2_meas_cnt, pao2_col, pao2_meas_cnt, fio2_est_arr, sao2_col, sao2_meas_cnt, ph_col, ph_meas_cnt ): ''' Collect regression data at time-stamps where we have a real PaO2 measurement, return partial training X,y pairs for this patient''' X_arr_collect=[] y_arr_collect=[] aux_collect=[] cur_pao2_cnt=0 cur_spo2_cnt=0 cur_sao2_cnt=0 cur_ph_cnt=0 pao2_real_meas=[] spo2_real_meas=[] sao2_real_meas=[] ph_real_meas=[] for jdx in range(spo2_col.size): if spo2_meas_cnt[jdx]>cur_spo2_cnt: spo2_real_meas.append(jdx) cur_spo2_cnt=spo2_meas_cnt[jdx] if sao2_meas_cnt[jdx]>cur_sao2_cnt: sao2_real_meas.append(jdx) cur_sao2_cnt=sao2_meas_cnt[jdx] if ph_meas_cnt[jdx]>cur_ph_cnt: ph_real_meas.append(jdx) cur_ph_cnt=ph_meas_cnt[jdx] if pao2_meas_cnt[jdx]>cur_pao2_cnt: pao2_real_meas.append(jdx) cur_pao2_cnt=pao2_meas_cnt[jdx] # Only start fitting the model from the 2nd measurement onwards if len(pao2_real_meas)>=2 and len(spo2_real_meas)>=2 and len(sao2_real_meas)>=2 and len(ph_real_meas)>=2: # Dimensions of features # 0: Last real SpO2 measurement # 1: Last real PaO2 measurement # 2: Last real SaO2 measurement # 3: Last real pH measurement # 4: Time to last real SpO2 measurement # 5: Time to last real PaO2 measurement # 6: Closest SpO2 to last real PaO2 measurement x_vect=np.array([spo2_col[jdx-1], pao2_col[jdx-1], sao2_col[jdx-1], ph_col[jdx-1], jdx-spo2_real_meas[-2], jdx-pao2_real_meas[-2],spo2_col[pao2_real_meas[-2]]]) y_val=pao2_col[jdx] aux_val=fio2_est_arr[jdx] if np.isnan(x_vect).sum()==0 and np.isfinite(y_val) and np.isfinite(aux_val): X_arr_collect.append(x_vect) y_arr_collect.append(y_val) aux_collect.append(aux_val) if len(X_arr_collect)>0: X_arr=np.vstack(X_arr_collect) y_arr=np.array(y_arr_collect) aux_arr=np.array(aux_collect) assert(
np.isnan(X_arr)
numpy.isnan
#! /usr/bin/env python3 import numpy as np import argparse from scipy.sparse.linalg import svds from sklearn.metrics import adjusted_rand_score as ari from scipy.sparse import coo_matrix import dcsbm ## Parser to give parameter values parser = argparse.ArgumentParser() parser.add_argument("-M", type=int, dest="M", default=25, const=True, nargs="?",\ help="Integer: number of simulations, default M.") parser.add_argument("-s", type=int, dest="s", default=171171, const=True, nargs="?",\ help="Integer: seed, default 171171.") ## Parse arguments args = parser.parse_args() ############################################################# ## Reproduces results in Section 6.1 for bipartite DCScBMs ## ############################################################# ## Arguments ns = [100, 200, 500, 1000, 2000] ns_prime = [150, 300, 750, 1500, 3000] M_sim = args.M K = 2 K_prime = 3 m = 10 ## Set maximum number of nodes n = int(np.max(ns)) n_max = int(
np.max(ns)
numpy.max
""" Helpers for dealing with RGB(A) images. """ import numpy as np import dask.array as da import xarray as xr import dask from typing import Tuple, Optional, List, Union from ._dask import randomize def is_rgb(x: xr.DataArray): if x.dtype != 'uint8': return False if x.ndim < 3: return False if x.shape[-1] not in (3, 4): return False return True def guess_rgb_names(bands: List[str]) -> Tuple[str, str, str]: out = [] for c in ('red', 'green', 'blue'): candidates = [name for name in bands if c in name] n = len(candidates) if n == 0: raise ValueError('Found no candidate for color "{}"'.format(c)) elif n > 1: raise ValueError('Found too many candidates for color "{}"'.format(c)) out.append(candidates[0]) r, g, b = out return (r, g, b) def auto_guess_clamp(ds: xr.Dataset): # TODO: deal with nodata > 0 case return (0, max(x.data.max() for x in ds.data_vars.values())) def to_u8(x: np.ndarray, x_min: float, x_max: float) -> np.ndarray: x =
np.clip(x, x_min, x_max)
numpy.clip
import time import numpy as np import copy import matplotlib.pyplot as plt import scipy.stats import sklearn.metrics import sklearn.utils.validation def accuracy(y, p_pred): """ Computes the accuracy. Parameters ---------- y : array-like Ground truth labels. p_pred : array-like Array of confidence estimates. Returns ------- accuracy : float """ return sklearn.metrics.accuracy_score(y_true=y, y_pred=np.argmax(p_pred, axis=1)) def error(y, p_pred): """ Computes the classification error. Parameters ---------- y : array-like Ground truth labels. p_pred : array-like Array of confidence estimates. Returns ------- error : float """ return 1 - accuracy(y=y, p_pred=p_pred) def odds_correctness(y, p_pred): """ Computes the odds of making a correct prediction. Parameters ---------- y : array-like Ground truth labels. p_pred : array-like Array of confidence estimates. Returns ------- odds : float """ return accuracy(y=y, p_pred=p_pred) / error(y=y, p_pred=p_pred) def expected_calibration_error(y, p_pred, n_bins=100, n_classes=None, p=1): """ Computes the expected calibration error ECE_p. Computes the empirical p-expected calibration error for a vector of confidence estimates by binning. Parameters ---------- y : array-like Ground truth labels. p_pred : array-like Array of confidence estimates. n_bins : int, default=15 Number of bins of :math:`[\\frac{1}{n_{\\text{classes}},1]` for the confidence estimates. n_classes : int default=None Number of classes. Estimated from `y` and `y_pred` if not given. p : int, default=1 Power of the calibration error, :math:`1 \\leq p \\leq \\infty`. Returns ------- float Expected calibration error """ # Check input y = sklearn.utils.validation.column_or_1d(y) y_pred = np.argmax(p_pred, axis=1) y_pred = sklearn.utils.validation.column_or_1d(y_pred) if n_classes is None: n_classes = np.unique(np.concatenate([y, y_pred])).shape[0] # Compute bin means bin_range = [1 / n_classes, 1] bins = np.linspace(bin_range[0], bin_range[1], n_bins + 1) # Find prediction confidence p_max = np.max(p_pred, axis=1) # Compute empirical accuracy empirical_acc = scipy.stats.binned_statistic(p_max, (y_pred == y).astype(int), bins=n_bins, range=bin_range)[0] nanindices = np.where(np.logical_not(np.isnan(empirical_acc)))[0] # Perfect calibration calibrated_acc = np.linspace(bin_range[0] + bin_range[1] / (2 * n_bins), bin_range[1] - bin_range[1] / (2 * n_bins), n_bins) # Expected calibration error weights_ece = np.histogram(p_max, bins)[0][nanindices] if p < np.inf: ece = np.average(abs(empirical_acc[nanindices] - calibrated_acc[nanindices]) ** p, weights=weights_ece) elif np.isinf(p): ece = np.max(abs(empirical_acc[nanindices] - calibrated_acc[nanindices])) return ece def sharpness(y, p_pred, ddof=1): """ Computes the empirical sharpness of a classifier. Computes the empirical sharpness of a classifier by computing the sample variance of a vector of confidence estimates. Parameters ---------- y : array-like Ground truth labels. Dummy argument for consistent cross validation. p_pred : array-like Array of confidence estimates ddof : int, optional, default=1 Degrees of freedom for the variance estimator. Returns ------- float Sharpness """ # Number of classes n_classes = np.shape(p_pred)[1] # Find prediction confidence p_max = np.max(p_pred, axis=1) # Compute sharpness sharp =
np.var(p_max, ddof=ddof)
numpy.var
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core, workspace from hypothesis import given import caffe2.python.hypothesis_test_util as hu import hypothesis.strategies as st import numpy as np import random class TestUtilityOps(hu.HypothesisTestCase): @given(X=hu.tensor(), args=st.booleans(), **hu.gcs) def test_slice(self, X, args, gc, dc): X = X.astype(dtype=np.float32) dim = random.randint(0, X.ndim - 1) slice_start = random.randint(0, X.shape[dim] - 1) slice_end = random.randint(slice_start, X.shape[dim] - 1) starts = np.array([0] * X.ndim).astype(np.int32) ends = np.array([-1] * X.ndim).astype(np.int32) starts[dim] = slice_start ends[dim] = slice_end if args: op = core.CreateOperator( "Slice", ["X"], ["Y"], starts=starts, ends=ends, device_option=gc ) def slice_ref(X): slc = [slice(None)] * X.ndim slc[dim] = slice(slice_start, slice_end) return [X[slc]] inputs = [X] else: op = core.CreateOperator( "Slice", ["X", "starts", "ends"], ["Y"], device_option=gc ) def slice_ref(x, starts, ends): slc = [slice(None)] * x.ndim slc[dim] = slice(slice_start, slice_end) return [x[slc]] inputs = [X, starts, ends] self.assertReferenceChecks(gc, op, inputs, slice_ref) self.assertDeviceChecks(dc, op, inputs, [0]) self.assertGradientChecks( device_option=gc, op=op, inputs=inputs, outputs_to_check=0, outputs_with_grads=[0], ) @given(dtype=st.sampled_from([np.float32, np.int32, np.int64]), ndims=st.integers(min_value=1, max_value=5), seed=st.integers(min_value=0, max_value=65536), null_axes=st.booleans(), engine=st.sampled_from(['CUDNN', None]), **hu.gcs) def test_transpose(self, dtype, ndims, seed, null_axes, engine, gc, dc): dims = (np.random.rand(ndims) * 16 + 1).astype(np.int32) X = (np.random.rand(*dims) * 16).astype(dtype) if null_axes: axes = None op = core.CreateOperator( "Transpose", ["input"], ["output"], engine=engine) else: np.random.seed(int(seed)) axes = [int(v) for v in list(np.random.permutation(X.ndim))] op = core.CreateOperator( "Transpose", ["input"], ["output"], axes=axes, engine=engine) def transpose_ref(x, axes): return (np.transpose(x, axes),) self.assertReferenceChecks(gc, op, [X, axes], transpose_ref) @given(m=st.integers(5, 10), n=st.integers(5, 10), o=st.integers(5, 10), nans=st.booleans(), **hu.gcs) def test_nan_check(self, m, n, o, nans, gc, dc): other = np.array([1, 2, 3]).astype(np.float32) X = np.random.rand(m, n, o).astype(np.float32) if nans: x_nan = np.random.randint(0, m) y_nan = np.random.randint(0, n) z_nan = np.random.randint(0, o) X[x_nan, y_nan, z_nan] = float('NaN') # print('nans: {}'.format(nans)) # print(X) def nan_reference(X, Y): if not np.isnan(X).any(): return [X] else: return [np.array([])] op = core.CreateOperator( "NanCheck", ["X", "other"], ["Y"] ) try: self.assertReferenceChecks( device_option=gc, op=op, inputs=[X, other], reference=nan_reference, ) if nans: self.assertTrue(False, "Did not fail when presented with NaN!") except RuntimeError: self.assertTrue(nans, "No NaNs but failed") try: self.assertGradientChecks( device_option=gc, op=op, inputs=[X], outputs_to_check=0, outputs_with_grads=[0], ) if nans: self.assertTrue(False, "Did not fail when gradient had NaN!") except RuntimeError: pass @given(n=st.integers(4, 5), m=st.integers(6, 7), d=st.integers(2, 3), **hu.gcs) def test_elementwise_max(self, n, m, d, gc, dc): X = np.random.rand(n, m, d).astype(np.float32) Y = np.random.rand(n, m, d).astype(np.float32) Z = np.random.rand(n, m, d).astype(np.float32) def max_op(X, Y, Z): return [np.maximum(np.maximum(X, Y), Z)] op = core.CreateOperator( "Max", ["X", "Y", "Z"], ["mx"] ) self.assertReferenceChecks( device_option=gc, op=op, inputs=[X, Y, Z], reference=max_op, ) @given(n=st.integers(4, 5), m=st.integers(6, 7), d=st.integers(2, 3), **hu.gcs) def test_elementwise_max_grad(self, n, m, d, gc, dc): go = np.random.rand(n, m, d).astype(np.float32) X = np.random.rand(n, m, d).astype(np.float32) Y = np.random.rand(n, m, d).astype(np.float32) Z = np.random.rand(n, m, d).astype(np.float32) mx = np.maximum(np.maximum(X, Y), Z) def max_grad_op(mx, go, X, Y, Z): def mx_grad(a): return go * (mx == a) return [mx_grad(a) for a in [X, Y, Z]] op = core.CreateOperator( "MaxGradient", ["mx", "go", "X", "Y", "Z"], ["gX", "gY", "gZ"] ) self.assertReferenceChecks( device_option=gc, op=op, inputs=[mx, go, X, Y, Z], reference=max_grad_op, ) @given( inputs=hu.lengths_tensor().flatmap( lambda pair: st.tuples( st.just(pair[0]), st.just(pair[1]), hu.dims(max_value=len(pair[1])), ) ).flatmap( lambda tup: st.tuples( st.just(tup[0]), st.just(tup[1]), hu.arrays( tup[2], dtype=np.int32, elements=st.integers( min_value=0, max_value=len(tup[1]) - 1)), ) ), **hu.gcs_cpu_only) def test_lengths_gather(self, inputs, gc, dc): items = inputs[0] lengths = inputs[1] indices = inputs[2] def lengths_gather_op(items, lengths, indices): ends =
np.cumsum(lengths)
numpy.cumsum
import pickle import cv2 import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg # ! GLOBALS # Define conversions in x and y from pixels space to meters ym_per_pix = 20/720 # meters per pixel in y dimension xm_per_pix = 3.7/780 # meters per pixel in x dimension def calibrate_camera(): # * dummy function only need to be run once, check calibrate_camera.py for details pass def clr_grad_thres(img, s_thresh=(170, 255), sx_thresh=(20, 100)): img = np.copy(img) # Convert to HLS color space and separate the V channel hls = cv2.cvtColor(img, cv2.COLOR_RGB2HLS) l_channel = hls[:,:,1] s_channel = hls[:,:,2] # Grayscale image # NOTE: we already saw that standard grayscaling lost color information for the lane lines # Explore gradients in other colors spaces / color channels to see what might work better gray = cv2.cvtColor(img, cv2.COLOR_RGB2HLS) # Sobel x # ! can also use gray instead of l_channel, but l_channel seems better sobelx = cv2.Sobel(l_channel, cv2.CV_64F, 1, 0) # Take the derivative in x abs_sobelx = np.absolute(sobelx) # Absolute x derivative to accentuate lines away from horizontal scaled_sobel = np.uint8(255*abs_sobelx/np.max(abs_sobelx)) # Threshold x gradient sxbinary = np.zeros_like(scaled_sobel) sxbinary[(scaled_sobel >= sx_thresh[0]) & (scaled_sobel <= sx_thresh[1])] = 1 # Threshold color channel s_binary = np.zeros_like(s_channel) s_binary[(s_channel >= s_thresh[0]) & (s_channel <= s_thresh[1])] = 1 # Stack each channel color_binary = np.dstack(( np.zeros_like(sxbinary), sxbinary, s_binary)) * 255 # Combine the two binary thresholds combined_binary = np.zeros_like(sxbinary) combined_binary[(s_binary == 1) | (sxbinary == 1)] = 1 return color_binary, combined_binary def undist_warp(img, mtx, dist, img_clr): # Pass in your image into this function # Write code to do the following steps # 1) Undistort using mtx and dist undist = cv2.undistort(img, mtx, dist, None, mtx) undist_clr = cv2.undistort(img_clr, mtx, dist, None, mtx) img_size = (undist.shape[1], undist.shape[0]) # b) define 4 source points src = np.float32([[,],[,],[,],[,]]) #Note: you could pick any four of the detected corners # as long as those four corners define a rectangle #One especially smart way to do this would be to use four well-chosen # corners that were automatically detected during the undistortion steps #We recommend using the automatic detection of corners in your code src = np.float32( [ [557, 476], [731, 476], [1042, 674], [281, 674] ] ) # c) define 4 destination points dst = np.float32([[,],[,],[,],[,]]) dst = np.float32( [ [280, 0], [1060, 0], [1060, 720], [280, 720] ] ) # d) use cv2.getPerspectiveTransform() to get M, the transform matrix M = cv2.getPerspectiveTransform(src, dst) Minv = cv2.getPerspectiveTransform(dst, src) # This is unnecessaary for this problem # e) use cv2.warpPerspective() to warp your image to a top-down view warped = cv2.warpPerspective(undist, M, img_size, flags=cv2.INTER_LINEAR) return warped, M, Minv, undist_clr def find_lane_pixels(binary_warped): # Take a histogram of the bottom half of the image histogram = np.sum(binary_warped[binary_warped.shape[0]//2:,:], axis=0) # Create an output image to draw on and visualize the result out_img = np.dstack((binary_warped, binary_warped, binary_warped)) # Find the peak of the left and right halves of the histogram # These will be the starting point for the left and right lines midpoint = np.int(histogram.shape[0]//2) leftx_base = np.argmax(histogram[:midpoint]) rightx_base = np.argmax(histogram[midpoint:]) + midpoint # HYPERPARAMETERS # Choose the number of sliding windows nwindows = 9 # Set the width of the windows +/- margin margin = 100 # Set minimum number of pixels found to recenter window minpix = 50 # ! 50 is recommended, but I think it should be way more # Set height of windows - based on nwindows above and image shape window_height = np.int(binary_warped.shape[0]//nwindows) # Identify the x and y positions of all nonzero pixels in the image nonzero = binary_warped.nonzero() nonzeroy = np.array(nonzero[0]) nonzerox = np.array(nonzero[1]) # Current positions to be updated later for each window in nwindows leftx_current = leftx_base rightx_current = rightx_base # Create empty lists to receive left and right lane pixel indices left_lane_inds = [] right_lane_inds = [] # Step through the windows one by one for window in range(nwindows): # Identify window boundaries in x and y (and right and left) win_y_low = binary_warped.shape[0] - (window+1)*window_height win_y_high = binary_warped.shape[0] - window*window_height ### TO-DO: Find the four below boundaries of the window ### win_xleft_low = leftx_current - margin # Update this win_xleft_high = leftx_current + margin # Update this win_xright_low = rightx_current - margin # Update this win_xright_high = rightx_current + margin # Update this # ! low means lower boundary, high means higher boundary # Draw the windows on the visualization image cv2.rectangle(out_img,(win_xleft_low,win_y_low), (win_xleft_high,win_y_high),(0,255,0), 2) cv2.rectangle(out_img,(win_xright_low,win_y_low), (win_xright_high,win_y_high),(0,255,0), 2) ### TO-DO: Identify the nonzero pixels in x and y within the window ### good_left_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & (nonzerox >= win_xleft_low) & (nonzerox < win_xleft_high)).nonzero()[0] good_right_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & (nonzerox >= win_xright_low) & (nonzerox < win_xright_high)).nonzero()[0] # Append these indices to the lists left_lane_inds.append(good_left_inds) right_lane_inds.append(good_right_inds) ### TO-DO: If you found > minpix pixels, recenter next window ### ### (`right` or `leftx_current`) on their mean position ### if len(good_left_inds) > minpix: leftx_current = np.int(np.mean(nonzerox[good_left_inds])) if len(good_right_inds) > minpix: rightx_current = np.int(np.mean(nonzerox[good_right_inds])) # pass # Remove this when you add your function # Concatenate the arrays of indices (previously was a list of lists of pixels) try: # ! need to concatenate because pixel ids are grouped by windows # print(left_lane_inds) left_lane_inds =
np.concatenate(left_lane_inds)
numpy.concatenate
''' Contains an abstract class that acts as a template for classes that stored and manipulate specific grid types and classes derived from this for specific grid types Created on Jan 13, 2016 @author: thomasriddick ''' import numpy as np import scipy.ndimage as ndi from abc import ABCMeta, abstractmethod from Dynamic_HD_Scripts.interface.fortran_interface \ import f2py_manager as f2py_mg import os.path as path import warnings import re from Dynamic_HD_Scripts.context import fortran_source_path class Grid(object, metaclass=ABCMeta): """Parent class for classes that store and manipulate specific grid types Public methods (all abstract): extend_mask_to_neighbours compute_flow_directions get_grid_dimensions set_grid_dimensions add_wrapping_halo remove_wrapping_halo mask_insignificant_gradient_changes calculate_gradients flip_ud one_hundred_eighty_degree_longitude_translation find_area_minima get_flagged_points_coords flag_point create_empty_field mask_outside_region replace_zeros_with_highest_valued_neighbor get_scale_factor_for_geographic_coords has_orientation_information needs_ud_flip needs_rotation_by_a_hundred_and_eighty_degrees set_coordinates get_coordinates find_all_local_minima get_npoints extract_data convert_data_to_code """ nlat = 1 nlong = 1 @abstractmethod def extend_mask_to_neighbours(self,changes_mask): """Extend a mask on this grid to include neighbouring points Arguments: changes_mask: the mask to be extended Implementations should return the extended mask """ pass @abstractmethod def compute_flow_directions(self,data): """Compute the flow direction from a given orography Arguments: data: the orography to compute the flow direction from Implementations should return the flow directions """ pass @abstractmethod def get_number_of_masked_neighbors(self,data): """Compute the number of neighbors of each masked cell that are masked""" pass @abstractmethod def get_grid_dimensions(self): """Get the dimension of the grid""" pass @abstractmethod def set_grid_dimensions(self): pass @abstractmethod def mask_insignificant_gradient_changes(self,gradient_changes,old_gradients, gc_method,**kwargs): """Mask a field of gradient changes where the changes are insignicant Arguments: gradient_changes: the gradient changes to consider old_gradients: the old gradients, possibly used in some gc_methods gc_method: the method/criteria used to decide which gradient changes are not significant **kwargs: parameters of the method/criteria used to decide which gradient changes are not significant Implementations should return the masked field of gradient changes """ pass @abstractmethod def calculate_gradients(self,orography): """Calculate gradients from an orography Arguments: orography: the orography to use Implementations should return the field of gradients calculated """ pass @abstractmethod def mark_river_mouths(self,flow_direction_data): """Mark all sea points that a river flows into as river mouth points Arguments: flow_direction_data: the flow direction data to work on Implementations should return the flow direction data with river-mouth sea points marked with the specified river mouth point flow direction value and other sea points left with the (general) sea point flow direction value """ pass @abstractmethod def flip_ud(self,data): """Flips input data in the up down (north south) direction Arguments: data: the data object to be flipped Implementations should return the flipped data object in the same format as the input data object """ pass @abstractmethod def one_hundred_eighty_degree_longitude_translation(self,data): """Translate the longitude of a grid by 180 degrees Arguments: data: the data object to be translated Implementations should return the translated data object in the same format as the input data object. This method effectively translate between a using the Greenwich Meridan as the origin of the x axis and placing it in the centre of the x axis. """ pass @abstractmethod def find_area_minima(self,data,area_corner_coords_list,area_size): """Find the minimum for each of a set of areas of a regular size Arguments: data: the data object to find minima in area_corner_coords_list: a list of the coordinates of the reference corner of each area area_size: the size of the areas specified as a tuple of the revelant lengths Implementations should return the minima marked as True in a field that is otherwise false given in the same format as the input data object. This method is intended to position true sinks points derived from a courser grid at the minima of the areas on the fine grid corresponding to the position/cell of the points on the course grid. """ pass @abstractmethod def get_flagged_points_coords(self,data): """Get the coordinates of points that are flagged true in a boolean field Arguments: the data object (to be interpreted as a boolean field) to find flagged points in Implementations should return the coordinates of the flagged points as list of objects of a type appropriate to represent objects on the grid type of the implementation. """ pass @abstractmethod def flag_point(self,data,coords): """Flag the point at the supplied coordinates as True (or equivalently 1) Arguments: data: the data object (to be interpreted as a boolean field) to flag the point in coords: the coordinates of the point to flag """ pass @abstractmethod def create_empty_field(self,dtype): """Creates a field full of zeros/False for this grid type Arguments: dtype: the data type of the field to create Implementations should return an empty field of zeros with the size and shape of this grid """ pass @abstractmethod def mask_outside_region(self,data,region): """Mask a supplied field outside a supplied region and return it Arguments: data: the data object to be masked region: dictionary; the appropriate set of coordinates required to specify a region on the grid child class in question. Returns: The data object with a masked added """ pass @abstractmethod def replace_zeros_with_highest_valued_neighbor(self,data): """Replace any zeros with the value of the highest value out of any (non negative) neighboring cell Arguments: data: the data object to replace the zeros in Returns: The data object with the zeros replaced by the highest (non negative) neighboring cells value If all neighboring cell are negative or zero then a zero valued cell is left unchanged """ pass @abstractmethod def get_scale_factor_for_geographic_coords(self): """Get the scale factor for this size of grid used to convert to geographical coordinates Arguments: none Returns: The scale factor used to convert coordinates values for this grid to geographical coordinates (actual latitude and longitude) """ pass @abstractmethod def has_orientation_information(self): """Return flag indicating if the grid has information indicating its information Arguments: None Returns: Nothing """ pass @abstractmethod def needs_ud_flip(self): """Returns a flag indicating if this grid needs to be flipped upside down Arguments: None Returns: A flag that is true if this grid object and any associated data needs to be flipped and false if they don't need to be flipped Only needs to be implemented for grid where up and down are meaningful concepts """ pass @abstractmethod def needs_rotation_by_a_hundred_and_eighty_degrees(self): """Returns a flag indicating if this grid needs to rotate by 180 degrees around the earth's axis Arguments: None Returns: A flag this is true if this grid boject and any associated data needs to be rotated 180 degrees around the earths axis and is otherwise false Only needs to be implemented for grids where such a rotation is meaningful. """ pass @abstractmethod def set_coordinates(self,coordinates): """Set the coordinates of points in the grid Arguments: coordinates: tuple of ndarrays; a tuple of arrays containing the coordinates of the points in the various dimensions of the grid Returns: nothing """ pass @abstractmethod def get_coordinates(self): pass @abstractmethod def find_all_local_minima(self): pass @abstractmethod def get_npoints(self): """Return total number of points in the grid""" pass @abstractmethod def add_wrapping_halo(self): pass @abstractmethod def remove_wrapping_halo(self): pass @abstractmethod def extract_data(self,data,section_coords,field_name,data_type,language): pass @abstractmethod def convert_data_to_code(data_section,field_name,data_type,language): pass class LatLongGrid(Grid): """Class that stores information on and functions to work with a Latitude-Longitude grid. Public methods: As for parent class and in addition get_sea_point_flow_direction_value get_longitude_offset_adjustment set_latitude_points set_longitude_points This class should work on any latitude-longitude grid that stores data in 2D array-like objects. Note iternally all the functions within this class will work even if the size of the array(s) given is not the same as the number of latitude and longitude points set. This allows for easy testing but means that there is no check that the size of arrays given as arguments to methods of this class are correct. """ flow_direction_labels=np.arange(1,10,dtype=np.float64) pole_boundary_condition = 1.0e+7 sea_point_flow_direction_value = -1 default_gc_method = 'all_neighbours' lat_points=None lon_points=None def __init__(self,nlat=360,nlong=720,longitude_offset_adjustment=0): """Class constructor. Set the grid size. Arguments: nlat (optional): integer; the number of latitude points in the grid nlong (optional): integer, the number of longitude points in the grid """ self.gc_methods = {'all_neighbours': LatLongGridGradientChangeMaskingHelper.all_neighbours_method} self.nlat = nlat self.nlong = nlong self.longitude_offset_adjustment = longitude_offset_adjustment def get_longitude_offset_adjustment(self): """Return the factor need to adjust the longitude offset compared to that of 1/2 degree grid Arguments: None Returns: the required longitude offset adjustment compared to that of the half degree grid required to give the correct longitude labels. This adjustment itself should of been set when the class was initialized pre-scaled such that it an offset on a 1/2 degree grid scale. """ return self.longitude_offset_adjustment def extend_mask_to_neighbours(self,changes_mask): """Extend a mask on this grid to include neighbouring points Arguments: changes_mask: numpy 2d array of boolean value; the mask to be extended Return: The extended mask as a numpy 2d array of boolean values Extends the mask using the binary erosion method from the morophology class of numpy's image processing module. The copies of the first and last column are inserted into the position after the last column and before the first column respectively to wrap the calculation around the globe. The borders at the poles assume the mask to be true and any cross pole neighbours are ignore in this calculation. """ #For an unknown reason insert only works as required if the array axis are #swapped so axis 0 is being inserted into. changes_mask = changes_mask.swapaxes(0,1) changes_mask = np.insert(changes_mask,obj=(0,np.size(changes_mask,axis=0)), values=(changes_mask[-1,:],changes_mask[0,:]), axis=0) changes_mask = changes_mask.swapaxes(0,1) #binary_erosion has a keyword mask that is nothing to do with the mask we are #manipulating; its value defaults to None but set this explicitly for clarity return ndi.morphology.binary_erosion(changes_mask, structure=ndi.generate_binary_structure(2,2), iterations=1, mask=None, border_value=1)[:,1:-1] def flow_direction_kernel(self,orog_section): """Find flow direction a single grid point Arguements: orog_section: a flatten 1d array-like object; a 3 by 3 square of orography centre on the grid point under consideration flattened into a 1d array Returns: A flow direction (which will take an integer value) as a numpy float 64 (for technical reasons) Takes coordinate of the minimum of the orography section (the first minimum if several point equal minima exist) and uses it to look up a flow direction. If this grid cell itself is also a minima then assign the flow to it (diretion 5; min_coord=4) instead of the first minimum found. """ #Only the first minimum is found by argmin. Thus it will be this that #is assigned as minima if two points have the same height min_coord = np.argmin(orog_section) if orog_section[4] == np.amin(orog_section): min_coord = 4 return self.flow_direction_labels[min_coord] def compute_flow_directions(self,data,use_fortran_kernel=True): """Compute the flow direction for a given orograpy Arguments: data: numpy array-like object; the orography to compute the flow direction for use_fortran_kernel: boolean: a flag to choose between using a python kernel (False) or using a Fortran kernel (True) Returns: A numpy array of flow directions as integers Inserts extra rows to ensure there is no cross pole flow; then flip the field to get the same first minima as Stefan uses for easy comparison. Setup the kernel function to use depending on the input flag. Then run a generic filter from the numpy image processing module that considers the 3 by 3 area around each grid cell; wrapping around the globe in the east-west direction. Return the output as an integer after flipping it back the right way up and removing the extra rows added at the top and bottom """ #insert extra rows across the top and bottom of the grid to ensure correct #treatmen of boundaries data = np.insert(data,obj=(0,np.size(data,axis=0)),values=self.pole_boundary_condition, axis=0) #processing the data upside down to ensure that the handling of the case where two neighbours #have exactly the same height matches that of Stefan's scripts data = np.flipud(data) if use_fortran_kernel: f2py_mngr = f2py_mg.f2py_manager(path.join(fortran_source_path, 'mod_grid_flow_direction_kernels.f90'), func_name='HDgrid_fdir_kernel') flow_direction_kernel = f2py_mngr.run_current_function_or_subroutine else: flow_direction_kernel = self.flow_direction_kernel flow_directions_as_float = ndi.generic_filter(data, flow_direction_kernel, size=(3,3), mode = 'wrap') flow_directions_as_float = np.flipud(flow_directions_as_float) return flow_directions_as_float[1:-1].astype(int) def get_number_of_masked_neighbors(self,data): """Compute the number of neighbors that are masked of each masked cell""" #insert extra rows across the top and bottom of the grid to ensure correct #treatmen of boundaries data = np.insert(data,obj=(0,np.size(data,axis=0)),values=False, axis=0) f2py_mngr = f2py_mg.f2py_manager(path.join(fortran_source_path, 'mod_grid_m_nbrs_kernels.f90'), func_name='HDgrid_masked_nbrs_kernel') nbrs_kernel = f2py_mngr.run_current_function_or_subroutine nbrs_num = ndi.generic_filter(data.astype(np.float64), nbrs_kernel, size=(3,3), mode = 'wrap') return nbrs_num[1:-1].astype(int) def get_grid_dimensions(self): """Get the dimension of the grid and return them as a tuple""" return (self.nlat,self.nlong) def set_grid_dimensions(self,dimensions): self.nlat,self.nlong = dimensions def get_sea_point_flow_direction_value(self): """Get the sea point flow direction value""" return self.sea_point_flow_direction_value def mask_insignificant_gradient_changes(self,gradient_changes,old_gradients, gc_method=default_gc_method,**kwargs): """Mask insignicant gradient changes using a keyword selected method Arguments: gradient_changes: numpy array; a numpy array with gradient changes in 8 direction from each grid cell plus flow to self gradient changes set to zero to make 9 elements per grid cell in an order matching the river flow direction 1-9 compass rose keypad labelling scheme. Thus this should be 9 by nlat by nlong sized numpy array. old_gradients: numpy array; the gradients from the base orography in the same format as the gradient changes gc_method: str; a keyword specifying which method to use to mask insignificant gradient changes **kwargs: keyword dictionary; keyword parameter to pass to the selected gradient change masking method Returns: the masked gradient changes returned by the selected method The methods selected should be from a helper class called LatLongGridGradientChangeMaskingHelper where all such methods should be stored in order to keep the main LatLongGrid class from becoming too cluttered. The gradient changes, old_gradient and **kwargs (except for gc_method) will be passed onto the selected method. """ return self.gc_methods[gc_method](gradient_changes,old_gradients,**kwargs) def calculate_gradients(self,orography): """Calculate the (pseudo) gradients between neighbouring cells from an orography Arguments: orography: numpy array; an array contain the orography data to calculate gradients for Returns: A numpy array that consists of the gradient from each point in all 8 directions (plus zero for the gradient to self). Thus the array has 1 more dimension than the input orography (i.e. 2+1 = 3 dimensions); the length of this extra dimension is 9 for a 9 by nlong by nlat array. The order of the 9 different kinds of gradient change for each grid point matches the 1-9 keypad compass rose numbering used to denote flow directions First adds extra columns to the start/end of the input orography that are equal to the last/first row respectively; thus allowing gradients that wrap in the longitudal direction to be calculated. Then calculate arrays of the edge differences using numpy's diff method. Calculate the corner differences by overlaying two offset version of the same orography field. Return all these gradients array stacked up to form the final array; inserting extra rows of zeros where no gradient exists as it would go over the pole (over the pole gradients are set to zero) and trimming off one (or where necessary both) of the extra columns added to facilitate wrapping. Notice the gradients calculated are actually just the differences between neighbouring cells and don't take into account the distances between the point at which the gradient is defined; if this point was the cell centre then the gradients would need to calculated different for diagonal neighbours from the direct (NESW) neighbours. """ #should be equal to nlat and nlong but redefining here allows for #easy testing of this method isolation naxis0 = np.size(orography,axis=0) naxis1 = np.size(orography,axis=1) #For an unknown reason insert only works as required if the array axis are #swapped so axis 0 is being inserted into. orography = orography.swapaxes(0,1) orography = np.insert(orography,obj=(0,np.size(orography,axis=0)), values=(orography[-1,:],orography[0,:]), axis=0) orography = orography.swapaxes(0,1) edge_differences_zeroth_axis = np.diff(orography,n=1,axis=0) edge_differences_first_axis = np.diff(orography,n=1,axis=1) corner_differences_pp_mm_indices = orography[1:,1:] - orography[:-1,:-1] corner_differences_pm_mp_indices = orography[1:,:-1] - orography[:-1,1:] #To simplify later calculations allow two copies of each gradient thus #allow us to associate set of gradients to each grid cell, note the #use of naxisx-0 instead of naxis0 to add to the final row because the #individual gradient arrays have all be reduced in size along the relevant #axis by 1. return np.stack([ #keypad direction 1 #extra row added to end of zeroth axis; an extra column is not #required due to wrapping np.insert(corner_differences_pm_mp_indices[:,:-1],obj=naxis0-1, values=0,axis=0), #keypad direction 2 #extra row added to end of zeroth axis np.insert(edge_differences_zeroth_axis[:,1:-1],obj=naxis0-1,values=0, axis=0), #keypad direction 3 #extra row added to end of zeroth axis; an extra column is not #required due to wrapping np.insert(corner_differences_pp_mm_indices[:,1:],obj=naxis0-1, values=0,axis=0), #keypad direction 4 #extra column not required due to wrapping -edge_differences_first_axis[:,:-1], #keypad direction 5. No gradient is defined but fill #with zero to produce a stack of 9 numbers for each #cell to correspond to the 9 flow directions np.zeros((naxis0,naxis1)), #keypad direction 6 #extra column not required due to wrapping edge_differences_first_axis[:,1:], #keypad direction 7 #extra row added to start of zeroth axis; an extra column is not #required due to wrapping np.insert(-corner_differences_pp_mm_indices[:,:-1],obj=0, values=0,axis=0), #keypad direction 8 #extra row added to start of zeroth axis np.insert(-edge_differences_zeroth_axis[:,1:-1],obj=0,values=0, axis=0), #keypad direction 9 #extra row added to start of zeroth axis; an extra column is not #required due to wrapping np.insert(-corner_differences_pm_mp_indices[:,1:],obj=0, values=0,axis=0)], axis=0) def mark_river_mouths(self,flow_direction_data): """Mark all sea points that a river flows into as river mouth points Arguments: flow_direction_data: ndarray; field of flow direction data to mark river mouths on Returns: ndarray of flow direction data with the river mouths marked Calls a fortran module as the kernel to ndimage generic filter in order to actually mark the river mouths """ #For an unknown reason insert only works as required if the array axis are #swapped so axis 0 is being inserted into. flow_direction_data = flow_direction_data.swapaxes(0,1) flow_direction_data = np.insert(flow_direction_data,obj=(0,np.size(flow_direction_data,axis=0)), values=(flow_direction_data[-1,:],flow_direction_data[0,:]), axis=0) flow_direction_data = flow_direction_data.swapaxes(0,1) f2py_mngr = f2py_mg.f2py_manager(path.join(fortran_source_path, 'mod_river_mouth_kernels.f90'), func_name='latlongrid_river_mouth_kernel') flow_direction_data = ndi.generic_filter(flow_direction_data, f2py_mngr.run_current_function_or_subroutine, size=(3,3), mode = 'constant', cval = float(self.sea_point_flow_direction_value)) return flow_direction_data[:,1:-1] def flip_ud(self,data): """Flips input data in the up down (north south) direction Arguments: data: ndarray; the data object to be flipped Returns: an ndarray contain the data flipped upside down in the up/down (north/south) direction """ if self.lat_points is not None: self.lat_points =
np.flipud(self.lat_points)
numpy.flipud
from collections import namedtuple from typing import List import numpy as np from astropy.stats import LombScargle from scipy import interpolate from scipy import signal from flirt.hrv.features.data_utils import DomainFeatures VlfBand = namedtuple("Vlf_band", ["low", "high"]) LfBand = namedtuple("Lf_band", ["low", "high"]) HfBand = namedtuple("Hf_band", ["low", "high"]) class FdFeatures(DomainFeatures): def __init__(self, sampling_frequency: int = 1, method: str = 'lomb'): self.sampling_frequency = sampling_frequency self.method = method def __get_type__(self) -> str: return "Frequency Domain" def __generate__(self, data: np.array) -> dict: return get_fd_features(data, method=self.method, sampling_frequency=self.sampling_frequency) def get_fd_features(data, method: str = "lomb", sampling_frequency: int = 4, interpolation_method: str = "linear", vlf_band: namedtuple = VlfBand(0.003, 0.04), lf_band: namedtuple = LfBand(0.04, 0.15), hf_band: namedtuple = HfBand(0.15, 0.40)): data_np = np.asarray(data) results = { 'hrv_total_power': np.nan, 'hrv_vlf': np.nan, 'hrv_lf': np.nan, 'hrv_hf': np.nan, 'hrv_lf_hf_ratio': np.nan, 'hrv_lfnu': np.nan, 'hrv_hfnu': np.nan, } results.update(__frequency_domain(nn_intervals=data_np, method=method, sampling_frequency=sampling_frequency, interpolation_method=interpolation_method, vlf_band=vlf_band, lf_band=lf_band, hf_band=hf_band)) return results def __frequency_domain(nn_intervals, method, sampling_frequency, interpolation_method, vlf_band, lf_band, hf_band): freq, psd = __get_freq_psd_from_nn_intervals(nn_intervals, method, sampling_frequency, interpolation_method, vlf_band, hf_band) frequency_domain_features = __get_features_from_psd(freq=freq, psd=psd, vlf_band=vlf_band, lf_band=lf_band, hf_band=hf_band) return frequency_domain_features def __get_freq_psd_from_nn_intervals(nn_intervals, method, sampling_frequency, interpolation_method, vlf_band, hf_band): timestamp_list = __create_timestamp_list(nn_intervals) if method == "welch": funct = interpolate.interp1d(x=timestamp_list, y=nn_intervals, kind=interpolation_method) timestamps_interpolation = __create_interpolated_timestamp_list(nn_intervals, sampling_frequency) nni_interpolation = funct(timestamps_interpolation) nni_normalized = nni_interpolation - np.mean(nni_interpolation) freq, psd = signal.welch(x=nni_normalized, fs=sampling_frequency, window='hann', nfft=4096) elif method == "lomb": freq, psd = LombScargle(timestamp_list, nn_intervals, normalization='psd').autopower( minimum_frequency=vlf_band[0], maximum_frequency=hf_band[1]) else: raise ValueError("Not a valid method. Choose between 'lomb' and 'welch'") return freq, psd def __create_timestamp_list(nn_intervals: List[float]): nni_tmstp = np.cumsum(nn_intervals) / 1000 return nni_tmstp - nni_tmstp[0] def __create_interpolated_timestamp_list(nn_intervals: List[float], sampling_frequency: int = 7): time_nni = __create_timestamp_list(nn_intervals) nni_interpolation_tmstp = np.arange(0, time_nni[-1], 1 / float(sampling_frequency)) return nni_interpolation_tmstp def __get_features_from_psd(freq: List[float], psd: List[float], vlf_band, lf_band, hf_band): vlf_indexes = np.logical_and(freq >= vlf_band[0], freq < vlf_band[1]) lf_indexes = np.logical_and(freq >= lf_band[0], freq < lf_band[1]) hf_indexes =
np.logical_and(freq >= hf_band[0], freq < hf_band[1])
numpy.logical_and
""" Here we collect only those functions needed scipy.optimize.least_squares() based minimization the RAC-models fit negative energies E depending on a strength parameter lambda: E(lambda) E is is written as E = -k**2 and the model actually used is lambda(k) the data to fit are passed as arrays: k, ksq = k**2, lbs of length M (this way, k**2 is computed only once) each model is a Pade or rational function approximation pade_31 implies a polynomial of third order devided by a polynomial of first order Each polynomial is parametrized in a highly specialized way motivated by quantum scattering theory. -> Fewer parameters than general Pade appromimants. -> More complicated formulas. -> All parameters are positive. To fit the model, minimize chi**2 = 1/M sum_i (rac-31(k_i)-lb_i)**2 This can be done by a minimizer or by non-linear least_squares - least_squares seems superior regarding gradient evaluations (May 2020) - minimize and least_squares need quite different interfaces and functions - for minimize a hand-coded chi**2 function and its gradient is required - as gradients we need for minimize the vector d(chi**2)d(parameter[j]) for least_squared the matrix d(model(k[i])-lambda[i])/d(parameter[j]) - minimize takes one function that returns f, and grad f, least_squares doesn't - least_squares seems rock stable for rac-42, too - the solution for rac-53 looks OK (good start parameters from [3,1] and [4,2]) - gradients for [5,3] work Jun 2, 2020 Jun 3, 2020 putting in weights: ramifications for all pade and all jacobian functions works for pade_31, should work for 42 and 53 Jun 12, 2020 everything up to [5,3] works with weights for each pade the is a function: pade_nm_lsq(params, k, ksq, lmbda, sigma) and the derivatives with respect to the parameters are returned by: pade_nmj_lsq(params, k, ksq, lmbda, sigma) nm = [21, 31, 32, 41, 42, 43, 52, 53] """ import sys import numpy as np from scipy.optimize import curve_fit def res_ene(alpha, beta): """ resonance energy Eres = Er - i*Gamma/2 from alpha and beta assumes a quadratic term: lambda = k**2 + 2*a**2*k + a**4 + b**2 solve for lambda = 0 """ Er = beta**2 - alpha**4 G = 4*alpha**2 * abs(beta) return Er, G def res_ene_gd(g, d): """ resonance energy from gamma and delta c.f. lambda = k**2 + 2*a**2*k + a**4 + b**2 with lambda = d*k**2 + g**2*k + 1 a = g/d/sqrt(2) b = sqrt(4-g**4)/(2*g**2) """ a = g/d/np.sqrt(2.) b = np.sqrt(4-g**4)/(2*g**2) Er = b**2 - a**4 G = 4*a**2 * abs(b) return Er, G def guess(Er, G): """ inverse of res_ene intented for computing a guess for alpha and beta from a guess for Eres """ ag=0.5*np.sqrt(2.0)*(-2*Er + np.sqrt(4*Er**2 + G**2))**0.25 bg=0.5*G/np.sqrt(-2*Er + np.sqrt(4*Er**2 + G**2)) return [ag, bg] def linear_extra(ls, Es): """ find E(l=0) from an f(l)=m*l+b model used to find start parameters """ def f(x, m, b): return m*x+b popt, pcov = curve_fit(f, ls, Es) return f(0,popt[0],popt[1]) def weights(M, kind, E0=0, Es=None, tiny=1e-8): """ weights for the least_squares() fitting functions least_squares computes the cost function: F(x) = 0.5 * sum f_i**2 the user has to supply a callable f() M : number of data points kind : kind of weights returned returns a numpy array of M sigmas (sqrt(weights)) kind = 'ones' all sigmas are equal to sqrt(1/M), this should be equivalent to the implicit-one-weights implementation f[i] = rac(k_i) - lambda_i, where the sum of the weights sum_i 1 = M = len(ks) was factored from the sum giving chi2 = 2*res.cost/len(ks)) weights may be non-equal, so we work with normalized weights throughout: f[i] = (rac(k_i) - lambda_i)*sigma_i with sum_i sigma_i**2 = 1 and chi2 = 2*res.cost kind = 'energy' sigma**2 is a maxium for E0 and falls off linearly to tiny for Es[0] and Es[-1] """ if 'one' in kind: sigmas = np.ones(M) * np.sqrt(1/M) elif 'energy' in kind: if len(Es) != M: sys.exit('Error in weights(): M and Es have con') ws = np.zeros(M) # line equations for Es greater and smaller than E0 # all Es are negative, but E[0] is closest to zero # for vertical lines, use m=0, b=1 if abs(E0-Es[0]) < tiny: m1 = 0 b1 = 1 else: m1 = 1/(E0-Es[0]) b1 = 1 - m1*E0 if abs(E0-Es[-1]) < tiny: m2 = 0 b2 = 1 else: m2 = 1/(E0-Es[-1]) b2 = 1 - m2*E0 for i in range(M): if Es[i] >= E0: ws[i] = m1*Es[i] + b1 + tiny else: ws[i] = m2*Es[i] + b2 + tiny sigmas = np.sqrt(ws)/np.sqrt(np.sum(ws)) else: sys.exit('Error in weights(): unknow kind=' + str(kind)) return sigmas def chi2_gen(params, ks, k2s, lbs, sigmas, pade): """ chi2 = mean of squared deviations passed to basin_hopping() the least_squares() wrapper function needs to return 2*res.cost/len(ks) """ diffs = pade(params, ks, k2s, lbs, sigmas) return np.sum(np.square(diffs)) def pade_gen_j_lsq(params, ks, k2s, lbs, sigmas, pade_lsq, step=1e-5, tiny=1e-8): """ for testing the pade_j_lsq() functions used in least_squares() setups never used in production runs, rather use the interal gradient """ n_kappa = len(ks) n_param = len(params) p0 = list(params) dfs = np.zeros((n_param,n_kappa)) for ip in range(n_param): h = step*params[ip] + tiny pp = np.array(p0[:ip] + [p0[ip]+h] + p0[ip+1:]) pm = np.array(p0[:ip] + [p0[ip]-h] + p0[ip+1:]) dp = pade_lsq(pp, ks, k2s, lbs, sigmas) dm = pade_lsq(pm, ks, k2s, lbs, sigmas) dfs[ip,:] = (dp-dm)/(2*h) return np.transpose(dfs) def pade_21_lsq(params, k, ksq, lmbda, sigma): """ model to fit f(k[i]) to lmbda[i] ksq = k**2 is computed only once params: [lambda0, alpha, beta] returns model(k) - lbs For details see DOI: 10.1140/epjd/e2016-70133-6 """ l0, a, b = params A, B = a**2, b**2 TA = 2*A A2B = A*A + B f1 = ksq + TA*k + A2B den = A2B + TA*k f=l0 * f1 / den return (f - lmbda)*sigma def pade_21j_lsq(params, k, ksq, lmbda, sigmas): """ 'jac' for pade_21_lsq arguments must be identical with pade_lsq() computes the matrix del pade(k[i])/del para[j] returns the M-by-N matrix needed by scipy.optimize.least_squares M = number of data points N = number of parameters least_squares() needs the transpose """ l0, a, b = params A, B = a**2, b**2 TA = 2*A A2B = A*A + B f1 = ksq + TA*k + A2B den = A2B + TA*k dl0 = f1 / den da = -4*a*ksq*l0 * (A + k) / den**2 db = -2*b*ksq*l0 / den**2 return np.transpose(np.array([dl0, da, db])*sigmas) def pade_31_lsq(params, k, ksq, lmbda, sigma): """ model to fit f(k[i]) to lmbda[i] ksq = k**2 is computed only once params: [lambda0, alpha, beta, delta] returns model(k) - lbs For details see DOI: 10.1140/epjd/e2016-70133-6 """ l0, a, b, d = params a4b2=a*a*a*a + b*b aak2=a*a*k*2 ddk=d*d*k num = (ksq + aak2 + a4b2) * (1 + ddk) den = a4b2 + aak2 + ddk*a4b2 rac31 = l0 * num / den return (rac31 - lmbda)*sigma def pade_31j_lsq(params, k, ksq, lbs, sigmas): """ 'jac' for pade_31_lsq arguments must be identical with pade_lsq() computes the matrix del pade(k[i])/del para[j] returns the M-by-N matrix needed by scipy.optimize.least_squares M = number of data points N = number of parameters least_squares() needs the transpose """ l, a, b, d = params a2, b2, d2 = a*a, b*b, d*d a4b2 = a2*a2 + b2 aak2 = a2*k*2 ddk = d2*k fr1 = (ksq + aak2 + a4b2) fr2 = (1 + ddk) den = a4b2 + aak2 + ddk*a4b2 dl = fr1*fr2/den da = -4*a*ksq*l * fr2 * (a2*a2*d2 + a2*fr2 - b2*d2 + k) / den**2 db = -2*b*ksq*l * fr2 * (2*a2*d2 + fr2) / den**2 dd = 4*a2*d*ksq*l * fr1/den**2 return np.transpose(np.array([dl, da, db, dd])*sigmas) def pade_32_lsq(params, k, ksq, lmbda, sigma): """ model to fit f(k[i]) to lmbda[i] ksq = k**2 is computed only once params: [lambda0, alpha, beta, delta, epsilon] returns model(k) - lbs For details see DOI: 10.1140/epjd/e2016-70133-6 """ l0, a, b, d, e = params A, B, D, E = a**2, b**2, d**2, e**2 TA = 2*A A2B = A*A + B f1 = ksq + TA*k + A2B f2 = 1 + D*k den = A2B + k*(TA + D*(A2B)) + E*ksq f= l0 * f1 * f2 /den return (f - lmbda)*sigma def pade_32j_lsq(params, k, ksq, lmbda, sigmas): """ 'jac' for pade_32_lsq arguments must be identical with pade_lsq() computes the matrix del pade(k[i])/del para[j] returns the M-by-N matrix needed by scipy.optimize.least_squares M = number of data points N = number of parameters least_squares() needs the transpose """ l0, a, b, d, e = params A, B, D, E = a**2, b**2, d**2, e**2 TA = 2*A A2B = A*A + B f1 = ksq + TA*k + A2B f2 = 1 + D*k den = A2B + k*(TA + D*(A2B)) + E*ksq dl0 = f1 * f2 / den da = -4*a*ksq*l0 * f2 * (A*A*D + A*D*k - A*E + A - B*D - E*k + k) / den**2 db = -2*b*ksq*l0 * f2 * (TA*D + D*k - E + 1) / den**2 dd = 2*d*ksq*l0 * f1 * (TA + E*k) / den**2 de = -2*e*ksq*l0 * f1 * f2 / den**2 return np.transpose(
np.array([dl0, da, db, dd, de])
numpy.array
import numpy import functools """ Convolutional neural network implementation using NumPy A tutorial that helps to get started (Building Convolutional Neural Network using NumPy from Scratch) available in these links: https://www.linkedin.com/pulse/building-convolutional-neural-network-using-numpy-from-ahmed-gad https://towardsdatascience.com/building-convolutional-neural-network-using-numpy-from-scratch-b30aac50e50a https://www.kdnuggets.com/2018/04/building-convolutional-neural-network-numpy-scratch.html It is also translated into Chinese: http://m.aliyun.com/yunqi/articles/585741 """ # Supported activation functions by the cnn.py module. supported_activation_functions = ("sigmoid", "relu", "softmax") def sigmoid(sop): """ Applies the sigmoid function. sop: The input to which the sigmoid function is applied. Returns the result of the sigmoid function. """ if type(sop) in [list, tuple]: sop = numpy.array(sop) return 1.0 / (1 + numpy.exp(-1 * sop)) def relu(sop): """ Applies the rectified linear unit (ReLU) function. sop: The input to which the relu function is applied. Returns the result of the ReLU function. """ if not (type(sop) in [list, tuple, numpy.ndarray]): if sop < 0: return 0 else: return sop elif type(sop) in [list, tuple]: sop =
numpy.array(sop)
numpy.array
from voice_activity_detection import vad from speech_emotion_recognition import feature_extraction as fe, ensemble import scipy import numpy as np from scipy import signal from scipy.io.wavfile import write import datetime def denoise(samples): """ :param samples: an array representing the sampled audio file :type samples: float :return: an array representing the clean audio file :rtype: float """ samples_wiener = scipy.signal.wiener(samples) return samples_wiener def execute_vad_ser(segmenter, filepath, prediction_scheme): """ :param segmenter: an instance of the Segmenter object of Ina Speech Segementer :type segmenter: Segmenter object :param filepath: a string representing the full-path of the input audio file :type filepath: string :param prediction_scheme: a string representing the aggregation strategy to be used in the ensemble :type prediction_scheme: string TO DO :return: an integer flag representing the action to be sent to the control center :rtype: int """ samples, sample_rate = fe.read_file(filepath) samples, sample_rate = resample(samples, sample_rate) new_samples = fe.cut_pad(samples) samples_wiener = denoise(new_samples) new_filepath = "voice_activity_detection/tmp.wav" write(new_filepath, sample_rate, samples_wiener) seg = vad.check_speech(segmenter, new_filepath) if seg == 'speech': print("#########################################\n") print("The audio contains speech. \nStarting Speech Emotion Recognition process.\n") print("#########################################\n") # start_time = datetime.datetime.now() final_prediction = ensemble.ensemble(new_samples, prediction_scheme) # elapsed = datetime.datetime.now() - start_time # print("Time elapsed for SER", elapsed) if final_prediction == 1: print("Speech contains disruptive emotion.") else: print("Speech does not contain disruptive emotion.") def resample(input_data, sample_rate, required_sample_rate=16000, amplify=False): """ Resampling function. Takes an audio with sample_rate and resamples it to required_sample_rate. Optionally, amplifies volume. ​ :param input_data: Input audio data :type input_data: numpy.ndarray :param sample_rate: Sample rate of input audio data :type sample_rate: int :param required_sample_rate: Sample rate to resample original audio, defaults to 16000 :type required_sample_rate: int, optional :param amplify: Whether to amplify audio volume, defaults to False :type amplify: bool, optional :return: Resampled audio and new sample rate :rtype: numpy.ndarray, int """ if sample_rate < required_sample_rate: resampling_factor = int(round(required_sample_rate/sample_rate, 0)) new_rate = sample_rate * resampling_factor samples = len(input_data) * resampling_factor resampled = signal.resample(input_data, samples) elif sample_rate > required_sample_rate: resampling_factor = int(round(sample_rate/required_sample_rate, 0)) new_rate = int(sample_rate / resampling_factor) resampled = signal.decimate(input_data, resampling_factor) else: resampling_factor = 1 new_rate = sample_rate resampled = input_data if amplify and input_data.size > 0: absolute_values = np.absolute(resampled) max_value = np.amax(absolute_values) max_range =
np.iinfo(np.int16)
numpy.iinfo
from __future__ import print_function __author__ = '__fbb__' #<NAME>, NYU #github: @fedhere #<EMAIL> #cosmo.nyu.edu/~fb55/ #created: December 2015 #module to plot time series as sparkle lines a' la Tufte. import numpy as np import pandas as pd import matplotlib.pyplot as pl import matplotlib as mpl from distutils.version import LooseVersion #color blindness safe colors kelly_colors_hex = [ '#FFB300', # Vivid Yellow '#803E75', # Strong Purple '#FF6800', # Vivid Orange '#A6BDD7', # Very Light Blue '#C10020', # Vivid Red '#CEA262', # Grayish Yellow '#817066', # Medium Gray '#007D34', # Vivid Green '#F6768E', # Strong Purplish Pink '#00538A', # Strong Blue '#FF7A5C', # Strong Yellowish Pink '#53377A', # Strong Violet '#FF8E00', # Vivid Orange Yellow '#B32851', # Strong Purplish Red '#F4C800', # Vivid Greenish Yellow '#7F180D', # Strong Reddish Brown '#93AA00', # Vivid Yellowish Green '#593315', # Deep Yellowish Brown '#F13A13', # Vivid Reddish Orange '#232C16', # Dark Olive Green ] axiscycler_key = "axes.color_cycle" axiscycler = lambda cc: cc if LooseVersion(mpl.__version__) >= '1.5.0': from cycler import cycler axiscycler_key = "axes.prop_cycle" axiscycler = lambda cc: (cycler('color', cc)) #the plots are on every other column of the subplot grid #(alternate columns reserved for labels) #the color cycle gets screwes since upgrade to MPL 1.5 and subbing #'prop_cycle' for 'color_cycle' newparams = { "lines.linewidth": 2.0, "axes.edgecolor": "#aaaaaa", "patch.linewidth": 1.0, "legend.fancybox": 'false', "axes.facecolor": "#ffffff", "axes.labelsize": "large", "axes.grid": 'false', "patch.edgecolor": "#555555", "axes.titlesize": "x-large", "svg.embed_char_paths": "path", axiscycler_key: axiscycler(kelly_colors_hex) } def sparklme(data, labels=None, datarange=None, rangecol=None, colors=None, figsize=None, figure=None, ncols=None, alpha=0.3, fontsize=15, minmaxformat='%.1f', xrangeformat='%.1f', labeloffset=0, minmaxoffset=0, flipy=False): #flipy is designad for astronomical mags: #min is at the top, #max at the bottom #setting up plotting parameters #number of columns in the plotting grid if not ncols: ncols = 2 #plotting color list if colors: if not isinstance(colors, (list, tuple, np.ndarray)): colors = [colors] else: colors = list(colors) newcolors = colors + kelly_colors_hex newparams[axiscycler_key] = axiscycler(newcolors) #setting up data #if it is a DataFrame if type(data) == pd.core.frame.DataFrame: N = len(data.columns) if not labels: labels = data.columns if datarange: if (not isinstance(datarange, (list, tuple, np.ndarray)) or not np.array(datarange).shape == (2, )): print("datarange incorrect") x0, x1 = '', '' else: x0, x1 = datarange elif rangecol: N -= 1 if rangecol in data.columns: x0, x1 = data[rangecol].values.min(), \ data[rangecol].values.max() else: print("rangecol incorrect") x0, x1 = '', '' data.drop(rangecol, 1, inplace=True) else: ldf = float(len(data)) x0, x1 = '0', '%d' % ldf xrangeformat = '%d' if 'd' in xrangeformat: x0, x1 = int(x0), int(x1) if 'f' in xrangeformat: x0, x1 = float(x0), float(x1) data = data.values.T #if it is a np.ndarray elif isinstance(data, (list, tuple, np.ndarray)): N = data.shape[0] Ndp = data.shape[1] if not labels: labels = [''] * N if not datarange or not isinstance(datarange, (list, tuple, np.ndarray)): if not (rangecol is None) and isinstance(rangecol, int): x0, x1 = data[rangecol].min(), data[rangecol].max() mask = np.ones(data.shape[0], dtype=bool) mask[rangecol] = False data = data[mask] labels = np.array(labels)[mask] N = N - 1 else: x0, x1 = 0, Ndp xrangeformat = '%d' else: x0, x1 = datarange if not len(labels) == N: print("length of lables array is incorrect") labels = [''] * N else: print("data type not understood") return -1 #saving old rc params and setting new ones oldparams = pl.rcParams pl.rcParams.update(newparams) nrows = int((N + 2) / ncols) print("number of rows:", nrows) if figure: fig = figure figsize = fig.get_size_inches() elif figsize: fig = pl.figure(figsize=figsize) else: figsize = (10, nrows) fig = pl.figure(figsize=figsize) print("figure size: ", fig.get_size_inches(), "in") ax = [] for i, data in enumerate(data): x2 = 0 if i % ncols == 0 else (i % ncols) * 3 #print (nrows, ncols * 2 + ncols, ((i/ncols), x2), i%ncols) ax.append(pl.subplot2grid((nrows, ncols * 2 + ncols), ((i / ncols), x2), colspan=2)) minhere = np.nanmin(data) maxhere = np.nanmax(data) ax[i].plot(data, 'k', alpha=alpha) ax[i].axis('off') ax[i].set_xlim(-len(data) * 0.3, len(data) * 1.3) try: bl, = ax[i].plot(np.where(data == minhere)[0], minhere, 'o') except ValueError: bl, = ax[i].plot(np.where(data == minhere)[0][0], minhere, 'o') if 'd' in minmaxformat: minhere = int(minhere) if 'f' in minmaxformat: minhere = float(minhere) ax[i].text(1.1 - minmaxoffset, 0.5, minmaxformat % (minhere), fontsize=fontsize, transform=ax[i].transAxes, ha='center', color=bl.get_color()) try: bl, = ax[i].plot(np.where(data == maxhere)[0], maxhere, 'o') except ValueError: bl, = ax[i].plot(np.where(data == maxhere)[0][0], maxhere, 'o') ax[i].text(1.3 - minmaxoffset, 0.5, minmaxformat % (maxhere), fontsize=fontsize, transform=ax[i].transAxes, color=bl.get_color()) ax[i].text(-0.1 - labeloffset, 0.5, labels[i], fontsize=fontsize, transform=ax[i].transAxes) if flipy: ax[i].set_ylim(ax[i].get_ylim()[1], ax[i].get_ylim()[0]) if i < 2: ax[i].plot((0, ax[i].get_xlim()[1]), (ax[i].get_ylim()[1], ax[i].get_ylim()[1]), 'k-', ) xrangeloc = 1.1 if flipy: xrangeloc = 0.9 xr = '{0:' + xrangeformat + '} - {1:' + xrangeformat + '}' xr = xr.replace('%', '') for axi in ax[:ncols]: axi.text(axi.get_xlim()[1] * 0.5, axi.get_ylim()[1] * xrangeloc, xr.format(x0, x1), ha='center', transform=axi.transData, fontsize=fontsize) axi.text(1.1 - minmaxoffset, 1.2, 'min', ha='center', transform=axi.transAxes, fontsize=fontsize) axi.text(1.3 - minmaxoffset, 1.2, 'max', transform=axi.transAxes, fontsize=fontsize) ''' ax[1].text (ax[1].get_xlim()[1]*0.5, ax[1].get_ylim()[1]*xrangeloc, xr.format(x0, x1), ha = 'center', transform = ax[1].transData, fontsize = fontsize) ax[1].text (1.1 - minmaxoffset, 1.2, 'min', ha = 'center', transform = ax[1].transAxes, fontsize = fontsize) ax[1].text (1.3 - minmaxoffset, 1.2, 'max', transform = ax[1].transAxes, fontsize = fontsize) ''' pl.rcParams.update(oldparams) return fig def sparkletest(): data =
np.ones((100, 10))
numpy.ones
import os import argparse from itertools import chain from operator import itemgetter import numpy as np from keras import backend as K from keras.preprocessing import sequence from keras.models import load_model, Model from keras.layers import Dense from keras.optimizers import SGD, Adam import tensorflow as tf from sklearn.model_selection import LeaveOneOut from sklearn.metrics import confusion_matrix, classification_report from nltk.corpus import stopwords from evidencedetection.reader import AnnotationReader from evidencedetection.vectorizer import EmbeddingVectorizer from evidencedetection.analyzer import Analyzer from evidencedetection.models.neuralnetwork import BiLSTM def parse_arguments(): parser = argparse.ArgumentParser("Tests an argument mining model on the evidence annotations.") parser.add_argument("--annotations", type=str, help="The path to the user annotations.") parser.add_argument("--test", type=str, help="The testing file.") parser.add_argument("--user", type=str, help="The user for which to test the model.") parser.add_argument("--embeddings", type=str, help="The path to the embeddings folder") parser.add_argument("--epochs", type=int, default=0, help="The number of epochs to train for") parser.add_argument("--initial", type=int, default=0, help="""The number of initial epochs in which all, except the new classifier layer are frozen. This number will be added to the other training epochs.""") parser.add_argument("--lr", type=float, default=0.001, help="The learning rate for the combined learning phase") parser.add_argument("--ilr", type=float, default=0.01, help="The learning for the initial learning phase.") parser.add_argument("--suffix", type=str, default="AM", help="The suffix to use, e.g. AM or ED") parser.add_argument("--modeldir", type=str, default="../models/sentential-argument-mining", help="The model directory. The directory name is also the specific model name + .h5") parser.add_argument("--maxlen", type=int, default=189, help="The maximum length of the input sentences") parser.add_argument("--topicSpecific", action="store_true", help="Specifies whether or not the model to load will be topic specific") parser.add_argument("--seed", type=int, default=0, help="The random seed to use for training.") return parser.parse_args() class Experiment: def __init__(self, vectorizer, epochs, initial, lr, ilr, model_name, max_length, seed): self.max_length = max_length self.vectorizer = vectorizer self.epochs = epochs self.initial = initial self.lr = lr self.ilr = ilr self.model_name = model_name self.seed = seed def run_experiment(self, train, test, old_model_name): loo = LeaveOneOut() all_preds = list() all_targets = list() training_data = list() for num_training_files, training_file in enumerate(reversed(train)): new_training_sentences = training_file[1] training_data.append(new_training_sentences) filename = test[0][0] print("Testing on: ", filename) test_data =
np.array(test[0][1])
numpy.array
# NB! update_diversion() in channels_base.py is now COMMENTED OUT. # #-------------------------------------------------------------------- # Copyright (c) 2001-2020, <NAME> # # May 2020. Wrote "vol_str()" for print_final_report() # Jan 2013. Revised handling of input/output names. # Oct 2012. CSDMS Standard Names and BMI. # May 2012. Q_outlet -> Q_outlet[0] (5/19/12) # May 2010. Changes to initialize() and read_cfg_file() # Feb 2010. Channels comp. now calls dp.update() itself.) # Apr, May, July, August 2009 # Jan 2009. Converted from IDL. # #-------------------------------------------------------------------- # # class topoflow_driver (inherits from BMI_base.py) # # get_component_name() # get_attribute() # (10/26/11) # get_input_var_names() # (5/16/12, Bolton) # get_output_var_names() # (5/16/12, Bolton) # get_var_name() # (5/16/12, Bolton) # get_var_units() # (5/16/12, Bolton) # --------------------- # set_constants() # run_model() # initialize() # update() # finalize() # ----------------------------------- # check_finished() # check_steady_state() ### # check_interrupt() # ----------------------------------- # initialize_stop_vars() # initialize_mass_totals() # (OBSOLETE ??) # initialize_GUI() # (commented out) # initialize_hydrograph_plot() # (commented out) # ----------------------------------- # update_mass_totals() # (OBSOLETE ??) # update_hydrograph_plot() # ----------------------------------- # vol_str() # print_final_report() # print_mins_and_maxes() # print_uniform_precip_data() # print_dimless_number_data() # print_mass_balance_report() # #----------------------------------------------------------------------- import numpy as np import os import time from topoflow.utils import BMI_base from topoflow.utils import cfg_files as cfg from topoflow.utils.tf_utils import TF_Print, TF_String, TF_Version #----------------------------------------------------------------------- class topoflow_driver( BMI_base.BMI_component ): #------------------------------------------------------------------- # Don't define an __init__() function. # We need to inherit the BMI_base.__init__() #------------------------------------------------------------------- _att_map = { 'model_name': 'TopoFlow_Driver', 'version': '3.1', 'author_name': '<NAME>', 'grid_type': 'uniform', 'time_step_type': 'fixed', 'step_method': 'explicit', #------------------------------------------------------------- 'comp_name': 'TopoFlow', 'model_family': 'TopoFlow', 'cfg_template_file': 'TopoFlow.cfg.in', 'cfg_extension': '_topoflow.cfg', 'cmt_var_prefix': '/TopoFlow/Input/Var/', 'gui_xml_file': '/home/csdms/cca/topoflow/3.1/src/share/cmt/gui/TopoFlow.xml', 'dialog_title': 'TopoFlow: Driver Parameters', 'time_units': 'seconds' } #------------------------------------------------------------------------------ # (2/3/13) Added "channel_model__time_step" since it is needed by # both the TopoFlow driver (topoflow.py) and Diversions (diversion_base.py). # But source and sink files provide "dt" for Diversions, so check. #------------------------------------------------------------------------------ _input_var_names = [ 'atmosphere_water__domain_time_integral_of_precipitation_leq-volume_flux', # vol_P@meteorology 'atmosphere_water__domain_time_max_of_precipitation_leq-volume_flux', # P_max@meteorology 'basin_outlet_water_flow__half_of_fanning_friction_factor', # f_outlet@channels 'basin_outlet_water_x-section__mean_depth', # d_outlet@channels 'basin_outlet_water_x-section__peak_time_of_depth', # Td_peak@channels 'basin_outlet_water_x-section__peak_time_of_volume_flow_rate', # T_peak@channels 'basin_outlet_water_x-section__peak_time_of_volume_flux', # Tu_peak@channels 'basin_outlet_water_x-section__time_integral_of_volume_flow_rate', # vol_Q@channels 'basin_outlet_water_x-section__time_max_of_mean_depth', # d_peak@channels 'basin_outlet_water_x-section__time_max_of_volume_flow_rate', # Q_peak@channels 'basin_outlet_water_x-section__time_max_of_volume_flux', # u_peak@channels 'basin_outlet_water_x-section__volume_flow_rate', # Q_outlet@channels 'basin_outlet_water_x-section__volume_flux', # u_outlet@channels 'channel_bottom_water_flow__domain_max_of_log_law_roughness_length', # z0val_max@channels 'channel_bottom_water_flow__domain_min_of_log_law_roughness_length', # z0val_min@channels ## 'channel_model__time_step', ####################### (no longer needed?) 'channel_water_flow__domain_max_of_manning_n_parameter', # nval_max@channels 'channel_water_flow__domain_min_of_manning_n_parameter', # nval_min@channels #----------------------------------------------------- # These might only be available at the end of run ?? # These are now over the entire domain (or DEM). #----------------------------------------------------- 'channel_water_x-section__domain_max_of_mean_depth', # d_max 'channel_water_x-section__domain_max_of_volume_flow_rate', # Q_max 'channel_water_x-section__domain_max_of_volume_flux', # u_max 'channel_water_x-section__domain_min_of_mean_depth', # d_min 'channel_water_x-section__domain_min_of_volume_flow_rate', # Q_min 'channel_water_x-section__domain_min_of_volume_flux', # u_min # 'snowpack__domain_max_of_depth', # hs_max # 'snowpack__domain_min_of_depth', # hs_min #----------------------------------------------------------- 'glacier_ice__domain_time_integral_of_melt_volume_flux', # vol_MR@ice 'land_surface_water__baseflow_volume_flux', # GW@satzone 'land_surface_water__domain_time_integral_of_baseflow_volume_flux', # vol_GW@satzone 'land_surface_water__domain_time_integral_of_evaporation_volume_flux', # vol_ET@evap 'land_surface_water__domain_time_integral_of_runoff_volume_flux', # vol_R@channels 'land_surface_water__runoff_volume_flux', # R@channels 'snowpack__domain_time_integral_of_liquid-equivalent_depth', # vol_swe@snow 'snowpack__domain_time_integral_of_melt_volume_flux', # vol_SM@snow 'soil_surface_water__domain_time_integral_of_infiltration_volume_flux', # vol_IN@infil 'soil_water__domain_time_integral_of_volume_fraction', # vol_soil 'soil_water_sat-zone_top__domain_time_integral_of_recharge_volume_flux', # vol_Rg #----------------------------------------------------------- 'network_channel_water__volume', # vol_chan@channels 'land_surface_water__area_integral_of_depth' ] # vol_land@channels #---------------------------------------------------------------- # The TopoFlow driver no longer needs to get the time_steps of # the other model components; this is now the framework's job. # That means it can't include them in its final report. #---------------------------------------------------------------- ## 'channel:model__time_step', # dt@channels ## 'diversion:model__time_step', ## 'evap:model_time_step', ## 'ice:model_time_step', ## 'infil:model__time_step', ## 'meteorology:model__time_step', ## 'satzone:model__time_step', ## 'snow:model__time_step' ] ################################################################### #### Bolton comments, 5/12/2012 --- #### Not sure what to do with these missing /unknow vars #### cp.get_status() #### save_pixels_dt@channels 'model__save_pixels_flag' ? #### MANNING@channels 'model__manning_flag' ? #### LAW_OF_WALL@channels 'model__wall_law_flag ? #### RICHARDS@infiltration 'model__richards_flag' ? ################################################################### _output_var_names = [ 'model__time_step' ] # dt _var_name_map = { 'atmosphere_water__domain_time_integral_of_precipitation_leq-volume_flux': 'vol_P', 'atmosphere_water__domain_time_max_of_precipitation_leq-volume_flux': 'P_max', 'basin_outlet_water_flow__half_of_fanning_friction_factor': 'f_outlet', 'basin_outlet_water_x-section__mean_depth': 'd_outlet', 'basin_outlet_water_x-section__peak_time_of_depth': 'Td_peak', 'basin_outlet_water_x-section__peak_time_of_volume_flow_rate': 'T_peak', 'basin_outlet_water_x-section__peak_time_of_volume_flux': 'Tu_peak', 'basin_outlet_water_x-section__time_integral_of_volume_flow_rate': 'vol_Q', 'basin_outlet_water_x-section__time_max_of_mean_depth': 'd_peak', 'basin_outlet_water_x-section__time_max_of_volume_flow_rate': 'Q_peak', 'basin_outlet_water_x-section__time_max_of_volume_flux': 'u_peak', 'basin_outlet_water_x-section__volume_flow_rate': 'Q_outlet', 'basin_outlet_water_x-section__volume_flux': 'u_outlet', 'channel_bottom_water_flow__domain_max_of_log_law_roughness_length': 'z0val_max', 'channel_bottom_water_flow__domain_min_of_log_law_roughness_length': 'z0val_min', ## 'channel_model__time_step': 'channel_dt', ## (2/3/13) 'channel_water_flow__domain_max_of_manning_n_parameter': 'nval_max', 'channel_water_flow__domain_min_of_manning_n_parameter': 'nval_min', #------------------------------------------------------- # These 6 might only be available at the end of run ?? #------------------------------------------------------- 'channel_water_x-section__domain_max_of_mean_depth': 'd_max', 'channel_water_x-section__domain_max_of_volume_flow_rate': 'Q_max', 'channel_water_x-section__domain_max_of_volume_flux': 'u_max', 'channel_water_x-section__domain_min_of_mean_depth': 'd_min', 'channel_water_x-section__domain_min_of_volume_flow_rate': 'Q_min', 'channel_water_x-section__domain_min_of_volume_flux': 'u_min', # 'snowpack__domain_max_of_depth': 'hs_max', # 'snowpack__domain_min_of_depth': 'hs_min', #------------------------------------------------------------ 'glacier_ice__domain_time_integral_of_melt_volume_flux': 'vol_MR', 'land_surface_water__baseflow_volume_flux': 'GW', 'land_surface_water__domain_time_integral_of_baseflow_volume_flux': 'vol_GW', 'land_surface_water__domain_time_integral_of_evaporation_volume_flux': 'vol_ET', 'land_surface_water__domain_time_integral_of_runoff_volume_flux': 'vol_R', 'land_surface_water__runoff_volume_flux': 'R', 'snowpack__domain_time_integral_of_liquid-equivalent_depth': 'vol_swe', 'snowpack__domain_time_integral_of_melt_volume_flux': 'vol_SM', 'soil_surface_water__domain_time_integral_of_infiltration_volume_flux': 'vol_IN', 'soil_water__domain_time_integral_of_volume_fraction': 'vol_soil', 'soil_water_sat-zone_top__domain_time_integral_of_recharge_volume_flux': 'vol_Rg', #--------------------- 'model__time_step': 'dt', #---------------------------------------------------------------------------- 'network_channel_water__volume': 'vol_chan', 'land_surface_water__area_integral_of_depth': 'vol_land' } _var_units_map = { 'atmosphere_water__domain_time_integral_of_precipitation_leq-volume_flux': 'm3', 'atmosphere_water__domain_time_max_of_precipitation_leq-volume_flux': 'm s-1', 'basin_outlet_water_flow__half_of_fanning_friction_factor': '1', 'basin_outlet_water_x-section__mean_depth': 'm', 'basin_outlet_water_x-section__peak_time_of_depth': 'min', 'basin_outlet_water_x-section__peak_time_of_volume_flow_rate': 'min', 'basin_outlet_water_x-section__peak_time_of_volume_flux': 'min', 'basin_outlet_water_x-section__time_integral_of_volume_flow_rate': 'm3', 'basin_outlet_water_x-section__time_max_of_mean_depth': 'm', 'basin_outlet_water_x-section__time_max_of_volume_flow_rate': 'm3 s-1', 'basin_outlet_water_x-section__time_max_of_volume_flux': 'm s-1', 'basin_outlet_water_x-section__volume_flow_rate': 'm3 s-1', 'basin_outlet_water_x-section__volume_flux': 'm s-1', 'channel_bottom_water_flow__domain_max_of_log_law_roughness_length': 'm', 'channel_bottom_water_flow__domain_min_of_log_law_roughness_length': 'm', ## 'channel_model__time_step': 's', ### (2/3/13) 'channel_water_flow__domain_max_of_manning_n_parameter': 'm-1/3 s', 'channel_water_flow__domain_min_of_manning_n_parameter': 'm-1/3 s', #----------------------------------------------------- # These might only be available at the end of run ?? #----------------------------------------------------- 'channel_water_x-section__domain_max_of_mean_depth': 'm', 'channel_water_x-section__domain_max_of_volume_flow_rate': 'm3 s-1', 'channel_water_x-section__domain_max_of_volume_flux': 'm s-1', 'channel_water_x-section__domain_min_of_mean_depth': 'm', 'channel_water_x-section__domain_min_of_volume_flow_rate': 'm3 s-1', 'channel_water_x-section__domain_min_of_volume_flux': 'm s-1', # 'snowpack__domain_max_of_depth': 'm', # 'snowpack__domain_min_of_depth': 'm', #------------------------------------------------------------ 'glacier_ice__domain_time_integral_of_melt_volume_flux': 'm3', 'land_surface_water__baseflow_volume_flux': 'm s-1', 'land_surface_water__domain_time_integral_of_baseflow_volume_flux': 'm3', 'land_surface_water__domain_time_integral_of_evaporation_volume_flux': 'm3', 'land_surface_water__domain_time_integral_of_runoff_volume_flux': 'm3', 'land_surface_water__runoff_volume_flux': 'm s-1', 'network_channel_water__volume': 'm3', 'snowpack__domain_time_integral_of_liquid-equivalent_depth': 'm3', 'snowpack__domain_time_integral_of_melt_volume_flux': 'm3', 'soil_surface_water__domain_time_integral_of_infiltration_volume_flux': 'm3', 'soil_water__domain_time_integral_of_volume_fraction': 'm3', 'soil_water_sat-zone_top__domain_time_integral_of_recharge_volume_flux': 'm3', #---------------------------- 'model__time_step': 's', #---------------------------------------------------------------------------- 'network_channel_water__volume': 'm3', 'land_surface_water__area_integral_of_depth': 'm3' } #------------------------------------------------ # Return NumPy string arrays vs. Python lists ? #------------------------------------------------ ## _input_var_names = np.array( _input_var_names ) ## _output_var_names = np.array( _output_var_names ) #------------------------------------------------------------------- def get_component_name(self): return 'TopoFlow_Driver' ##### TopoFlow_Run_Monitor, Report_Maker? # get_component_name() #------------------------------------------------------------------- def get_attribute(self, att_name): try: return self._att_map[ att_name.lower() ] except: print('###################################################') print(' ERROR: Could not find attribute: ' + att_name) print('###################################################') print(' ') # get_attribute() #------------------------------------------------------------------- def get_input_var_names(self): #-------------------------------------------------------- # Note: These are currently variables needed from other # components vs. those read from files or GUI. #-------------------------------------------------------- return self._input_var_names # get_input_var_names() #------------------------------------------------------------------- def get_output_var_names(self): return self._output_var_names # get_output_var_names() #------------------------------------------------------------------- def get_var_name(self, long_var_name): return self._var_name_map[ long_var_name ] # get_var_name() #------------------------------------------------------------------- def get_var_units(self, long_var_name): return self._var_units_map[ long_var_name ] # get_var_units() #------------------------------------------------------------------- def set_constants(self): #------------------------ # Define some constants #------------------------ self.mps_to_mmph = np.float64(3600000) # [m/s] to [mm/hr] #------------------------------------------ # Moved these from __init__() on 5/17/12. #------------------------------------------ self.OK = True self.comment = None self.WRITE_LOG = True self.VERBOSE = False self.PLOT = False # set_constants() #------------------------------------------------------------------- def initialize(self, cfg_file=None, mode="nondriver", SILENT=False): #------------------------------------------------------ # Note: If using as a CCA component, then we need to # call "get_cca_ports()" before calling this # "initialize()" method in the component's CCA # Impl file. #------------------------------------------------------ if not(SILENT): print('TopoFlow component: Initializing...') self.status = 'initializing' # (OpenMI 2.0 convention) self.mode = mode self.cfg_file = cfg_file #----------------------------------------------- # Load component parameters from a config file #----------------------------------------------- self.set_constants() self.initialize_config_vars() # self.read_grid_info() # NOW IN initialize_config_vars() self.initialize_basin_vars() # (5/14/10) #---------------------------------- # Has component been turned off ? #---------------------------------- if (self.comp_status == 'Disabled'): if not(SILENT): print('TopoFlow Main component: Disabled in CFG file.') self.DONE = True self.status = 'initialized.' # (OpenMI 2.0 convention) return dc = (self.out_directory + self.case_prefix) self.comment_file = dc + '_comments.txt' self.log_file = dc + '.log' #----------------------- # Initialize variables #----------------------- self.initialize_time_vars() # (uses cp.dt from above) self.initialize_stop_vars() #### (do this with CFG file ?) #### self.nz = self.ip.get_scalar_long('nz') ####### #------------------------------------ # Check if output options are valid #------------------------------------ ## outlet_IDs, n_outlets, outlet_ID, OK = \ ## Check_Output_Options(grid_vars, rv, cv, sv, ev, iv, gv, nx, ny) #--------------------- # Open the logfile ? *** (Append or overwrite ??) #--------------------- if (self.WRITE_LOG): if (self.log_file == None): self.log_file = (self.case_prefix + '_LOG.txt') print('Opening log file:') print(' log_file = ' + self.log_file) self.log_unit = open(self.log_file, 'w') #---------------------- # Print start message #---------------------- TF_Print(' ') TF_Print('Starting TopoFlow model run...') hline = ''.ljust(60, '-') TF_Print(hline) self.status = 'initialized' # initialize() #------------------------------------------------------------- ## def update(self, dt=-1.0, time_seconds=None): def update(self, dt=-1.0): #-------------------------------------------------- # Note: This method no longer calls the update() # methods of other components; this is now taken # care of by the EMELI framework, regardless of # which component is the "driver". (2/4/13) #-------------------------------------------------- # Note: In "*_topoflow.cfg", should set dt to # smallest value of other components, otherwise # print_time_and_value() may not report info at # the requested time interval (e.g. 0.5 secs). #-------------------------------------------------- #------------------------------- # Check for interrupt by user ? #------------------------------- # OK = self.check_interrupt() # if not(OK): # self.status = 'stopped' # return # self.DEBUG = True ######################## self.status = 'updating' OK = True ## if (self.VERBOSE): if (self.mode == 'driver'): self.print_time_and_value(self.Q_outlet, 'Q_out', '[m^3/s]', interval=0.5) # [seconds] ## self.update_hydrograph_plot() #------------------------- # Increment the timestep #------------------------------------------------------- # Note that the update_time() method in BMI_base.py # calls "check_finished()". There is a simple version # of "check_finished()" in BMI_base.py and another # version in this file that supports more general # stopping conditions, including "steady state". #------------------------------------------------------ self.update_time( dt ) self.status = 'updated' # update() #------------------------------------------------------------- def finalize(self): self.status = 'finalizing' #-------------------------------------------- # This is called by the update() method. # We'd like to force another output, but it # is now based on elapsed time. 10/29/11. #-------------------------------------------- # if (self.mode == 'driver'): # self.print_time_and_value(self.Q_outlet, 'Q_out', '[m^3/s]') print('=======================') print('Simulation complete.') print('=======================') print(' ') #---------------- # Print reports #---------------- self.print_final_report() ## self.print_mins_and_maxes( FINAL=True ) # (Moved into final report.) ## self.print_uniform_precip_data() # (not ready yet) ## self.print_mass_balance_report() # (not ready yet) #-------------------- # Close the logfile #-------------------- if (self.WRITE_LOG): ## print '### Closing log file.' self.log_unit.close() #---------------------- # Print final message #---------------------- TF_Print('Finished.' + ' (' + self.case_prefix + ')') TF_Print(' ') self.status = 'finalized' # finalize() #------------------------------------------------------------- def check_finished(self): #------------------------------------------------------ # Notes: This version of "check_finished()" overrides # the simpler one that all components inherit # from BMI_base.py. #------------------------------------------------------ #--------------------------------- # Methods to stop the simulation #--------------------------------- if (self.stop_method == 'Q_peak_fraction'): #---------------------------------------------------- # Run until the outlet hydrograph drops to less # than "Qp_fraction" of the peak value before that. #---------------------------------------------------- FALLING_LIMB = (self.Q_last > self.Q_outlet) ## if (FALLING_LIMB): print "ON FALLING LIMB..." ## print 'self.Q_last =', self.Q_last ## print 'self.Q_outlet =', self.Q_outlet ## print ' ' #-------------------------------------------------------- # With DYNAMIC_WAVE, it is possible for some reason for # Q_outlet to drop back to zero early in the simulation # so that model run ends right away. (2/13/07) # Uncomment the debugging section below. #-------------------------------------------------------- if (FALLING_LIMB): Q_stop = (self.Q_peak * self.Qp_fraction) self.DONE = (self.Q_outlet <= Q_stop) and \ (self.Q_outlet > 0) if (self.DONE): stop_str = str(self.Qp_fraction) + '.\n' print('Stopping: Reached Q_peak fraction = ' + stop_str) ## print 'FALLING_LIMB =', FALLING_LIMB ## print 'Q_last =', self.Q_last ## print 'Q_peak =', self.Q_peak ## print 'Qpeak_fraction =', self.Qp_fraction ## print ' ' #-------------- # For testing #-------------- #if (DONE): # print 'Q_last =', self.Q_last # print 'Q_peak =', self.Q_peak # print 'Qpeak_fraction =', self.Qp_fraction # print 'Q[self.outlet_ID] =', Q_outlet # print 'Q_stop =', Q_stop # print ' ' elif (self.stop_method == 'Until_model_time'): #-------------------------------------------------- # Run until specified "stopping time", in minutes #-------------------------------------------------- self.DONE = (self.time_min >= self.T_stop) # [minutes] if (self.DONE): stop_str = str(self.T_stop) + '.\n' print('Stopping: Reached stop time = ' + stop_str) elif (self.stop_method == 'Until_n_steps'): #-------------------------------------- # Run for a specified number of steps #-------------------------------------- self.DONE = (self.time_index >= self.n_steps) if (self.DONE): stop_str = str(self.n_steps) + '.\n' print('Stopping: Reached number of steps = ' + stop_str) else: raise RuntimeError('No match found for expression') #-------------------------------------------------------------- # This model run is finished if the user-selected stopping # condition has been reached (above) OR if the model appears # to have reached a steady-state condition with discharge, # OR if the channel component has failed for some reason. # (2/4/13) #-------------------------------------------------------------- FINISHED = self.DONE STEADY = self.check_steady_state() # FAILED = (self.cp.get_status() == 'failed') ###### FIX SOON (5/18/12) FAILED = False if (FAILED): if (self.DEBUG): print('CHANNELS.update() failed.') self.status = 'failed' ### self.Q_outlet = np.float64(0) # (why is this here?) ### self.Q_last = self.Q_outlet self.Q_last = self.Q_outlet.copy() ## (2/7/13) self.DONE = (FINISHED or STEADY or FAILED) return self.DONE # check_finished() #------------------------------------------------------------------- def check_steady_state(self): #------------------------------------------------------- # Notes: See "initialize_stop_vars()" for definitions # of steady_tol, nonzero_tol, n_same_max and # Q_last. #------------------------------------------------------- STEADY = False #------------------------------------------ # Count number of steps with same Q-value #------------------------------------------ delta_Q = np.absolute(self.Q_outlet - self.Q_last) if ( delta_Q <= self.steady_tol ): ## print '(time_index, dQ) =', self.time_index, delta_Q self.n_same += 1 else: self.n_same = 0 #------------------------------------ # Check for steady-state, with Q > 0 #------------------------------------ if (self.stop_method == 'Q_peak_fraction') and \ (self.Q_outlet > self.nonzero_tol) and \ (self.n_same > self.n_same_max): STEADY = True if not(self.DONE): # (5/19/12. No message if already done.) msg = ['-----------------------------------------------------------', \ 'WARNING: It appears that discharge, Q, has reached', \ ' a steady-state condition.', \ ' Discharge at outlet near: ' + str(self.Q_outlet), \ ' for ' + str(self.n_same) + ' timesteps.', \ ' Aborting model run.', \ '-----------------------------------------------------------', \ ' '] ### 'Do you want to continue anyway ?', ' ']) for line in msg: print(line) ## answer = GUI_Message(msg, QUESTION=True) ## DONE = (answer.lower() == 'no') ## if not(DONE): ## n_same = int32(0) ## #TF_Print,'****************************************************' #TF_Print,'Aborting model run: ' #TF_Print,'Discharge, Q, has reached steady-state.' #TF_Print,'****************************************************' #msg = [ $ #'WARNING: Route_Flow aborted.', ' ',$ #'Discharge, Q, has reached steady-state. ', ' '] #GUI_Error_Message, msg #STEADY = True #----------------------------------------------- # (3/20/07) Commented out, since user can now # press any key to stop the model run. Note # that Q-value can remain zero for a long time # if everything is infiltrating or snow depth # is building, etc. #----------------------------------------------- # Check for unchanging Q-value of zero ? #----------------------------------------- #if (STOP_METHOD eq 0b) AND (Q_peak eq 0.0) AND (n_same gt nn) then begin # msg = [' ', $ # 'ERROR: ', ' ', $ # 'Discharge at outlet is zero for all times. ', ' ',$ # 'Is there a runoff-producing process ? ', ' '] # TF_Print,'*************************************************' # TF_Print, msg[1] # TF_Print, msg[3] # TF_Print,'*************************************************' # TF_Print,' ' # GUI_Error_Message, msg # DONE = 1b #endif return STEADY # check_steady_state #------------------------------------------------------------- def check_interrupt(self): #------------------------------------------------------------ #( 3/21/07) This method checks for a keyboard interrupt # after a fixed amount of real time has elapsed. This # works much better than using something like (n mod n_check) # since it avoids checking fast runs too often (which slows # down performance) or slow runs too seldom (which means the # user can't interrupt the run). It only checks the elapsed # time once each time through the loop, however, so the time # required for one pass imposes a lower bound. #------------------------------------------------------------ elapsed_time = (time.time() - self.last_check_time) if (elapsed_time > 2): #print,'****************************************************' #print,'Checking interrupt: n = ' + TF_String(n) #print,'****************************************************' ######################################## ## REPLACE WITH THE CODE ITSELF ######################################## ## Check_Interrupt(STOP_ID, OK) OK = True # (over-ridden, for now) if not(OK): self.finalize() TF_Print(' ') TF_Print('----------------------------------') TF_Print(' Simulation terminated by user.') TF_Print('----------------------------------') return self.last_check_time = time.time() # check_interrupt() #------------------------------------------------------------- def initialize_time_vars(self): #------------------ # Start the clock #------------------ self.start_time = time.time() #-------------------------------- # Initialize the time variables #-------------------------------- self.time_units = 'seconds' self.time_index = np.int32(0) self.time = np.float64(0) self.DONE = False self.time_sec = np.float64(0) self.time_min = np.float64(0) self.last_check_time = time.time() # (for check_interrupt() ) self.last_print_time = time.time() # (for print_time_and_value() ) self.last_plot_time = np.float64(0) # (for update_hydrograph_plot() ) #--------------------------------------- # Set the model run timestep to that # of the "channel_flow" process [secs] #--------------------------------------- ### self.dt = self.channel_dt # (5/17/12. New framework approach.) # initialize_time_vars() #------------------------------------------------------------- def initialize_stop_vars(self): TF_Print('Setting stop method to: ' + self.stop_method) #--------------------------------------------------------- # Define some constants for "check_steady_state() method #---------------------------------------------------------------- # Best value of tolerance also depends on the time step. # For "plane" case, result changed with timestep = 2 or 4 secs. #---------------------------------------------------------------- # "Optimal" value of steady_tol was found by trial and error. #---------------------------------------------------------------- self.steady_tol = np.float64(1E-5) self.nonzero_tol = np.float64(1E-5) #self.nonzero_tol = 1e-6 #(worked better for "plane" case with step=2s) self.n_same = np.int32(0) self.n_same_max = np.int32(499) # (a number of time steps) #-------------------------------------------------------------- # Note: Q_last will be compared to Q_outlet later, so we # must use copy() method for them to ever be different. # Q_outlet is a mutable scalar reference from channels. #-------------------------------------------------------------- self.Q_last = self.Q_outlet.copy() if (self.stop_method == 'Q_peak_fraction'): #---------------------------------------------------- # Run until the outlet hydrograph drops to less # than "Qp_fraction" of the peak value before that. #---------------------------------------------------- T_stop = 0 Tstr = ' [min]' elif (self.stop_method == 'Until_model_time'): #-------------------------------------------------- # Run until specified "stopping time", in minutes #-------------------------------------------------- T_stop = self.T_stop_model mstr = ('%10.2f' % T_stop) Tstr = ' of ' + mstr + ' [min]' elif (self.stop_method == 'Until_n_steps'): #-------------------------------------- # Run for a specified number of steps #-------------------------------------- n_steps = self.n_steps T_stop = (n_steps * self.dt / np.float64(60)) #[sec] -> [min] mstr = ('%10.2f' % T_stop) Tstr = ' of ' + mstr + ' [min]' else: print('ERROR: Invalid stopping method.') return self.T_stop = T_stop self.Tstr = Tstr # initialize_stop_vars() #------------------------------------------------------------- ## def initialize_gui(self): ## ## #----------------------------------------- ## # Set various widget IDs and info ## # (should this be called by __init__ ??) ## #----------------------------------------- ## self.leader_ID = np.int32(0) ## self.base_ID = int32(0) ## self.start_ID = int32(0) ## self.stop_ID = int32(0) ## self.draw_ID = int32(0) ## self.win_num = int32(0) ######## ## self.temp_winID = int32(-1) ## self.npanels = npanels ## self.panel_IDs = zeros([npanels], dtype='Int32') ## ## self.stop_method_ID = int32(0) ##### ## ## #---------------------------------------- ## # Option to plot hydrograph dynamically ## #---------------------------------------- ## if (self.PLOT): ## self.initialize_hydrograph_plot() ## ## # initialize_gui() #------------------------------------------------------------- ## def initialize_hydrograph_plot(self): ## ## #------------------------------------------------------ ## # NB! Get the window number for the draw widget. ## # This assumes that a small draw window has been ## # added in the output log panel. See the function ## # called GUI_Stopping in GUI_main.pro. ## #------------------------------------------------------ ## # NB! Rainbow + white color table was loaded earlier ## # by GUI_Stopping, so black=0 and white=255. ## #------------------------------------------------------ ## ## Initialize_Hydrograph_Window(DRAW_ID, win_num) ## ## self.nQ = int32(0) ## self.nQ_init = int16(1000) ## nQ_max = self.nQ_init ## self.tvals = zeros([nQ_max], dtype='Float32') ## self.Qvals = zeros([nQ_max], dtype='Float32') ## ## # initialize_hydrograph_plot() #------------------------------------------------------------- def update_hydrograph_plot(self): #----------------------------------------- # Plot hydrograph up until now (3/22/07) #----------------------------------------- # plus sign (psym=1), point (psym=3) #----------------------------------------- elapsed_plot_time = (self.time_min - self.last_plot_time) if (self.PLOT and (elapsed_plot_time > 1.0)): #------------------------------------ # Report an "instantaneous" Q value #------------------------------------ ######################## nQ = self.nQ nQ_init = self.nQ_init tvals = self.tvals Qvals = self.Qvals ######################## Q_main_out = Pixel_Var(self.cp.Q, self.outlet_ID) ######## self.tvals[nQ] = self.time_min self.Qvals[nQ] = Q_main_out matplotlib.pyplot.figure( self.win_num + 1 ) matplotlib.pyplot.plot(tvals[0:nQ+1], Qvals[0:nQ+1], \ color='k', marker='.') matplotlib.pyplot.axes(axisbg='w') matplotlib.pyplot.ylim(np.array(0, np.float64(1.03) * Qvals.max())) matplotlib.pyplot.show() #**** -1 time.sleep( np.float64(0.005) ) #[seconds] nQ = (nQ + np.int32(1)) if (nQ == self.nQ_max): ## Use np.concatenate() here ?? tvals = array([tvals, np.zeros([nQ_init], dtype='Float32')]) Qvals = array([Qvals, np.zeros([nQ_init], dtype='Float32')]) self.nQ_max = np.size(tvals) self.last_plot_time = self.time_min ######################## self.nQ = nQ self.tvals = tvals self.Qvals = Qvals ######################## # update_hydrograph_plot() #------------------------------------------------------------- def vol_str( self, value ): if (value < 1e6): return (str(value) + ' [m^3]') else: new_val = (value / 1e6) return (str(new_val) + ' x 10^6 [m^3]') # vol_str() #------------------------------------------------------------- def print_final_report(self, comp_name='TopoFlow', mode='nondriver'): #------------------------------------------------------ # NB! This overrides BMI_base.print_final_report(), # so it must have the same arguments. (10/27/11) #------------------------------------------------------ #------------------------------------ # Gather information for the report #------------------------------------ NAME = self.site_prefix COMMENT = self.comment T_stop = self.T_stop Q_final = self.Q_outlet T_final = self.time_min outlet_ID = self.outlet_ID n_steps = self.time_index # outlet_col = (outlet_ID % self.nx) ## (may need this) # outlet_row = (outlet_ID / self.nx) #--------------------------------------- # New framework method with 0-d numpy # arrays for mutable scalars (2/7/13). #--------------------------------------- Q_peak = self.Q_peak T_peak = self.T_peak u_peak = self.u_peak Tu_peak = self.Tu_peak d_peak = self.d_peak Td_peak = self.Td_peak #----------------------------- P_max = self.P_max vol_P = self.vol_P vol_Q = self.vol_Q vol_SM = self.vol_SM vol_swe = self.vol_swe # (2020-05-05) vol_MR = self.vol_MR vol_ET = self.vol_ET vol_IN = self.vol_IN vol_Rg = self.vol_Rg vol_GW = self.vol_GW vol_R = self.vol_R vol_soil = self.vol_soil # (2020-05-08) vol_chan = self.vol_chan # (2019-09-17) vol_land = self.vol_land # (2019-09-17) #----------------------------------------------------------------- # (2/6/13) BMI_base.py has an "initialize_basin_vars()" method # that embeds an instance of the "basin" component in the caller # as "bp". So this block of code should still work. #----------------------------------------------------------------- basin_area = self.basin_area ################################################################## # We need an "update_basin_vars()" method to be called from each # component's update() method in order to compute "volume_in". # Then we can set TRACK_VOLUME to True. ################################################################## ## volume_in = self.bp.volume_in TRACK_VOLUME = False ##### (since not ready yet) ###### volume_in = self.initialize_scalar( 0, dtype='float64') #---------------------------- # Construct run time string #---------------------------- run_time = (time.time() - self.start_time) if (run_time > 60): run_time = run_time / np.float64(60) rt_units = ' [min]' else: rt_units = ' [sec]' run_time_str = str(run_time) + rt_units if (TRACK_VOLUME): if (volume_in != 0): percent_out = np.float64(100) * vol_Q / volume_in else: percent_out = np.float64(0) #----------------------------------------------- # Prepare to save report as a list of strings #----------------------------------------------- report = list() ############# (NEW: 11/15/16) #------------------- # Build the report #------------------- hline = ''.ljust(60, '-') report.append( hline ) report.append( TF_Version() ) report.append( time.asctime() ) ##### report.append(' ') # report.append('Simulated Hydrograph for ' + NAME) report.append('Input directory: ' + self.in_directory) report.append('Output directory: ' + self.out_directory) report.append('Site prefix: ' + self.site_prefix) report.append('Case prefix: ' + self.case_prefix) if (COMMENT is not None): report.append(' ') report.append( COMMENT ) report.append(' ') report.append('Simulated time: ' + str(T_final) + ' [min]') report.append('Program run time: ' + run_time_str) report.append(' ') report.append('Number of timesteps: ' + str(n_steps)) report.append('Number of columns: ' + str(self.nx) ) report.append('Number of rows: ' + str(self.ny) ) report.append(' ') #------------------------------------------------------------ # (2/6/13) With the new framework and use of CSDMS Standard # Names there is no simple way for the TopoFlow driver to # get the time steps from the other components. That is, # it can request "model__time_step" from the framework, but # cannot specify which component(s) that it wants it from. # The framework has no trouble getting and printing this # info however, and this is now done instead. But current # approach does not write time steps to the log_file. #------------------------------------------------------------ ## TF_Print('Channel timestep: ' + str(cp_dt) + ' [s]') ## TF_Print('Precip/met timestep: ' + str(mp_dt) + ' [s]') ## TF_Print('Snowmelt timestep: ' + str(sp_dt) + ' [s]') ## TF_Print('ET timestep: ' + str(ep_dt) + ' [s]') ## TF_Print('Infiltr. timestep: ' + str(ip_dt) + ' [s]') ## TF_Print('Sat. zone timestep: ' + str(gp_dt) + ' [s]') ## TF_Print('Icemelt timestep: ' + str(iip_dt) + ' [s]') # TF_Print('Overland timestep: ' + str(op_dt) + ' [s]') # TF_Print('Sampled timestep: ' + str(sample_dt) + ' [s]') if (self.stop_method == 'Until_model_time'): report.append('T_stop: ' + str(T_stop) + ' [min]') report.append(' ') report.append('Main outlet ID: ' + str(outlet_ID) + ' (row, col)') report.append('Basin_area: ' + str(basin_area) + ' [km^2] ') #*** report.append('Basin_length: ' + TF_String(basin_length) + ' [m]') report.append(' ') if (hasattr(self, 'nval_min')): if (self.nval_min != -1): report.append("Min Manning's n: " + str(self.nval_min)) report.append("Max Manning's n: " + str(self.nval_max)) if (hasattr(self, 'z0val_min')): if (self.z0val_min != -1): report.append("Min z0 value: " + str(self.z0val_min) + ' [m]') report.append("Max z0 value: " + str(self.z0val_max) + ' [m]') report.append(' ') report.append('Q_final: ' + str(Q_final) + ' [m^3/s]') report.append('Q_peak: ' + str(Q_peak) + ' [m^3/s]') report.append('Q_peak_time: ' + str(T_peak) + ' [min]') report.append('u_peak: ' + str(u_peak) + ' [m/s]') report.append('u_peak_time: ' + str(Tu_peak) + ' [min]') report.append('d_peak: ' + str(d_peak) + ' [m]') report.append('d_peak_time: ' + str(Td_peak) + ' [min]') report.append(' ') ############################################################################## if (TRACK_VOLUME): report.append('Total volume out: ' + str(vol_Q) + ' [m^3]') if (basin_area != 0): report.append('Rain volume in: ' + str(volume_in) + ' [m^3]') report.append('Percentage out: ' + str(percent_out) + ' [%]') report.append(' ') ############################################################################## #-------------------------------- # Print the maximum precip rate #-------------------------------- MPR = (P_max * self.mps_to_mmph) # ([m/s] -> [mm/hr]) report.append('Max(precip rate): ' + str(MPR) + ' [mm/hr]') report.append(' ') #-------------------------------------------- # Print the area_time integrals over domain #-------------------------------------------- report.append('Total accumulated volumes over entire DEM:') report.append('vol_P (precip): ' + self.vol_str(vol_P) + ' (incl. leq snowfall)') report.append('vol_Q (discharge): ' + self.vol_str(vol_Q) + ' (main basin outlet)') report.append('vol_SM (snowmelt): ' + self.vol_str(vol_SM)) report.append('vol_MR (icemelt): ' + self.vol_str(vol_MR)) report.append('vol_ET (evaporation): ' + self.vol_str(vol_ET)) report.append('vol_IN (infiltration): ' + self.vol_str(vol_IN)) report.append('vol_Rg (recharge): ' + self.vol_str(vol_Rg) + ' (bottom loss)') report.append('vol_GW (baseflow): ' + self.vol_str(vol_GW)) report.append('vol_R (runoff): ' + self.vol_str(vol_R) + ' R = (P+SM+MR) - (ET+IN)') report.append('vol_soil (infiltration): ' + self.vol_str(vol_soil) + ' (change in storage)') report.append('vol_chan (channels): ' + self.vol_str(vol_chan)) report.append('vol_land (surface): ' + self.vol_str(vol_land)) report.append('vol_swe (snowpack): ' + self.vol_str(vol_swe)) report.append(' ') #---------------------------------- # Print the report to the console #---------------------------------- for line in report: print(line) #---------------------------------- # Print the report to a logfile ? #---------------------------------- if (self.WRITE_LOG): for line in report: self.log_unit.write( line + '\n' ) self.print_mins_and_maxes( FINAL=True ) if (self.WRITE_LOG): #------------------------------------------------ # This line is printed to console in finalize() #------------------------------------------------ self.log_unit.write( 'Finished. (' + self.case_prefix + ')\n' ) self.log_unit.write( '\n' ) # print_final_report() #------------------------------------------------------------- def print_mins_and_maxes(self, FINAL=False): #------------------------------- # New framework method, 2/6/13 #------------------------------- Q_min = self.Q_min Q_max = self.Q_max u_min = self.u_min u_max = self.u_max d_min = self.d_min d_max = self.d_max f1 = '(F14.4)' #(2/12/07) Qstr = TF_String( Q_min, FORMAT=f1 ) Qstr = Qstr + ', ' + TF_String( Q_max, FORMAT=f1 ) #---------------------------------------------------- ustr = TF_String( u_min, FORMAT=f1 ) ustr = ustr + ', ' + TF_String( u_max, FORMAT=f1 ) #---------------------------------------------------- dstr = TF_String( d_min, FORMAT=f1 ) dstr = dstr + ', ' + TF_String( d_max, FORMAT=f1 ) #----------------------------------------------- # Prepare to save report as a list of strings #----------------------------------------------- report = list() ############# (NEW: 11/15/16) if (FINAL): report.append('Final grid mins and maxes:') else: report.append('------------------------------------------') report.append('Min(Q), Max(Q): ' + Qstr + ' [m^3/s]') report.append('Min(u), Max(u): ' + ustr + ' [m/s]') report.append('Min(d), Max(d): ' + dstr + ' [m]') report.append(' ') #---------------------------------- # Print the report to the console #---------------------------------- for line in report: print(line) #---------------------------------- # Print the report to a logfile ? #---------------------------------- if (self.WRITE_LOG): for line in report: self.log_unit.write( line + '\n' ) # print_mins_and_maxes() #------------------------------------------------------------- def print_uniform_precip_data(self): ## precip_method = self.pp.method precip_method = 2 #--------------------------------------------------- # Precip method 1 is special and spatially uniform #--------------------------------------------------- if (precip_method == 1): rates = (self.pp.method1_rates * self.mps_to_mmph) #[m/s] -> [mm/hr] durs = self.pp.method1_durations nr =
np.size(rates)
numpy.size
#! /usr/bin/env python3 """ PPO: Proximal Policy Optimization Written by <NAME> (pat-coady.github.io) PPO uses a loss function and gradient descent to approximate Trust Region Policy Optimization (TRPO). See these papers for details: TRPO / PPO: https://arxiv.org/pdf/1502.05477.pdf (Schulman et al., 2016) Distributed PPO: https://arxiv.org/abs/1707.02286 (Heess et al., 2017) Generalized Advantage Estimation: https://arxiv.org/pdf/1506.02438.pdf And, also, this GitHub repo which was helpful to me during implementation: https://github.com/joschu/modular_rl This implementation learns policies for continuous environments in the OpenAI Gym (https://gym.openai.com/). Testing was focused on the MuJoCo control tasks. """ import gym import numpy as np from gym import wrappers from policy import Policy from value_function import NNValueFunction import scipy.signal from utils import Logger, Scaler from datetime import datetime import os import argparse import signal from osim.env import RunEnv from multiprocessing import Pool import multiprocessing import urllib import http.client import json, pickle import time class GracefulKiller: """ Gracefully exit program on CTRL-C """ def __init__(self): self.kill_now = False signal.signal(signal.SIGINT, self.exit_gracefully) signal.signal(signal.SIGTERM, self.exit_gracefully) def exit_gracefully(self, signum, frame): self.kill_now = True def init_gym(): """ Initialize gym environment, return dimension of observation and action spaces. Args: env_name: str environment name (e.g. "Humanoid-v1") Returns: 3-tuple gym environment (object) number of observation dimensions (int) number of action dimensions (int) """ # env = gym.make(env_name) env = RunEnv(visualize=False) obs_dim = env.observation_space.shape[0] act_dim = env.action_space.shape[0] return env, obs_dim, act_dim def run_episode(env, policy, scaler, animate=False): """ Run single episode with option to animate Args: env: ai gym environment policy: policy object with sample() method scaler: scaler object, used to scale/offset each observation dimension to a similar range animate: boolean, True uses env.render() method to animate episode Returns: 4-tuple of NumPy arrays observes: shape = (episode len, obs_dim) actions: shape = (episode len, act_dim) rewards: shape = (episode len,) unscaled_obs: useful for training scaler, shape = (episode len, obs_dim) """ pass # print("Episode run") # obs = env.reset(difficulty=2) # observes, actions, rewards, unscaled_obs = [], [], [], [] # done = False # step = 0.0 # scale, offset = scaler.get() # scale[-1] = 1.0 # don't scale time step feature # offset[-1] = 0.0 # don't offset time step feature # while not done: # if animate: # env.render() # obs = np.asarray(obs) # obs = obs.astype(np.float64).reshape((1, -1)) # obs = np.append(obs, [[step]], axis=1) # add time step feature # unscaled_obs.append(obs) # obs = (obs - offset) * scale # center and scale observations # observes.append(obs) # action = policy.sample(obs).reshape((1, -1)).astype(np.float64) # actions.append(action) # obs, reward, done, _ = env.step(action[0]) # if not isinstance(reward, float): # reward = np.asscalar(reward) # rewards.append(reward) # step += 1e-3 # increment time step feature # # trajectory = {'observes': np.concatenate(observes), # 'actions': np.concatenate(actions), # 'rewards': np.array(rewards, dtype=np.float64), # 'unscaled_obs': np.concatenate(unscaled_obs)} # return trajectory # # return (np.concatenate(observes), np.concatenate(actions), # # np.array(rewards, dtype=np.float64), np.concatenate(unscaled_obs)) def run_policy(env, policy, scaler, logger, episodes, cores, port): """ Run policy and collect data for a minimum of min_steps and min_episodes Args: env: ai gym environment policy: policy object with sample() method scaler: scaler object, used to scale/offset each observation dimension to a similar range logger: logger object, used to save stats from episodes episodes: total episodes to run Returns: list of trajectory dictionaries, list length = number of episodes 'observes' : NumPy array of states from episode 'actions' : NumPy array of actions from episode 'rewards' : NumPy array of (un-discounted) rewards from episode 'unscaled_obs' : NumPy array of (un-discounted) rewards from episode """ if cores > 1: conn_str = '127.0.0.1:' + str(port) conn = http.client.HTTPConnection(conn_str) headers = { "cache-control": "no-cache" } query = { "chk_dir": logger.log_dir, "episodes": episodes, "cores": cores } encoded_query = urllib.parse.urlencode(query) response = None while response != 'OK': conn.request("GET", "/get_episodes?" + encoded_query, headers=headers) res = conn.getresponse() response = json.loads(res.read())['Success'] trajectories = pickle.load(open(logger.log_dir + '/episodes_latest', 'rb')) else: trajectories = [run_episode(env, policy, scaler) for x in range(episodes)] total_steps = sum([t['observes'].shape[0] for t in trajectories]) unscaled = np.concatenate([t['unscaled_obs'] for t in trajectories]) scaler.update(unscaled) # update running statistics for scaling observations logger.log({'_MeanReward': np.mean([t['rewards'].sum() for t in trajectories]), 'MaxReward': np.max([t['rewards'].sum() for t in trajectories]), 'MinReward': np.min([t['rewards'].sum() for t in trajectories]), 'MeanLen': np.mean([len(t['rewards']) for t in trajectories]), 'Steps': total_steps}) return trajectories def discount(x, gamma): """ Calculate discounted forward sum of a sequence at each point """ return scipy.signal.lfilter([1.0], [1.0, -gamma], x[::-1])[::-1] def add_disc_sum_rew(trajectories, gamma): """ Adds discounted sum of rewards to all time steps of all trajectories Args: trajectories: as returned by run_policy() gamma: discount Returns: None (mutates trajectories dictionary to add 'disc_sum_rew') """ for trajectory in trajectories: if gamma < 0.999: # don't scale for gamma ~= 1 rewards = trajectory['rewards'] * (1 - gamma) else: rewards = trajectory['rewards'] disc_sum_rew = discount(rewards, gamma) trajectory['disc_sum_rew'] = disc_sum_rew def add_value(trajectories, val_func): """ Adds estimated value to all time steps of all trajectories Args: trajectories: as returned by run_policy() val_func: object with predict() method, takes observations and returns predicted state value Returns: None (mutates trajectories dictionary to add 'values') """ for trajectory in trajectories: observes = trajectory['observes'] values = val_func.predict(observes) trajectory['values'] = values def add_gae(trajectories, gamma, lam): """ Add generalized advantage estimator. https://arxiv.org/pdf/1506.02438.pdf Args: trajectories: as returned by run_policy(), must include 'values' key from add_value(). gamma: reward discount lam: lambda (see paper). lam=0 : use TD residuals lam=1 : A = Sum Discounted Rewards - V_hat(s) Returns: None (mutates trajectories dictionary to add 'advantages') """ for trajectory in trajectories: if gamma < 0.999: # don't scale for gamma ~= 1 rewards = trajectory['rewards'] * (1 - gamma) else: rewards = trajectory['rewards'] values = trajectory['values'] # temporal differences tds = rewards - values + np.append(values[1:] * gamma, 0) advantages = discount(tds, gamma * lam) trajectory['advantages'] = advantages def build_train_set(trajectories): """ Args: trajectories: trajectories after processing by add_disc_sum_rew(), add_value(), and add_gae() Returns: 4-tuple of NumPy arrays observes: shape = (N, obs_dim) actions: shape = (N, act_dim) advantages: shape = (N,) disc_sum_rew: shape = (N,) """ observes = np.concatenate([t['observes'] for t in trajectories]) actions = np.concatenate([t['actions'] for t in trajectories]) disc_sum_rew = np.concatenate([t['disc_sum_rew'] for t in trajectories]) advantages = np.concatenate([t['advantages'] for t in trajectories]) # normalize advantages advantages = (advantages - advantages.mean()) / (advantages.std() + 1e-6) return observes, actions, advantages, disc_sum_rew def log_batch_stats(observes, actions, advantages, disc_sum_rew, logger, episode): """ Log various batch statistics """ logger.log({'_mean_obs': np.mean(observes), '_min_obs': np.min(observes), '_max_obs': np.max(observes), '_std_obs': np.mean(np.var(observes, axis=0)), '_mean_act': np.mean(actions), '_min_act': np.min(actions), '_max_act': np.max(actions), '_std_act': np.mean(np.var(actions, axis=0)), '_mean_adv': np.mean(advantages), '_min_adv': np.min(advantages), '_max_adv': np.max(advantages), '_std_adv': np.var(advantages), '_mean_discrew': np.mean(disc_sum_rew), '_min_discrew':
np.min(disc_sum_rew)
numpy.min
import numpy as np import pandas as pd from bisect import bisect_right import torch from torch.utils.data import Dataset class WindowBasedSequenceDataset(Dataset): def __init__(self, seq, seq_ids, feat_cols=None, window_len=2, pos_reg_len_in_seq=2): self.seq = seq self.feat_cols = feat_cols if isinstance(seq_ids, str): self.seq_ids = seq[seq_ids].values else: self.seq_ids =
np.array(seq_ids)
numpy.array
import io as sysio import time import numba import numpy as np from scipy.interpolate import interp1d from det3d.ops.nms.nms_gpu import rotate_iou_gpu_eval from det3d.core.bbox import box_np_ops from det3d.datasets.utils.eval import box3d_overlap_kernel from det3d.datasets.utils.eval import box3d_overlap from det3d.datasets.utils.eval import calculate_iou_partly from det3d.datasets.utils.eval import prepare_data from det3d.datasets.utils.eval import compute_statistics_jit @numba.jit def get_thresholds(scores: np.ndarray, num_gt, num_sample_pts=41): scores.sort() scores = scores[::-1] current_recall = 0 thresholds = [] for i, score in enumerate(scores): l_recall = (i + 1) / num_gt if i < (len(scores) - 1): r_recall = (i + 2) / num_gt else: r_recall = l_recall if ((r_recall - current_recall) < (current_recall - l_recall)) and ( i < (len(scores) - 1) ): continue # recall = l_recall thresholds.append(score) current_recall += 1 / (num_sample_pts - 1.0) # print(len(thresholds), len(scores), num_gt) return thresholds def clean_data(gt_anno, dt_anno, current_class, difficulty): CLASS_NAMES = [ "car", "pedestrian", "bicycle", "truck", "bus", "trailer", "construction_vehicle", "motorcycle", "barrier", "traffic_cone", "cyclist", ] MIN_HEIGHT = [40, 25, 25] MAX_OCCLUSION = [0, 1, 2] MAX_TRUNCATION = [0.15, 0.3, 0.5] dc_bboxes, ignored_gt, ignored_dt = [], [], [] current_cls_name = CLASS_NAMES[current_class].lower() num_gt = len(gt_anno["name"]) num_dt = len(dt_anno["name"]) num_valid_gt = 0 for i in range(num_gt): bbox = gt_anno["bbox"][i] gt_name = gt_anno["name"][i].lower() height = bbox[3] - bbox[1] valid_class = -1 if gt_name == current_cls_name: valid_class = 1 elif ( current_cls_name == "Pedestrian".lower() and "Person_sitting".lower() == gt_name ): valid_class = 0 elif current_cls_name == "Car".lower() and "Van".lower() == gt_name: valid_class = 0 else: valid_class = -1 ignore = False if ( (gt_anno["occluded"][i] > MAX_OCCLUSION[difficulty]) or (gt_anno["truncated"][i] > MAX_TRUNCATION[difficulty]) or (height <= MIN_HEIGHT[difficulty]) ): ignore = True if valid_class == 1 and not ignore: ignored_gt.append(0) num_valid_gt += 1 elif valid_class == 0 or (ignore and (valid_class == 1)): ignored_gt.append(1) else: ignored_gt.append(-1) # for i in range(num_gt): if (gt_anno["name"][i] == "DontCare") or (gt_anno["name"][i] == "ignore"): dc_bboxes.append(gt_anno["bbox"][i]) for i in range(num_dt): if dt_anno["name"][i].lower() == current_cls_name: valid_class = 1 else: valid_class = -1 height = abs(dt_anno["bbox"][i, 3] - dt_anno["bbox"][i, 1]) if height < MIN_HEIGHT[difficulty]: ignored_dt.append(1) elif valid_class == 1: ignored_dt.append(0) else: ignored_dt.append(-1) return num_valid_gt, ignored_gt, ignored_dt, dc_bboxes def get_split_parts(num, num_part): same_part = num // num_part remain_num = num % num_part if remain_num == 0: return [same_part] * num_part else: return [same_part] * num_part + [remain_num] @numba.jit(nopython=True) def fused_compute_statistics( overlaps, pr, gt_nums, dt_nums, dc_nums, gt_datas, dt_datas, dontcares, ignored_gts, ignored_dets, metric, min_overlap, thresholds, compute_aos=False, ): gt_num = 0 dt_num = 0 dc_num = 0 for i in range(gt_nums.shape[0]): for t, thresh in enumerate(thresholds): overlap = overlaps[ dt_num : dt_num + dt_nums[i], gt_num : gt_num + gt_nums[i] ] gt_data = gt_datas[gt_num : gt_num + gt_nums[i]] dt_data = dt_datas[dt_num : dt_num + dt_nums[i]] ignored_gt = ignored_gts[gt_num : gt_num + gt_nums[i]] ignored_det = ignored_dets[dt_num : dt_num + dt_nums[i]] dontcare = dontcares[dc_num : dc_num + dc_nums[i]] tp, fp, fn, similarity, _ = compute_statistics_jit( overlap, gt_data, dt_data, ignored_gt, ignored_det, dontcare, metric, min_overlap=min_overlap, thresh=thresh, compute_fp=True, compute_aos=compute_aos, ) pr[t, 0] += tp pr[t, 1] += fp pr[t, 2] += fn if similarity != -1: pr[t, 3] += similarity gt_num += gt_nums[i] dt_num += dt_nums[i] dc_num += dc_nums[i] def eval_class_v3( gt_annos, dt_annos, current_classes, difficultys, metric, min_overlaps, compute_aos=False, z_axis=1, z_center=1.0, num_parts=50, ): """Kitti eval. support 2d/bev/3d/aos eval. support 0.5:0.05:0.95 coco AP. Args: gt_annos: dict, must from get_label_annos() in kitti_common.py dt_annos: dict, must from get_label_annos() in kitti_common.py current_class: int, 0: car, 1: pedestrian, 2: cyclist difficulty: int. eval difficulty, 0: easy, 1: normal, 2: hard metric: eval type. 0: bbox, 1: bev, 2: 3d min_overlap: float, min overlap. official: [[0.7, 0.5, 0.5], [0.7, 0.5, 0.5], [0.7, 0.5, 0.5]] format: [metric, class]. choose one from matrix above. num_parts: int. a parameter for fast calculate algorithm Returns: dict of recall, precision and aos """ assert len(gt_annos) == len(dt_annos) num_examples = len(gt_annos) split_parts = get_split_parts(num_examples, num_parts) split_parts = [i for i in split_parts if i != 0] rets = calculate_iou_partly( dt_annos, gt_annos, metric, num_parts, z_axis=z_axis, z_center=z_center ) overlaps, parted_overlaps, total_dt_num, total_gt_num = rets N_SAMPLE_PTS = 41 num_minoverlap = len(min_overlaps) num_class = len(current_classes) num_difficulty = len(difficultys) precision = np.zeros([num_class, num_difficulty, num_minoverlap, N_SAMPLE_PTS]) recall = np.zeros([num_class, num_difficulty, num_minoverlap, N_SAMPLE_PTS]) aos = np.zeros([num_class, num_difficulty, num_minoverlap, N_SAMPLE_PTS]) all_thresholds = np.zeros([num_class, num_difficulty, num_minoverlap, N_SAMPLE_PTS]) for m, current_class in enumerate(current_classes): for l, difficulty in enumerate(difficultys): rets = prepare_data( gt_annos, dt_annos, current_class, difficulty=difficulty, clean_data=clean_data, ) ( gt_datas_list, dt_datas_list, ignored_gts, ignored_dets, dontcares, total_dc_num, total_num_valid_gt, ) = rets for k, min_overlap in enumerate(min_overlaps[:, metric, m]): thresholdss = [] for i in range(len(gt_annos)): rets = compute_statistics_jit( overlaps[i], gt_datas_list[i], dt_datas_list[i], ignored_gts[i], ignored_dets[i], dontcares[i], metric, min_overlap=min_overlap, thresh=0.0, compute_fp=False, ) tp, fp, fn, similarity, thresholds = rets thresholdss += thresholds.tolist() thresholdss = np.array(thresholdss) thresholds = get_thresholds(thresholdss, total_num_valid_gt) thresholds = np.array(thresholds) # print(thresholds) all_thresholds[m, l, k, : len(thresholds)] = thresholds pr = np.zeros([len(thresholds), 4]) idx = 0 for j, num_part in enumerate(split_parts): gt_datas_part = np.concatenate( gt_datas_list[idx : idx + num_part], 0 ) dt_datas_part = np.concatenate( dt_datas_list[idx : idx + num_part], 0 ) dc_datas_part = np.concatenate(dontcares[idx : idx + num_part], 0) ignored_dets_part = np.concatenate( ignored_dets[idx : idx + num_part], 0 ) ignored_gts_part = np.concatenate( ignored_gts[idx : idx + num_part], 0 ) fused_compute_statistics( parted_overlaps[j], pr, total_gt_num[idx : idx + num_part], total_dt_num[idx : idx + num_part], total_dc_num[idx : idx + num_part], gt_datas_part, dt_datas_part, dc_datas_part, ignored_gts_part, ignored_dets_part, metric, min_overlap=min_overlap, thresholds=thresholds, compute_aos=compute_aos, ) idx += num_part for i in range(len(thresholds)): # recall[m, l, k, i] = pr[i, 0] / (pr[i, 0] + pr[i, 2]) precision[m, l, k, i] = pr[i, 0] / (pr[i, 0] + pr[i, 1]) if compute_aos: aos[m, l, k, i] = pr[i, 3] / (pr[i, 0] + pr[i, 1]) for i in range(len(thresholds)): precision[m, l, k, i] = np.max(precision[m, l, k, i:], axis=-1) if compute_aos: aos[m, l, k, i] = np.max(aos[m, l, k, i:], axis=-1) # use interp to calculate recall """ current_recalls = np.linspace(0, 1, 41) prec_unique, inds = np.unique(precision[m, l, k], return_index=True) current_recalls = current_recalls[inds] f = interp1d(prec_unique, current_recalls) precs_for_recall = np.linspace(0, 1, 41) max_prec = np.max(precision[m, l, k]) valid_prec = precs_for_recall < max_prec num_valid_prec = valid_prec.sum() recall[m, l, k, :num_valid_prec] = f(precs_for_recall[valid_prec]) """ ret_dict = { "recall": recall, # [num_class, num_difficulty, num_minoverlap, N_SAMPLE_PTS] "precision": precision, "orientation": aos, "thresholds": all_thresholds, "min_overlaps": min_overlaps, } return ret_dict def get_mAP2(prec): sums = 0 interval = 4 for i in range(0, prec.shape[-1], interval): sums = sums + prec[..., i] return sums / int(prec.shape[-1] / interval) * 100 def get_mAP(prec): sums = 0 for i in range(0, prec.shape[-1], 4): sums = sums + prec[..., i] return sums / 11 * 100 #def get_mAP(prec): # sums = 0 # for i in range(0, prec.shape[-1], 1): # sums = sums + prec[..., i] # return sums / 40 * 100 def do_eval_v2( gt_annos, dt_annos, current_classes, min_overlaps, compute_aos=False, difficultys=(0, 1, 2), z_axis=1, z_center=1.0, ): # min_overlaps: [num_minoverlap, metric, num_class] ret = eval_class_v3( gt_annos, dt_annos, current_classes, difficultys, 0, min_overlaps, compute_aos, z_axis=z_axis, z_center=z_center, ) # ret: [num_class, num_diff, num_minoverlap, num_sample_points] mAP_bbox = get_mAP(ret["precision"]) mAP_aos = None if compute_aos: mAP_aos = get_mAP(ret["orientation"]) ret = eval_class_v3( gt_annos, dt_annos, current_classes, difficultys, 1, min_overlaps, z_axis=z_axis, z_center=z_center, ) mAP_bev = get_mAP(ret["precision"]) ret = eval_class_v3( gt_annos, dt_annos, current_classes, difficultys, 2, min_overlaps, z_axis=z_axis, z_center=z_center, ) mAP_3d = get_mAP(ret["precision"]) return mAP_bbox, mAP_bev, mAP_3d, mAP_aos def do_eval_v3( gt_annos, dt_annos, current_classes, min_overlaps, compute_aos=False, difficultys=(0, 1, 2), z_axis=1, z_center=1.0, ): # min_overlaps: [num_minoverlap, metric, num_class] types = ["bbox", "bev", "3d"] metrics = {} for i in range(3): ret = eval_class_v3( gt_annos, dt_annos, current_classes, difficultys, i, min_overlaps, compute_aos, z_axis=z_axis, z_center=z_center, ) metrics[types[i]] = ret return metrics def do_coco_style_eval( gt_annos, dt_annos, current_classes, overlap_ranges, compute_aos, z_axis=1, z_center=1.0, ): # overlap_ranges: [range, metric, num_class] min_overlaps = np.zeros([10, *overlap_ranges.shape[1:]]) for i in range(overlap_ranges.shape[1]): for j in range(overlap_ranges.shape[2]): min_overlaps[:, i, j] = np.linspace(*overlap_ranges[:, i, j]) mAP_bbox, mAP_bev, mAP_3d, mAP_aos = do_eval_v2( gt_annos, dt_annos, current_classes, min_overlaps, compute_aos, z_axis=z_axis, z_center=z_center, ) # ret: [num_class, num_diff, num_minoverlap] mAP_bbox = mAP_bbox.mean(-1) mAP_bev = mAP_bev.mean(-1) mAP_3d = mAP_3d.mean(-1) if mAP_aos is not None: mAP_aos = mAP_aos.mean(-1) return mAP_bbox, mAP_bev, mAP_3d, mAP_aos def print_str(value, *arg, sstream=None): if sstream is None: sstream = sysio.StringIO() sstream.truncate(0) sstream.seek(0) print(value, *arg, file=sstream) return sstream.getvalue() def get_official_eval_result( gt_annos, dt_annos, current_classes, difficultys=[0, 1, 2], z_axis=1, z_center=1.0 ): """ gt_annos and dt_annos must contains following keys: [bbox, location, dimensions, rotation, score] """ overlap_mod = np.array( [ [0.7, 0.5, 0.5, 0.7, 0.7, 0.7, 0.7, 0.5, 0.5, 0.5, 0.5], [0.7, 0.5, 0.5, 0.7, 0.7, 0.7, 0.7, 0.5, 0.5, 0.5, 0.5], [0.7, 0.5, 0.5, 0.7, 0.7, 0.7, 0.7, 0.5, 0.5, 0.5, 0.5], ] ) overlap_easy = np.array( [ [0.7, 0.5, 0.5, 0.7, 0.7, 0.7, 0.7, 0.5, 0.25, 0.25, 0.5], [0.5, 0.25, 0.25, 0.5, 0.5, 0.5, 0.5, 0.25, 0.25, 0.25, 0.25], [0.5, 0.25, 0.25, 0.5, 0.5, 0.5, 0.5, 0.25, 0.25, 0.25, 0.25], ] ) min_overlaps =
np.stack([overlap_mod, overlap_easy], axis=0)
numpy.stack
import numpy as np import sys def evaluate_linear_layer(layer, state): return np.dot(layer, state) def evaluate_relu(state): return (state > 0) * state def evaluate_malleated_relu(state, shift=20): state = state + shift state = (state > 0) * state state = state - shift return state def evaluate_masked_relu(state, mask_start, mask_stop, shift=20): mask = np.full(state.shape, -shift) mask[mask_start:mask_stop] = shift state = state + mask state = (state > 0) * state mask = (mask > 0) * mask state = state - mask return state def evaluate_network_upto(linear_layers, state, stop_at): for (i, layer) in enumerate(linear_layers[:stop_at]): state = evaluate_linear_layer(layer, state) # only perform ReLU if we're not the last layer if i != len(layer) - 1: state = evaluate_relu(state) return state def evaluate_network_after_malleation(linear_layers, state, start_at, shift=20): for (i, layer) in enumerate(linear_layers[start_at:]): state = evaluate_linear_layer(layer, state) # only perform ReLU if we're not the last layer if i != len(layer) - 1: state = evaluate_malleated_relu(state, shift) return state def unit_vector(dim, i): vec = np.zeros(dim) vec[i] = 1.0 return vec def extract_network(linear_layers): starting_dim = linear_layers[0].shape[1] num_classes = linear_layers[-1].shape[0] initial_state = np.zeros((starting_dim, 1)) extracted_layers = [] num_queries = 0 # We iterate in reverse. for (i, layer) in list(enumerate(linear_layers))[::-1]: (num_rows, num_cols) = layer.shape extracted_layer =
np.zeros(layer.shape)
numpy.zeros
"""Module for interactive plotting of interferograms. """ import os from datetime import date, datetime import logging from multiprocessing.pool import Pool from scipy.ndimage import gaussian_filter import matplotlib.cm as cm import matplotlib.dates as mpl_dates import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap import numpy as np import yaml from . import inversion from . import insar from . import workflow from . import nimrod from . import util from . import config from . import train import argparse plt.style.use('ggplot') params = { 'axes.labelsize': 9, 'font.size': 9, 'xtick.labelsize': 8, 'ytick.labelsize': 8, 'font.family': 'Source Sans Pro', } plt.rcParams.update(params) COAST_DETAIL = 'f' FIGSIZE = None DPI = None def _parse_unwrapped_ifg_args(args): if args.time_series: plot_time_series_ifg(args.master, args.slave, args.output) else: kind = 'original' if args.resampled: kind = 'resampled' if args.corrected: kind = 'corrected' plot_unwrapped_ifg(args.master, args.slave, args.output, kind) def plot_unwrapped_ifg(master_date, slave_date, fname=None, kind='original'): """ master_date, slc_date : str or date If a string, should be in the format '%Y%m%d'. fname : str, opt The path to save the image to or `None`. If set, interactive plotting will be disabled. kind : str, opt One of 'original', 'resampled', 'corrected' meaning to plot the original, resampled or corrected interferogram. Returns ------- None """ if isinstance(master_date, date): master_date = master_date.strftime("%Y%m%d") if isinstance(slave_date, date): slave_date = slave_date.strftime("%Y%m%d") logging.info('Plotting master/slave pairing: {} / {}'.format(master_date, slave_date)) ifg_name = '{}_{}'.format(slave_date, master_date) ifg_path = '' ifg = None if kind == 'resampled': ifg_path = os.path.join(config.SCRATCH_DIR, 'uifg_resampled', ifg_name + '.npy') data = np.load(ifg_path) lons, lats = workflow.read_grid_from_file(os.path.join(config.SCRATCH_DIR, 'grid.txt')) ifg = insar.InSAR(lons, lats, data, datetime.strptime(master_date, '%Y%m%d').date(), datetime.strptime(slave_date, '%Y%m%d').date()) elif kind == 'original': ifg_path = os.path.join(config.UIFG_DIR, ifg_name + '.nc') ifg = insar.InSAR.from_netcdf(ifg_path) elif kind == 'corrected': ifg_path = os.path.join(config.SCRATCH_DIR, 'corrected_ifg', ifg_name + '.nc') ifg = insar.InSAR.from_netcdf(ifg_path) else: raise ValueError('Unknown plotting mode {}'.format(kind)) fig, _ = plot_ifg(ifg) if fname: fig.savefig(fname, bbox_inches='tight') plt.close() else: plt.show() plt.close() return None def plot_ifg(ifg, axes=None, center_zero=True): """Plot an insar.InSAR instance or an insar.SAR instance. Returns a figure handle""" if axes: fig = axes.get_figure() else: fig = plt.figure(dpi=DPI, figsize=FIGSIZE) axes = fig.add_subplot(1, 1, 1) bmap = Basemap(llcrnrlon=ifg.lons[0], llcrnrlat=ifg.lats[0], urcrnrlon=ifg.lons[-1], urcrnrlat=ifg.lats[-1], resolution=COAST_DETAIL, projection='merc', ax=axes) parallels = np.linspace(ifg.lats[0], ifg.lats[-1], 5) meridians = np.linspace(ifg.lons[0], ifg.lons[-1], 5) bmap.drawcoastlines() bmap.drawparallels(parallels, labels=[True, False, False, False], fmt="%.2f", fontsize=plt.rcParams['ytick.labelsize']) bmap.drawmeridians(meridians, labels=[False, False, False, True], fmt="%.2f", fontsize=plt.rcParams['xtick.labelsize']) bmap.drawmapboundary() vmax = (np.absolute(ifg.data).max()) vmin = vmax * -1 lon_mesh, lat_mesh = np.meshgrid(ifg.lons, ifg.lats) image = None if center_zero is True: image = bmap.pcolormesh(lon_mesh, lat_mesh, ifg.data, latlon=True, cmap=cm.RdBu_r, vmin=vmin, vmax=vmax) else: image = bmap.pcolormesh(lon_mesh, lat_mesh, ifg.data, latlon=True, cmap=cm.RdBu_r,) cbar = fig.colorbar(image, pad=0.07, ax=axes) cbar.set_label('LOS Delay / cm') if isinstance(ifg, insar.InSAR): title = 'Unwrapped Interferogram\nMaster: {0}\nSlave: {1}'.format( ifg.master_date.strftime('%Y-%m-%d'), ifg.slave_date.strftime('%Y-%m-%d')) axes.set_title(title) else: title = 'SAR Image ({})'.format(ifg.date.strftime('%Y-%m-%d')) axes.set_title(title) fig.tight_layout() return fig, bmap def plot_time_series_ifg(master_date, slave_date, fname=None): if isinstance(master_date, date): master_date = master_date.strftime('%Y%m%d') if isinstance(slave_date, date): slave_date = slave_date.strftime('%Y%m%d') lons, lats = workflow.read_grid_from_file(os.path.join(config.SCRATCH_DIR, 'grid.txt')) ifg_ts = np.load(os.path.join(config.SCRATCH_DIR, 'uifg_ts', master_date + '.npy'), mmap_mode='r') slave_date_idx = 0 with open(os.path.join(config.SCRATCH_DIR, 'uifg_ts', master_date + '.yml')) as f: ts_date_indexes = yaml.safe_load(f) slave_date_date = datetime.strptime(slave_date, '%Y%m%d').date() slave_date_idx = ts_date_indexes.index(slave_date_date) ifg = insar.InSAR(lons, lats, ifg_ts[:, :, slave_date_idx], datetime.strptime(master_date, '%Y%m%d').date(), datetime.strptime(slave_date, '%Y%m%d').date()) fig, _ = plot_ifg(ifg) if fname: fig.savefig(fname, bbox_inches='tight') else: plt.show() plt.close() def _plot_dem_error(args): if args.master_date: plot_dem_error(args.master_date, args.output) else: plot_dem_error(config.MASTER_DATE.date(), args.output) def plot_dem_error(master_date, fname=None): if isinstance(master_date, date): master_date = master_date.strftime('%Y%m%d') dem_error = np.load(os.path.join(config.SCRATCH_DIR, 'dem_error', master_date + '.npy'), mmap_mode='r') lons, lats = workflow.read_grid_from_file(os.path.join(config.SCRATCH_DIR, 'grid.txt')) sar = insar.SAR(lons, lats, dem_error, datetime.strptime(master_date, '%Y%m%d').date()) fig, _ = plot_ifg(sar) axes = fig.get_axes()[0] axes.set_title('DEM Error\n{}' .format(sar.date.strftime('%Y-%m-%d'))) if fname: fig.savefig(fname, bbox_inches='tight') else: plt.show() def _plot_master_atmosphere(args): """Plot the master atmosphere from the command line.""" if args.master_date: plot_master_atmosphere(args.master_date, args.output) else: plot_master_atmosphere(config.MASTER_DATE.date(), args.output) def plot_master_atmosphere(master_date, fname=None): """Plot the master atmosphere for a given date.""" if isinstance(master_date, date): master_date = master_date.strftime('%Y%m%d') # Load the master atmosphere master_atmosphere = np.load(os.path.join(config.SCRATCH_DIR, 'master_atmosphere', master_date + '.npy'), mmap_mode='r') lons, lats = workflow.read_grid_from_file(os.path.join(config.SCRATCH_DIR, 'grid.txt')) sar = insar.SAR(lons, lats, master_atmosphere, datetime.strptime(master_date, '%Y%m%d').date()) fig, _ = plot_ifg(sar) axes = fig.get_axes()[0] if fname: fig.savefig(fname, bbox_inches='tight') else: axes.set_title('Master Atmosphere\n{}' .format(sar.date.strftime('%Y-%m-%d'))) plt.show() def _plot_delay_rainfall_scatter(args): date = args.date or config.MASTER_DATE if isinstance(date, str): date = datetime.strptime(date, '%Y%m%d') date = datetime(date.year, date.month, date.day, config.MASTER_DATE.hour, config.MASTER_DATE.minute) plot_delay_rainfall_scatter(date, args.output) def plot_delay_rainfall_scatter(date, fname=None): atmos_path = os.path.join(config.SCRATCH_DIR, 'master_atmosphere', date.strftime('%Y%m%d') + '.npy') _, wr_path = workflow.find_closest_weather_radar_files(date) atmos = np.load(atmos_path) wr = nimrod.Nimrod.from_netcdf(wr_path) # Load in the grid and resample the weather radar image to it. lons, lats = workflow.read_grid_from_file(os.path.join(config.SCRATCH_DIR, 'grid.txt')) lon_min, lon_max = lons.min(), lons.max() lat_min, lat_max = lats.min(), lats.max() lon_bounds = (lon_min - 0.5, lon_max + 0.5) lat_bounds = (lat_min - 0.5, lat_max + 0.5) wr.clip(lon_bounds, lat_bounds) wr.interp(lons, lats, method='nearest') fig = plt.figure(dpi=DPI, figsize=FIGSIZE) axes = fig.add_subplot(1, 1, 1) axes.plot(wr.data.ravel(), atmos.ravel(), 'o', markersize=1) axes.set_xlabel(r'Rainfall Rate / mm hr$^{-1}$') axes.set_ylabel(r'LOS Delay / cm') axes.set_title('Rainfall Scatter ({})' .format(date.strftime('%Y-%m-%d'))) if fname: fig.savefig(fname, bbox_inches='tight') else: plt.show() plt.close() def plot_wr(wr, axes=None): """Plot a `nimrod.Nimrod` instance. Returns a figure handle and a basemap object.""" if axes: fig = axes.get_figure() else: fig = plt.figure(dpi=DPI, figsize=FIGSIZE) axes = fig.add_subplot(1, 1, 1) bmap = Basemap(llcrnrlon=wr.lons[0], llcrnrlat=wr.lats[0], urcrnrlon=wr.lons[-1], urcrnrlat=wr.lats[-1], resolution=COAST_DETAIL, projection='merc', ax=axes) parallels = np.linspace(wr.lats[0], wr.lats[-1], 5) meridians = np.linspace(wr.lons[0], wr.lons[-1], 5) bmap.drawcoastlines() bmap.drawparallels(parallels, labels=[True, False, False, False], fmt="%.2f", fontsize=plt.rcParams['ytick.labelsize']) bmap.drawmeridians(meridians, labels=[False, False, False, True], fmt="%.2f", fontsize=plt.rcParams['xtick.labelsize']) bmap.drawmapboundary() lon_mesh, lat_mesh = np.meshgrid(wr.lons, wr.lats) image = bmap.pcolormesh(lon_mesh, lat_mesh, np.ma.masked_values(wr.data, 0), latlon=True, cmap=cm.Spectral_r, vmin=0) cbar = fig.colorbar(image, pad=0.07, ax=axes) cbar.set_label(r'Rainfall / mm hr$^{-1}$') if wr.interpolated: title = ('Rainfall Radar Image\n({0})[I]' .format(wr.date.strftime('%Y-%m-%dT%H:%M'))) else: title = ('Rainfall Radar Image\n({0})' .format(wr.date.strftime('%Y-%m-%dT%H:%M'))) axes.set_title(title) fig.tight_layout() return (fig, bmap) def _plot_weather(args): if args.date: plot_weather(args.date, args.full, args.output) else: plot_weather(config.MASTER_DATE, args.full, args.output) def plot_weather(wr_date, full=False, fname=None): """Plot a weather radar image. """ if isinstance(wr_date, str): wr_date = datetime.strptime(wr_date, '%Y%m%dT%H%M') # Load the weather radar image wr_before, wr_after = workflow.find_closest_weather_radar_files(wr_date) if wr_before != wr_after: logging.warning('Found two different radar images near %s. Interpolating', wr_date) wr_before = nimrod.Nimrod.from_netcdf(wr_before) wr_after = nimrod.Nimrod.from_netcdf(wr_after) # wr = nimrod.Nimrod.interp_radar(wr_before, wr_after, wr_date) wr = wr_after if not full: # Clip image to target region lon_bounds = (config.REGION['lon_min'], config.REGION['lon_max']) lat_bounds = (config.REGION['lat_min'], config.REGION['lat_max']) wr.clip(lon_bounds, lat_bounds) fig, _ = plot_wr(wr) if fname: fig.savefig(fname, bbox_inches='tight') else: plt.show() plt.close() def _plot_profile(args): date = args.date or config.MASTER_DATE if isinstance(date, str): date = datetime.strptime(date, '%Y%m%d') date = datetime(date.year, date.month, date.day, config.MASTER_DATE.hour, config.MASTER_DATE.minute) plot_profile(date, args.longitude, args.blur, args.output) def plot_profile(master_date, longitude, filter_std, fname=None): if isinstance(master_date, str): master_date = datetime.strptime(master_date, '%Y%m%dT%H%M') fig = plt.figure(dpi=DPI, figsize=FIGSIZE) sar_ax = plt.subplot2grid((2, 2), (0, 0)) wr_ax = plt.subplot2grid((2, 2), (0, 1)) profile_ax = plt.subplot2grid((2, 2), (1, 0), colspan=2) # Load master atmosphere for master date. master_atmosphere = np.load(os.path.join(config.SCRATCH_DIR, 'master_atmosphere', master_date.strftime('%Y%m%d') + '.npy'), mmap_mode='r') lons, lats = workflow.read_grid_from_file(os.path.join(config.SCRATCH_DIR, 'grid.txt')) sar = insar.SAR(lons, lats, master_atmosphere, master_date) # Load weather radar image, clip and resample to IFG resolution. lon_bounds = (np.amin(sar.lons), np.amax(sar.lons)) lat_bounds = (np.amin(sar.lats), np.amax(sar.lats)) _, wr_after_path = workflow.find_closest_weather_radar_files(master_date) wr = nimrod.Nimrod.from_netcdf(wr_after_path) wr.clip(lon_bounds, lat_bounds) wr.interp(sar.lons, sar.lats, method='nearest') wr.data = gaussian_filter(wr.data, filter_std) # Plot and configure sar _, bmap_sar = plot_ifg(sar, axes=sar_ax) sar_ax.set_title('Master Atmosphere\n({})'.format(master_date.strftime('%Y-%m-%dT%H:%M'))) bmap_sar.plot([longitude, longitude], lat_bounds, latlon=True, linewidth=1, color='white', ax=sar_ax) bmap_sar.plot([longitude, longitude], lat_bounds, latlon=True, linewidth=0.5, ax=sar_ax) # Plot and configure weather radar image _, bmap_wr = plot_wr(wr, axes=wr_ax) bmap_wr.plot([longitude, longitude], lat_bounds, latlon=True, linewidth=1, color='white', ax=wr_ax) bmap_wr.plot([longitude, longitude], lat_bounds, latlon=True, linewidth=0.5, ax=wr_ax) # Plot the profile ## LOS Delay sar_lon_idx = np.argmin(np.absolute(sar.lons - longitude)) wr_lon_idx = np.argmin(np.absolute(wr.lons - longitude)) profile_ax.plot(sar.lats, sar.data[:, sar_lon_idx], color='#67a9cf') profile_ax.tick_params('y', colors='#67a9cf') profile_ax.set_ylabel('LOS Delay / cm') profile_ax.set_xlabel(r'Latitude / $\degree$') profile_ax.grid(b=False, axis='y') ## Rainfall profile_ax_rain = profile_ax.twinx() profile_ax_rain.plot(wr.lats, wr.data[:, wr_lon_idx], color='#ef8a62') profile_ax_rain.tick_params('y', colors='#ef8a62') profile_ax_rain.set_ylabel(r'Rainfall / mm hr$^{-1}$') profile_ax_rain.grid(b=False) if fname: fig.savefig(fname, bbox_inches='tight') else: plt.show() plt.close() def _plot_baseline_plot(args): if args.master_date: plot_baseline_plot(args.master_date, args.output) else: plot_baseline_plot(config.MASTER_DATE, args.output) def plot_baseline_plot(master_date, fname=None): """Make a baseline plot using the baselines in config.BPERP_FILE_PATH""" if isinstance(master_date, str): master_date = datetime.strptime(master_date, '%Y%m%d').date() if isinstance(master_date, datetime): master_date = master_date.date() baseline_list = inversion.calculate_inverse_bperp(config.BPERP_FILE_PATH, master_date) baseline_list = list(baseline_list) slave_dates = [date for (date, _) in baseline_list] baselines = [baseline for (_, baseline) in baseline_list] bperp_contents = inversion.read_bperp_file(config.BPERP_FILE_PATH) ifg_master_dates = [date for (date, _, _) in bperp_contents] ifg_slave_dates = [date for (_, date, _) in bperp_contents] slc_dates = sorted(set(ifg_master_dates + ifg_slave_dates)) # Set up the plot fig = plt.figure(dpi=DPI, figsize=FIGSIZE) axes = fig.add_subplot(1, 1, 1) # Plot lines connecting dates for interferograms line_color = axes._get_lines.get_next_color() line = None for (master, slave) in zip(ifg_master_dates, ifg_slave_dates): master_perp_base = baselines[slave_dates.index(master)] slave_perp_base = baselines[slave_dates.index(slave)] line = axes.plot_date([master, slave], [master_perp_base, slave_perp_base], '-', linewidth=0.5, color=line_color, label='Interferogram Pairing') # Plot Acquisitions xs = [] # Time baseline in days ys = [] # Perpendicular baseline in metres for slc_date in slc_dates: xs += [slc_date] ys += [baselines[slave_dates.index(slc_date)]] points = axes.plot_date(xs, ys, label='Acquisition') # Axes styling axes.legend(handles=[points[0], line[0]]) axes.set_xlabel('Date') axes.set_ylabel('Perpendicular Baseline / m') axes.set_title('Baseline Plot') axes.xaxis.set_major_formatter(mpl_dates.DateFormatter('%Y-%b')) if fname: fig.savefig(fname, bbox_inches='tight') else: plt.show() plt.close() def _plot_train_sar_delay(args): if not args.hydrostatic and not args.wet and not args.total: # TODO: Print to stderr print("Error, must specify one of hydro, wet or total") exit(1) date = args.date if args.date else config.MASTER_DATE if args.hydrostatic: output = args.output if output: comps = os.path.splitext(output) output = comps[0] + '_hydro' + comps[1] plot_train_sar_delay(date, kind='hydro', output=output) if args.wet: output = args.output if output: comps = os.path.splitext(output) output = comps[0] + '_wet' + comps[1] plot_train_sar_delay(date, kind='wet', output=output) if args.total: output = args.output if output: comps = os.path.splitext(output) output = comps[0] + '_total' + comps[1] plot_train_sar_delay(date, kind='total', output=output) def plot_train_sar_delay(master_date, kind='total', output=None): """Plot the slant delay for a date computed from ERA by TRAIN Arguments --------- master_date : date The date to plot the delay for. kind : str, opt The type of delay to plot. One of 'hydro', 'wet' or 'total' (default). output : str, opt Name of the file to save the plot to. """ if isinstance(master_date, str): master_date = datetime.strptime(master_date, '%Y%m%d').date() master_datestamp = master_date.strftime('%Y%m%d') era_dir = workflow.get_train_era_slant_dir() delay_fpath = os.path.join(era_dir, master_datestamp + '.mat') era_delays = train.load_train_slant_delay(delay_fpath) data = np.zeros(era_delays['wet_delay'].shape) if kind == 'wet': data[:, :] = era_delays['wet_delay'] elif kind == 'hydro': data[:, :] = era_delays['hydro_delay'] elif kind == 'total': data[:, :] = era_delays['wet_delay'] + era_delays['hydro_delay'] else: raise KeyError('Unknown kind {}'.format(kind)) # Mask the data to remove NaNs data = np.ma.masked_invalid(data) # Get a mask for water from one of the interferograms ifg_path = os.path.join(config.SCRATCH_DIR, 'master_atmosphere', config.MASTER_DATE.strftime('%Y%m%d') + '.npy') ifg_data = np.load(ifg_path) ifg_data = np.ma.masked_values(ifg_data, 0) # Combine masks data.mask = ifg_data.mask | data.mask sar = insar.SAR(era_delays['lons'], era_delays['lats'], data, master_date) fig, bmap = plot_ifg(sar, center_zero=False) title_map = {'total': 'Total', 'hydro': 'Hydrostatic', 'wet': 'Wet'} title_str = "{kind:s} Delay\n{date:}".format(kind=title_map[kind], date=master_date) axes = fig.get_axes()[0] axes.set_title(title_str) if output: fig.savefig(output, bbox_inches='tight') else: plt.show() plt.close() def _plot_train_ifg_delay(args): if not args.hydrostatic and not args.wet and not args.total: # TODO: Print to stderr print("Error, must specify one or more of hydro, wet or total") exit(1) master_date = args.master_date slave_date = args.slave_date if args.hydrostatic: output = args.output if output: comps = os.path.splitext(output) output = comps[0] + '_hydro' + comps[1] plot_train_ifg_delay(master_date, slave_date, kind='hydro', output=output) if args.wet: output = args.output if output: comps = os.path.splitext(output) output = comps[0] + '_wet' + comps[1] plot_train_ifg_delay(master_date, slave_date, kind='wet', output=output) if args.total: output = args.output if output: comps = os.path.splitext(output) output = comps[0] + '_total' + comps[1] plot_train_ifg_delay(master_date, slave_date, kind='total', output=output) def plot_train_ifg_delay(master_date, slave_date, kind='total', output=None): """Plot the interferometric delay for a date computed from ERA by TRAIN Arguments --------- master_date : date The date to plot the delay for. slave_date : date The slave date to plot the delay for. kind : str, opt The type of delay to plot. One of 'hydro', 'wet' or 'total' (default). output : str, opt Name of the file to save the plot to. """ if isinstance(master_date, str): master_date = datetime.strptime(master_date, '%Y%m%d').date() if isinstance(slave_date, str): slave_date = datetime.strptime(slave_date, '%Y%m%d').date() train_dir = os.path.join(config.SCRATCH_DIR, 'train') correction_fpath = os.path.join(train_dir, 'tca2.mat') dates_fpath = os.path.join(train_dir, 'ifgday.mat') grid_fpath = os.path.join(train_dir, 'll.mat') corrections = train.load_train_ifg_delay(correction_fpath, grid_fpath, dates_fpath, master_date, slave_date) data = np.zeros(corrections['wet_delay'].shape) if kind == 'hydro': data[:, :] = corrections['hydro_delay'] elif kind == 'wet': data[:, :] = corrections['wet_delay'] elif kind == 'total': data[:, :] = corrections['total_delay'] else: raise KeyError('"kind" was not one of hydro, wet or total') # Mask invalid data data = np.ma.masked_invalid(data) # Get a mask for water from the interferogram ifg_path = os.path.join(config.SCRATCH_DIR, 'uifg_resampled', (slave_date.strftime('%Y%m%d') + '_' + master_date.strftime('%Y%m%d') + '.npy')) ifg_data = np.load(ifg_path) ifg_data = np.ma.masked_values(ifg_data, 0) # Combine masks data.mask = ifg_data.mask | data.mask ifg = insar.InSAR(corrections['lons'], corrections['lats'], data, master_date, slave_date) fig, bmap = plot_ifg(ifg) axes = fig.get_axes()[0] title_map = {'wet': 'Wet', 'hydro': 'Hydrostatic', 'total': 'Total'} title = '{:s} Delay\nMaster: {:s}\nSlave: {:s}'.format(title_map[kind], master_date.strftime('%Y-%m-%d'), slave_date.strftime('%Y-%m-%d')) axes.set_title(title) if output: fig.savefig(output, bbox_inches='tight') else: plt.show() plt.close() def _plot_sar_delay(args): date = args.date if args.date else config.MASTER_DATE kinds = [] if args.hydrostatic: kinds += ['dry'] if args.wet: kinds += ['wet'] if args.liquid: kinds += ['liquid'] if args.total: kinds += ['total'] for kind in kinds: plot_sar_delay(date, kind, args.zenith, args.output) def plot_sar_delay(date, kind='total', zenith=False, output=None): if isinstance(date, str): date = datetime.strptime(date, '%Y%m%d').date() if kind not in ('total', 'dry', 'wet', 'liquid'): raise KeyError('Unknown kind {}'.format(kind)) datestamp = date.strftime('%Y%m%d') delay_dir = "" if zenith: delay_dir = os.path.join(config.SCRATCH_DIR, 'zenith_delays') else: delay_dir = os.path.join(config.SCRATCH_DIR, 'slant_delays') delay_file = os.path.join(delay_dir, datestamp + '_' + kind + '.npy') delay = np.load(delay_file) lons, lats = workflow.read_grid_from_file(os.path.join(config.SCRATCH_DIR, 'grid.txt')) # Get a mask for water from one of the interferograms ifg_path = os.path.join(config.SCRATCH_DIR, 'master_atmosphere', config.MASTER_DATE.strftime('%Y%m%d') + '.npy') ifg_data = np.load(ifg_path) ifg_data = np.ma.masked_values(ifg_data, 0) delay =
np.ma.masked_invalid(delay)
numpy.ma.masked_invalid
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import numpy as np from pycuda import gpuarray import pycuda.driver as cuda from svirl import config as cfg from svirl.storage import GArray class Vars(object): """This class contains setters and getters for solution variables order parameter and vector potential""" def __init__(self, Par, mesh): self.par = Par self.mesh = mesh # Persistent storage: Primary variables that are solved for self._psi = None self._vp = None # TODO: this will be renamed to self._a eventually # Temp storage: Stored on cells, nodes, and edges. # Used in observables and other classes and fairly general purpose self._tmp_node_var = None self._tmp_edge_var = None self._tmp_cell_var = None # Temp Storage: Allocated only for reductions self._tmp_psi_real = None self._tmp_A_real = None # copied from variables/parameters.py self.solveA = np.bool(not np.isposinf(cfg.gl_parameter)) if cfg.order_parameter == 'random': self.order_parameter = 1.0 self.randomize_order_parameter(level = cfg.random_level, seed = cfg.random_seed) else: self.order_parameter = cfg.order_parameter # set order parameter manually # vector potential is set up here instead of its setter because # we don't plan on supporting setter for it shapes = [(cfg.Nxa, cfg.Nya), (cfg.Nxb, cfg.Nyb)] self._vp = GArray(shape = shapes, dtype = cfg.dtype) def __del__(self): pass @property def order_parameter(self): self._psi.sync() psi = self._psi.get_h().copy() return psi @order_parameter.setter def order_parameter(self, order_parameter): if isinstance(order_parameter, (np.complexfloating, complex, np.floating, float, np.integer, int)): order_parameter = cfg.dtype_complex(order_parameter) * np.ones((cfg.Nx, cfg.Ny), cfg.dtype_complex) assert order_parameter.shape == (cfg.Nx, cfg.Ny) if self._psi is None: self._psi = GArray(like = order_parameter) else: self._psi.set_h(order_parameter) self.set_order_parameter_to_zero_outside_material() self._psi.sync() def order_parameter_h(self): return self._psi.get_d_obj() def set_order_parameter_to_zero_outside_material(self): if self._psi is None or not self.mesh.have_material_tiling(): return mt_at_nodes = self.mesh._get_material_tiling_at_nodes() psi = self._psi.get_h() psi[~mt_at_nodes] = 0.0 self._psi.need_htod_sync() self._psi.sync() def randomize_order_parameter(self, level=1.0, seed=None): """Randomizes order parameter: absolute value *= 1 - level*rand phase += level*pi*(2.0*rand()-1.0), where rand is uniformly distributed in [0, 1] """ assert 0.0 <= level <= 1.0 self._psi.sync() if seed is not None: np.random.seed(seed) data = (1.0 - level*np.random.rand(cfg.N)) * np.exp(level * 1.0j*np.pi*(2.0*np.random.rand(cfg.N) - 1.0)) self._psi.set_h(data) self._psi.sync() @property def vector_potential(self): if self._vp is None: return (np.zeros((cfg.Nxa, cfg.Nya), dtype=cfg.dtype), np.zeros((cfg.Nxb, cfg.Nyb), dtype=cfg.dtype)) self._vp.sync() return self._vp.get_vec_h() @vector_potential.setter def vector_potential(self, vector_potential): a, b = vector_potential self._vp.set_vec_h(a, b) self._vp.sync() def vector_potential_h(self): if self._vp is not None: return self._vp.get_d_obj() return
np.uintp(0)
numpy.uintp
# coding=utf-8 # Copyright 2021 The Deeplab2 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. """Visualizes and stores results of a panoptic-deeplab model.""" import os.path from typing import Any, Dict, List, Text import numpy as np import tensorflow as tf from deeplab2 import common from deeplab2.data import coco_constants from deeplab2.data import dataset from deeplab2.trainer import vis_utils # The format of the labels. _IMAGE_FORMAT = '%06d_image' _CENTER_LABEL_FORMAT = '%06d_center_label' _OFFSET_LABEL_FORMAT = '%06d_offset_label' _PANOPTIC_LABEL_FORMAT = '%06d_panoptic_label' _SEMANTIC_LABEL_FORMAT = '%06d_semantic_label' # The format of the predictions. _INSTANCE_PREDICTION_FORMAT = '%06d_instance_prediction' _CENTER_HEATMAP_PREDICTION_FORMAT = '%06d_center_prediction' _OFFSET_PREDICTION_RGB_FORMAT = '%06d_offset_prediction_rgb' _PANOPTIC_PREDICTION_FORMAT = '%06d_panoptic_prediction' _SEMANTIC_PREDICTION_FORMAT = '%06d_semantic_prediction' # The format of others. _ANALYSIS_FORMAT = '%06d_semantic_error' # Conversion from train id to eval id. _CITYSCAPES_TRAIN_ID_TO_EVAL_ID = ( 7, 8, 11, 12, 13, 17, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 31, 32, 33, 0 ) _COCO_TRAIN_ID_TO_EVAL_ID = coco_constants.get_id_mapping_inverse() def _convert_train_id_to_eval_id( prediction: np.ndarray, dataset_name: str) -> np.ndarray: """Converts the predicted label for evaluation. There are cases where the training labels are not equal to the evaluation labels. This function is used to perform the conversion so that we could evaluate the results on the evaluation server. Args: prediction: Semantic segmentation prediction. dataset_name: Dataset name. Returns: Semantic segmentation prediction whose labels have been changed. Raises: ValueError: If the dataset is not supported. """ if 'cityscapes' in dataset_name: train_id_to_eval_id = _CITYSCAPES_TRAIN_ID_TO_EVAL_ID elif 'coco' in dataset_name: train_id_to_eval_id = _COCO_TRAIN_ID_TO_EVAL_ID else: raise ValueError( 'Unsupported dataset %s for converting semantic class IDs.' % dataset_name) length = np.maximum(256, len(train_id_to_eval_id)) to_eval_id_map = np.zeros((length), dtype=prediction.dtype) dataset_ids = np.asarray( train_id_to_eval_id, dtype=prediction.dtype) to_eval_id_map[:len(train_id_to_eval_id)] = dataset_ids return to_eval_id_map[prediction] def _get_fg_mask(label_map: np.ndarray, thing_list: List[int]) -> np.ndarray: fg_mask = np.zeros_like(label_map, np.bool) for class_id in
np.unique(label_map)
numpy.unique
# Licensed under a 3-clause BSD style license - see LICENSE.rst """First set of tests.""" from __future__ import (absolute_import, unicode_literals, division, print_function) import maltpynt as mp import numpy as np import logging import os import unittest import pytest MP_FILE_EXTENSION = mp.io.MP_FILE_EXTENSION logging.basicConfig(filename='MP.log', level=logging.DEBUG, filemode='w') curdir = os.path.abspath(os.path.dirname(__file__)) datadir = os.path.join(curdir, 'data') def _ratio(a, b): return np.abs(a - b) / np.abs(a + b) class TestPDS(unittest.TestCase): """Test PDS statistics.""" @classmethod def setUpClass(cls): """Produce common products for all subsequent tests.""" print("Setting up.") import numpy.random as ra cls.length = 512000 cls.tstart = 0 cls.tstop = cls.tstart + cls.length cls.ctrate = 100 cls.bintime = 1 ra.seed(seed=1234) cls.nphot =
ra.poisson(cls.length * cls.ctrate)
numpy.random.poisson
# Copyright 2021 Huawei Technologies Co., Ltd # # 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. # ============================================================================ """dcgan cell""" import numpy as np from mindspore import nn, ops from mindspore.ops import functional as F from mindspore.common import dtype as mstype from mindspore.common.initializer import Initializer, _assignment class Reshape(nn.Cell): """ Reshapes input tensor with the same values based on a given shape tuple. """ def __init__(self, shape, auto_prefix=True): super().__init__(auto_prefix=auto_prefix) self.shape = shape def construct(self, x): return ops.operations.Reshape()(x, self.shape) class Normal(Initializer): """ Draw random samples from a normal (Gaussian) distribution. """ def __init__(self, mean=0.0, sigma=0.01): super(Normal, self).__init__() self.sigma = sigma self.mean = mean def _initialize(self, arr):
np.random.seed(999)
numpy.random.seed
from .myqt import QT import pyqtgraph as pg import numpy as np #import seaborn as sns from ..tools import median_mad, rgba_to_int32 from .. import labelcodes from ..catalogueconstructor import _persistent_metrics from .base import ControllerBase import time class CatalogueController(ControllerBase): def __init__(self, catalogueconstructor=None,parent=None): ControllerBase.__init__(self, parent=parent) self.cc = self.catalogueconstructor = catalogueconstructor self.dataio = catalogueconstructor.dataio self.nb_channel = self.dataio.nb_channel(self.chan_grp) self.channels =
np.arange(self.nb_channel, dtype='int64')
numpy.arange
import numpy as np #from apmeter import APMeter from sklearn.metrics import average_precision_score from sklearn.metrics import roc_auc_score def get_intervals(seq, thres=0.0001, mean=False): ''' Get the positive interval of a prediction score sequence with the given threshold Input: seq - Input sequence with prediction score, 1*N thres - threshold value to determine the positive interval, default=0.0001 mean - get the mean value of each interval and return as the interval score, default=False Output: intervals - a list containing (start, end) frame of the positive intervals ''' intervals = [] score = [] flag = True # flag to note if not in a positive interval for i, pos in enumerate(seq >= thres): if pos and flag: start = i # start frame of positive interval flag = False if (not pos) and (not flag): end = i-1 # end frame of positive interval flag = True intervals.append((start, end)) if mean: score.append(np.mean(seq[start:end+1])) # if in a positive interval at the end of the sequence if not flag: end = i intervals.append((start, end)) if mean: score.append(np.mean(seq[start:end + 1])) if mean: return intervals,
np.array(score)
numpy.array
import os import tempfile import numpy as np import scipy.ndimage.measurements as meas from functools import reduce import warnings import sys sys.path.append(os.path.abspath(r'../lib')) import NumCppPy as NumCpp # noqa E402 #################################################################################### def factors(n): return set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))) #################################################################################### def test_seed(): np.random.seed(1) #################################################################################### def test_abs(): randValue = np.random.randint(-100, -1, [1, ]).astype(np.double).item() assert NumCpp.absScaler(randValue) == np.abs(randValue) components = np.random.randint(-100, -1, [2, ]).astype(np.double) value = complex(components[0], components[1]) assert np.round(NumCpp.absScaler(value), 9) == np.round(np.abs(value), 9) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(-100, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.absArray(cArray), np.abs(data)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) data = np.random.randint(-100, 100, [shape.rows, shape.cols]) + \ 1j * np.random.randint(-100, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.absArray(cArray), 9), np.round(np.abs(data), 9)) #################################################################################### def test_add(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArray(shape) data1 = np.random.randint(-100, 100, [shape.rows, shape.cols]) data2 = np.random.randint(-100, 100, [shape.rows, shape.cols]) cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.add(cArray1, cArray2), data1 + data2) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(-100, 100, [shape.rows, shape.cols]) cArray.setArray(data) value = np.random.randint(-100, 100) assert np.array_equal(NumCpp.add(cArray, value), data + value) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(-100, 100, [shape.rows, shape.cols]) cArray.setArray(data) value = np.random.randint(-100, 100) assert np.array_equal(NumCpp.add(value, cArray), data + value) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArrayComplexDouble(shape) cArray2 = NumCpp.NdArrayComplexDouble(shape) real1 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag1 = np.random.randint(1, 100, [shape.rows, shape.cols]) data1 = real1 + 1j * imag1 real2 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag2 = np.random.randint(1, 100, [shape.rows, shape.cols]) data2 = real2 + 1j * imag2 cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.add(cArray1, cArray2), data1 + data2) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) value = np.random.randint(-100, 100) + 1j * np.random.randint(-100, 100) assert np.array_equal(NumCpp.add(cArray, value), data + value) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) value = np.random.randint(-100, 100) + 1j * np.random.randint(-100, 100) assert np.array_equal(NumCpp.add(value, cArray), data + value) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArrayComplexDouble(shape) cArray2 = NumCpp.NdArray(shape) real1 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag1 = np.random.randint(1, 100, [shape.rows, shape.cols]) data1 = real1 + 1j * imag1 data2 = np.random.randint(1, 100, [shape.rows, shape.cols]) cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.add(cArray1, cArray2), data1 + data2) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArrayComplexDouble(shape) data1 = np.random.randint(1, 100, [shape.rows, shape.cols]) real2 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag2 = np.random.randint(1, 100, [shape.rows, shape.cols]) data2 = real2 + 1j * imag2 cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.add(cArray1, cArray2), data1 + data2) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(-100, 100, [shape.rows, shape.cols]) cArray.setArray(data) value = np.random.randint(-100, 100) + 1j * np.random.randint(-100, 100) assert np.array_equal(NumCpp.add(cArray, value), data + value) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(-100, 100, [shape.rows, shape.cols]) cArray.setArray(data) value = np.random.randint(-100, 100) + 1j * np.random.randint(-100, 100) assert np.array_equal(NumCpp.add(value, cArray), data + value) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) value = np.random.randint(-100, 100) assert np.array_equal(NumCpp.add(cArray, value), data + value) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) value = np.random.randint(-100, 100) assert np.array_equal(NumCpp.add(value, cArray), data + value) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArrayComplexDouble(shape) cArray2 = NumCpp.NdArrayComplexDouble(shape) real1 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag1 = np.random.randint(1, 100, [shape.rows, shape.cols]) data1 = real1 + 1j * imag1 real2 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag2 = np.random.randint(1, 100, [shape.rows, shape.cols]) data2 = real2 + 1j * imag2 cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.add(cArray1, cArray2), data1 + data2) #################################################################################### def test_alen(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(-100, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert NumCpp.alen(cArray) == shape.rows #################################################################################### def test_all(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert NumCpp.all(cArray, NumCpp.Axis.NONE).astype(bool).item() == np.all(data).item() shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert NumCpp.all(cArray, NumCpp.Axis.NONE).astype(bool).item() == np.all(data).item() shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.all(cArray, NumCpp.Axis.ROW).flatten().astype(bool), np.all(data, axis=0)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.all(cArray, NumCpp.Axis.ROW).flatten().astype(bool), np.all(data, axis=0)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.all(cArray, NumCpp.Axis.COL).flatten().astype(bool), np.all(data, axis=1)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.all(cArray, NumCpp.Axis.COL).flatten().astype(bool), np.all(data, axis=1)) #################################################################################### def test_allclose(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArray(shape) cArray3 = NumCpp.NdArray(shape) tolerance = 1e-5 data1 = np.random.randn(shape.rows, shape.cols) data2 = data1 + tolerance / 10 data3 = data1 + 1 cArray1.setArray(data1) cArray2.setArray(data2) cArray3.setArray(data3) assert NumCpp.allclose(cArray1, cArray2, tolerance) and not NumCpp.allclose(cArray1, cArray3, tolerance) #################################################################################### def test_amax(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert NumCpp.amax(cArray, NumCpp.Axis.NONE).item() == np.max(data) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert NumCpp.amax(cArray, NumCpp.Axis.NONE).item() == np.max(data) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.amax(cArray, NumCpp.Axis.ROW).flatten(), np.max(data, axis=0)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.amax(cArray, NumCpp.Axis.ROW).flatten(), np.max(data, axis=0)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.amax(cArray, NumCpp.Axis.COL).flatten(), np.max(data, axis=1)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.amax(cArray, NumCpp.Axis.COL).flatten(), np.max(data, axis=1)) #################################################################################### def test_amin(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert NumCpp.amin(cArray, NumCpp.Axis.NONE).item() == np.min(data) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert NumCpp.amin(cArray, NumCpp.Axis.NONE).item() == np.min(data) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.amin(cArray, NumCpp.Axis.ROW).flatten(), np.min(data, axis=0)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.amin(cArray, NumCpp.Axis.ROW).flatten(), np.min(data, axis=0)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.amin(cArray, NumCpp.Axis.COL).flatten(), np.min(data, axis=1)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.amin(cArray, NumCpp.Axis.COL).flatten(), np.min(data, axis=1)) #################################################################################### def test_angle(): components = np.random.randint(-100, -1, [2, ]).astype(np.double) value = complex(components[0], components[1]) assert np.round(NumCpp.angleScaler(value), 9) == np.round(np.angle(value), 9) # noqa shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) data = np.random.randint(-100, 100, [shape.rows, shape.cols]) + \ 1j * np.random.randint(-100, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.angleArray(cArray), 9), np.round(np.angle(data), 9)) #################################################################################### def test_any(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert NumCpp.any(cArray, NumCpp.Axis.NONE).astype(bool).item() == np.any(data).item() shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert NumCpp.any(cArray, NumCpp.Axis.NONE).astype(bool).item() == np.any(data).item() shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.any(cArray, NumCpp.Axis.ROW).flatten().astype(bool), np.any(data, axis=0)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.any(cArray, NumCpp.Axis.ROW).flatten().astype(bool), np.any(data, axis=0)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.any(cArray, NumCpp.Axis.COL).flatten().astype(bool), np.any(data, axis=1)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.any(cArray, NumCpp.Axis.COL).flatten().astype(bool), np.any(data, axis=1)) #################################################################################### def test_append(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArray(shape) data1 = np.random.randint(0, 100, [shape.rows, shape.cols]) data2 = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.append(cArray1, cArray2, NumCpp.Axis.NONE).getNumpyArray().flatten(), np.append(data1, data2)) shapeInput = np.random.randint(20, 100, [2, ]) numRows = np.random.randint(1, 100, [1, ]).item() shape1 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) shape2 = NumCpp.Shape(shapeInput[0].item() + numRows, shapeInput[1].item()) cArray1 = NumCpp.NdArray(shape1) cArray2 = NumCpp.NdArray(shape2) data1 = np.random.randint(0, 100, [shape1.rows, shape1.cols]) data2 = np.random.randint(0, 100, [shape2.rows, shape2.cols]) cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.append(cArray1, cArray2, NumCpp.Axis.ROW).getNumpyArray(), np.append(data1, data2, axis=0)) shapeInput = np.random.randint(20, 100, [2, ]) NumCppols = np.random.randint(1, 100, [1, ]).item() shape1 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) shape2 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item() + NumCppols) cArray1 = NumCpp.NdArray(shape1) cArray2 = NumCpp.NdArray(shape2) data1 = np.random.randint(0, 100, [shape1.rows, shape1.cols]) data2 = np.random.randint(0, 100, [shape2.rows, shape2.cols]) cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.append(cArray1, cArray2, NumCpp.Axis.COL).getNumpyArray(), np.append(data1, data2, axis=1)) #################################################################################### def test_arange(): start = np.random.randn(1).item() stop = np.random.randn(1).item() * 100 step = np.abs(np.random.randn(1).item()) if stop < start: step *= -1 data = np.arange(start, stop, step) assert np.array_equal(np.round(NumCpp.arange(start, stop, step).flatten(), 9), np.round(data, 9)) #################################################################################### def test_arccos(): value = np.abs(np.random.rand(1).item()) assert np.round(NumCpp.arccosScaler(value), 9) == np.round(np.arccos(value), 9) components = np.random.rand(2).astype(np.double) value = complex(components[0], components[1]) assert np.round(NumCpp.arccosScaler(value), 9) == np.round(np.arccos(value), 9) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.rand(shape.rows, shape.cols) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.arccosArray(cArray), 9), np.round(np.arccos(data), 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) data = np.random.rand(shape.rows, shape.cols) + 1j * np.random.rand(shape.rows, shape.cols) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.arccosArray(cArray), 9), np.round(np.arccos(data), 9)) #################################################################################### def test_arccosh(): value = np.abs(np.random.rand(1).item()) + 1 assert np.round(NumCpp.arccoshScaler(value), 9) == np.round(np.arccosh(value), 9) components = np.random.rand(2).astype(np.double) value = complex(components[0], components[1]) assert np.round(NumCpp.arccoshScaler(value), 9) == np.round(np.arccosh(value), 9) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.rand(shape.rows, shape.cols) + 1 cArray.setArray(data) assert np.array_equal(np.round(NumCpp.arccoshArray(cArray), 9), np.round(np.arccosh(data), 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) data = np.random.rand(shape.rows, shape.cols) + 1j * np.random.rand(shape.rows, shape.cols) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.arccoshArray(cArray), 9), np.round(np.arccosh(data), 9)) #################################################################################### def test_arcsin(): value = np.abs(np.random.rand(1).item()) assert np.round(NumCpp.arcsinScaler(value), 9) == np.round(np.arcsin(value), 9) components = np.random.rand(2).astype(np.double) value = complex(components[0], components[1]) assert np.round(NumCpp.arcsinScaler(value), 9) == np.round(np.arcsin(value), 9) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.rand(shape.rows, shape.cols) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.arcsinArray(cArray), 9), np.round(np.arcsin(data), 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) data = np.random.rand(shape.rows, shape.cols) + 1j * np.random.rand(shape.rows, shape.cols) cArray.setArray(data) np.array_equal(np.round(NumCpp.arcsinArray(cArray), 9), np.round(np.arcsin(data), 9)) #################################################################################### def test_arcsinh(): value = np.abs(np.random.rand(1).item()) assert np.round(NumCpp.arcsinhScaler(value), 9) == np.round(np.arcsinh(value), 9) components = np.random.rand(2).astype(np.double) value = complex(components[0], components[1]) assert np.round(NumCpp.arcsinhScaler(value), 9) == np.round(np.arcsinh(value), 9) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.rand(shape.rows, shape.cols) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.arcsinhArray(cArray), 9), np.round(np.arcsinh(data), 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) data = np.random.rand(shape.rows, shape.cols) + 1j * np.random.rand(shape.rows, shape.cols) cArray.setArray(data) np.array_equal(np.round(NumCpp.arcsinhArray(cArray), 9), np.round(np.arcsinh(data), 9)) #################################################################################### def test_arctan(): value = np.abs(np.random.rand(1).item()) assert np.round(NumCpp.arctanScaler(value), 9) == np.round(np.arctan(value), 9) components = np.random.rand(2).astype(np.double) value = complex(components[0], components[1]) assert np.round(NumCpp.arctanScaler(value), 9) == np.round(np.arctan(value), 9) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.rand(shape.rows, shape.cols) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.arctanArray(cArray), 9), np.round(np.arctan(data), 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) data = np.random.rand(shape.rows, shape.cols) + 1j * np.random.rand(shape.rows, shape.cols) cArray.setArray(data) np.array_equal(np.round(NumCpp.arctanArray(cArray), 9), np.round(np.arctan(data), 9)) #################################################################################### def test_arctan2(): xy = np.random.rand(2) * 2 - 1 assert np.round(NumCpp.arctan2Scaler(xy[1], xy[0]), 9) == np.round(np.arctan2(xy[1], xy[0]), 9) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArrayX = NumCpp.NdArray(shape) cArrayY = NumCpp.NdArray(shape) xy = np.random.rand(*shapeInput, 2) * 2 - 1 xData = xy[:, :, 0].reshape(shapeInput) yData = xy[:, :, 1].reshape(shapeInput) cArrayX.setArray(xData) cArrayY.setArray(yData) assert np.array_equal(np.round(NumCpp.arctan2Array(cArrayY, cArrayX), 9), np.round(np.arctan2(yData, xData), 9)) #################################################################################### def test_arctanh(): value = np.abs(np.random.rand(1).item()) assert np.round(NumCpp.arctanhScaler(value), 9) == np.round(np.arctanh(value), 9) components = np.random.rand(2).astype(np.double) value = complex(components[0], components[1]) assert np.round(NumCpp.arctanhScaler(value), 9) == np.round(np.arctanh(value), 9) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.rand(shape.rows, shape.cols) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.arctanhArray(cArray), 9), np.round(np.arctanh(data), 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) data = np.random.rand(shape.rows, shape.cols) + 1j * np.random.rand(shape.rows, shape.cols) cArray.setArray(data) np.array_equal(np.round(NumCpp.arctanhArray(cArray), 9), np.round(np.arctanh(data), 9)) #################################################################################### def test_argmax(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.argmax(cArray, NumCpp.Axis.NONE).item(), np.argmax(data)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.argmax(cArray, NumCpp.Axis.NONE).item(), np.argmax(data)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.argmax(cArray, NumCpp.Axis.ROW).flatten(), np.argmax(data, axis=0)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.argmax(cArray, NumCpp.Axis.ROW).flatten(), np.argmax(data, axis=0)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.argmax(cArray, NumCpp.Axis.COL).flatten(), np.argmax(data, axis=1)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.argmax(cArray, NumCpp.Axis.COL).flatten(), np.argmax(data, axis=1)) #################################################################################### def test_argmin(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.argmin(cArray, NumCpp.Axis.NONE).item(), np.argmin(data)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.argmin(cArray, NumCpp.Axis.NONE).item(), np.argmin(data)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.argmin(cArray, NumCpp.Axis.ROW).flatten(), np.argmin(data, axis=0)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.argmin(cArray, NumCpp.Axis.ROW).flatten(), np.argmin(data, axis=0)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.argmin(cArray, NumCpp.Axis.COL).flatten(), np.argmin(data, axis=1)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.argmin(cArray, NumCpp.Axis.COL).flatten(), np.argmin(data, axis=1)) #################################################################################### def test_argsort(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) dataFlat = data.flatten() assert np.array_equal(dataFlat[NumCpp.argsort(cArray, NumCpp.Axis.NONE).flatten().astype(np.uint32)], dataFlat[np.argsort(data, axis=None)]) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) dataFlat = data.flatten() assert np.array_equal(dataFlat[NumCpp.argsort(cArray, NumCpp.Axis.NONE).flatten().astype(np.uint32)], dataFlat[np.argsort(data, axis=None)]) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) pIdx = np.argsort(data, axis=0) cIdx = NumCpp.argsort(cArray, NumCpp.Axis.ROW).astype(np.uint16) allPass = True for idx, row in enumerate(data.T): if not np.array_equal(row[cIdx[:, idx]], row[pIdx[:, idx]]): allPass = False break assert allPass shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) pIdx = np.argsort(data, axis=0) cIdx = NumCpp.argsort(cArray, NumCpp.Axis.ROW).astype(np.uint16) allPass = True for idx, row in enumerate(data.T): if not np.array_equal(row[cIdx[:, idx]], row[pIdx[:, idx]]): allPass = False break assert allPass shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) pIdx = np.argsort(data, axis=1) cIdx = NumCpp.argsort(cArray, NumCpp.Axis.COL).astype(np.uint16) allPass = True for idx, row in enumerate(data): if not np.array_equal(row[cIdx[idx, :]], row[pIdx[idx, :]]): # noqa allPass = False break assert allPass shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) pIdx = np.argsort(data, axis=1) cIdx = NumCpp.argsort(cArray, NumCpp.Axis.COL).astype(np.uint16) allPass = True for idx, row in enumerate(data): if not np.array_equal(row[cIdx[idx, :]], row[pIdx[idx, :]]): allPass = False break assert allPass #################################################################################### def test_argwhere(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) randValue = np.random.randint(0, 100, [1, ]).item() data2 = data > randValue cArray.setArray(data2) assert np.array_equal(NumCpp.argwhere(cArray).flatten(), np.argwhere(data.flatten() > randValue).flatten()) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag randValue = np.random.randint(0, 100, [1, ]).item() data2 = data > randValue cArray.setArray(data2) assert np.array_equal(NumCpp.argwhere(cArray).flatten(), np.argwhere(data.flatten() > randValue).flatten()) #################################################################################### def test_around(): value = np.abs(np.random.rand(1).item()) * np.random.randint(1, 10, [1, ]).item() numDecimalsRound = np.random.randint(0, 10, [1, ]).astype(np.uint8).item() assert NumCpp.aroundScaler(value, numDecimalsRound) == np.round(value, numDecimalsRound) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.rand(shape.rows, shape.cols) * np.random.randint(1, 10, [1, ]).item() cArray.setArray(data) numDecimalsRound = np.random.randint(0, 10, [1, ]).astype(np.uint8).item() assert np.array_equal(NumCpp.aroundArray(cArray, numDecimalsRound), np.round(data, numDecimalsRound)) #################################################################################### def test_array_equal(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArray(shape) cArray3 = NumCpp.NdArray(shape) data1 = np.random.randint(1, 100, shapeInput) data2 = np.random.randint(1, 100, shapeInput) cArray1.setArray(data1) cArray2.setArray(data1) cArray3.setArray(data2) assert NumCpp.array_equal(cArray1, cArray2) and not NumCpp.array_equal(cArray1, cArray3) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArrayComplexDouble(shape) cArray2 = NumCpp.NdArrayComplexDouble(shape) cArray3 = NumCpp.NdArrayComplexDouble(shape) real1 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag1 = np.random.randint(1, 100, [shape.rows, shape.cols]) data1 = real1 + 1j * imag1 real2 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag2 = np.random.randint(1, 100, [shape.rows, shape.cols]) data2 = real2 + 1j * imag2 cArray1.setArray(data1) cArray2.setArray(data1) cArray3.setArray(data2) assert NumCpp.array_equal(cArray1, cArray2) and not NumCpp.array_equal(cArray1, cArray3) #################################################################################### def test_array_equiv(): shapeInput1 = np.random.randint(1, 100, [2, ]) shapeInput3 = np.random.randint(1, 100, [2, ]) shape1 = NumCpp.Shape(shapeInput1[0].item(), shapeInput1[1].item()) shape2 = NumCpp.Shape(shapeInput1[1].item(), shapeInput1[0].item()) shape3 = NumCpp.Shape(shapeInput3[0].item(), shapeInput3[1].item()) cArray1 = NumCpp.NdArray(shape1) cArray2 = NumCpp.NdArray(shape2) cArray3 = NumCpp.NdArray(shape3) data1 = np.random.randint(1, 100, shapeInput1) data3 = np.random.randint(1, 100, shapeInput3) cArray1.setArray(data1) cArray2.setArray(data1.reshape([shapeInput1[1].item(), shapeInput1[0].item()])) cArray3.setArray(data3) assert NumCpp.array_equiv(cArray1, cArray2) and not NumCpp.array_equiv(cArray1, cArray3) shapeInput1 = np.random.randint(1, 100, [2, ]) shapeInput3 = np.random.randint(1, 100, [2, ]) shape1 = NumCpp.Shape(shapeInput1[0].item(), shapeInput1[1].item()) shape2 = NumCpp.Shape(shapeInput1[1].item(), shapeInput1[0].item()) shape3 = NumCpp.Shape(shapeInput3[0].item(), shapeInput3[1].item()) cArray1 = NumCpp.NdArrayComplexDouble(shape1) cArray2 = NumCpp.NdArrayComplexDouble(shape2) cArray3 = NumCpp.NdArrayComplexDouble(shape3) real1 = np.random.randint(1, 100, [shape1.rows, shape1.cols]) imag1 = np.random.randint(1, 100, [shape1.rows, shape1.cols]) data1 = real1 + 1j * imag1 real3 = np.random.randint(1, 100, [shape3.rows, shape3.cols]) imag3 = np.random.randint(1, 100, [shape3.rows, shape3.cols]) data3 = real3 + 1j * imag3 cArray1.setArray(data1) cArray2.setArray(data1.reshape([shapeInput1[1].item(), shapeInput1[0].item()])) cArray3.setArray(data3) assert NumCpp.array_equiv(cArray1, cArray2) and not NumCpp.array_equiv(cArray1, cArray3) #################################################################################### def test_asarray(): values = np.random.randint(0, 100, [2, ]).astype(np.double) assert np.array_equal(NumCpp.asarrayArray1D(*values).flatten(), values) real = np.random.randint(0, 100, [2, ]).astype(np.double) imag = np.random.randint(0, 100, [2, ]).astype(np.double) values = real + 1j * imag assert np.array_equal(NumCpp.asarrayArray1D(*values).flatten(), values) values = np.random.randint(0, 100, [2, ]).astype(np.double) assert np.array_equal(NumCpp.asarrayArray1DCopy(*values).flatten(), values) real = np.random.randint(0, 100, [2, ]).astype(np.double) imag = np.random.randint(0, 100, [2, ]).astype(np.double) values = real + 1j * imag assert np.array_equal(NumCpp.asarrayArray1DCopy(*values).flatten(), values) values = np.random.randint(0, 100, [2, ]).astype(np.double) data = np.vstack([values, values]) assert np.array_equal(NumCpp.asarrayArray2D(*values), data) real = np.random.randint(0, 100, [2, ]).astype(np.double) imag = np.random.randint(0, 100, [2, ]).astype(np.double) values = real + 1j * imag data = np.vstack([values, values]) assert np.array_equal(NumCpp.asarrayArray2D(*values), data) values = np.random.randint(0, 100, [2, ]).astype(np.double) data = np.vstack([values, values]) assert np.array_equal(NumCpp.asarrayArray2DCopy(*values), data) real = np.random.randint(0, 100, [2, ]).astype(np.double) imag = np.random.randint(0, 100, [2, ]).astype(np.double) values = real + 1j * imag data = np.vstack([values, values]) assert np.array_equal(NumCpp.asarrayArray2DCopy(*values), data) values = np.random.randint(0, 100, [2, ]).astype(np.double) assert np.array_equal(NumCpp.asarrayVector1D(*values).flatten(), values) real = np.random.randint(0, 100, [2, ]).astype(np.double) imag = np.random.randint(0, 100, [2, ]).astype(np.double) values = real + 1j * imag assert np.array_equal(NumCpp.asarrayVector1D(*values).flatten(), values) values = np.random.randint(0, 100, [2, ]).astype(np.double) assert np.array_equal(NumCpp.asarrayVector1DCopy(*values).flatten(), values) real = np.random.randint(0, 100, [2, ]).astype(np.double) imag = np.random.randint(0, 100, [2, ]).astype(np.double) values = real + 1j * imag assert np.array_equal(NumCpp.asarrayVector1DCopy(*values).flatten(), values) values = np.random.randint(0, 100, [2, ]).astype(np.double) data = np.vstack([values, values]) assert np.array_equal(NumCpp.asarrayVector2D(*values), data) real = np.random.randint(0, 100, [2, ]).astype(np.double) imag = np.random.randint(0, 100, [2, ]).astype(np.double) values = real + 1j * imag data = np.vstack([values, values]) assert np.array_equal(NumCpp.asarrayVector2D(*values), data) values = np.random.randint(0, 100, [2, ]).astype(np.double) data = np.vstack([values, values]) assert np.array_equal(NumCpp.asarrayVectorArray2D(*values), data) real = np.random.randint(0, 100, [2, ]).astype(np.double) imag = np.random.randint(0, 100, [2, ]).astype(np.double) values = real + 1j * imag data = np.vstack([values, values]) assert np.array_equal(NumCpp.asarrayVectorArray2D(*values), data) values = np.random.randint(0, 100, [2, ]).astype(np.double) data = np.vstack([values, values]) assert np.array_equal(NumCpp.asarrayVectorArray2DCopy(*values), data) real = np.random.randint(0, 100, [2, ]).astype(np.double) imag = np.random.randint(0, 100, [2, ]).astype(np.double) values = real + 1j * imag data = np.vstack([values, values]) assert np.array_equal(NumCpp.asarrayVectorArray2DCopy(*values), data) values = np.random.randint(0, 100, [2, ]).astype(np.double) assert np.array_equal(NumCpp.asarrayDeque1D(*values).flatten(), values) real = np.random.randint(0, 100, [2, ]).astype(np.double) imag = np.random.randint(0, 100, [2, ]).astype(np.double) values = real + 1j * imag assert np.array_equal(NumCpp.asarrayDeque1D(*values).flatten(), values) values = np.random.randint(0, 100, [2, ]).astype(np.double) data = np.vstack([values, values]) assert np.array_equal(NumCpp.asarrayDeque2D(*values), data) real = np.random.randint(0, 100, [2, ]).astype(np.double) imag = np.random.randint(0, 100, [2, ]).astype(np.double) values = real + 1j * imag data = np.vstack([values, values]) assert np.array_equal(NumCpp.asarrayDeque2D(*values), data) values = np.random.randint(0, 100, [2, ]).astype(np.double) assert np.array_equal(NumCpp.asarrayList(*values).flatten(), values) real = np.random.randint(0, 100, [2, ]).astype(np.double) imag = np.random.randint(0, 100, [2, ]).astype(np.double) values = real + 1j * imag assert np.array_equal(NumCpp.asarrayList(*values).flatten(), values) values = np.random.randint(0, 100, [2, ]).astype(np.double) assert np.array_equal(NumCpp.asarrayIterators(*values).flatten(), values) real = np.random.randint(0, 100, [2, ]).astype(np.double) imag = np.random.randint(0, 100, [2, ]).astype(np.double) values = real + 1j * imag assert np.array_equal(NumCpp.asarrayIterators(*values).flatten(), values) values = np.random.randint(0, 100, [2, ]).astype(np.double) assert np.array_equal(NumCpp.asarrayPointerIterators(*values).flatten(), values) real = np.random.randint(0, 100, [2, ]).astype(np.double) imag = np.random.randint(0, 100, [2, ]).astype(np.double) values = real + 1j * imag assert np.array_equal(NumCpp.asarrayPointerIterators(*values).flatten(), values) values = np.random.randint(0, 100, [2, ]).astype(np.double) assert np.array_equal(NumCpp.asarrayPointer(*values).flatten(), values) real = np.random.randint(0, 100, [2, ]).astype(np.double) imag = np.random.randint(0, 100, [2, ]).astype(np.double) values = real + 1j * imag assert np.array_equal(NumCpp.asarrayPointer(*values).flatten(), values) values = np.random.randint(0, 100, [2, ]).astype(np.double) data = np.vstack([values, values]) assert np.array_equal(NumCpp.asarrayPointer2D(*values), data) real = np.random.randint(0, 100, [2, ]).astype(np.double) imag = np.random.randint(0, 100, [2, ]).astype(np.double) values = real + 1j * imag data = np.vstack([values, values]) assert np.array_equal(NumCpp.asarrayPointer2D(*values), data) values = np.random.randint(0, 100, [2, ]).astype(np.double) assert np.array_equal(NumCpp.asarrayPointerShell(*values).flatten(), values) real = np.random.randint(0, 100, [2, ]).astype(np.double) imag = np.random.randint(0, 100, [2, ]).astype(np.double) values = real + 1j * imag assert np.array_equal(NumCpp.asarrayPointerShell(*values).flatten(), values) values = np.random.randint(0, 100, [2, ]).astype(np.double) data = np.vstack([values, values]) assert np.array_equal(NumCpp.asarrayPointerShell2D(*values), data) real = np.random.randint(0, 100, [2, ]).astype(np.double) imag = np.random.randint(0, 100, [2, ]).astype(np.double) values = real + 1j * imag data = np.vstack([values, values]) assert np.array_equal(NumCpp.asarrayPointerShell2D(*values), data) values = np.random.randint(0, 100, [2, ]).astype(np.double) assert np.array_equal(NumCpp.asarrayPointerShellTakeOwnership(*values).flatten(), values) real = np.random.randint(0, 100, [2, ]).astype(np.double) imag = np.random.randint(0, 100, [2, ]).astype(np.double) values = real + 1j * imag assert np.array_equal(NumCpp.asarrayPointerShellTakeOwnership(*values).flatten(), values) values = np.random.randint(0, 100, [2, ]).astype(np.double) data = np.vstack([values, values]) assert np.array_equal(NumCpp.asarrayPointerShell2DTakeOwnership(*values), data) real = np.random.randint(0, 100, [2, ]).astype(np.double) imag = np.random.randint(0, 100, [2, ]).astype(np.double) values = real + 1j * imag data = np.vstack([values, values]) assert np.array_equal(NumCpp.asarrayPointerShell2DTakeOwnership(*values), data) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) cArrayCast = NumCpp.astypeDoubleToUint32(cArray).getNumpyArray() assert np.array_equal(cArrayCast, data.astype(np.uint32)) assert cArrayCast.dtype == np.uint32 shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) cArrayCast = NumCpp.astypeDoubleToComplex(cArray).getNumpyArray() assert np.array_equal(cArrayCast, data.astype(np.complex128)) assert cArrayCast.dtype == np.complex128 shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) cArrayCast = NumCpp.astypeComplexToComplex(cArray).getNumpyArray() assert np.array_equal(cArrayCast, data.astype(np.complex64)) assert cArrayCast.dtype == np.complex64 shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) cArrayCast = NumCpp.astypeComplexToDouble(cArray).getNumpyArray() warnings.filterwarnings('ignore', category=np.ComplexWarning) assert np.array_equal(cArrayCast, data.astype(np.double)) warnings.filters.pop() # noqa assert cArrayCast.dtype == np.double #################################################################################### def test_average(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.round(NumCpp.average(cArray, NumCpp.Axis.NONE).item(), 9) == np.round(np.average(data), 9) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.round(NumCpp.average(cArray, NumCpp.Axis.NONE).item(), 9) == np.round(np.average(data), 9) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.average(cArray, NumCpp.Axis.ROW).flatten(), 9), np.round(np.average(data, axis=0), 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(np.round(NumCpp.average(cArray, NumCpp.Axis.ROW).flatten(), 9), np.round(np.average(data, axis=0), 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.average(cArray, NumCpp.Axis.COL).flatten(), 9), np.round(np.average(data, axis=1), 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(np.round(NumCpp.average(cArray, NumCpp.Axis.COL).flatten(), 9), np.round(np.average(data, axis=1), 9)) #################################################################################### def test_averageWeighted(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) cWeights = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) weights = np.random.randint(1, 5, [shape.rows, shape.cols]) cArray.setArray(data) cWeights.setArray(weights) assert np.round(NumCpp.averageWeighted(cArray, cWeights, NumCpp.Axis.NONE).item(), 9) == \ np.round(np.average(data, weights=weights), 9) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) cWeights = NumCpp.NdArray(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag weights = np.random.randint(1, 5, [shape.rows, shape.cols]) cArray.setArray(data) cWeights.setArray(weights) assert np.round(NumCpp.averageWeighted(cArray, cWeights, NumCpp.Axis.NONE).item(), 9) == \ np.round(np.average(data, weights=weights), 9) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) cWeights = NumCpp.NdArray(1, shape.cols) data = np.random.randint(0, 100, [shape.rows, shape.cols]) weights = np.random.randint(1, 5, [1, shape.rows]) cArray.setArray(data) cWeights.setArray(weights) assert np.array_equal(np.round(NumCpp.averageWeighted(cArray, cWeights, NumCpp.Axis.ROW).flatten(), 9), np.round(np.average(data, weights=weights.flatten(), axis=0), 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) cWeights = NumCpp.NdArray(1, shape.cols) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag weights = np.random.randint(1, 5, [1, shape.rows]) cArray.setArray(data) cWeights.setArray(weights) assert np.array_equal(np.round(NumCpp.averageWeighted(cArray, cWeights, NumCpp.Axis.ROW).flatten(), 9), np.round(np.average(data, weights=weights.flatten(), axis=0), 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) cWeights = NumCpp.NdArray(1, shape.rows) data = np.random.randint(0, 100, [shape.rows, shape.cols]) weights = np.random.randint(1, 5, [1, shape.cols]) cWeights.setArray(weights) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.averageWeighted(cArray, cWeights, NumCpp.Axis.COL).flatten(), 9), np.round(np.average(data, weights=weights.flatten(), axis=1), 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) cWeights = NumCpp.NdArray(1, shape.rows) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag weights = np.random.randint(1, 5, [1, shape.cols]) cWeights.setArray(weights) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.averageWeighted(cArray, cWeights, NumCpp.Axis.COL).flatten(), 9), np.round(np.average(data, weights=weights.flatten(), axis=1), 9)) #################################################################################### def test_binaryRepr(): value = np.random.randint(0, np.iinfo(np.uint64).max, [1, ], dtype=np.uint64).item() assert NumCpp.binaryRepr(np.uint64(value)) == np.binary_repr(value, np.iinfo(np.uint64).bits) #################################################################################### def test_bincount(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayUInt32(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.uint16) cArray.setArray(data) assert np.array_equal(NumCpp.bincount(cArray, 0).flatten(), np.bincount(data.flatten(), minlength=0)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayUInt32(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.uint16) cArray.setArray(data) minLength = int(np.max(data) + 10) assert np.array_equal(NumCpp.bincount(cArray, minLength).flatten(), np.bincount(data.flatten(), minlength=minLength)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayUInt32(shape) cWeights = NumCpp.NdArrayUInt32(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.uint16) weights = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.uint16) cArray.setArray(data) cWeights.setArray(weights) assert np.array_equal(NumCpp.bincountWeighted(cArray, cWeights, 0).flatten(), np.bincount(data.flatten(), minlength=0, weights=weights.flatten())) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayUInt32(shape) cWeights = NumCpp.NdArrayUInt32(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.uint16) weights = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.uint16) cArray.setArray(data) cWeights.setArray(weights) minLength = int(np.max(data) + 10) assert np.array_equal(NumCpp.bincountWeighted(cArray, cWeights, minLength).flatten(), np.bincount(data.flatten(), minlength=minLength, weights=weights.flatten())) #################################################################################### def test_bitwise_and(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArrayUInt64(shape) cArray2 = NumCpp.NdArrayUInt64(shape) data1 = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.uint64) data2 = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.uint64) cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.bitwise_and(cArray1, cArray2), np.bitwise_and(data1, data2)) #################################################################################### def test_bitwise_not(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayUInt64(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.uint64) cArray.setArray(data) assert np.array_equal(NumCpp.bitwise_not(cArray), np.bitwise_not(data)) #################################################################################### def test_bitwise_or(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArrayUInt64(shape) cArray2 = NumCpp.NdArrayUInt64(shape) data1 = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.uint64) data2 = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.uint64) cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.bitwise_or(cArray1, cArray2), np.bitwise_or(data1, data2)) #################################################################################### def test_bitwise_xor(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArrayUInt64(shape) cArray2 = NumCpp.NdArrayUInt64(shape) data1 = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.uint64) data2 = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.uint64) cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.bitwise_xor(cArray1, cArray2), np.bitwise_xor(data1, data2)) #################################################################################### def test_byteswap(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayUInt64(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.uint64) cArray.setArray(data) assert np.array_equal(NumCpp.byteswap(cArray).shape, shapeInput) #################################################################################### def test_cbrt(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]).astype(np.double) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.cbrtArray(cArray), 9), np.round(np.cbrt(data), 9)) #################################################################################### def test_ceil(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randn(shape.rows, shape.cols).astype(np.double) * 1000 cArray.setArray(data) assert np.array_equal(np.round(NumCpp.ceilArray(cArray), 9), np.round(np.ceil(data), 9)) #################################################################################### def test_center_of_mass(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randn(shape.rows, shape.cols).astype(np.double) * 1000 cArray.setArray(data) assert np.array_equal(np.round(NumCpp.centerOfMass(cArray, NumCpp.Axis.NONE).flatten(), 9), np.round(meas.center_of_mass(data), 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randn(shape.rows, shape.cols).astype(np.double) * 1000 cArray.setArray(data) coms = list() for col in range(data.shape[1]): coms.append(np.round(meas.center_of_mass(data[:, col])[0], 9)) assert np.array_equal(np.round(NumCpp.centerOfMass(cArray, NumCpp.Axis.ROW).flatten(), 9), np.round(coms, 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randn(shape.rows, shape.cols).astype(np.double) * 1000 cArray.setArray(data) coms = list() for row in range(data.shape[0]): coms.append(np.round(meas.center_of_mass(data[row, :])[0], 9)) assert np.array_equal(np.round(NumCpp.centerOfMass(cArray, NumCpp.Axis.COL).flatten(), 9), np.round(coms, 9)) #################################################################################### def test_clip(): value = np.random.randint(0, 100, [1, ]).item() minValue = np.random.randint(0, 10, [1, ]).item() maxValue = np.random.randint(90, 100, [1, ]).item() assert NumCpp.clipScaler(value, minValue, maxValue) == np.clip(value, minValue, maxValue) value = np.random.randint(0, 100, [1, ]).item() + 1j * np.random.randint(0, 100, [1, ]).item() minValue = np.random.randint(0, 10, [1, ]).item() + 1j * np.random.randint(0, 10, [1, ]).item() maxValue = np.random.randint(90, 100, [1, ]).item() + 1j * np.random.randint(0, 100, [1, ]).item() assert NumCpp.clipScaler(value, minValue, maxValue) == np.clip(value, minValue, maxValue) # noqa shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) minValue = np.random.randint(0, 10, [1, ]).item() maxValue = np.random.randint(90, 100, [1, ]).item() assert np.array_equal(NumCpp.clipArray(cArray, minValue, maxValue), np.clip(data, minValue, maxValue)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) minValue = np.random.randint(0, 10, [1, ]).item() + 1j * np.random.randint(0, 10, [1, ]).item() maxValue = np.random.randint(90, 100, [1, ]).item() + 1j * np.random.randint(0, 100, [1, ]).item() assert np.array_equal(NumCpp.clipArray(cArray, minValue, maxValue), np.clip(data, minValue, maxValue)) # noqa #################################################################################### def test_column_stack(): shapeInput = np.random.randint(20, 100, [2, ]) shape1 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) shape2 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item() + np.random.randint(1, 10, [1, ]).item()) shape3 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item() + np.random.randint(1, 10, [1, ]).item()) shape4 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item() + np.random.randint(1, 10, [1, ]).item()) cArray1 = NumCpp.NdArray(shape1) cArray2 = NumCpp.NdArray(shape2) cArray3 = NumCpp.NdArray(shape3) cArray4 = NumCpp.NdArray(shape4) data1 = np.random.randint(1, 100, [shape1.rows, shape1.cols]) data2 = np.random.randint(1, 100, [shape2.rows, shape2.cols]) data3 = np.random.randint(1, 100, [shape3.rows, shape3.cols]) data4 = np.random.randint(1, 100, [shape4.rows, shape4.cols]) cArray1.setArray(data1) cArray2.setArray(data2) cArray3.setArray(data3) cArray4.setArray(data4) assert np.array_equal(NumCpp.column_stack(cArray1, cArray2, cArray3, cArray4), np.column_stack([data1, data2, data3, data4])) #################################################################################### def test_complex(): real = np.random.rand(1).astype(np.double).item() value = complex(real) assert np.round(NumCpp.complexScaler(real), 9) == np.round(value, 9) components = np.random.rand(2).astype(np.double) value = complex(components[0], components[1]) assert np.round(NumCpp.complexScaler(components[0], components[1]), 9) == np.round(value, 9) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) realArray = NumCpp.NdArray(shape) real = np.random.rand(shape.rows, shape.cols) realArray.setArray(real) assert np.array_equal(np.round(NumCpp.complexArray(realArray), 9), np.round(real + 1j * np.zeros_like(real), 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) realArray = NumCpp.NdArray(shape) imagArray = NumCpp.NdArray(shape) real = np.random.rand(shape.rows, shape.cols) imag = np.random.rand(shape.rows, shape.cols) realArray.setArray(real) imagArray.setArray(imag) assert np.array_equal(np.round(NumCpp.complexArray(realArray, imagArray), 9), np.round(real + 1j * imag, 9)) #################################################################################### def test_concatenate(): shapeInput = np.random.randint(20, 100, [2, ]) shape1 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) shape2 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item() + np.random.randint(1, 10, [1, ]).item()) shape3 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item() + np.random.randint(1, 10, [1, ]).item()) shape4 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item() + np.random.randint(1, 10, [1, ]).item()) cArray1 = NumCpp.NdArray(shape1) cArray2 = NumCpp.NdArray(shape2) cArray3 = NumCpp.NdArray(shape3) cArray4 = NumCpp.NdArray(shape4) data1 = np.random.randint(1, 100, [shape1.rows, shape1.cols]) data2 = np.random.randint(1, 100, [shape2.rows, shape2.cols]) data3 = np.random.randint(1, 100, [shape3.rows, shape3.cols]) data4 = np.random.randint(1, 100, [shape4.rows, shape4.cols]) cArray1.setArray(data1) cArray2.setArray(data2) cArray3.setArray(data3) cArray4.setArray(data4) assert np.array_equal(NumCpp.concatenate(cArray1, cArray2, cArray3, cArray4, NumCpp.Axis.NONE).flatten(), np.concatenate([data1.flatten(), data2.flatten(), data3.flatten(), data4.flatten()])) shapeInput = np.random.randint(20, 100, [2, ]) shape1 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) shape2 = NumCpp.Shape(shapeInput[0].item() + np.random.randint(1, 10, [1, ]).item(), shapeInput[1].item()) shape3 = NumCpp.Shape(shapeInput[0].item() + np.random.randint(1, 10, [1, ]).item(), shapeInput[1].item()) shape4 = NumCpp.Shape(shapeInput[0].item() + np.random.randint(1, 10, [1, ]).item(), shapeInput[1].item()) cArray1 = NumCpp.NdArray(shape1) cArray2 = NumCpp.NdArray(shape2) cArray3 = NumCpp.NdArray(shape3) cArray4 = NumCpp.NdArray(shape4) data1 = np.random.randint(1, 100, [shape1.rows, shape1.cols]) data2 = np.random.randint(1, 100, [shape2.rows, shape2.cols]) data3 = np.random.randint(1, 100, [shape3.rows, shape3.cols]) data4 = np.random.randint(1, 100, [shape4.rows, shape4.cols]) cArray1.setArray(data1) cArray2.setArray(data2) cArray3.setArray(data3) cArray4.setArray(data4) assert np.array_equal(NumCpp.concatenate(cArray1, cArray2, cArray3, cArray4, NumCpp.Axis.ROW), np.concatenate([data1, data2, data3, data4], axis=0)) shapeInput = np.random.randint(20, 100, [2, ]) shape1 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) shape2 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item() + np.random.randint(1, 10, [1, ]).item()) shape3 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item() + np.random.randint(1, 10, [1, ]).item()) shape4 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item() + np.random.randint(1, 10, [1, ]).item()) cArray1 = NumCpp.NdArray(shape1) cArray2 = NumCpp.NdArray(shape2) cArray3 = NumCpp.NdArray(shape3) cArray4 = NumCpp.NdArray(shape4) data1 = np.random.randint(1, 100, [shape1.rows, shape1.cols]) data2 = np.random.randint(1, 100, [shape2.rows, shape2.cols]) data3 = np.random.randint(1, 100, [shape3.rows, shape3.cols]) data4 = np.random.randint(1, 100, [shape4.rows, shape4.cols]) cArray1.setArray(data1) cArray2.setArray(data2) cArray3.setArray(data3) cArray4.setArray(data4) assert np.array_equal(NumCpp.concatenate(cArray1, cArray2, cArray3, cArray4, NumCpp.Axis.COL), np.concatenate([data1, data2, data3, data4], axis=1)) #################################################################################### def test_conj(): components = np.random.rand(2).astype(np.double) value = complex(components[0], components[1]) assert np.round(NumCpp.conjScaler(value), 9) == np.round(np.conj(value), 9) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) data = np.random.rand(shape.rows, shape.cols) + 1j * np.random.rand(shape.rows, shape.cols) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.conjArray(cArray), 9), np.round(np.conj(data), 9)) #################################################################################### def test_contains(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) value = np.random.randint(0, 100, [1, ]).item() cArray.setArray(data) assert NumCpp.contains(cArray, value, NumCpp.Axis.NONE).getNumpyArray().item() == (value in data) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag value = np.random.randint(0, 100, [1, ]).item() + 1j * np.random.randint(0, 100, [1, ]).item() cArray.setArray(data) assert NumCpp.contains(cArray, value, NumCpp.Axis.NONE).getNumpyArray().item() == (value in data) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) value = np.random.randint(0, 100, [1, ]).item() cArray.setArray(data) truth = list() for row in data: truth.append(value in row) assert np.array_equal(NumCpp.contains(cArray, value, NumCpp.Axis.COL).getNumpyArray().flatten(), np.asarray(truth)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag value = np.random.randint(0, 100, [1, ]).item() + 1j * np.random.randint(0, 100, [1, ]).item() cArray.setArray(data) truth = list() for row in data: truth.append(value in row) assert np.array_equal(NumCpp.contains(cArray, value, NumCpp.Axis.COL).getNumpyArray().flatten(), np.asarray(truth)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) value = np.random.randint(0, 100, [1, ]).item() cArray.setArray(data) truth = list() for row in data.T: truth.append(value in row) assert np.array_equal(NumCpp.contains(cArray, value, NumCpp.Axis.ROW).getNumpyArray().flatten(), np.asarray(truth)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag value = np.random.randint(0, 100, [1, ]).item() + 1j * np.random.randint(0, 100, [1, ]).item() cArray.setArray(data) truth = list() for row in data.T: truth.append(value in row) assert np.array_equal(NumCpp.contains(cArray, value, NumCpp.Axis.ROW).getNumpyArray().flatten(), np.asarray(truth)) #################################################################################### def test_copy(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.copy(cArray), data) #################################################################################### def test_copysign(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArray(shape) data1 = np.random.randint(-100, 100, [shape.rows, shape.cols]) data2 = np.random.randint(-100, 100, [shape.rows, shape.cols]) cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.copysign(cArray1, cArray2), np.copysign(data1, data2)) #################################################################################### def test_copyto(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArray() data1 = np.random.randint(-100, 100, [shape.rows, shape.cols]) cArray1.setArray(data1) assert np.array_equal(NumCpp.copyto(cArray2, cArray1), data1) #################################################################################### def test_cos(): value = np.abs(np.random.rand(1).item()) assert np.round(NumCpp.cosScaler(value), 9) == np.round(np.cos(value), 9) components = np.random.rand(2).astype(np.double) value = complex(components[0], components[1]) assert np.round(NumCpp.cosScaler(value), 9) == np.round(np.cos(value), 9) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.rand(shape.rows, shape.cols) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.cosArray(cArray), 9), np.round(np.cos(data), 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) data = np.random.rand(shape.rows, shape.cols) + 1j * np.random.rand(shape.rows, shape.cols) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.cosArray(cArray), 9), np.round(np.cos(data), 9)) #################################################################################### def test_cosh(): value = np.abs(np.random.rand(1).item()) assert np.round(NumCpp.coshScaler(value), 9) == np.round(np.cosh(value), 9) components = np.random.rand(2).astype(np.double) value = complex(components[0], components[1]) assert np.round(NumCpp.coshScaler(value), 9) == np.round(np.cosh(value), 9) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.rand(shape.rows, shape.cols) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.coshArray(cArray), 9), np.round(np.cosh(data), 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) data = np.random.rand(shape.rows, shape.cols) + 1j * np.random.rand(shape.rows, shape.cols) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.coshArray(cArray), 9), np.round(np.cosh(data), 9)) #################################################################################### def test_count_nonzero(): shapeInput = np.random.randint(1, 50, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 3, [shape.rows, shape.cols], dtype=np.uint32) cArray.setArray(data) assert NumCpp.count_nonzero(cArray, NumCpp.Axis.NONE) == np.count_nonzero(data) shapeInput = np.random.randint(1, 50, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 3, [shape.rows, shape.cols]) imag = np.random.randint(1, 3, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert NumCpp.count_nonzero(cArray, NumCpp.Axis.NONE) == np.count_nonzero(data) shapeInput = np.random.randint(1, 50, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 3, [shape.rows, shape.cols], dtype=np.uint32) cArray.setArray(data) assert np.array_equal(NumCpp.count_nonzero(cArray, NumCpp.Axis.ROW).flatten(), np.count_nonzero(data, axis=0)) shapeInput = np.random.randint(1, 50, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 3, [shape.rows, shape.cols]) imag = np.random.randint(1, 3, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.count_nonzero(cArray, NumCpp.Axis.ROW).flatten(), np.count_nonzero(data, axis=0)) shapeInput = np.random.randint(1, 50, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(0, 3, [shape.rows, shape.cols], dtype=np.uint32) cArray.setArray(data) assert np.array_equal(NumCpp.count_nonzero(cArray, NumCpp.Axis.COL).flatten(), np.count_nonzero(data, axis=1)) shapeInput = np.random.randint(1, 50, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 3, [shape.rows, shape.cols]) imag = np.random.randint(1, 3, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.count_nonzero(cArray, NumCpp.Axis.COL).flatten(), np.count_nonzero(data, axis=1)) #################################################################################### def test_cross(): shape = NumCpp.Shape(1, 2) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArray(shape) data1 = np.random.randint(1, 10, [shape.rows, shape.cols]).astype(np.double) data2 = np.random.randint(1, 10, [shape.rows, shape.cols]).astype(np.double) cArray1.setArray(data1) cArray2.setArray(data2) assert NumCpp.cross(cArray1, cArray2, NumCpp.Axis.NONE).item() == np.cross(data1, data2).item() shape = NumCpp.Shape(1, 2) cArray1 = NumCpp.NdArrayComplexDouble(shape) cArray2 = NumCpp.NdArrayComplexDouble(shape) real1 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag1 = np.random.randint(1, 100, [shape.rows, shape.cols]) data1 = real1 + 1j * imag1 real2 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag2 = np.random.randint(1, 100, [shape.rows, shape.cols]) data2 = real2 + 1j * imag2 cArray1.setArray(data1) cArray2.setArray(data2) assert NumCpp.cross(cArray1, cArray2, NumCpp.Axis.NONE).item() == np.cross(data1, data2).item() shape = NumCpp.Shape(2, np.random.randint(1, 100, [1, ]).item()) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArray(shape) data1 = np.random.randint(1, 10, [shape.rows, shape.cols]).astype(np.double) data2 = np.random.randint(1, 10, [shape.rows, shape.cols]).astype(np.double) cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.cross(cArray1, cArray2, NumCpp.Axis.ROW).getNumpyArray().flatten(), np.cross(data1, data2, axis=0)) shape = NumCpp.Shape(2, np.random.randint(1, 100, [1, ]).item()) cArray1 = NumCpp.NdArrayComplexDouble(shape) cArray2 = NumCpp.NdArrayComplexDouble(shape) real1 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag1 = np.random.randint(1, 100, [shape.rows, shape.cols]) data1 = real1 + 1j * imag1 real2 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag2 = np.random.randint(1, 100, [shape.rows, shape.cols]) data2 = real2 + 1j * imag2 cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.cross(cArray1, cArray2, NumCpp.Axis.ROW).getNumpyArray().flatten(), np.cross(data1, data2, axis=0)) shape = NumCpp.Shape(np.random.randint(1, 100, [1, ]).item(), 2) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArray(shape) data1 = np.random.randint(1, 10, [shape.rows, shape.cols]).astype(np.double) data2 = np.random.randint(1, 10, [shape.rows, shape.cols]).astype(np.double) cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.cross(cArray1, cArray2, NumCpp.Axis.COL).getNumpyArray().flatten(), np.cross(data1, data2, axis=1)) shape = NumCpp.Shape(np.random.randint(1, 100, [1, ]).item(), 2) cArray1 = NumCpp.NdArrayComplexDouble(shape) cArray2 = NumCpp.NdArrayComplexDouble(shape) real1 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag1 = np.random.randint(1, 100, [shape.rows, shape.cols]) data1 = real1 + 1j * imag1 real2 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag2 = np.random.randint(1, 100, [shape.rows, shape.cols]) data2 = real2 + 1j * imag2 cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.cross(cArray1, cArray2, NumCpp.Axis.COL).getNumpyArray().flatten(), np.cross(data1, data2, axis=1)) shape = NumCpp.Shape(1, 3) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArray(shape) data1 = np.random.randint(1, 10, [shape.rows, shape.cols]).astype(np.double) data2 = np.random.randint(1, 10, [shape.rows, shape.cols]).astype(np.double) cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.cross(cArray1, cArray2, NumCpp.Axis.NONE).getNumpyArray().flatten(), np.cross(data1, data2).flatten()) shape = NumCpp.Shape(1, 3) cArray1 = NumCpp.NdArrayComplexDouble(shape) cArray2 = NumCpp.NdArrayComplexDouble(shape) real1 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag1 = np.random.randint(1, 100, [shape.rows, shape.cols]) data1 = real1 + 1j * imag1 real2 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag2 = np.random.randint(1, 100, [shape.rows, shape.cols]) data2 = real2 + 1j * imag2 cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.cross(cArray1, cArray2, NumCpp.Axis.NONE).getNumpyArray().flatten(), np.cross(data1, data2).flatten()) shape = NumCpp.Shape(3, np.random.randint(1, 100, [1, ]).item()) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArray(shape) data1 = np.random.randint(1, 10, [shape.rows, shape.cols]).astype(np.double) data2 = np.random.randint(1, 10, [shape.rows, shape.cols]).astype(np.double) cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.cross(cArray1, cArray2, NumCpp.Axis.ROW).getNumpyArray(), np.cross(data1, data2, axis=0)) shape = NumCpp.Shape(3, np.random.randint(1, 100, [1, ]).item()) cArray1 = NumCpp.NdArrayComplexDouble(shape) cArray2 = NumCpp.NdArrayComplexDouble(shape) real1 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag1 = np.random.randint(1, 100, [shape.rows, shape.cols]) data1 = real1 + 1j * imag1 real2 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag2 = np.random.randint(1, 100, [shape.rows, shape.cols]) data2 = real2 + 1j * imag2 cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.cross(cArray1, cArray2, NumCpp.Axis.ROW).getNumpyArray(), np.cross(data1, data2, axis=0)) shape = NumCpp.Shape(np.random.randint(1, 100, [1, ]).item(), 3) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArray(shape) data1 = np.random.randint(1, 10, [shape.rows, shape.cols]).astype(np.double) data2 = np.random.randint(1, 10, [shape.rows, shape.cols]).astype(np.double) cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.cross(cArray1, cArray2, NumCpp.Axis.COL).getNumpyArray(), np.cross(data1, data2, axis=1)) shape = NumCpp.Shape(np.random.randint(1, 100, [1, ]).item(), 3) cArray1 = NumCpp.NdArrayComplexDouble(shape) cArray2 = NumCpp.NdArrayComplexDouble(shape) real1 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag1 = np.random.randint(1, 100, [shape.rows, shape.cols]) data1 = real1 + 1j * imag1 real2 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag2 = np.random.randint(1, 100, [shape.rows, shape.cols]) data2 = real2 + 1j * imag2 cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.cross(cArray1, cArray2, NumCpp.Axis.COL).getNumpyArray(), np.cross(data1, data2, axis=1)) #################################################################################### def test_cube(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.rand(shape.rows, shape.cols) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.cube(cArray), 9), np.round(data * data * data, 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(np.round(NumCpp.cube(cArray), 9), np.round(data * data * data, 9)) #################################################################################### def test_cumprod(): shapeInput = np.random.randint(1, 5, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 4, [shape.rows, shape.cols], dtype=np.uint32) cArray.setArray(data) assert np.array_equal(NumCpp.cumprod(cArray, NumCpp.Axis.NONE).flatten(), data.cumprod()) shapeInput = np.random.randint(1, 5, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 4, [shape.rows, shape.cols]) imag = np.random.randint(1, 4, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.cumprod(cArray, NumCpp.Axis.NONE).flatten(), data.cumprod()) shapeInput = np.random.randint(1, 5, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 4, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.cumprod(cArray, NumCpp.Axis.ROW), data.cumprod(axis=0)) shapeInput = np.random.randint(1, 5, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 4, [shape.rows, shape.cols]) imag = np.random.randint(1, 4, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.cumprod(cArray, NumCpp.Axis.ROW), data.cumprod(axis=0)) shapeInput = np.random.randint(1, 5, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 4, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.cumprod(cArray, NumCpp.Axis.COL), data.cumprod(axis=1)) shapeInput = np.random.randint(1, 5, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 4, [shape.rows, shape.cols]) imag = np.random.randint(1, 4, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.cumprod(cArray, NumCpp.Axis.COL), data.cumprod(axis=1)) #################################################################################### def test_cumsum(): shapeInput = np.random.randint(1, 50, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 50, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.cumsum(cArray, NumCpp.Axis.NONE).flatten(), data.cumsum()) shapeInput = np.random.randint(1, 50, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 50, [shape.rows, shape.cols]) imag = np.random.randint(1, 50, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.cumsum(cArray, NumCpp.Axis.NONE).flatten(), data.cumsum()) shapeInput = np.random.randint(1, 50, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 50, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.cumsum(cArray, NumCpp.Axis.ROW), data.cumsum(axis=0)) shapeInput = np.random.randint(1, 50, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 50, [shape.rows, shape.cols]) imag = np.random.randint(1, 50, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.cumsum(cArray, NumCpp.Axis.ROW), data.cumsum(axis=0)) shapeInput = np.random.randint(1, 50, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 50, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.cumsum(cArray, NumCpp.Axis.COL), data.cumsum(axis=1)) shapeInput = np.random.randint(1, 50, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 50, [shape.rows, shape.cols]) imag = np.random.randint(1, 50, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.cumsum(cArray, NumCpp.Axis.COL), data.cumsum(axis=1)) #################################################################################### def test_deg2rad(): value = np.abs(np.random.rand(1).item()) * 360 assert np.round(NumCpp.deg2radScaler(value), 9) == np.round(np.deg2rad(value), 9) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.rand(shape.rows, shape.cols) * 360 cArray.setArray(data) assert np.array_equal(np.round(NumCpp.deg2radArray(cArray), 9), np.round(np.deg2rad(data), 9)) #################################################################################### def test_degrees(): value = np.abs(np.random.rand(1).item()) * 2 * np.pi assert np.round(NumCpp.degreesScaler(value), 9) == np.round(np.degrees(value), 9) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.rand(shape.rows, shape.cols) * 2 * np.pi cArray.setArray(data) assert np.array_equal(np.round(NumCpp.degreesArray(cArray), 9), np.round(np.degrees(data), 9)) #################################################################################### def test_deleteIndices(): shapeInput = np.asarray([100, 100]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 100, [shape.rows, shape.cols]) indices = NumCpp.Slice(0, 100, 4) indicesPy = slice(0, 99, 4) cArray.setArray(data) assert np.array_equal(NumCpp.deleteIndicesSlice(cArray, indices, NumCpp.Axis.NONE).flatten(), np.delete(data, indicesPy, axis=None)) shapeInput = np.asarray([100, 100]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 100, [shape.rows, shape.cols]) indices = NumCpp.Slice(0, 100, 4) indicesPy = slice(0, 99, 4) cArray.setArray(data) assert np.array_equal(NumCpp.deleteIndicesSlice(cArray, indices, NumCpp.Axis.ROW), np.delete(data, indicesPy, axis=0)) shapeInput = np.asarray([100, 100]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 100, [shape.rows, shape.cols]) indices = NumCpp.Slice(0, 100, 4) indicesPy = slice(0, 99, 4) cArray.setArray(data) assert np.array_equal(NumCpp.deleteIndicesSlice(cArray, indices, NumCpp.Axis.COL), np.delete(data, indicesPy, axis=1)) shapeInput = np.asarray([100, 100]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 100, [shape.rows, shape.cols]) index = np.random.randint(0, shape.size(), [1, ]).item() cArray.setArray(data) assert np.array_equal(NumCpp.deleteIndicesScaler(cArray, index, NumCpp.Axis.NONE).flatten(), np.delete(data, index, axis=None)) shapeInput = np.asarray([100, 100]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 100, [shape.rows, shape.cols]) index = np.random.randint(0, 100, [1, ]).item() cArray.setArray(data) assert np.array_equal(NumCpp.deleteIndicesScaler(cArray, index, NumCpp.Axis.ROW), np.delete(data, index, axis=0)) shapeInput = np.asarray([100, 100]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 100, [shape.rows, shape.cols]) index = np.random.randint(0, 100, [1, ]).item() cArray.setArray(data) assert np.array_equal(NumCpp.deleteIndicesScaler(cArray, index, NumCpp.Axis.COL), np.delete(data, index, axis=1)) #################################################################################### def test_diag(): shapeInput = np.random.randint(2, 25, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) k = np.random.randint(0, np.min(shapeInput), [1, ]).item() elements = np.random.randint(1, 100, shapeInput) cElements = NumCpp.NdArray(shape) cElements.setArray(elements) assert np.array_equal(NumCpp.diag(cElements, k).flatten(), np.diag(elements, k)) shapeInput = np.random.randint(2, 25, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) k = np.random.randint(0, np.min(shapeInput), [1, ]).item() real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) elements = real + 1j * imag cElements = NumCpp.NdArrayComplexDouble(shape) cElements.setArray(elements) assert np.array_equal(NumCpp.diag(cElements, k).flatten(), np.diag(elements, k)) #################################################################################### def test_diagflat(): numElements = np.random.randint(2, 25, [1, ]).item() shape = NumCpp.Shape(1, numElements) k = np.random.randint(0, 10, [1, ]).item() elements = np.random.randint(1, 100, [numElements, ]) cElements = NumCpp.NdArray(shape) cElements.setArray(elements) assert np.array_equal(NumCpp.diagflat(cElements, k), np.diagflat(elements, k)) numElements = np.random.randint(2, 25, [1, ]).item() shape = NumCpp.Shape(1, numElements) k = np.random.randint(0, 10, [1, ]).item() real = np.random.randint(1, 100, [numElements, ]) imag = np.random.randint(1, 100, [numElements, ]) elements = real + 1j * imag cElements = NumCpp.NdArrayComplexDouble(shape) cElements.setArray(elements) assert np.array_equal(NumCpp.diagflat(cElements, k), np.diagflat(elements, k)) numElements = np.random.randint(1, 25, [1, ]).item() shape = NumCpp.Shape(1, numElements) k = np.random.randint(0, 10, [1, ]).item() elements = np.random.randint(1, 100, [numElements, ]) cElements = NumCpp.NdArray(shape) cElements.setArray(elements) assert np.array_equal(NumCpp.diagflat(cElements, k), np.diagflat(elements, k)) numElements = np.random.randint(1, 25, [1, ]).item() shape = NumCpp.Shape(1, numElements) k = np.random.randint(0, 10, [1, ]).item() real = np.random.randint(1, 100, [numElements, ]) imag = np.random.randint(1, 100, [numElements, ]) elements = real + 1j * imag cElements = NumCpp.NdArrayComplexDouble(shape) cElements.setArray(elements) assert np.array_equal(NumCpp.diagflat(cElements, k), np.diagflat(elements, k)) #################################################################################### def test_diagonal(): shapeInput = np.random.randint(1, 50, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 50, [shape.rows, shape.cols]) cArray.setArray(data) offset = np.random.randint(0, min(shape.rows, shape.cols), [1, ]).item() assert np.array_equal(NumCpp.diagonal(cArray, offset, NumCpp.Axis.ROW).flatten(), np.diagonal(data, offset, axis1=0, axis2=1)) shapeInput = np.random.randint(1, 50, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 50, [shape.rows, shape.cols]) imag = np.random.randint(1, 50, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) offset = np.random.randint(0, min(shape.rows, shape.cols), [1, ]).item() assert np.array_equal(NumCpp.diagonal(cArray, offset, NumCpp.Axis.ROW).flatten(), np.diagonal(data, offset, axis1=0, axis2=1)) shapeInput = np.random.randint(1, 50, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 50, [shape.rows, shape.cols]) cArray.setArray(data) offset = np.random.randint(0, min(shape.rows, shape.cols), [1, ]).item() assert np.array_equal(NumCpp.diagonal(cArray, offset, NumCpp.Axis.COL).flatten(), np.diagonal(data, offset, axis1=1, axis2=0)) shapeInput = np.random.randint(1, 50, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 50, [shape.rows, shape.cols]) imag = np.random.randint(1, 50, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) offset = np.random.randint(0, min(shape.rows, shape.cols), [1, ]).item() assert np.array_equal(NumCpp.diagonal(cArray, offset, NumCpp.Axis.COL).flatten(), np.diagonal(data, offset, axis1=1, axis2=0)) #################################################################################### def test_diff(): shapeInput = np.random.randint(10, 50, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 50, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.diff(cArray, NumCpp.Axis.NONE).flatten(), np.diff(data.flatten())) shapeInput = np.random.randint(10, 50, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 50, [shape.rows, shape.cols]) imag = np.random.randint(1, 50, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.diff(cArray, NumCpp.Axis.NONE).flatten(), np.diff(data.flatten())) shapeInput = np.random.randint(10, 50, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 50, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.diff(cArray, NumCpp.Axis.ROW), np.diff(data, axis=0)) shapeInput = np.random.randint(10, 50, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 50, [shape.rows, shape.cols]) imag = np.random.randint(1, 50, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.diff(cArray, NumCpp.Axis.ROW), np.diff(data, axis=0)) shapeInput = np.random.randint(10, 50, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 50, [shape.rows, shape.cols]).astype(np.uint32) cArray.setArray(data) assert np.array_equal(NumCpp.diff(cArray, NumCpp.Axis.COL).astype(np.uint32), np.diff(data, axis=1)) shapeInput = np.random.randint(10, 50, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 50, [shape.rows, shape.cols]) imag = np.random.randint(1, 50, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.diff(cArray, NumCpp.Axis.COL), np.diff(data, axis=1)) #################################################################################### def test_divide(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArray(shape) data1 = np.random.randint(-100, 100, [shape.rows, shape.cols]) data2 = np.random.randint(-100, 100, [shape.rows, shape.cols]) data2[data2 == 0] = 1 cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(np.round(NumCpp.divide(cArray1, cArray2), 9), np.round(data1 / data2, 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(-100, 100, [shape.rows, shape.cols]) cArray.setArray(data) value = 0 while value == 0: value = np.random.randint(-100, 100) assert np.array_equal(np.round(NumCpp.divide(cArray, value), 9), np.round(data / value, 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(-100, 100, [shape.rows, shape.cols]) data[data == 0] = 1 cArray.setArray(data) value = np.random.randint(-100, 100) assert np.array_equal(np.round(NumCpp.divide(value, cArray), 9), np.round(value / data, 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArrayComplexDouble(shape) cArray2 = NumCpp.NdArrayComplexDouble(shape) real1 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag1 = np.random.randint(1, 100, [shape.rows, shape.cols]) data1 = real1 + 1j * imag1 real2 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag2 = np.random.randint(1, 100, [shape.rows, shape.cols]) data2 = real2 + 1j * imag2 data2[data2 == complex(0)] = complex(1) cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(np.round(NumCpp.divide(cArray1, cArray2), 9), np.round(data1 / data2, 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) value = 0 while value == complex(0): value = np.random.randint(-100, 100) + 1j * np.random.randint(-100, 100) assert np.array_equal(np.round(NumCpp.divide(cArray, value), 9), np.round(data / value, 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag data[data == complex(0)] = complex(1) cArray.setArray(data) value = np.random.randint(-100, 100) + 1j * np.random.randint(-100, 100) assert np.array_equal(np.round(NumCpp.divide(value, cArray), 9), np.round(value / data, 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArrayComplexDouble(shape) cArray2 = NumCpp.NdArray(shape) real1 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag1 = np.random.randint(1, 100, [shape.rows, shape.cols]) data1 = real1 + 1j * imag1 data2 = np.random.randint(1, 100, [shape.rows, shape.cols]) data2[data2 == 0] = 1 cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(np.round(NumCpp.divide(cArray1, cArray2), 9), np.round(data1 / data2, 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArrayComplexDouble(shape) data1 = np.random.randint(1, 100, [shape.rows, shape.cols]) real2 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag2 = np.random.randint(1, 100, [shape.rows, shape.cols]) data2 = real2 + 1j * imag2 data2[data2 == complex(0)] = complex(1) cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(np.round(NumCpp.divide(cArray1, cArray2), 9), np.round(data1 / data2, 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(-100, 100, [shape.rows, shape.cols]) cArray.setArray(data) while value == complex(0): value = np.random.randint(-100, 100) + 1j * np.random.randint(-100, 100) assert np.array_equal(np.round(NumCpp.divide(cArray, value), 9), np.round(data / value, 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(-100, 100, [shape.rows, shape.cols]) data[data == 0] = 1 cArray.setArray(data) value = np.random.randint(-100, 100) + 1j * np.random.randint(-100, 100) assert np.array_equal(np.round(NumCpp.divide(value, cArray), 9), np.round(value / data, 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) value = 0 while value == 0: value = np.random.randint(-100, 100) assert np.array_equal(np.round(NumCpp.divide(cArray, value), 9), np.round(data / value, 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag data[data == complex(0)] = complex(1) cArray.setArray(data) value = np.random.randint(-100, 100) assert np.array_equal(np.round(NumCpp.divide(value, cArray), 9), np.round(value / data, 9)) #################################################################################### def test_dot(): size = np.random.randint(1, 100, [1, ]).item() shape = NumCpp.Shape(1, size) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArray(shape) data1 = np.random.randint(1, 50, [shape.rows, shape.cols]) data2 = np.random.randint(1, 50, [shape.rows, shape.cols]) cArray1.setArray(data1) cArray2.setArray(data2) assert NumCpp.dot(cArray1, cArray2).item() == np.dot(data1, data2.T).item() size = np.random.randint(1, 100, [1, ]).item() shape = NumCpp.Shape(1, size) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArrayComplexDouble(shape) data1 = np.random.randint(1, 50, [shape.rows, shape.cols]) real2 = np.random.randint(1, 50, [shape.rows, shape.cols]) imag2 = np.random.randint(1, 50, [shape.rows, shape.cols]) data2 = real2 + 1j * imag2 cArray1.setArray(data1) cArray2.setArray(data2) assert NumCpp.dot(cArray1, cArray2).item() == np.dot(data1, data2.T).item() size = np.random.randint(1, 100, [1, ]).item() shape = NumCpp.Shape(1, size) cArray1 = NumCpp.NdArrayComplexDouble(shape) cArray2 = NumCpp.NdArrayComplexDouble(shape) real1 = np.random.randint(1, 50, [shape.rows, shape.cols]) imag1 = np.random.randint(1, 50, [shape.rows, shape.cols]) data1 = real1 + 1j * imag1 real2 = np.random.randint(1, 50, [shape.rows, shape.cols]) imag2 = np.random.randint(1, 50, [shape.rows, shape.cols]) data2 = real2 + 1j * imag2 cArray1.setArray(data1) cArray2.setArray(data2) assert NumCpp.dot(cArray1, cArray2).item() == np.dot(data1, data2.T).item() size = np.random.randint(1, 100, [1, ]).item() shape = NumCpp.Shape(1, size) cArray1 = NumCpp.NdArrayComplexDouble(shape) cArray2 = NumCpp.NdArray(shape) real1 = np.random.randint(1, 50, [shape.rows, shape.cols]) imag1 = np.random.randint(1, 50, [shape.rows, shape.cols]) data1 = real1 + 1j * imag1 data2 = np.random.randint(1, 50, [shape.rows, shape.cols]) cArray1.setArray(data1) cArray2.setArray(data2) assert NumCpp.dot(cArray1, cArray2).item() == np.dot(data1, data2.T).item() shapeInput = np.random.randint(1, 100, [2, ]) shape1 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) shape2 = NumCpp.Shape(shapeInput[1].item(), np.random.randint(1, 100, [1, ]).item()) cArray1 = NumCpp.NdArray(shape1) cArray2 = NumCpp.NdArray(shape2) data1 = np.random.randint(1, 50, [shape1.rows, shape1.cols]) data2 = np.random.randint(1, 50, [shape2.rows, shape2.cols]) cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.dot(cArray1, cArray2), np.dot(data1, data2)) shapeInput = np.random.randint(1, 100, [2, ]) shape1 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) shape2 = NumCpp.Shape(shapeInput[1].item(), np.random.randint(1, 100, [1, ]).item()) cArray1 = NumCpp.NdArrayComplexDouble(shape1) cArray2 = NumCpp.NdArrayComplexDouble(shape2) real1 = np.random.randint(1, 50, [shape1.rows, shape1.cols]) imag1 = np.random.randint(1, 50, [shape1.rows, shape1.cols]) data1 = real1 + 1j * imag1 real2 = np.random.randint(1, 50, [shape2.rows, shape2.cols]) imag2 = np.random.randint(1, 50, [shape2.rows, shape2.cols]) data2 = real2 + 1j * imag2 cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.dot(cArray1, cArray2), np.dot(data1, data2)) #################################################################################### def test_empty(): shapeInput = np.random.randint(1, 100, [2, ]) cArray = NumCpp.emptyRowCol(shapeInput[0].item(), shapeInput[1].item()) assert cArray.shape[0] == shapeInput[0] assert cArray.shape[1] == shapeInput[1] assert cArray.size == shapeInput.prod() shapeInput = np.random.randint(1, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.emptyShape(shape) assert cArray.shape[0] == shape.rows assert cArray.shape[1] == shape.cols assert cArray.size == shapeInput.prod() shapeInput = np.random.randint(1, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.empty_like(cArray1) assert cArray2.shape().rows == shape.rows assert cArray2.shape().cols == shape.cols assert cArray2.size() == shapeInput.prod() #################################################################################### def test_endianess(): shapeInput = np.random.randint(1, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) assert NumCpp.endianess(cArray) == NumCpp.Endian.NATIVE #################################################################################### def test_equal(): shapeInput = np.random.randint(1, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArray(shape) data1 = np.random.randint(0, 10, [shape.rows, shape.cols]) data2 = np.random.randint(0, 10, [shape.rows, shape.cols]) cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.equal(cArray1, cArray2), np.equal(data1, data2)) shapeInput = np.random.randint(1, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArrayComplexDouble(shape) cArray2 = NumCpp.NdArrayComplexDouble(shape) real1 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag1 = np.random.randint(1, 100, [shape.rows, shape.cols]) data1 = real1 + 1j * imag1 real2 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag2 = np.random.randint(1, 100, [shape.rows, shape.cols]) data2 = real2 + 1j * imag2 cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.equal(cArray1, cArray2), np.equal(data1, data2)) #################################################################################### def test_exp2(): value = np.abs(np.random.rand(1).item()) assert np.round(NumCpp.expScaler(value), 9) == np.round(np.exp(value), 9) components = np.random.rand(2).astype(np.double) value = complex(components[0], components[1]) assert np.round(NumCpp.expScaler(value), 9) == np.round(np.exp(value), 9) value = np.abs(np.random.rand(1).item()) assert np.round(NumCpp.exp2Scaler(value), 9) == np.round(np.exp2(value), 9) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.rand(shape.rows, shape.cols) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.exp2Array(cArray), 9), np.round(np.exp2(data), 9)) #################################################################################### def test_exp(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.rand(shape.rows, shape.cols) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.expArray(cArray), 9), np.round(np.exp(data), 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) data = np.random.rand(shape.rows, shape.cols) + 1j * np.random.rand(shape.rows, shape.cols) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.expArray(cArray), 9), np.round(np.exp(data), 9)) value = np.abs(np.random.rand(1).item()) assert np.round(NumCpp.expm1Scaler(value), 9) == np.round(np.expm1(value), 9) components = np.random.rand(2).astype(np.double) value = complex(components[0], components[1]) assert np.round(NumCpp.expm1Scaler(value), 9) == np.round(np.expm1(value), 9) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.rand(shape.rows, shape.cols) cArray.setArray(data) assert np.array_equal(np.round(NumCpp.expm1Array(cArray), 9), np.round(np.expm1(data), 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.rand(shape.rows, shape.cols) imag = np.random.rand(shape.rows, shape.cols) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(np.round(NumCpp.expm1Array(cArray), 9), np.round(np.expm1(data), 9)) #################################################################################### def test_eye(): shapeInput = np.random.randint(1, 100, [1, ]).item() randK = np.random.randint(0, shapeInput, [1, ]).item() assert np.array_equal(NumCpp.eye1D(shapeInput, randK), np.eye(shapeInput, k=randK)) shapeInput = np.random.randint(1, 100, [1, ]).item() randK = np.random.randint(0, shapeInput, [1, ]).item() assert np.array_equal(NumCpp.eye1DComplex(shapeInput, randK), np.eye(shapeInput, k=randK) + 1j * np.zeros([shapeInput, shapeInput])) shapeInput = np.random.randint(10, 100, [2, ]) randK = np.random.randint(0, np.min(shapeInput), [1, ]).item() assert np.array_equal(NumCpp.eye2D(shapeInput[0].item(), shapeInput[1].item(), randK), np.eye(shapeInput[0].item(), shapeInput[1].item(), k=randK)) shapeInput = np.random.randint(10, 100, [2, ]) randK = np.random.randint(0, np.min(shapeInput), [1, ]).item() assert np.array_equal(NumCpp.eye2DComplex(shapeInput[0].item(), shapeInput[1].item(), randK), np.eye(shapeInput[0].item(), shapeInput[1].item(), k=randK) + 1j * np.zeros(shapeInput)) shapeInput = np.random.randint(10, 100, [2, ]) cShape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) randK = np.random.randint(0, np.min(shapeInput), [1, ]).item() assert np.array_equal(NumCpp.eyeShape(cShape, randK), np.eye(shapeInput[0].item(), shapeInput[1].item(), k=randK)) shapeInput = np.random.randint(10, 100, [2, ]) cShape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) randK = np.random.randint(0, np.min(shapeInput), [1, ]).item() assert np.array_equal(NumCpp.eyeShapeComplex(cShape, randK), np.eye(shapeInput[0].item(), shapeInput[1].item(), k=randK) + 1j * np.zeros(shapeInput)) #################################################################################### def test_fill_diagonal(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randn(shape.rows, shape.cols) * 100 cArray.setArray(data) NumCpp.fillDiagonal(cArray, 666) np.fill_diagonal(data, 666) assert np.array_equal(cArray.getNumpyArray(), data) #################################################################################### def test_find(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randn(shape.rows, shape.cols) * 100 cArray.setArray(data) value = data.mean() cMask = NumCpp.operatorGreater(cArray, value) cMaskArray = NumCpp.NdArrayBool(cMask.shape[0], cMask.shape[1]) cMaskArray.setArray(cMask) idxs = NumCpp.find(cMaskArray).astype(np.int64) idxsPy = np.nonzero((data > value).flatten())[0] assert np.array_equal(idxs.flatten(), idxsPy) #################################################################################### def test_findN(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randn(shape.rows, shape.cols) * 100 cArray.setArray(data) value = data.mean() cMask = NumCpp.operatorGreater(cArray, value) cMaskArray = NumCpp.NdArrayBool(cMask.shape[0], cMask.shape[1]) cMaskArray.setArray(cMask) idxs = NumCpp.findN(cMaskArray, 8).astype(np.int64) idxsPy = np.nonzero((data > value).flatten())[0] assert np.array_equal(idxs.flatten(), idxsPy[:8]) #################################################################################### def fix(): value = np.random.randn(1).item() * 100 assert NumCpp.fixScaler(value) == np.fix(value) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randn(shape.rows, shape.cols) * 100 cArray.setArray(data) assert np.array_equal(NumCpp.fixArray(cArray), np.fix(data)) #################################################################################### def test_flatten(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.flatten(cArray).getNumpyArray(), np.resize(data, [1, data.size])) #################################################################################### def test_flatnonzero(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.flatnonzero(cArray).getNumpyArray().flatten(), np.flatnonzero(data)) #################################################################################### def test_flip(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.flip(cArray, NumCpp.Axis.NONE).getNumpyArray(), np.flip(data.reshape(1, data.size), axis=1).reshape(shapeInput)) #################################################################################### def test_fliplr(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.fliplr(cArray).getNumpyArray(), np.fliplr(data)) #################################################################################### def test_flipud(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.flipud(cArray).getNumpyArray(), np.flipud(data)) #################################################################################### def test_floor(): value = np.random.randn(1).item() * 100 assert NumCpp.floorScaler(value) == np.floor(value) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randn(shape.rows, shape.cols) * 100 cArray.setArray(data) assert np.array_equal(NumCpp.floorArray(cArray), np.floor(data)) #################################################################################### def test_floor_divide(): value1 = np.random.randn(1).item() * 100 + 1000 value2 = np.random.randn(1).item() * 100 + 1000 assert NumCpp.floor_divideScaler(value1, value2) == np.floor_divide(value1, value2) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArray(shape) data1 = np.random.randn(shape.rows, shape.cols) * 100 + 1000 data2 = np.random.randn(shape.rows, shape.cols) * 100 + 1000 cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.floor_divideArray(cArray1, cArray2), np.floor_divide(data1, data2)) #################################################################################### def test_fmax(): value1 = np.random.randn(1).item() * 100 + 1000 value2 = np.random.randn(1).item() * 100 + 1000 assert NumCpp.fmaxScaler(value1, value2) == np.fmax(value1, value2) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArray(shape) data1 = np.random.randn(shape.rows, shape.cols) * 100 + 1000 data2 = np.random.randn(shape.rows, shape.cols) * 100 + 1000 cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.fmaxArray(cArray1, cArray2), np.fmax(data1, data2)) #################################################################################### def test_fmin(): value1 = np.random.randn(1).item() * 100 + 1000 value2 = np.random.randn(1).item() * 100 + 1000 assert NumCpp.fminScaler(value1, value2) == np.fmin(value1, value2) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArray(shape) data1 = np.random.randn(shape.rows, shape.cols) * 100 + 1000 data2 = np.random.randn(shape.rows, shape.cols) * 100 + 1000 cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.fminArray(cArray1, cArray2), np.fmin(data1, data2)) #################################################################################### def test_fmod(): value1 = np.random.randint(1, 100, [1, ]).item() * 100 + 1000 value2 = np.random.randint(1, 100, [1, ]).item() * 100 + 1000 assert NumCpp.fmodScaler(value1, value2) == np.fmod(value1, value2) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArrayUInt32(shape) cArray2 = NumCpp.NdArrayUInt32(shape) data1 = np.random.randint(1, 100, [shape.rows, shape.cols], dtype=np.uint32) * 100 + 1000 data2 = np.random.randint(1, 100, [shape.rows, shape.cols], dtype=np.uint32) * 100 + 1000 cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.fmodArray(cArray1, cArray2), np.fmod(data1, data2)) #################################################################################### def test_fromfile(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 50, [shape.rows, shape.cols]).astype(np.double) cArray.setArray(data) tempDir = r'C:\Temp' if not os.path.exists(tempDir): os.mkdir(tempDir) tempFile = os.path.join(tempDir, 'NdArrayDump.bin') NumCpp.dump(cArray, tempFile) assert os.path.isfile(tempFile) data2 = NumCpp.fromfile(tempFile, '').reshape(shape) assert np.array_equal(data, data2) os.remove(tempFile) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 50, [shape.rows, shape.cols]).astype(np.double) cArray.setArray(data) tempDir = tempfile.gettempdir() tempFile = os.path.join(tempDir, 'NdArrayDump') NumCpp.tofile(cArray, tempFile, '\n') assert os.path.exists(tempFile + '.txt') data2 = NumCpp.fromfile(tempFile + '.txt', '\n').reshape(shape) assert np.array_equal(data, data2) os.remove(tempFile + '.txt') #################################################################################### def test_fromiter(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 100, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.fromiter(cArray).flatten(), data.flatten()) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 100, [shape.rows, shape.cols]) imag = np.random.randint(1, 100, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.fromiter(cArray).flatten(), data.flatten()) #################################################################################### def test_full(): shapeInput = np.random.randint(1, 100, [1, ]).item() value = np.random.randint(1, 100, [1, ]).item() cArray = NumCpp.fullSquare(shapeInput, value) assert (cArray.shape[0] == shapeInput and cArray.shape[1] == shapeInput and cArray.size == shapeInput**2 and np.all(cArray == value)) shapeInput = np.random.randint(1, 100, [1, ]).item() value = np.random.randint(1, 100, [1, ]).item() + 1j * np.random.randint(1, 100, [1, ]).item() cArray = NumCpp.fullSquareComplex(shapeInput, value) assert (cArray.shape[0] == shapeInput and cArray.shape[1] == shapeInput and cArray.size == shapeInput**2 and np.all(cArray == value)) shapeInput = np.random.randint(1, 100, [2, ]) value = np.random.randint(1, 100, [1, ]).item() cArray = NumCpp.fullRowCol(shapeInput[0].item(), shapeInput[1].item(), value) assert (cArray.shape[0] == shapeInput[0] and cArray.shape[1] == shapeInput[1] and cArray.size == shapeInput.prod() and np.all(cArray == value)) shapeInput = np.random.randint(1, 100, [2, ]) value = np.random.randint(1, 100, [1, ]).item() + 1j * np.random.randint(1, 100, [1, ]).item() cArray = NumCpp.fullRowColComplex(shapeInput[0].item(), shapeInput[1].item(), value) assert (cArray.shape[0] == shapeInput[0] and cArray.shape[1] == shapeInput[1] and cArray.size == shapeInput.prod() and np.all(cArray == value)) shapeInput = np.random.randint(1, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) value = np.random.randint(1, 100, [1, ]).item() cArray = NumCpp.fullShape(shape, value) assert (cArray.shape[0] == shape.rows and cArray.shape[1] == shape.cols and cArray.size == shapeInput.prod() and np.all(cArray == value)) shapeInput = np.random.randint(1, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) value = np.random.randint(1, 100, [1, ]).item() cArray = NumCpp.fullShape(shape, value) assert (cArray.shape[0] == shape.rows and cArray.shape[1] == shape.cols and cArray.size == shapeInput.prod() and np.all(cArray == value)) #################################################################################### def test_full_like(): shapeInput = np.random.randint(1, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArray(shape) value = np.random.randint(1, 100, [1, ]).item() cArray2 = NumCpp.full_like(cArray1, value) assert (cArray2.shape().rows == shape.rows and cArray2.shape().cols == shape.cols and cArray2.size() == shapeInput.prod() and np.all(cArray2.getNumpyArray() == value)) shapeInput = np.random.randint(1, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArrayComplexDouble(shape) value = np.random.randint(1, 100, [1, ]).item() + 1j * np.random.randint(1, 100, [1, ]).item() cArray2 = NumCpp.full_likeComplex(cArray1, value) assert (cArray2.shape().rows == shape.rows and cArray2.shape().cols == shape.cols and cArray2.size() == shapeInput.prod() and np.all(cArray2.getNumpyArray() == value)) #################################################################################### def test_gcd(): if not NumCpp.NUMCPP_NO_USE_BOOST or NumCpp.STL_GCD_LCM: value1 = np.random.randint(1, 1000, [1, ]).item() value2 = np.random.randint(1, 1000, [1, ]).item() assert NumCpp.gcdScaler(value1, value2) == np.gcd(value1, value2) if not NumCpp.NUMCPP_NO_USE_BOOST: size = np.random.randint(20, 100, [1, ]).item() cArray = NumCpp.NdArrayUInt32(1, size) data = np.random.randint(1, 1000, [size, ], dtype=np.uint32) cArray.setArray(data) assert NumCpp.gcdArray(cArray) == np.gcd.reduce(data) # noqa #################################################################################### def test_gradient(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 1000, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.gradient(cArray, NumCpp.Axis.ROW), np.gradient(data, axis=0)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 1000, [shape.rows, shape.cols]) imag = np.random.randint(1, 1000, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.gradient(cArray, NumCpp.Axis.ROW), np.gradient(data, axis=0)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 1000, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.gradient(cArray, NumCpp.Axis.COL), np.gradient(data, axis=1)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 1000, [shape.rows, shape.cols]) imag = np.random.randint(1, 1000, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.gradient(cArray, NumCpp.Axis.COL), np.gradient(data, axis=1)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArray(shape) data = np.random.randint(1, 1000, [shape.rows, shape.cols]) cArray.setArray(data) assert np.array_equal(NumCpp.gradient(cArray, NumCpp.Axis.NONE).flatten(), np.gradient(data.flatten(), axis=0)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray = NumCpp.NdArrayComplexDouble(shape) real = np.random.randint(1, 1000, [shape.rows, shape.cols]) imag = np.random.randint(1, 1000, [shape.rows, shape.cols]) data = real + 1j * imag cArray.setArray(data) assert np.array_equal(NumCpp.gradient(cArray, NumCpp.Axis.NONE).flatten(), np.gradient(data.flatten(), axis=0)) #################################################################################### def test_greater(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArray(shape) data1 = np.random.randint(1, 100, [shape.rows, shape.cols]) data2 = np.random.randint(1, 100, [shape.rows, shape.cols]) cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.greater(cArray1, cArray2).getNumpyArray(), np.greater(data1, data2)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArrayComplexDouble(shape) cArray2 = NumCpp.NdArrayComplexDouble(shape) real1 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag1 = np.random.randint(1, 100, [shape.rows, shape.cols]) data1 = real1 + 1j * imag1 real2 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag2 = np.random.randint(1, 100, [shape.rows, shape.cols]) data2 = real2 + 1j * imag2 cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.greater(cArray1, cArray2).getNumpyArray(), np.greater(data1, data2)) #################################################################################### def test_greater_equal(): shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArray(shape) data1 = np.random.randint(1, 100, [shape.rows, shape.cols]) data2 = np.random.randint(1, 100, [shape.rows, shape.cols]) cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.greater_equal(cArray1, cArray2).getNumpyArray(), np.greater_equal(data1, data2)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArrayComplexDouble(shape) cArray2 = NumCpp.NdArrayComplexDouble(shape) real1 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag1 = np.random.randint(1, 100, [shape.rows, shape.cols]) data1 = real1 + 1j * imag1 real2 = np.random.randint(1, 100, [shape.rows, shape.cols]) imag2 = np.random.randint(1, 100, [shape.rows, shape.cols]) data2 = real2 + 1j * imag2 cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(NumCpp.greater_equal(cArray1, cArray2).getNumpyArray(), np.greater_equal(data1, data2)) #################################################################################### def test_histogram(): shape = NumCpp.Shape(1024, 1024) cArray = NumCpp.NdArray(shape) data = np.random.randn(1024, 1024) * np.random.randint(1, 10, [1, ]).item() + np.random.randint(1, 10, [1, ]).item() cArray.setArray(data) numBins = np.random.randint(10, 30, [1, ]).item() histogram, bins = NumCpp.histogram(cArray, numBins) h, b = np.histogram(data, numBins) assert np.array_equal(histogram.getNumpyArray().flatten().astype(np.int32), h) assert np.array_equal(np.round(bins.getNumpyArray().flatten(), 9), np.round(b, 9)) shape = NumCpp.Shape(1024, 1024) cArray = NumCpp.NdArray(shape) data = np.random.randn(1024, 1024) * np.random.randint(1, 10, [1, ]).item() + np.random.randint(1, 10, [1, ]).item() cArray.setArray(data) binEdges = np.linspace(data.min(), data.max(), 15, endpoint=True) cBinEdges = NumCpp.NdArray(1, binEdges.size) cBinEdges.setArray(binEdges) histogram = NumCpp.histogram(cArray, cBinEdges) h, _ = np.histogram(data, binEdges) assert np.array_equal(histogram.flatten().astype(np.int32), h) #################################################################################### def test_hstack(): shapeInput = np.random.randint(20, 100, [2, ]) shape1 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) shape2 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item() + np.random.randint(1, 10, [1, ]).item()) shape3 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item() + np.random.randint(1, 10, [1, ]).item()) shape4 = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item() + np.random.randint(1, 10, [1, ]).item()) cArray1 = NumCpp.NdArray(shape1) cArray2 = NumCpp.NdArray(shape2) cArray3 = NumCpp.NdArray(shape3) cArray4 = NumCpp.NdArray(shape4) data1 = np.random.randint(1, 100, [shape1.rows, shape1.cols]) data2 = np.random.randint(1, 100, [shape2.rows, shape2.cols]) data3 = np.random.randint(1, 100, [shape3.rows, shape3.cols]) data4 = np.random.randint(1, 100, [shape4.rows, shape4.cols]) cArray1.setArray(data1) cArray2.setArray(data2) cArray3.setArray(data3) cArray4.setArray(data4) assert np.array_equal(NumCpp.hstack(cArray1, cArray2, cArray3, cArray4), np.hstack([data1, data2, data3, data4])) #################################################################################### def test_hypot(): value1 = np.random.randn(1).item() * 100 + 1000 value2 = np.random.randn(1).item() * 100 + 1000 assert NumCpp.hypotScaler(value1, value2) == np.hypot(value1, value2) value1 = np.random.randn(1).item() * 100 + 1000 value2 = np.random.randn(1).item() * 100 + 1000 value3 = np.random.randn(1).item() * 100 + 1000 assert (np.round(NumCpp.hypotScalerTriple(value1, value2, value3), 9) == np.round(np.sqrt(value1**2 + value2**2 + value3**2), 9)) shapeInput = np.random.randint(20, 100, [2, ]) shape = NumCpp.Shape(shapeInput[0].item(), shapeInput[1].item()) cArray1 = NumCpp.NdArray(shape) cArray2 = NumCpp.NdArray(shape) data1 = np.random.randn(shape.rows, shape.cols) * 100 + 1000 data2 = np.random.randn(shape.rows, shape.cols) * 100 + 1000 cArray1.setArray(data1) cArray2.setArray(data2) assert np.array_equal(np.round(NumCpp.hypotArray(cArray1, cArray2), 9), np.round(np.hypot(data1, data2), 9)) #################################################################################### def test_identity(): squareSize = np.random.randint(10, 100, [1, ]).item() assert np.array_equal(NumCpp.identity(squareSize).getNumpyArray(), np.identity(squareSize)) squareSize = np.random.randint(10, 100, [1, ]).item() assert np.array_equal(NumCpp.identityComplex(squareSize).getNumpyArray(), np.identity(squareSize) + 1j * np.zeros([squareSize, squareSize])) #################################################################################### def test_imag(): components = np.random.rand(2).astype(np.double) value = complex(components[0], components[1]) assert np.round(NumCpp.imagScaler(value), 9) == np.round(
np.imag(value)
numpy.imag
import numpy as np import cv2 import time import warnings warnings.filterwarnings('error') # allow the camera to warmup time.sleep(0.1) # class for lane detection class Lines(): def __init__(self): # were the lines detected at least once self.detected_first = False # were the lines detected in the last iteration? self.detected = False # average x values of the fitted lines self.bestxl = None self.bestyl = None self.bestxr = None self.bestyr = None # polynomial coefficients averaged over the last iterations self.best_fit_l = None self.best_fit_r = None # polynomial coefficients for the most recent fit self.current_fit_l = None self.current_fit_r = None # radius of curvature of the lines in meters self.left_curverad = None self.right_curverad = None # distance in meters of vehicle center from the line self.offset = None # x values for detected line pixels self.allxl = None self.allxr = None # y values for detected line pixels self.allyl = None self.allyr = None # camera calibration parameters self.cam_mtx = None self.cam_dst = None # camera distortion parameters self.M = None self.Minv = None # image shape self.im_shape = (None, None) # distance to look ahead in meters self.look_ahead = 10 self.remove_pixels = 90 # enlarge output image self.enlarge = 2.5 # warning from numpy polyfit self.poly_warning = False # set camera calibration parameters def set_cam_calib_param(self, mtx, dst): self.cam_mtx = mtx self.cam_dst = dst # undistort image def undistort(self, img): return cv2.undistort(img, self.cam_mtx, self.cam_dst, None, self.cam_mtx) # get binary image based on color thresholding def color_thresh(self, img, thresh=(0, 255)): # convert to HSV color space and separate the V channel hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HLS).astype(np.float) s_channel = hsv[:, :, 2] # threshold color channel s_binary = np.zeros_like(s_channel) s_binary[(s_channel >= thresh[0]) & (s_channel <= thresh[1])] = 1 return s_binary # get binary image based on sobel gradient thresholding def abs_sobel_thresh(self, sobel, thresh=(0, 255)): abs_sobel = np.absolute(sobel) max_s = np.max(abs_sobel) if max_s == 0: max_s = 1 scaled_sobel = np.uint8(255 * abs_sobel / max_s) sbinary = np.zeros_like(scaled_sobel) sbinary[(scaled_sobel >= thresh[0]) & (scaled_sobel <= thresh[1])] = 1 return sbinary # get binary image based on sobel magnitude gradient thresholding def mag_thresh(self, sobelx, sobely, mag_thresh=(0, 255)): abs_sobel = np.sqrt(sobelx ** 2 + sobely ** 2) max_s = np.max(abs_sobel) if max_s == 0: max_s = 1 scaled_sobel = np.uint8(255 * abs_sobel / max_s) sbinary = np.zeros_like(scaled_sobel) sbinary[(scaled_sobel >= mag_thresh[0]) & (scaled_sobel <= mag_thresh[1])] = 1 return sbinary # get binary image based on directional gradient thresholding def dir_threshold(self, sobelx, sobely, thresh=(0, np.pi / 2)): abs_sobelx = np.abs(sobelx) abs_sobely = np.abs(sobely) grad_sobel = np.arctan2(abs_sobely, abs_sobelx) sbinary = np.zeros_like(grad_sobel) sbinary[(grad_sobel >= thresh[0]) & (grad_sobel <= thresh[1])] = 1 return sbinary # get binary combining various thresholding methods def binary_extraction(self, image, ksize=3): # undistort first # image = self.undistort(image) color_bin = self.color_thresh(image, thresh=(90, 150)) # initial values 110, 255 gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize) sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize) gradx = self.abs_sobel_thresh(sobelx, thresh=(100, 190)) # initial values 40, 160 grady = self.abs_sobel_thresh(sobely, thresh=(100, 190)) # initial values 40, 160 mag_binary = self.mag_thresh(sobelx, sobely, mag_thresh=(100, 190)) # initial values 40, 160 # dir_binary = self.dir_threshold(sobelx, sobely, thresh=(0.7, 1.3)) combined = np.zeros_like(gradx) # combined[(((gradx == 1) & (grady == 1)) | ((mag_binary == 1) & (dir_binary == 1))) | (color_bin==1) ] = 1 combined[(((gradx == 1) & (grady == 1)) | (mag_binary == 1)) | (color_bin == 1)] = 1 # combined[(((gradx == 1) & (grady == 1)) | (mag_binary == 1)) ] = 1 return combined # transform perspective def trans_per(self, image): image = self.binary_extraction(image) self.binary_image = image ysize = image.shape[0] xsize = image.shape[1] # define region of interest left_bottom = (xsize / 10, ysize) apex_l = (xsize / 2 - 2600 / (self.look_ahead ** 2), ysize - self.look_ahead * 275 / 30) apex_r = (xsize / 2 + 2600 / (self.look_ahead ** 2), ysize - self.look_ahead * 275 / 30) right_bottom = (xsize - xsize / 10, ysize) # define vertices for perspective transformation src = np.array([[left_bottom], [apex_l], [apex_r], [right_bottom]], dtype=np.float32) dst = np.float32([[xsize / 3, ysize], [xsize / 4.5, 0], [xsize - xsize / 4.5, 0], [xsize - xsize / 3, ysize]]) self.M = cv2.getPerspectiveTransform(src, dst) self.Minv = cv2.getPerspectiveTransform(dst, src) if len(image.shape) > 2: warped = cv2.warpPerspective(image, self.M, image.shape[-2:None:-1], flags=cv2.INTER_LINEAR) else: warped = cv2.warpPerspective(image, self.M, image.shape[-1:None:-1], flags=cv2.INTER_LINEAR) return warped # creat window mask for lane detecion def window_mask(self, width, height, img_ref, center, level): output = np.zeros_like(img_ref) output[int(img_ref.shape[0] - (level + 1) * height):int(img_ref.shape[0] - level * height), \ max(0, int(center - width / 2)):min(int(center + width / 2), img_ref.shape[1])] = 1 return output # find widow centroids of left and right lane def find_window_centroids(self, warped, window_width, window_height, margin): window_centroids = [] # Store the (left,right) window centroid positions per level window = np.ones(window_width) # Create our window template that we will use for convolutions # First find the two starting positions for the left and right lane by using np.sum to get the vertical image slice # and then np.convolve the vertical image slice with the window template # Sum quarter bottom of image to get slice, could use a different ratio l_sum = np.sum(warped[int(3 * warped.shape[0] / 4):, :int(warped.shape[1] / 2)], axis=0) l_center = np.argmax(np.convolve(window, l_sum)) - window_width / 2 r_sum = np.sum(warped[int(3 * warped.shape[0] / 4):, int(warped.shape[1] / 2):], axis=0) r_center = np.argmax(np.convolve(window, r_sum)) - window_width / 2 + int(warped.shape[1] / 2) # Add what we found for the first layer window_centroids.append((l_center, r_center)) # Go through each layer looking for max pixel locations for level in range(1, (int)(warped.shape[0] / window_height)): # convolve the window into the vertical slice of the image image_layer = np.sum( warped[int(warped.shape[0] - (level + 1) * window_height):int(warped.shape[0] - level * window_height), :], axis=0) conv_signal = np.convolve(window, image_layer) # Find the best left centroid by using past left center as a reference # Use window_width/2 as offset because convolution signal reference is at right side of window, not center of window offset = window_width / 2 l_min_index = int(max(l_center + offset - margin, 0)) l_max_index = int(min(l_center + offset + margin, warped.shape[1])) l_center = np.argmax(conv_signal[l_min_index:l_max_index]) + l_min_index - offset # Find the best right centroid by using past right center as a reference r_min_index = int(max(r_center + offset - margin, 0)) r_max_index = int(min(r_center + offset + margin, warped.shape[1])) r_center = np.argmax(conv_signal[r_min_index:r_max_index]) + r_min_index - offset # Add what we found for that layer window_centroids.append((l_center, r_center)) return window_centroids # fit polynomials on the extracted left and right lane def get_fit(self, image): # check if the lanes were detected in the last iteration, if not search for the lanes if not self.detected: # window settings window_width = 40 window_height = 40 # break image into 9 vertical layers since image height is 720 margin = 10 # how much to slide left and right for searching window_centroids = self.find_window_centroids(image, window_width, window_height, margin) # if we found any window centers if len(window_centroids) > 0: # points used to draw all the left and right windows l_points = np.zeros_like(image) r_points = np.zeros_like(image) # go through each level and draw the windows for level in range(0, len(window_centroids)): # Window_mask is a function to draw window areas l_mask = self.window_mask(window_width, window_height, image, window_centroids[level][0], level) r_mask = self.window_mask(window_width, window_height, image, window_centroids[level][1], level) # Add graphic points from window mask here to total pixels found l_points[(image == 1) & (l_mask == 1)] = 1 r_points[(image == 1) & (r_mask == 1)] = 1 # construct images of the results template_l = np.array(l_points * 255, np.uint8) # add left window pixels template_r = np.array(r_points * 255, np.uint8) # add right window pixels zero_channel = np.zeros_like(template_l) # create a zero color channel left_right = np.array(cv2.merge((template_l, zero_channel, template_r)), np.uint8) # make color image left and right lane # get points for polynomial fit self.allyl, self.allxl = l_points.nonzero() self.allyr, self.allxr = r_points.nonzero() # check if lanes are detected if (len(self.allxl) > 0) & (len(self.allxr) > 0): try: self.current_fit_l = np.polyfit(self.allyl, self.allxl, 2) self.current_fit_r = np.polyfit(self.allyr, self.allxr, 2) self.poly_warning = False except np.RankWarning: self.poly_warning = True pass # check if lanes are detected correctly if self.check_fit(): self.detected = True # if this is the first detection initialize the best values if not self.detected_first: self.best_fit_l = self.current_fit_l self.best_fit_r = self.current_fit_r # if not then average with new else: self.best_fit_l = self.best_fit_l * 0.6 + self.current_fit_l * 0.4 self.best_fit_r = self.best_fit_r * 0.6 + self.current_fit_r * 0.4 # assign new best values based on this iteration self.detected_first = True self.bestxl = self.allxl self.bestyl = self.allyl self.bestxr = self.allxr self.bestyr = self.allyr self.left_right = left_right # set flag if lanes are not detected correctly else: self.detected = False # if lanes were detected in the last frame, search area for current frame else: non_zero_y, non_zero_x = image.nonzero() margin = 10 # search area margin left_lane_points_indx = ((non_zero_x > ( self.best_fit_l[0] * (non_zero_y ** 2) + self.best_fit_l[1] * non_zero_y + self.best_fit_l[ 2] - margin)) & ( non_zero_x < ( self.best_fit_l[0] * (non_zero_y ** 2) + self.best_fit_l[1] * non_zero_y + self.best_fit_l[2] + margin))) right_lane_points_indx = ((non_zero_x > ( self.best_fit_r[0] * (non_zero_y ** 2) + self.best_fit_r[1] * non_zero_y + self.best_fit_r[ 2] - margin)) & ( non_zero_x < ( self.best_fit_r[0] * (non_zero_y ** 2) + self.best_fit_r[1] * non_zero_y + self.best_fit_r[2] + margin))) # extracted lef lane pixels self.allxl = non_zero_x[left_lane_points_indx] self.allyl = non_zero_y[left_lane_points_indx] # extracted rightt lane pixels self.allxr = non_zero_x[right_lane_points_indx] self.allyr = non_zero_y[right_lane_points_indx] # if lines were found if (len(self.allxl) > 0) & (len(self.allxr) > 0): try: self.current_fit_l = np.polyfit(self.allyl, self.allxl, 2) self.current_fit_r = np.polyfit(self.allyr, self.allxr, 2) except np.RankWarning: self.poly_warning = True pass # check if lanes are detected correctly if self.check_fit(): # average out the best fit with new values self.best_fit_l = self.best_fit_l * 0.6 + self.current_fit_l * 0.4 self.best_fit_r = self.best_fit_r * 0.6 + self.current_fit_r * 0.4 # assign new best values based on this iteration self.bestxl = self.allxl self.bestyl = self.allyl self.bestxr = self.allxr self.bestyr = self.allyr # construct images of the results template_l = np.copy(image).astype(np.uint8) template_r = np.copy(image).astype(np.uint8) template_l[non_zero_y[left_lane_points_indx], non_zero_x[ left_lane_points_indx]] = 255 # add left window pixels template_r[non_zero_y[right_lane_points_indx], non_zero_x[ right_lane_points_indx]] = 255 # add right window pixels zero_channel =
np.zeros_like(template_l)
numpy.zeros_like
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Fri Dec 8 10:13:01 2017 + ; NAME: ; ; izi_mcmc ; ; PURPOSE: ; ; Compute the posterior PDF of the gas-phase metallicity, ionization ; parameter and dust EBV given a set of observed emission line fluxes ; and errors, and a photo-ionization model grid. The code assumed a Calzetti ; extinction law. ; ; CALLING SEQUENCE: ; ; result = IZI(flux, error, id, gridfile=None, templ_dir='', grid=None, plot=True, plot_z_steps=False, plot_q_steps=False, plot_ebv_steps=False, plot_derivatives=False, logohsun=None, epsilon=None, nz=None, nq=None, intergridfile=None, integrid=None, outgridfile=False, logzlimits=None, logqlimits=None, logzprior=None, logqprior=None, nonorm=0, quiet=False) ; ; ; INPUT PARAMETERS: ; ; FLUX: array of emission line fluxes in arbitrary units. Fluxes ; are nornalized internally in the code to the flux of H-beta, or ; in the case H-beta is not provided to the flux of the brightest ; input emission line. Fluxes should NOT be corrected for dust extinction. ; ; ERROR: array of emission line flux errors. Upper limits can be ; provided by setting the a value of -666 in the FLUX array and ; providing the 1 sigma upper limit in the ERROR parameter. ; ; ID: array of strings containing the emission line IDs. The ; names of the lines must comply with the IDs stored in the FITS ; table storing the photo-ionization model grid. For all the grids that ; are provided with IZI the following are some (not all) of the ; adopted IDs: ; ; 'oii3726' for [OII]-3726 ; 'oii3729' for [OII]-3729 ; 'hgamma' for H_gamma-4341 ; 'oiii4959' for [OIII]-4959 ; 'hbeta' for H_beta-4861 ; 'oiii5007' for [OIII]-5007 ; 'oi6300' for [OI]-6300 ; 'nii6548' for [NII]-6548 ; 'halpha' for H_alpha-6563 ; 'nii6584' for [NII]-6584 ; 'sii6717' for [SII]-6717 ; 'sii6731' for [SII]-6731 ; 'siii9068' for [SIII]-9068 ; 'siii9532' for [SIII]-9532 ; ; ; For a complete list of lines included in a particular grid read ; the photo-ionization model grid into Python and check ; the ID tag. ; ; Summed doublets (e.g. [OII]3726,9 at low resolution) can be ; considered as a single line by providing the IDs of the ; components separated by a semicolon in IDIN (e.g. 'oii3726;oii3729'). ; Note that this should only be done when the doublet are close in ; wavelength since the code applies an extinction correction based on the ; wavelength of the first line ; ; ; KEYWORD PARAMETERS: ; ; GRIDFILE: string containing the filename for the photo-ionization ; model grid to be used. If not provided IZI defaults to the ; Levesque et al. 2010 models with high mass loss, constant star ; formation history, n=1e2 cm^-3 and age of 6.0Myr. The format of ; the grid files is a FITS table read as an astropy table with an ; entry for each (Z,q) element in the grid and the following tags for ; each entry: ; ; NAME STRING name of the photo-ionization model ; LOGOHSUN FLOAT assumed 12+log(O/H) solar abundance in the model ; LOGZ FLOAT log of metallicity (Z) in solar units ; LOGQ FLOAT log of ion. parameter in log(cm/s) units ; ID STRING[Nlines] emission line IDs ; FLUX FLOAT[Nlines] emission line fluxes ; ; PLOT: set this keyword to True to produce corner plots of the ; parameters PDFs. ; ; PLOT_Z_STEPS: set this keyword to True to produce a plot of the log(Z) values found by ; the walkers of the mcmc as a function of the number of steps (use to check for convergence). ; ; PLOT_Q_STEPS: set this keyword to True to produce a plot of the log(q) values found by ; the walkers of the mcmc as a function of the number of steps (use to check for convergence). ; ; PLOT_EBV_STEPS: set this keyword to True to produce a plot of the E(B-V) values found by ; the walkers of the mcmc as a function of the number of steps (use to check for convergence). ; ; LOGOHSUN: set this keyword to a user supplied value which is used ; instead of the LOGOHSUN value in the model grid file. ; ; EPSILON: systematic uncertainty in dex for the emission line ; fluxes in the model (see equation 3 in Blanc et al. 2014). If not ; provided the code assumes a default value is 0.1 dex. ; ; NZ: number of log(Z) elements in the interpolated grid, if not ; provided the default is NZ=100. NZ must be 100 or larger to minimise the ; error in the interpolation. ; ; NQ: number of log(q) elements in the interpolated grid, if not ; provided the default is NZ=50. NQ must be 100 or larger to minimise the ; error in the interpolation. ; ; INTERGRIDFILE: string containing the filename for an already ; interpolated photo-ionization model grid. If provided this file ; is used intead of GRIDFILE and the interpolation step is ; skiped. This interpolated grid file should be created using the ; OUTGRIDFILE keyword. It is strongly adivces to use this keyword for ; speeding computation time when running IZI_MCMC for a large sample of objects. ; ; OUTGRIDFILE: set this keyword to True to produce to save the ; interpolated grid file for latter use with INTERGRIDFILE ; ; LOGZLIMITS: 2 element array containing the lower and upper ; log(Z) limits for the interpolated grid (section 3 of Blanc et ; al. 2014) in units of 12+log(O/H) ; ; LOGQLIMITS: 2 element array containing the lower and upper ; log(Z) limits for the interpolated grid (section 3 of Blanc et ; al. 2014) in units of log(cm/s) ; ; NONORM: set this keyword to avoid the normalization of the line ; fluxes. This is useful when using model grids of line ratios ; instead of line fluxes. ; ; QUIET: set to true to avoid printing output to terminal ; ; LOGQPRIOR: 2 element list containing the expected value of the parameter logq ; and its uncertainty. A gaussian centred on this value multiplies the ; likelihood function. ; ; LOGZPRIOR: 2 element list containing the expected value of the parameter logZ ; and its uncertainty. A gaussian centred on this value multiplies the ; likelihood function. ; ; OUTPUT: ; ; RESULT.sol: a dictionary containing the output best fit parameters and PDFs ; ; id: names of the emission lines in the photo-ionization model ; flux: nomalized input line fluxes, same size as id ; error: error in normalized line fluxes, same size as id ; Z, err_down_Z, err_up_Z: median, 16th and 84th percentiles of the metallicity PDF in units of 12+log(O/H) ; q, err_down_q, err_up_q: median, 16th and 84th percentiles of the ionization parameter PDF in units of log(cm/s) ; ebv, err_down_ebv, err_up_ebv: median, 16th and 84th percentiles of the dust attenuation E(B_V) in units of mag ; zarr, qarr, ebvarr: array of metallicity, ionization parameter, extinction values in units of 12+log(O/H), log(cm/s), mag ; z_pdf, q_pdf, ebv_pdf: 1D marginalized metallicity PDF as a function of zarr, qarr, ebvarr ; chi2: chi^2 between observed fluxes and model fluxes at mode of the joint PDF ; acc_fraction: acceptance fraction ; flag: [znpeaks, qnpeaks, ebvnpeaks, zlimit, qlimit, ebvlimit] with ; znpeaks, qnpeaks, ebvnpeaks: number of peaks in log(Z), log(q) and E(B-V) marginalized PDFs; ; zlimit, qlimit, ebvlimit: flags stating if the marginalized PDF is bound (0), or is either an upper (1) or lower (2) limit, or completely unconstrained (3). ; Z_max, q_max, ebv_max: array with 12+log(O/H), log(q), E(B-V) max values and the corrisponding PDF values, with a length equal to zarr, qarr, ebvarr length ; .fig: The figure object corresponding to the corner plots of the output .samples: the full MCMC samples array. It has dimensions (Nsamples, 3), where 3 corresponds to the 3 free paramters: metallicity (12+log(O/H), ionisation parameter (logq) and EBV (mag). ; ; ; RESULT.line_stat: a dictionary containing the best model fit for each line and ; other diagnostic information ; ; id: names of the emission lines, same size and *same order* as the input flux array ; fobs: normalised emission line flux, same size and *same order* as the input flux array ; eobs: normalised emission line flux error, same size and *same order* as the input flux array ; fmod: normalised best fit model flux, same size and *same order* as the input flux array ; emod: normalised best fit model flux error, same size and *same order* as the input flux array ; chi2_line: chi2 for each emission line, same size and *same order* as the input flux array ; ; USAGE EXAMPLE: ; see test_mcmc.py ; ; MODIFICATION HISTORY: dates are in European format ; ; V1.0 - Created by <NAME> ; V2.0 - Translated into Python by <NAME>, 23 Jan 2018line ; V2.1 - (25/03/18 FB) Final tweaks to the Python version and updated the docstring. ; V3.1.0 - (04/06/18 FB) First version of izi_MCMC ; V3.1.1 - (23/08/18 FB) Added functionality for having a different epsilon for the ; Balmer lines (only HA implemented), in order to avoid biases in the extinction. ; Also added samples as output. ; V3.1.2 - (23/08/18 FB): Added modelFlux object to calculate the model fluxes ; associated with each MCMC sample and the intrinsic Balmer decrement PDF ; V4.0 - Added possibility of inserting a Gaussian prior on log(q) ; and/or 12+log(O/H) variables by <NAME>, 1 March 2019 ; (see Mingozzi et. al. A&A 636, A42 2020 for more details) ; V5.0.0 - (9/06/20 MM): Upgraded to Python3 ; V5.0.1 - (10/06/20 FB): checked to release ; ===================================================================================== @author: <NAME> """ import numpy as np import matplotlib.pyplot as plt from astropy.io import fits, ascii import astropy.table as table from scipy import interpolate from scipy.integrate import simps from scipy import special from scipy.signal import find_peaks import pdb from os import path import time import emcee import corner from emcee.autocorr import integrated_time import random import warnings warnings.filterwarnings("ignore") from izi import fb_extinction as ext import izi as izi_package class modelFluxes(object): def __init__(self, izi_obj): self.samples=izi_obj.samples self.grid = izi_obj.intergrid self.logohsun=izi_obj.logohsun model_fluxes = np.zeros( (self.samples.shape[0], \ len(izi_obj.intergrid['ID'][0])) ) for ii in range(self.samples.shape[0]): out1= grid.value_grid_at_no_interp(self.grid, \ self.samples[ii,0] -self.logohsun ,self.samples[ii,1]) model_fluxes[ii, :] = out1 self.model_fluxes = model_fluxes def calculate_instrinsic_Balmer_decrements(self): wha = self.grid['ID'][0]=='halpha' return self.model_fluxes[:,wha] class grid(object): def __init__(self, gridfile, templ_dir=None,logohsun=None): self.gridfile=gridfile self.logohsun=logohsun self.templ_dir=templ_dir if self.templ_dir == None: self.templ_dir='/grids/' print('looking for grids in the izi/grids directory...') # READ GRID try: grid0=table.Table.read(self.templ_dir+self.gridfile+'.fits') grid0.convert_bytestring_to_unicode() except IOError: raise IOError('no grid file found in '+self.templ_dir+self.gridfile+'.fits') # get rid of the empty spaces around line names grid0id= [num.strip() for num in grid0['ID'][0]] # number of lines nlines0=len(grid0['ID'][0]) # number of steps in log(Z) * number of steps in log(q) ngrid0=len(grid0['LOGZ']) # rename grid0["ID"] to get rid of the empty spaces grid0['ID']=[grid0id]*ngrid0 #pdb.set_trace() self.grid0=grid0 # TAKE SOLAR OXYGEN ABUNDANCE FROM MODEL GRID IF NOT PROVIDED if self.logohsun ==None: self.logohsun = grid0[0]['LOGOHSUN'] def apply_limits(self, logzlimits=None, logqlimits=None): # CUT GRID TO LOGZLIMITS AND LOGQLIMITS self.logzlimits=logzlimits self.logqlimits=logqlimits if self.logzlimits==None: self.logzlimits=[np.min(self.grid0['LOGZ']+self.logohsun), np.max(self.grid0['LOGZ']+self.logohsun)] if self.logqlimits==None: self.logqlimits=[np.min(self.grid0['LOGQ']), np.max(self.grid0['LOGQ'])] self.grid0=self.grid0[ (self.grid0['LOGZ']+self.logohsun >= self.logzlimits[0]) & (self.grid0['LOGZ']+self.logohsun <= self.logzlimits[1]) & (self.grid0['LOGQ'] >= self.logqlimits[0]) & (self.grid0['LOGQ'] <= self.logqlimits[1]) ] return self def interpolate_grid(self, nz=50, nq=50): self.nz=nz self.nq=nq zarr=np.linspace(np.min(self.grid0['LOGZ']), np.max(self.grid0['LOGZ']), self.nz) qarr=np.linspace(np.min(self.grid0['LOGQ']), np.max(self.grid0['LOGQ']), self.nq) nlines0=len(self.grid0['ID'][0]) fluxarr=np.zeros((self.nz, self.nq, nlines0)) grid_x, grid_y = np.meshgrid(zarr, qarr) intergrid=self.nz*self.nq # define the new interpolated grid as a table intergrid=table.Table() intergrid['LOGQ']=grid_y.flatten() intergrid['LOGZ']=grid_x.flatten() intergrid['LOGOHSUN']=[self.grid0['LOGOHSUN'][0]]*self.nq*self.nz intergrid['ID']=[self.grid0['ID'][0]]*self.nq*self.nz flux=np.array(self.grid0['FLUX']) logzin=np.array(self.grid0['LOGZ']) logqin=np.array(self.grid0['LOGQ']) for i in range(nlines0): fluxarr[:,:,i]=interpolate.griddata( (logzin,logqin), flux[:,i], (grid_x, grid_y), method='cubic') # GOING FROM A 2D grid to a 1D grid intergrid['FLUX']= self.make_grid_1d(intergrid, grid_x, grid_y, fluxarr) self.intergrid=intergrid return self @staticmethod def make_grid_1d(intergrid, grid_x, grid_y, fluxarr): nintergrid=len(intergrid['LOGZ']) nlines0=len(intergrid['ID'][0]) intergrid_flux= np.zeros((nintergrid, nlines0)) for j in range(nlines0): for i in range(nintergrid): ww= (grid_x == intergrid['LOGZ'][i]) & (grid_y == intergrid['LOGQ'][i]) flux2d=fluxarr[:,:,j] intergrid_flux[i,j]=flux2d[ww] return intergrid_flux def value_grid_at(self, zz, qq): flux=np.array(self.grid0['FLUX']) logzin=np.array(self.grid0['LOGZ']) logqin=np.array(self.grid0['LOGQ']) nlines0=len(self.grid0['ID'][0]) flux_at=np.zeros(nlines0) for i in range(nlines0): flux_at[i]=interpolate.griddata( (logzin,logqin), flux[:,i], (zz, qq), method='linear') return flux_at @staticmethod def value_grid_at_no_interp(grid0, zz, qq): flux=np.array(grid0['FLUX']) logzin=np.array(grid0['LOGZ']) logqin=np.array(grid0['LOGQ']) www = np.argmin( (logzin-zz)**2 + (logqin-qq)**2 ) flux_at=flux[www] return flux_at class izi_MCMC(object): plt.ioff() def __init__(self, flux, error, id, gridfile=None, templ_dir=None, logzlimits=None, logqlimits=None, logohsun=None, epsilon=0.1, nz=100, nq=100, intergridfile=None, outgridfile=False, nonorm=0, quiet=False, plot=True, plot_z_steps=False, plot_q_steps=False, plot_ebv_steps=False, logqprior=None, logzprior=None):#plot_derivatives=False #DECLARE INPUT TO SELF self.flux = flux # flux array self.error = error # error flux array self.id = np.copy(id) # IDs of different emission lines self.gridfile = gridfile self.templ_dir = templ_dir self.logzlimits = logzlimits self.logqlimits = logqlimits self.intergridfile=intergridfile self.nonorm=nonorm self.outgridfile=outgridfile self.logohsun=logohsun self.plot=plot self.plot_z_steps=plot_z_steps self.plot_q_steps= plot_q_steps self.plot_ebv_steps=plot_ebv_steps #self.plot_derivatives=plot_derivatives self.nz=nz self.nq=nq self.quiet=quiet self.epsilon=epsilon self.logzprior=logzprior self.logqprior=logqprior nlines_in=len(self.flux) assert len(self.error) == nlines_in and len(self.id) == nlines_in, \ 'ERROR Flux, Error, and ID arrays do not have the same number of elements' assert self.nz>99 and self.nq>99,\ 'ERROR, nz and nq must be larger than 100 for proper interpolation of the model grid' # # INPUT FILES CHECKING # IF NOT SPECIFIED BY USER USE DEFAULT Levesque models with density # 10^2 cm-3, composite SF, and 6Myr age if self.gridfile == None: self.gridfile='l09_high_csf_n1e2_6.0Myr' # self.gridfile='d13_kappa20' else: self.gridfile=gridfile if self.templ_dir==None: self.templ_dir = path.dirname(path.realpath(izi_package.__file__))[:-4]+'/grids/' if self.intergridfile == None: # PREPARE ORIGINAL GRID # READ GRID using the grid class grid0=grid(self.gridfile, templ_dir=self.templ_dir) # APPLY LIMITS to grid grid0.apply_limits(logzlimits=self.logzlimits, logqlimits=self.logqlimits) # if self.logohsun is None: self.logohsun=grid0.logohsun nlines0=len(grid0.grid0['ID'][0]) # number of steps in log(Z) * number of steps in log(q) #INTERPOLATE GRID # pdb.set_trace() grid0.interpolate_grid(nz=self.nz, nq=self.nq) self.intergrid=grid0.intergrid #DEFINE PARAMTERS OF GRID # zarr=np.linspace(np.min(self.intergrid['LOGZ']), np.max(self.intergrid['LOGZ']), self.nz) # qarr=np.linspace(np.min(self.intergrid['LOGQ']), np.max(self.intergrid['LOGQ']), self.nq) # nintergrid=len(self.intergrid['ID']) # Read emission line wavelengths and match them to the current order # of adopted Cloudy grid. Wavelengths needed for extinction line_params=ascii.read(path.dirname(path.realpath(izi_package.__file__))+'/line_names.txt') line_wav=np.zeros(nlines0) for ii in range(nlines0): line_name=self.intergrid['ID'][0][ii] ww = (line_params['line_name']==line_name) assert ww.sum() == 1, 'ERROR: ===== Line ID '+\ self.intergrid['ID'][0][ii]+'not included in wavelength list=====' line_wav[ii]=line_params['wav'][ww] grid0.intergrid['WAV']=[line_wav]*self.nq*self.nz self.intergrid=grid0.intergrid # WRITE INTERPOLATED GRID IF USER WANTS TO if self.outgridfile ==True: a=self.intergrid a.write(self.templ_dir+'/interpolgrid_'+str(self.nz)+'_'+\ str(self.nq)+self.gridfile+'.fits', overwrite=True) else: # READ GRID using the grid class grid0=grid(self.intergridfile, templ_dir=self.templ_dir) self.intergrid=grid0.grid0 nlines0=len(self.intergrid['ID'][0]) self.nz=len(np.unique(self.intergrid['LOGZ'])) self.nq=len(np.unique(self.intergrid['LOGQ'])) if self.logohsun is None: self.logohsun=grid0.logohsun # Read emission line wavelengths and match them to the current order # of adopted Cloudy grid. Wavelengths needed for extinction line_params=ascii.read(path.dirname(path.realpath(__file__))+'/line_names.txt') line_wav=np.zeros(nlines0) #pdb.set_trace() for ii in range(nlines0): line_name=self.intergrid['ID'][0][ii] ww = (line_params['line_name']==line_name) assert ww.sum() == 1, 'ERROR: ===== Line ID '+\ self.intergrid['ID'][0][ii]+'not included in wavelength list=====' line_wav[ii]=line_params['wav'][ww] grid0.grid0['WAV']=[line_wav]*self.nq*self.nz self.intergrid=grid0.grid0 # Check for summed sets of lines in input ID array and sum fluxes in grid # All fluxes are summed to the first line and ID is set to that line for i in range(nlines_in): idsum=self.id[i].split(';') if len(idsum) >1: for j in range(len(idsum)-1): w0= (self.intergrid['ID'][0] == idsum[0]) wj= (self.intergrid['ID'][0] == idsum[j+1]) self.intergrid['FLUX'][:,w0]=self.intergrid['FLUX'][:,w0] +\ self.intergrid['FLUX'][:,wj] self.id[i]=idsum[0] #; CREATE DATA STRUCTURE CONTAINING LINE FLUXES AND ESTIMATED PARAMETERS dd={'id': self.intergrid['ID'][0], # line id 'flux': np.zeros(nlines0)+np.nan, # line flux 'error': np.zeros(nlines0)+np.nan, 'flag': np.zeros(6), 'Z_max': np.zeros((2,19))+np.nan, 'q_max': np.zeros((2,19))+np.nan, 'ebv_max': np.zeros((2,19))+np.nan} #FILL STRUCTURE WITH LINE FLUXES for i in range(nlines_in): auxind=(dd['id'] == self.id[i]) nmatch=auxind.sum() assert nmatch == 1, 'ERROR: ===== Line ID '+self.id[i]+'not recognized =====' dd['flux'][auxind]=self.flux[i] dd['error'][auxind]=self.error[i] # INDEX LINES WITH MEASUREMENTS good=(np.isfinite(dd['error'])) # ngood=good.sum() measured=(np.isfinite(dd['flux'])) upperlim=((np.isfinite(dd['error'])) & (dd['flux'] == -666)) flag0=np.zeros(nlines0) flag0[measured]=1 #measured flux flag0[upperlim]=2 #upper limit on flux #This array has length ngood, which is the number of lines with #given error measurements. If error is given but no flux this is treated #as an upper limit flag=flag0[good] # NORMALIZE LINE FLUXES TO HBETA OR # IF ABSENT NORMALIZE TO BRIGHTEST LINE if self.nonorm ==0: #; use nonorm for line ratio fitting idnorm='hbeta' in_idnorm= (dd['id']==idnorm) if (np.isnan(dd['flux'][in_idnorm]) | (dd['flux'][in_idnorm] ==-666)): a=dd['id'][measured] idnorm=a[[np.argmax(dd['flux'][measured])]] in_idnorm= (dd['id']==idnorm) norm=dd['flux'][in_idnorm] #NORMALISE INPUT FLUXES dd['flux'][measured]=dd['flux'][measured]/norm[0] dd['error'][good]=dd['error'][good]/norm[0] dd['flux'][upperlim] = -666 dd['epsilon']=np.zeros(len(dd['flux'])) + self.epsilon*np.log(10) in_idnorm= (dd['id']=='halpha') dd['epsilon'][in_idnorm]=0.01*np.log(10) # pdb.set_trace() #Define zrange and qrange for use in the prior calculation zrange=[np.min(self.intergrid['LOGZ']), np.max(self.intergrid['LOGZ'])] qrange=[np.min(self.intergrid['LOGQ']), np.max(self.intergrid['LOGQ'])] # SET UP MCMC max_ebv=1.0 ndim, nwalkers, nchains, nburn = 3, 100, 200, 100 # global count # count=0 wha= (dd['id']=='halpha') whb= (dd['id']=='hbeta') if (np.isnan(dd['flux'][whb]) | (dd['flux'][whb] ==-666)) : ebv_0 = 0.5*max_ebv else: ebv_0 = ext.calc_ebv(dd['flux'][wha]/dd['flux'][whb]) #even though already normalized if ebv_0<=0: ebv_0=1.e-3 #cannot be less than 0 par=[0.5*(zrange[1]-zrange[0])+zrange[0], 0.5*(qrange[1]-qrange[0])+qrange[0], ebv_0] pos_start=self.generate_start(par, ndim, nwalkers, zrange, qrange, max_ebv) # pdb.set_trace() ########################################################################## if quiet ==False: print('starting the MCMC run with %d walkers, each chain %d samples long' \ % (nwalkers, nchains)) random.seed(18) sampler = emcee.EnsembleSampler(nwalkers, ndim, self.lnprob, \ args=(dd, good, flag, self.intergrid, zrange, qrange, max_ebv, idnorm)) sampler.run_mcmc(pos_start, nchains) # CHAIN is an array of dimensions: nwalkers, nsteps, ndim samples = sampler.chain[:,nburn:, :].reshape((-1, ndim)) ## flattening the chain... samples[:,0]=samples[:,0]+self.logohsun # this function produces: median, upper error bar (84-50th percent), lower error bar (50-16th percent) zz_mcmc, qq_mcmc, ebv_mcmc= map(lambda v: (v[1], v[2]-v[1], v[1]-v[0]), zip(*np.percentile(samples, [16, 50, 84],axis=0))) # chain = sampler.chain # pdb.set_trace() # tau = np.mean([integrated_time(walker) for walker in chain], axis=0) if self.plot==True: # pdb.set_trace() fig = corner.corner(samples, \ labels=[r"$\rm 12+log(O/H)$", r"$\rm log(q) \ [cm s^{-1}]$", r"$ \rm E(B-V) \ [mag]$"],\ show_titles=True, title_kwargs={"fontsize": 10},\ label_kwargs={"fontsize": 14},\ data_kwargs={"ms": 0.6}) self.fig=fig plt.show() if self.plot_z_steps==True: fig=plt.subplots() for i in range(nwalkers): plt.plot(range(len(sampler.chain[i,:,0])),sampler.chain[i,:,0]+self.logohsun, c="gray", alpha=0.3) plt.plot(range(nburn,len(sampler.chain[i,:,0])),sampler.chain[i,nburn:,0]+self.logohsun, c="red", alpha=0.3) plt.axhline(np.median(sampler.chain[:,nburn:,0])+self.logohsun, c="blue", ls="dashed") plt.axvline(nburn, c="blue", ls="dotted", alpha=0.3) plt.xlabel("Nstep") plt.ylabel("12+log(O/H)") plt.show() if self.plot_q_steps==True: fig=plt.subplots() for i in range(nwalkers): plt.plot(range(len(sampler.chain[i,:,1])),sampler.chain[i,:,1], c="gray", alpha=0.3) plt.plot(range(nburn,len(sampler.chain[i,:,1])),sampler.chain[i,nburn:,1], c="red", alpha=0.3) plt.axhline(np.median(sampler.chain[:,nburn:,1]), c="blue", ls="dashed") plt.axvline(nburn, c="blue", ls="dotted", alpha=0.3) plt.xlabel("Nstep") plt.ylabel("log(q)") plt.show() if self.plot_ebv_steps==True: fig=plt.subplots() for i in range(nwalkers): plt.plot(range(len(sampler.chain[i,:,2])),sampler.chain[i,:,2], c="gray", alpha=0.3) plt.plot(range(nburn,len(sampler.chain[i,:,2])),sampler.chain[i,nburn:,2], c="red", alpha=0.3) plt.axhline(np.median(sampler.chain[:,nburn:,2]), c="blue", ls="dashed") plt.axvline(nburn, c="blue", ls="dotted", alpha=0.3) plt.xlabel("Nstep") plt.ylabel("E(B-V)") plt.show() dd['zarr']=np.linspace(zrange[0]+self.logohsun, zrange[1]+self.logohsun, 20) dd['qarr']=np.linspace(qrange[0], qrange[1], 20) dd['ebvarr']=np.linspace(0, max_ebv, 20) dd['z_pdf'], dd['zarr'] = np.histogram(samples[:,0], density=True,bins= dd['zarr']) dd['q_pdf'], dd['qarr'] = np.histogram(samples[:,1], density=True,bins= dd['qarr']) dd['ebv_pdf'], dd['ebvarr'] = np.histogram(samples[:,2], density=True,bins= dd['ebvarr']) dd['zarr'] = (dd['zarr'][1:]+dd['zarr'][:-1])/2. dd['qarr'] = (dd['qarr'][1:]+dd['qarr'][:-1])/2. dd['ebvarr'] = (dd['ebvarr'][1:]+dd['ebvarr'][:-1])/2. dd['Z']=zz_mcmc[0] dd['err_up_Z']=zz_mcmc[1] dd['err_down_Z']=zz_mcmc[2] dd['q']=qq_mcmc[0] dd['err_up_q']=qq_mcmc[1] dd['err_down_q']=qq_mcmc[2] dd['ebv']=ebv_mcmc[0] dd['err_up_ebv']=ebv_mcmc[1] dd['err_down_ebv']=ebv_mcmc[2] dd['acc_fraction'] = np.mean(sampler.acceptance_fraction) #to find peaks in PDFs z_peaks, _ = find_peaks(dd['z_pdf'], prominence=(0.1, None)) q_peaks, _ = find_peaks(dd['q_pdf'], prominence=(0.1, None)) ebv_peaks, _ = find_peaks(dd['ebv_pdf'], prominence=(0.1, None)) # dx = (dd['zarr'][1] - dd['zarr'][0])/2. # dz_pdf = np.gradient(dd['z_pdf'],dx) # ddz_pdf = np.gradient( dz_pdf, dx ) # dx = (dd['qarr'][1] - dd['qarr'][0])/2. # dq_pdf = np.gradient(dd['q_pdf'], dx) # ddq_pdf = np.gradient( dq_pdf, dx ) # dx = (dd['ebvarr'][1] - dd['ebvarr'][0])/2. # debv_pdf = np.gradient(dd['ebv_pdf'], dx) # ddebv_pdf = np.gradient( debv_pdf, dx ) # if self.plot_derivatives==True: # fig, (ax1,ax2,ax3) = plt.subplots(nrows=1,ncols=3,figsize=(20,10)) # ax1.axhline(y=0,linestyle='dashed',color='magenta') # ax1.scatter(dd['zarr'], dd['z_pdf'],color='k',s=25) # ax1.plot(dd['zarr'], dz_pdf,color='green',label='Z_pdf I derivative') # ax1.plot(dd['zarr'], ddz_pdf,color='red',label='Z_pdf II derivative') # ax1.scatter(dd['zarr'][z_peaks], dd['z_pdf'][z_peaks],color='cyan',s=15,label='Z_pdf peaks') # ax1.set_xlabel('12+log(O/H)') # ax1.legend() # ax2.axhline(y=0,linestyle='dashed',color='magenta') # ax2.scatter(dd['qarr'], dd['q_pdf'],color='k') # ax2.plot(dd['qarr'], dq_pdf,color='green',label='q_pdf I derivative') # ax2.plot(dd['qarr'], ddq_pdf,color='red',label='q_pdf II derivative') # ax2.scatter(dd['qarr'][q_peaks], dd['q_pdf'][q_peaks],color='cyan',s=15,label='q_pdf peaks') # ax2.set_xlabel('log(q)') # ax3.axhline(y=0,linestyle='dashed',color='magenta') # ax3.scatter(dd['ebvarr'], dd['ebv_pdf'],color='k') # ax3.plot(dd['ebvarr'], debv_pdf,color='green',label='ebv_pdf I derivative') # ax3.plot(dd['ebvarr'], ddebv_pdf,color='red',label='ebv_pdf II derivative') # ax3.scatter(dd['ebvarr'][ebv_peaks], dd['ebv_pdf'][ebv_peaks],color='cyan',s=15,label='ebv_pdf peaks') # ax3.set_xlabel('E(B-V)') # ax3.legend() # plt.show() dd['flag'][0] = len(z_peaks) dd['flag'][1] = len(q_peaks) dd['flag'][2] = len(ebv_peaks) dd['Z_max'][0][0:len(z_peaks)] = dd['zarr'][z_peaks] dd['Z_max'][1][0:len(z_peaks)] = dd['z_pdf'][z_peaks] dd['q_max'][0][0:len(q_peaks)] = dd['qarr'][q_peaks] dd['q_max'][1][0:len(q_peaks)] = dd['q_pdf'][q_peaks] dd['ebv_max'][0][0:len(ebv_peaks)] = dd['ebvarr'][ebv_peaks] dd['ebv_max'][1][0:len(ebv_peaks)] = dd['ebv_pdf'][ebv_peaks] if (np.max(dd['z_pdf'][0:1]) >= 0.5*np.max(dd['z_pdf'])): dd['flag'][3] = 1 if (np.max(dd['z_pdf'][-2:-1]) >= 0.5*np.max(dd['z_pdf'])): dd['flag'][3] = 2 if (np.max(dd['z_pdf'][0:1]) >= 0.5*np.max(dd['z_pdf'])) & (np.max(dd['z_pdf'][-2:-1]) > 0.5*np.max(dd['z_pdf'])): dd['flag'][3] = 3 if (np.max(dd['q_pdf'][0:1]) >= 0.5*np.max(dd['q_pdf'])): dd['flag'][4] = 1 if (np.max(dd['q_pdf'][-2:-1]) >= 0.5*np.max(dd['q_pdf'])): dd['flag'][4] = 2 if (np.max(dd['q_pdf'][0:1]) >= 0.5*np.max(dd['q_pdf'])) & (np.max(dd['q_pdf'][-2:-1]) > 0.5*np.max(dd['q_pdf'])): dd['flag'][4] = 3 if (np.max(dd['ebv_pdf'][0:1]) >= 0.5*np.max(dd['ebv_pdf'])): dd['flag'][5] = 1 if (np.max(dd['ebv_pdf'][-2:-1]) >= 0.5*np.max(dd['ebv_pdf'])): dd['flag'][5] = 2 if (np.max(dd['ebv_pdf'][0:1]) >= 0.5*np.max(dd['ebv_pdf'])) & (np.max(dd['ebv_pdf'][-2:-1]) > 0.5*np.max(dd['ebv_pdf'])): dd['flag'][5] = 3 # calculate chi-square w = np.isfinite(dd['flux']) & (dd['flux'] != -666) #read observed values fobs=dd['flux'] eobs=dd['error'] # fmod not corrected for reddening #not interpolating fmod = self.flux_grid_ext(self.intergrid, zz_mcmc[0]-self.logohsun, qq_mcmc[0], ebv_mcmc[0], idnorm) emod=dd['epsilon']*fmod chi2=np.nansum((fobs[w]-fmod[w])**2/(eobs[w]**2+emod[w]**2))/(len(fobs[w])-ndim) #reduced chi-square dd['chi2']=chi2 line_info={'id':self.id, 'fobs':np.array(self.flux)+np.nan, 'fmod':np.array(self.flux)+np.nan, \ 'eobs':np.array(self.flux)+np.nan, 'emod':np.array(self.flux)+np.nan, \ 'chi2_line':np.array(self.flux)+np.nan} for i in range(nlines_in): auxind=(dd['id']==self.id[i]) line_info['fmod'][i]=self.flux_grid_ext(self.intergrid, zz_mcmc[0]-self.logohsun, qq_mcmc[0], ebv_mcmc[0], idnorm)[auxind]#grid.value_grid_at(grid0,zz_mcmc[0]-self.logohsun, qq_mcmc[0])[auxind] line_info['emod'][i]=dd['epsilon'][auxind]*line_info['fmod'][i] line_info['fobs'][i]=dd['flux'][auxind] line_info['eobs'][i]=dd['error'][auxind] if
np.isfinite(dd['flux'][auxind])
numpy.isfinite
import json import matplotlib.pyplot as plt import numpy as np import odrive import time # velocity PID controller ''' p: 0.080000 i: 0.012000 d: 0.012000 r: 0.000000 threshold: 10 anti_ripple: 0 Connecting... Connected! Loop freq.: 225.830078Hz std c: 1568.547296 std v: 1111.231645 max c: 10398.316341 mean: 1219.847200 max v: 11500.000977 mean: 9705 p: 0.080000 i: 0.012000 d: 0.012000 r: 0.000000 threshold: 10 anti_ripple: 0 Connecting... Connected! Loop freq.: 225.769043Hz std c: 896.060882 std v: 442.692430 max c: 3388.145270 mean: 794.037284 max v: 2500.000244 mean: 984 p: 0.080000 i: 0.007000 d: 0.009000 r: 0.000000 threshold: 10 anti_ripple: 0 Connecting... Connected! Loop freq.: 153.808594Hz std c: 597.658625 std v: 492.960539 max c: 1948.304413 mean: 615.204410 max v: 2500.000244 mean: 993 ''' cpr = 8192 vel_max = 300000 cur_max = 12 vel_threshold = 10 anti_ripple = False vel_target = 200 t_run = (cpr / vel_target) * 1 p_gain = 0.08 i_gain = 0.012 d_gain = 0.012 r_gain = 0 #p_gain = 0.02 #i_gain = 0.001 #d_gain = 0.01 #r_gain = 0.2 print("p: %f\ti: %f\td: %f\tr: %f\tthreshold: %d\tanti_ripple: %i" % (p_gain, i_gain, d_gain, r_gain, vel_threshold, anti_ripple)) def overspeed(arg): return arg > vel_max def overcurrent(arg): return arg > cur_max def cpr2rad(arg): return 2 * np.pi * (arg / cpr) map = [0] * cpr def round(x): i = int(x) dec = x - i if dec >= 0.5: return i+1 return i def next_non_zero(start): for i in range(start+1, cpr): if 0 != map[i]: return i return -1 def interpolate(input): # build sparse map for d in input: p = d[0] c = d[1] * -1 p = round(p) map[p] = c # find first value first = next_non_zero(0) last = first next = next_non_zero(last) while next > 0: c_last = map[last] c_next = map[next] diff = next - last # 'next' pos already has a value, so don't count it diff -= 1 if 1 == diff: map[last + 1] = c_next else: half = int(diff/2) for i in range(half): map[last + 1 + i] = c_last i = last + 1 + half while i < next: map[i] = c_next i += 1 last = next next = next_non_zero(last) # fill in leading 0's c_leading = map[first] c_trailing = map[last] leading = first trailing = cpr - 1 - last diff = leading + trailing half = int(diff/2) for i in range(half): index = last + 1 + i if index > cpr - 1: index -= (cpr) map[index] = c_last i = last + 1 + half if i > cpr - 1: i -= (cpr) while i != first: map[i] = c_next i += 1 if i > cpr - 1: i -= (cpr) data = None with open("data/pos_cur_b.json", 'r') as file: data = json.load(file) data = data["forward"] interpolate(data) print("Connecting...") d = odrive.find_any() print("Connected!") x = d.axis0 x.controller.config.control_mode = 1 x.controller.current_setpoint = 0 v_plt = [] c_plt = [] t_plt = [] buf_err = [0] err_last = 0 c = 0 t_start = time.time() t_last = t_start time.sleep(0.01) c_rip_last = 0 count = 0 while t_last - t_start < t_run: t_now = time.time() v = x.encoder.vel_estimate if overspeed(v): print("Overspeed!") x.controller.current_setpoint = 0 break v_err = cpr2rad( vel_target - v) p_val = v_err * p_gain if abs(v_err) < vel_threshold: buf_err = [0] buf_err.append(v_err) i_val = sum(buf_err) * i_gain err_diff = v_err - err_last t_diff = t_now - t_last d_val = (err_diff / t_diff) * d_gain c += p_val + i_val + d_val if anti_ripple: pos = x.encoder.pos_cpr pr = round(pos) if pr > cpr - 1: pr -= cpr c_rip = map[pr] * -1 c += (c_rip - c_rip_last) * r_gain if overcurrent(c): print("Overcurrent! %f" % (c)) x.controller.current_setpoint = 0 break x.controller.current_setpoint = c t_last = t_now err_last = v_err v_plt.append(v) c_plt.append(c * 1000) t_plt.append(t_now - t_start) count += 1 x.controller.current_setpoint = 0 x.controller.config.control_mode = 3 print("Loop freq.: %fHz" % (count / t_run)) print("std c: %f\tstd v: %f" % (
np.std(c_plt)
numpy.std
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from dynamicgem.embedding.dynamic_graph_embedding import DynamicGraphEmbedding from dynamicgem.utils import graph_util from dynamicgem.utils import plot_util from dynamicgem.visualization import plot_dynamic_sbm_embedding from dynamicgem.graph_generation import dynamic_SBM_graph class GraphFactorization(DynamicGraphEmbedding): """Graph Facgorization based network embedding It utilizes factorization based method to acquire the embedding of the graph nodes. Args: d (int): dimension of the embedding eta (float): learning rate of sgd regu (float): regularization coefficient of magnitude of weights beta (float): penalty parameter in matrix B of 2nd order objective n_iter (int): number of sgd iterations for first embedding (const) method_name (str): method name initEmbed (Matrix): Previous timestep embedding initialized for the current timestep Examples: >>> from dynamicgem.embedding.graphFac_dynamic import GraphFactorization >>> from dynamicgem.graph_generation import dynamic_SBM_graph >>> node_num = 100 >>> community_num = 2 >>> node_change_num = 2 >>> length = 5 >>> dynamic_sbm_series = dynamic_SBM_graph.get_random_perturbation_series_v2(node_num, community_num, length, node_change_num) >>> dynamic_embeddings = GraphFactorization(100, 100, 10, 5 * 10 ** -2, 1.0, 1.0) >>> dynamic_embeddings.learn_embeddings([g[0] for g in dynamic_sbm_series]) >>> plot_dynamic_sbm_embedding.plot_dynamic_sbm_embedding(dynamic_embeddings.get_embeddings(), dynamic_sbm_series) >>> plt.show() """ def __init__(self, d, n_iter, n_iter_sub, eta, regu, kappa, initEmbed=None): """ Initialize the GraphFactorization class""" self._d = d self._eta = eta self._regu = regu self._n_iter = n_iter self._n_iter_sub = n_iter_sub self._kappa = kappa self._method_name = 'graph_factor_sgd' if initEmbed is not None: self._initEmbed = initEmbed def get_method_name(self): """Function to return the method name. Returns: String: Name of the method. """ return self._method_name def get_method_summary(self): """Function to return the summary of the algorithm. Returns: String: Method summary """ return '%s_%d' % (self._method_name, self._d) def getFVal(self, adj_mtx, X, prev_step_emb=None): """Function to Factorize the adjacency matrix.""" f1 = np.linalg.norm(adj_mtx - np.dot(X, X.T)) ** 2 f2 = self._regu * (np.linalg.norm(X) ** 2) f3 = 0 if prev_step_emb is not None: f3 = self._kappa * ( np.linalg.norm(X[:prev_step_emb.shape[0], :prev_step_emb.shape[1]] - prev_step_emb) ** 2) # print 'Prev[0][0]: %g, curr[0][0]: %g' % (prev_step_emb[0][0], X[0][0]) return [f1, f2, f3, f1 + f2 + f3] def learn_embedding(self, graph, prevEmbed=None): """Learns the embedding of the nodes. Attributes: graph (Object): Networkx Graph Object Returns: List: Node embeddings and time taken by the algorithm """ # pdb.set_trace() A = graph_util.transform_DiGraph_to_adj(graph) if not np.allclose(A.T, A): print("laplace eigmap approach only works for symmetric graphs!") return self._node_num = A.shape[0] edgeList = np.where(A > 0) self._num_iter = self._n_iter self._X = 0.01 * np.random.randn(self._node_num, self._d) if prevEmbed is not None: print('Initializing X_t with X_t-1') # self._X = 0.01*np.random.randn(self._node_num, self._d) self._X[:prevEmbed.shape[0], :] = np.copy(prevEmbed) self._num_iter = self._n_iter_sub # pdb.set_trace() for iter_id in range(self._num_iter): if not iter_id % 100: [f1, f2, f3, f] = self.getFVal(A, self._X, prevEmbed) print('Iter: %d, Objective value: %g, f1: %g, f2: %g, f3: %g' % (iter_id, f, f1, f2, f3)) for i, j in zip(edgeList[0], edgeList[1]): if i >= j: continue delPhi1 = -(A[i, j] - np.dot(self._X[i, :], self._X[j, :])) * self._X[j, :] delPhi2 = self._regu * self._X[i, :] delPhi3 =
np.zeros(self._d)
numpy.zeros
################################################################################ # 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)) A = SumMultiply(X, ['i']) self.assertEqual(A.dims, ((), ())) A = SumMultiply('i', X) self.assertEqual(A.dims, ((), ())) A = SumMultiply(X, ['i'], ['i']) self.assertEqual(A.dims, ((1,), (1,1))) A = SumMultiply('i->i', X) self.assertEqual(A.dims, ((1,), (1,1))) A = SumMultiply(X, ['i'], Y, ['j'], ['i','j']) self.assertEqual(A.dims, ((1,3), (1,3,1,3))) A = SumMultiply('i,j->ij', X, Y) self.assertEqual(A.dims, ((1,3), (1,3,1,3))) A = SumMultiply(V, [], X, ['i'], Y, ['i'], []) self.assertEqual(A.dims, ((), ())) A = SumMultiply(',i,i->', V, X, Y) self.assertEqual(A.dims, ((), ())) # Gaussian-gamma parents C = GaussianGamma(np.ones(3), np.identity(3), 1, 1) A = SumMultiply(Y, ['i'], C, ['i'], ['i']) self.assertEqual(A.dims, ((3,), (3,3), (), ())) A = SumMultiply('i,i->i', Y, C) self.assertEqual(A.dims, ((3,), (3,3), (), ())) C = GaussianGamma(np.ones(3), np.identity(3), 1, 1) A = SumMultiply(Y, ['i'], C, ['i'], []) self.assertEqual(A.dims, ((), (), (), ())) A = SumMultiply('i,i->', Y, C) self.assertEqual(A.dims, ((), (), (), ())) # Error: not enough inputs self.assertRaises(ValueError, SumMultiply) self.assertRaises(ValueError, SumMultiply, X) # Error: too many keys self.assertRaises(ValueError, SumMultiply, Y, ['i', 'j']) self.assertRaises(ValueError, SumMultiply, 'ij', Y) # Error: not broadcastable self.assertRaises(ValueError, SumMultiply, Y, ['i'], Z, ['i']) self.assertRaises(ValueError, SumMultiply, 'i,i', Y, Z) # Error: output key not in inputs self.assertRaises(ValueError, SumMultiply, X, ['i'], ['j']) self.assertRaises(ValueError, SumMultiply, 'i->j', X) # Error: non-unique input keys self.assertRaises(ValueError, SumMultiply, X, ['i','i']) self.assertRaises(ValueError, SumMultiply, 'ii', X) # Error: non-unique output keys self.assertRaises(ValueError, SumMultiply, X, ['i'], ['i','i']) self.assertRaises(ValueError, SumMultiply, 'i->ii', X) # String has too many '->' self.assertRaises(ValueError, SumMultiply, 'i->i->i', X) # String has too many input nodes self.assertRaises(ValueError, SumMultiply, 'i,i->i', X) # Same parent several times self.assertRaises(ValueError, SumMultiply, 'i,i->i', X, X) # Same parent several times via deterministic node Xh = SumMultiply('i->i', X) self.assertRaises(ValueError, SumMultiply, 'i,i->i', X, Xh) def test_message_to_child(self): """ Test the message from SumMultiply to its children. """ def compare_moments(u0, u1, *args): Y = SumMultiply(*args) u_Y = Y.get_moments() self.assertAllClose(u_Y[0], u0) self.assertAllClose(u_Y[1], u1) # Test constant parent y = np.random.randn(2,3,4) compare_moments(y, linalg.outer(y, y, ndim=2), 'ij->ij', y) # Do nothing for 2-D array Y = GaussianARD(np.random.randn(5,2,3), np.random.rand(5,2,3), plates=(5,), shape=(2,3)) y = Y.get_moments() compare_moments(y[0], y[1], 'ij->ij', Y) compare_moments(y[0], y[1], Y, [0,1], [0,1]) # Sum over the rows of a matrix Y = GaussianARD(np.random.randn(5,2,3), np.random.rand(5,2,3), plates=(5,), shape=(2,3)) y = Y.get_moments() mu = np.einsum('...ij->...j', y[0]) cov = np.einsum('...ijkl->...jl', y[1]) compare_moments(mu, cov, 'ij->j', Y) compare_moments(mu, cov, Y, [0,1], [1]) # Inner product of three vectors X1 = GaussianARD(np.random.randn(2), np.random.rand(2), plates=(), shape=(2,)) x1 = X1.get_moments() X2 = GaussianARD(np.random.randn(6,1,2), np.random.rand(6,1,2), plates=(6,1), shape=(2,)) x2 = X2.get_moments() X3 = GaussianARD(np.random.randn(7,6,5,2), np.random.rand(7,6,5,2), plates=(7,6,5), shape=(2,)) x3 = X3.get_moments() mu = np.einsum('...i,...i,...i->...', x1[0], x2[0], x3[0]) cov = np.einsum('...ij,...ij,...ij->...', x1[1], x2[1], x3[1]) compare_moments(mu, cov, 'i,i,i', X1, X2, X3) compare_moments(mu, cov, 'i,i,i->', X1, X2, X3) compare_moments(mu, cov, X1, [9], X2, [9], X3, [9]) compare_moments(mu, cov, X1, [9], X2, [9], X3, [9], []) # Outer product of two vectors X1 = GaussianARD(np.random.randn(2), np.random.rand(2), plates=(5,), shape=(2,)) x1 = X1.get_moments() X2 = GaussianARD(np.random.randn(6,1,2), np.random.rand(6,1,2), plates=(6,1), shape=(2,)) x2 = X2.get_moments() mu = np.einsum('...i,...j->...ij', x1[0], x2[0]) cov = np.einsum('...ik,...jl->...ijkl', x1[1], x2[1]) compare_moments(mu, cov, 'i,j->ij', X1, X2) compare_moments(mu, cov, X1, [9], X2, [7], [9,7]) # Matrix product Y1 = GaussianARD(np.random.randn(3,2), np.random.rand(3,2), plates=(), shape=(3,2)) y1 = Y1.get_moments() Y2 = GaussianARD(np.random.randn(5,2,3), np.random.rand(5,2,3), plates=(5,), shape=(2,3)) y2 = Y2.get_moments() mu = np.einsum('...ik,...kj->...ij', y1[0], y2[0]) cov = np.einsum('...ikjl,...kmln->...imjn', y1[1], y2[1]) compare_moments(mu, cov, 'ik,kj->ij', Y1, Y2) compare_moments(mu, cov, Y1, ['i','k'], Y2, ['k','j'], ['i','j']) # Trace of a matrix product Y1 = GaussianARD(np.random.randn(3,2), np.random.rand(3,2), plates=(), shape=(3,2)) y1 = Y1.get_moments() Y2 = GaussianARD(np.random.randn(5,2,3), np.random.rand(5,2,3), plates=(5,), shape=(2,3)) y2 = Y2.get_moments() mu = np.einsum('...ij,...ji->...', y1[0], y2[0]) cov = np.einsum('...ikjl,...kilj->...', y1[1], y2[1]) compare_moments(mu, cov, 'ij,ji', Y1, Y2) compare_moments(mu, cov, 'ij,ji->', Y1, Y2) compare_moments(mu, cov, Y1, ['i','j'], Y2, ['j','i']) compare_moments(mu, cov, Y1, ['i','j'], Y2, ['j','i'], []) # Vector-matrix-vector product X1 = GaussianARD(np.random.randn(3), np.random.rand(3), plates=(), shape=(3,)) x1 = X1.get_moments() X2 = GaussianARD(np.random.randn(6,1,2), np.random.rand(6,1,2), plates=(6,1), shape=(2,)) x2 = X2.get_moments() Y = GaussianARD(np.random.randn(3,2), np.random.rand(3,2), plates=(), shape=(3,2)) y = Y.get_moments() mu = np.einsum('...i,...ij,...j->...', x1[0], y[0], x2[0]) cov = np.einsum('...ia,...ijab,...jb->...', x1[1], y[1], x2[1]) compare_moments(mu, cov, 'i,ij,j', X1, Y, X2) compare_moments(mu, cov, X1, [1], Y, [1,2], X2, [2]) # Complex sum-product of 0-D, 1-D, 2-D and 3-D arrays V = GaussianARD(np.random.randn(7,6,5), np.random.rand(7,6,5), plates=(7,6,5), shape=()) v = V.get_moments() X = GaussianARD(
np.random.randn(6,1,2)
numpy.random.randn
from __future__ import print_function import json import os from argparse import ArgumentParser from time import strftime, localtime, time import numpy as np import torch from matplotlib import pyplot as plt from torch.utils.data.dataset import random_split, Subset from gpn.struct2seq.data import StructureDataset, StructureLoader from gpn.struct2seq.noam_opt import get_std_opt from gpn.struct2seq.seq_model import LanguageRNN, SequenceModel plt.switch_backend('agg') parser = ArgumentParser(description='Structure to sequence modeling') parser.add_argument('--hidden', type=int, default=256, help='number of hidden dimensions') parser.add_argument('--file_data', type=str, default='../data/cath/chain_set.jsonl', help='input chain file') parser.add_argument('--file_splits', type=str, default='../data/cath/chain_set_splits.json', help='input chain file') parser.add_argument('--batch_tokens', type=int, default=2500, help='batch size') parser.add_argument('--epochs', type=int, default=100, help='number of epochs') parser.add_argument('--seed', type=int, default=1111, help='random seed for reproducibility') parser.add_argument('--cuda', action='store_true', help='whether to use CUDA for computation') parser.add_argument('--augment', action='store_true', help='Enrich with alignments') parser.add_argument('--rnn', action='store_true', help='RNN model') parser.add_argument('--split_random', action='store_true', help='Split randomly') args = parser.parse_args() # Set the random seed manually for reproducibility. np.random.seed(args.seed) torch.manual_seed(args.seed) if torch.cuda.is_available(): if not args.cuda: print("WARNING: You have a CUDA device, so you should probably run with --cuda") else: torch.cuda.manual_seed(args.seed) torch.set_default_tensor_type(torch.cuda.FloatTensor) # Hyperparameters hyperparams = { 'rnn': args.rnn, 'batch_size': args.batch_tokens, 'hidden': args.hidden, 'letters': 20 } device = torch.device("cuda:0" if (torch.cuda.is_available()) else "cpu") # Build the model MODEL = LanguageRNN if args.rnn else SequenceModel model = MODEL( num_letters=hyperparams['letters'], hidden_dim=hyperparams['hidden'] ).to(device) print('Number of parameters: {}'.format(sum([p.numel() for p in model.parameters()]))) # DEBUG load the checkpoint # checkpoint_path = 'log/19Mar04_0533PM_h256_suspicious/checkpoints/epoch18_step21960.pt' # checkpoint_path = 'log/19Mar04_1118PM/checkpoints/epoch50_step60000.pt' # model.load_state_dict(torch.load(checkpoint_path, map_location='cpu')) optimizer = get_std_opt(model.parameters(), hyperparams['hidden']) criterion = torch.nn.NLLLoss(reduction='none') # Load the dataset dataset = StructureDataset(args.file_data, truncate=None, max_length=500) if args.split_random: # Split print('Random split') split_frac = 0.1 num_test = int(len(dataset) * split_frac) train_set, test_set = random_split(dataset, [len(dataset) - num_test, num_test]) train_set, validation_set = random_split(train_set, [len(train_set) - num_test, num_test]) loader_train, loader_validation, loader_test = [StructureLoader(d, batch_size=hyperparams['batch_size']) for d in [train_set, validation_set, test_set]] else: # Split the dataset print('Structural split') dataset_indices = {d['name']: i for i, d in enumerate(dataset)} with open(args.file_splits) as f: dataset_splits = json.load(f) train_set, validation_set, test_set = [ Subset(dataset, [dataset_indices[chain_name] for chain_name in dataset_splits[key]]) for key in ['train', 'validation', 'test'] ] loader_train, loader_validation, loader_test = [StructureLoader(d, batch_size=hyperparams['batch_size']) for d in [train_set, validation_set, test_set]] print('Training:{}, Validation:{}, Test:{}'.format(len(train_set), len(validation_set), len(test_set))) # Build basepath for experiment base_folder = strftime("log/%y%b%d_%I%M%p/", localtime()) if not os.path.exists(base_folder): os.makedirs(base_folder) for subfolder in ['checkpoints']: if not os.path.exists(base_folder + subfolder): os.makedirs(base_folder + subfolder) # Log files logfile = base_folder + 'log.txt' with open(logfile, 'w') as f: f.write('Epoch\tTrain\tValidation\n') with open(base_folder + 'hyperparams.json', 'w') as f: json.dump(hyperparams, f) def _plot_log_probs(log_probs, total_step): alphabet = 'ACDEFGHIKLMNPQRSTVWY' reorder = 'DEKRHQNSTPGAVILMCFWY' permute_ix = np.array([alphabet.index(c) for c in reorder]) plt.close() fig = plt.figure(figsize=(8, 3)) ax = fig.add_subplot(111) P = np.exp(log_probs.cpu().data.numpy())[0].T plt.imshow(P[permute_ix]) plt.clim(0, 1) plt.colorbar() plt.yticks(np.arange(20), [a for a in reorder]) ax.tick_params( axis=u'both', which=u'both', length=0, labelsize=5 ) plt.tight_layout() plt.savefig(base_folder + 'probs{}.pdf'.format(total_step)) return def _featurize(batch): """ Represent structure as an attributed graph """ alphabet = 'AC<KEY>' B = len(batch) lengths = np.array([len(b['seq']) for b in batch], dtype=np.int32) L_max = max([len(b['seq']) for b in batch]) X = np.zeros([B, L_max, 3, 3]) S = np.zeros([B, L_max], dtype=np.int32) # Build the batch for i, b in enumerate(batch): x_n = b['coords']['N'] x_ca = b['coords']['CA'] x_c = b['coords']['C'] x =
np.stack([x_n, x_ca, x_c], 1)
numpy.stack
from mss import mss from PIL import Image import sys import time import mss.tools as MSSTools import io import numpy as np import cv2 import pyaudio import aubio import numpy as np # ############################################################## # Commandline arguments: # arg[1] = Display preview of monitor (0), or run (1 - also runs audio | anything else will not run audio) # arg[2] = Monitor to capture # arg[3] = X_COORD # arg[4] = Y_COORD # arg[5] = Width of screen to capture # arg[6] = Height of screen to capture # arg[7] = Section # by index # arg[8] = How many subsections we need to split and calculate dominant RGB for within the section index (for optimization) (sections.Count) # # Example execution for the top left of Monitor 1, with a 200x200 box: # py -3.6 .\clientcapture.py 1 1 0 0 1920 200 0 20 -- Example of capturing a 1920x1080 monitor with 20 subsections (this is testing TOP) # py -3.6 .\clientcapture.py 1 1 1820 0 100 1080 3 15 -- Example of capturing a 1920x1080 monitor with 15 subsections (this is testing RIGHT) # Example of section for testing monitor 1 (with open image) # py -3.6 .\clientcapture.py 0 1 # ############################################################## # ############################################################## # For testing image, use # t = Image.open(io.BytesIO(raw_bytes)) # t.show() # ############################################################## #start = time.time() if sys.argv[1] == '1': SIMULATED_SQUARES = 10 TIME_IN_SECS = 10 # CHANGE AT YOUR OWN RISK CHUNK = 2**11 RATE = 44100 # CHANGE AT YOUR OWN RISK p=pyaudio.PyAudio() stream=p.open(format=pyaudio.paInt16,channels=1,rate=RATE,input=True, frames_per_buffer=CHUNK) def readSoundOutputAlpha(): data = np.frombuffer(stream.read(CHUNK, exception_on_overflow = False),dtype=np.int16) peak=np.average(np.abs(data))*2 # colorBars = int(50*peak/2**10) % (1+SIMULATED_SQUARES) colorBars = int(3*peak/2**6) # bars="#"*colorBars # print("%05d %s"%(peak,bars)) if(colorBars > 255): colorBars = 255 return colorBars with mss() as sct: #print(sys.argv) if sys.argv[1] == '0': MONITOR_NUMBER = int(sys.argv[2]) mon = sct.monitors[MONITOR_NUMBER] monitor = { "top": mon["top"], "left": mon["left"], "width": mon["width"], "height": mon["height"], "mon": MONITOR_NUMBER } im = sct.grab(monitor) raw = MSSTools.to_png(im.rgb, im.size) b = Image.open(io.BytesIO(raw)) b.show() else: SECTION_IND = sys.argv[7] SUB_SECTION_COUNT = int(sys.argv[8]) X_COORD = int(sys.argv[3]) Y_COORD = int(sys.argv[4]) WIDTH = int(sys.argv[5]) HEIGHT = int(sys.argv[6]) MONITOR_NUMBER = int(sys.argv[2]) mon = sct.monitors[MONITOR_NUMBER] # Capture a bbox using percent values monitor = { "top": mon["top"] + Y_COORD, "left": mon["left"] + X_COORD, "width": WIDTH, "height": HEIGHT, "mon": MONITOR_NUMBER } isVert = True if WIDTH == 100 else False pixels_per_subsection = 0 if isVert: pixels_per_subsection = int(HEIGHT / SUB_SECTION_COUNT) else: pixels_per_subsection = int(WIDTH / SUB_SECTION_COUNT) # Continuously loop until process is killed while True: image_output = 'image_in_sec_' + SECTION_IND + '_.png'.format(**monitor) im = sct.grab(monitor) raw = MSSTools.to_png(im.rgb, im.size) #b = Image.open(io.BytesIO(raw)) #b.show() #break #Split image into equal sections img = Image.open(io.BytesIO(raw)) sub_sections = [] curr_x = 0 curr_y = 0 for i in np.arange(SUB_SECTION_COUNT): if isVert: area = (curr_x, curr_y, WIDTH, curr_y + pixels_per_subsection) sub_sections.append(img.crop(area)) curr_y += pixels_per_subsection else: area = (curr_x, curr_y, curr_x + pixels_per_subsection, HEIGHT) sub_sections.append(img.crop(area)) curr_x += pixels_per_subsection rgb = '' for i in np.arange(SUB_SECTION_COUNT): sub_section_image = sub_sections[i] raw = io.BytesIO() sub_section_image.save(raw, format='PNG') raw = raw.getvalue() nparr = np.frombuffer(raw, np.uint8) cimg = cv2.imdecode(nparr, cv2.IMREAD_COLOR) avg_per_row = np.average(cimg, axis=0) avg =
np.average(avg_per_row, axis=0)
numpy.average
import sys sys.path.append("..") import batman import lightkurve as lk import numpy as np import copy import os from matplotlib import pyplot as plt import tqdm from dev.kf import jacobian, KFilter re = 0.009158 eps = 1e-6 # EKF functions for the light curve def get_a(period, mstar, Go4pi=2945.4625385377644/(4*np.pi*np.pi)): """ https://dfm.io/posts/exopop/ Compute the semi-major axis of an orbit in Solar radii. :param period: the period in days :param mstar: the stellar mass in Solar masses """ return (Go4pi*period*period*mstar) ** (1./3) def set_params(): # to update more generally dt = 30 / (60 * 60 * 24) # 30 minute cadence in days mstar = 0.9707 rstar = 0.964 params = batman.TransitParams() params.t0 = 0.25 params.per = 2.4706 params.rp = 13.04 * re / rstar params.a = get_a(params.per, mstar) params.inc = 90. params.ecc = 0. params.w = 90. #longitude of periastron (in degrees) params.u = [0.93, -0.23, 0, 0] #limb darkening coefficients [u1-u4]''' params.limb_dark = "nonlinear" #limb darkening model t = np.arange(0, params.per + dt, dt) m = batman.TransitModel(params, t) model_flux = m.light_curve(params) err_flux = m.calc_err() / 1e6 return mstar, rstar, m, params, t, model_flux, err_flux def batman_to_partial_state(params): state = np.array([ params.per, params.rp, params.inc, params.ecc, params.w ]) state = np.concatenate((state, params.u)) return state def get_measured_flux(star_id = "KIC11446443"): if os.path.exists("../data/flux_{}.npy".format(star_id)): lc_time, lc_flux = np.load("../data/time_{}.npy".format(star_id)), np.load("../data/flux_{}.npy".format(star_id)) else: pixelfile = lk.search_targetpixelfile(star_id, quarter=1).download(quality_bitmask='hardest') lc = pixelfile.to_lightcurve(aperture_mask='all') lc_time, lc_flux = lc.time, lc.flux lc_flux /= max(lc_flux) np.save("time_{}.npy".format(star_id), lc_time) np.save("flux_{}.npy".format(star_id), lc_flux) return lc_time, lc_flux # TIC Contamination Ratio 0.05501 class LightcurveKFilter(KFilter): def __init__(self, star_id = "KIC11446443"): self.t_idx = 0 self.mstar, self.rstar, self.transitmodel, self.params, self.t, self.model_flux, self.err_flux = set_params() # add in a discretization error term Q = np.diag([ self.err_flux, # var(flux) = variance of batman model flux + inherent variance eps, # var(period) between timesteps, should be small eps, # var(prad) eps, # var(inc) eps, # var(ecc) eps, # var(omega) *[eps] * len(self.params.u) # var(limbdarks) ]) R = np.array([[eps]]) # to be replaced by PRF stuff super().__init__(self.f, Q, self.h, R, state=self.default_state()) def compute_lightcurve(self): self.params.per, self.params.rp, self.params.inc, self.params.ecc, self.params.w = self.state[1:6] self.params.a = get_a(self.params.per, self.mstar) self.params.u = self.state[6:] self.model_flux = self.transitmodel.light_curve(self.params) def f(self, state=None, mutate=False): ''' Takes in a state: [flux, period, prad, incl, ecc, omega, *limbdark1-4]. Returns the state at the next timestep. ''' if state is None: state = self.state if len(state.shape) > 1: # passing in an array from the Jacobian return np.vstack([self.f(row) for row in state]) if not np.allclose(batman_to_partial_state(self.params), state[1:]): # the Kalman update did something that'll need to be changed in the light curve self.compute_lightcurve() if mutate: self.t_idx += 1 state[0] = self.model_flux[self.t_idx] return state def h(self, state=None): if state is None: state = self.state return
np.array([state[0]])
numpy.array
import neural_network_lyapunov.examples.car.rrt_star as rrt_star import neural_network_lyapunov.examples.car.unicycle as unicycle import numpy as np import torch import unittest class TestRrtStar(unittest.TestCase): def setUp(self): self.plant = unicycle.Unicycle(torch.float64) self.u_lo = np.array([-3, -0.25 * np.pi]) self.u_up = np.array([6, 0.25 * np.pi]) def test_constructor(self): x_goal = np.array([0, 0., 0.]) dut = rrt_star.RrtStar(self.plant, 3, self.u_lo, self.u_up, x_goal) np.testing.assert_allclose(dut.node_state, x_goal.reshape((1, -1))) self.assertListEqual(dut.node_parent, [None]) self.assertListEqual(dut.node_children, [set()]) np.testing.assert_allclose(dut.node_cost_to_root, np.array([0.])) np.testing.assert_allclose(dut.node_cost_to_parent, np.array([0.])) def test_add_node(self): x_goal = np.array([0, 0., 0.]) dut = rrt_star.RrtStar(self.plant, 3, self.u_lo, self.u_up, x_goal) x_node1 = np.array([3, 2, 1]) node1_idx = dut._add_node(x_node1, parent_idx=0, cost_to_parent=4.) self.assertEqual(node1_idx, 1) np.testing.assert_allclose(dut.node_state, np.vstack( (x_goal, x_node1))) self.assertEqual(dut.node_state.shape, (2, 3)) self.assertListEqual(dut.node_parent, [None, 0]) self.assertListEqual(dut.node_children, [{1}, set()]) np.testing.assert_allclose(dut.node_cost_to_root, np.array([0., 4.])) np.testing.assert_allclose(dut.node_cost_to_parent, np.array([0., 4.])) x_node2 = np.array([4, 5., 6.]) node2_idx = dut._add_node(x_node2, parent_idx=1, cost_to_parent=3.) self.assertEqual(node2_idx, 2) np.testing.assert_allclose(dut.node_state, np.vstack((x_goal, x_node1, x_node2))) self.assertListEqual(dut.node_parent, [None, 0, 1]) self.assertListEqual(dut.node_children, [{1}, {2}, set()]) np.testing.assert_allclose(dut.node_cost_to_root, np.array([0., 4., 7.])) np.testing.assert_allclose(dut.node_cost_to_parent, np.array([0., 4., 3.])) def test_state_distance(self): x_goal = np.array([0, 0., 0.]) dut = rrt_star.RrtStar(self.plant, 3, self.u_lo, self.u_up, x_goal) def eval_distance(x1, x2): return (x1 - x2) @ (Q @ (x1 - x2)) Q = np.diag([1., 1., 0.5]) x1 = np.array([1., 2., 3.]) x2 = np.array([3., 1., 2.]) np.testing.assert_allclose(dut.state_distance(x1, x2), np.array([eval_distance(x1, x2)])) x1 = np.array([[1., 2., 3.], [4., -2., -1.]]) np.testing.assert_allclose( dut.state_distance(x1, x2), np.array([eval_distance(x1[0], x2), eval_distance(x1[1], x2)])) np.testing.assert_allclose( dut.state_distance(x2, x1), np.array([eval_distance(x1[0], x2), eval_distance(x1[1], x2)])) def test_extend_node(self): x_goal = np.array([0, 0., 0.]) dut = rrt_star.RrtStar(self.plant, 3, self.u_lo, self.u_up, x_goal) x_node =
np.array([1., 2., 3.])
numpy.array
''' @author: <NAME> @copyright: Copyright 2016-2019, <NAME>. @license: MIT @contact: <EMAIL> ''' ## Extract features import os import numpy as np from scipy import stats import pandas as pd from .sigproc import (mad, peakfreq_from_fft, spectralRollOff, spectralCentroidAndSpread, chromaFeatures, chromaFeaturesInit, rssq,\ peak2rms, rms, range_bytes, energy, zcr_2, zcr, recursive_sta_lta) from .entropy import spectral_entropy, sample_entropy, shannon_entropy from .speech_features import mfcc import time class FeatureExtractor: def __init__(self): self.dataset = None self.feature_data = None def set_dataset(self, df): self.dataset = df def set_class_labels(self, labels): self.class_labels = labels def save_features(self, file_name): self.feature_data.to_csv(file_name) print('\nFeatures data saved!\n') def extract_features(self, fs, window_length, overlap_length, signal_length): labels = self.dataset['Class'] filenames = self.dataset['FileName'] data = np.array(self.dataset.loc[:, list(range(signal_length))], dtype = np.float) step_length = window_length - overlap_length number_of_windows = int(np.floor((signal_length-window_length)/step_length) + 1) #print(number_of_windows) wins = [] for i in range(number_of_windows): wstart = i * step_length wend = i * step_length + window_length if i == 0: wins = [np.arange(wstart, wend)] else: wins = np.append(wins, [np.arange(wstart, wend)], axis = 0) #print(wins) n_win = len(wins) nsignal, nsample = data.shape signalClass = [] fileName = [] meanValue = [] medianValue = [] varianceValue = [] # variance value feature ptpValue = [] # Maximum-to-minimum difference feature ptrmsValue = [] # peak-magnitude-to-RMS ratio feature (Determine the crest factor of a signal using the peak2rms function) rssqValue = [] # root-sum-of-squares level feature stdValue = [] # standard deviation madValue = [] # median absolute deviation percentile25Value = [] # 25th percentile, the value below which 25% of observations fall percentile75Value = [] # 25th percentile, the value below which 25% of observations fall interPercentileValue = [] # the difference between 25th percentile and 75th percentile skewnessValue = [] # a measure of symmetry relative to a normal distribution kurtosisValue = [] # a measure of whether the data are heavy-tailed or light-tailed relative to a normal distribution zcrValue = [] # the rate of sign-changes along a signal, i.e., the rate at which the signal changes from positive to negative or back energyValue = [] # the sum of squares of the signal values shannonEntropyValue = [] # Shannon's entropy value of the signal energyEntropyValue = [] # the entropy of normalized energies, a measure of abrupt changes spectralEntropyValue = [] # the entropy of normalized spectral energies spectralCentroidValue = [] # indice of the dominant frequency spectralSpreadValue = [] # the second central moment of the spectrum spectralRolloffValue = [] # the frequency below which 85% of the total spectral energy lies rmsValue = [] # root-mean-square energy peakFreqValue = [] # peak frequency staltaValue = [] # STA/LTA # MFCC - Mel Frequency Cepstral Coefficients, form a cepstral representation where the frequency bands are not linear but distributed according to the mel-scale samplerate = 500 # Hz winlen = window_length / samplerate # analysis frame duration (s) winstep = step_length / samplerate # analysis fram shift (s) numcep = 13; # the number of cepstrum to return, default 13 nfilt = 26 # the number of filters in the filterbank, default 26. nfft= window_length # the FFT size. Default is 64. lowfreq=0 # lowest band edge of mel filters. In Hz, default is 0. highfreq= samplerate / 2 # highest band edge of mel filters. In Hz, default is samplerate/2 preemph=0.97 # apply preemphasis filter with preemph as coefficient. 0 is no filter. Default is 0.97. ceplifter=22 # apply a lifter to final cepstral coefficients. 0 is no lifter. Default is 22. mfcc_array = np.zeros((n_win, numcep), dtype = np.float32) mfcc1 = [] mfcc2 = [] mfcc3 = [] mfcc4 = [] mfcc5 = [] mfcc6 = [] mfcc7 = [] mfcc8 = [] mfcc9 = [] mfcc10 = [] mfcc11 = [] mfcc12 = [] mfcc13 = [] # Chroma Vector and Deviation chromavector1 = [] chromavector2 = [] chromavector3 = [] chromavector4 = [] chromavector5 = [] chromavector6 = [] chromavector7 = [] chromavector8 = [] chromavector9 = [] chromavector10 = [] chromavector11 = [] chromavector12 = [] chromaStd = [] # extract features based on window sliding print("Extracting features in progress...\n") start = time.clock() for i in range(nsignal): print('Extracting features for #(%d) segment' %(i+1)) for ind, val in enumerate(wins): fileName.append(filenames[i]) signalClass.append(labels[i]) # error ocurred when using numpy array here # signal = (data[i, val].reshape(-1,1)).copy() signal = (data[i, val]) meanValue.append(np.mean(signal)) medianValue.append(
np.mean(signal)
numpy.mean
"""GNSS utility functions, mostly based on satellite ephemerides. Author: <NAME> """ try: import autograd.numpy as np except(ImportError): print("""Package 'autograd' not found. 'autograd.numpy' is necessary for coarse-time navigation via maximum-likelihood estimation. Falling back to 'numpy'.""") import numpy as np import pymap3d as pm try: import mkl_fft as fft_lib except(ImportError): print("""Package 'mkl_fft' not found. Consider installing 'mkl_fft' with 'conda install -c intel mkl_fft' for faster FFT and IFFT. Falling back to 'numpy.fft'.""") import numpy.fft as fft_lib def get_sat_pos_vel_acc(t, eph): """Calculate positions, velocities, and accelerations of satellites. Accepts arrays for t / eph, i.e., can calculate multiple points in time / multiple satellites at once. Does not interpolate GLONASS. Implemented according to <NAME>., et al. “Computing GPS Satellite Velocity and Acceleration from the Broadcast Navigation Message.” Annual of Navigation, vol. 66, no. 4, 2019, pp. 769–779. https://www.gps.gov/technical/icwg/meetings/2019/09/GPS-SV-velocity-and-acceleration.pdf Inputs: t - GPS time(s) [s] (ignored for SBAS) eph - Ephemeris as array(s) Outputs: positions - Satellite position(s) in ECEF XYZ as array(s) [m] velocities - Satellite velocity/ies in ECEF XYZ as array(s) [m/s] accelerations - Sat. acceleration(s) in ECEF XYZ as array(s) [m/s^2] Author: <NAME> """ if not np.isnan(eph[2]).any(): # No SBAS / GLONASS t = np.mod(t, 7 * 24 * 60 * 60) cic = eph[13] # "cic"] crs = eph[10] # "crs"] Omega0 = eph[15] # "Omega0"] Deltan = eph[4] # "Deltan"] cis = eph[14] # "cis"] M0 = eph[2] # "M0"] i0 = eph[11] # "i0"] cuc = eph[7] # "cuc"] crc = eph[9] # "crc"] e = eph[5] # "e"] Omega = eph[6] # "Omega"] cus = eph[8] # "cus"] OmegaDot = eph[16] # "OmegaDot"] sqrtA = eph[3] # "sqrtA"] IDOT = eph[12] # "IDOT"] toe = eph[20] # "toe"] # Broadcast Navigation User Equations # WGS 84 value of the earth’s gravitational constant for GPS user [m^3/s^2] mu = 3.986005e14 # WGS 84 value of the earth’s rotation rate [rad/s] OmegaeDot = 7.2921151467e-5 # Semi-major axis A = sqrtA ** 2 # Computed mean motion [rad/s] n0 = np.sqrt(mu / A ** 3) # Time from ephemeris reference epoch tk = np.array(t - toe) # t is GPS system time at time of transmission, i.e., GPS time corrected # for transit time (range/speed of light). Furthermore, tk shall be the # actual total time difference between the time t and the epoch time toe, # and must account for beginning or end of week crossovers. That is, if tk # is greater than 302,400 seconds, subtract 604,800 seconds from tk. If tk # is less than -302,400 seconds, add 604,800 seconds to tk. with np.nditer(tk, op_flags=["readwrite"]) as it: for tk_i in it: if tk_i > 302400: tk_i[...] = tk_i - 604800 elif tk_i < -302400: tk_i[...] = tk_i + 604800 # Corrected mean motion n = n0 + Deltan # Mean anomaly Mk = M0 + n * tk # Kepler’s equation (Mk = Ek - e*np.sin(Ek)) solved for eccentric anomaly # (Ek) by iteration: # Initial value [rad] Ek = Mk # Refined value, three iterations, (j = 0,1,2) for j in range(3): Ek = Ek + (Mk - Ek + e * np.sin(Ek)) / (1 - e * np.cos(Ek)) # True anomaly (unambiguous quadrant) nuk = 2 * np.arctan(np.sqrt((1 + e) / (1 - e)) * np.tan(Ek / 2)) # Argument of Latitude Phik = nuk + Omega # Argument of Latitude Correction deltauk = cus * np.sin(2 * Phik) + cuc * np.cos(2 * Phik) # Radius Correction deltark = crs * np.sin(2 * Phik) + crc * np.cos(2 * Phik) # Inclination Correction deltaik = cis * np.sin(2 * Phik) + cic * np.cos(2 * Phik) # Corrected Argument of Latitude uk = Phik + deltauk # Corrected Radius rk = A * (1 - e * np.cos(Ek)) + deltark # Corrected Inclination ik = i0 + deltaik + IDOT * tk # Positions in Orbital Plane xkDash = rk * np.cos(uk) ykDash = rk * np.sin(uk) # Corrected longitude of ascending node Omegak = Omega0 + (OmegaDot - OmegaeDot) * tk - OmegaeDot * toe # Earth-fixed coordinates xk = xkDash * np.cos(Omegak) - ykDash * np.cos(ik) * np.sin(Omegak) yk = xkDash * np.sin(Omegak) + ykDash * np.cos(ik) * np.cos(Omegak) zk = ykDash * np.sin(ik) # SV Velocity # Eccentric anomaly rate EkDot = n / (1 - e * np.cos(Ek)) # True anomaly rate nukDot = EkDot * np.sqrt(1 - e ** 2) / (1 - e * np.cos(Ek)) # Corrected Inclination rate dik_dt = IDOT + 2 * nukDot * ( cis * np.cos(2 * Phik) - cic * np.sin(2 * Phik) ) # Corrected Argument of Latitude rate ukDot = nukDot + 2 * nukDot * ( cus * np.cos(2 * Phik) - cuc * np.sin(2 * Phik) ) # Corrected Radius rate rkDot = e * A * EkDot * np.sin(Ek) + 2 * nukDot * ( crs * np.cos(2 * Phik) - crc * np.sin(2 * Phik) ) # Longitude of ascending node rate OmegakDot = OmegaDot - OmegaeDot # In-plane x velocity xkDashDot = rkDot * np.cos(uk) - rk * ukDot * np.sin(uk) # In-plane y velocity ykDashDot = rkDot * np.sin(uk) + rk * ukDot * np.cos(uk) # Earth-fixed x velocity [m/s] xkDot = ( -xkDash * OmegakDot * np.sin(Omegak) + xkDashDot * np.cos(Omegak) - ykDashDot * np.sin(Omegak) * np.cos(ik) - ykDash * ( OmegakDot * np.cos(Omegak) * np.cos(ik) - dik_dt * np.sin(Omegak) * np.sin(ik) ) ) # Earth-fixed y velocity [m/s] ykDot = ( xkDash * OmegakDot * np.cos(Omegak) + xkDashDot * np.sin(Omegak) + ykDashDot * np.cos(Omegak) * np.cos(ik) - ykDash * ( OmegakDot * np.sin(Omegak) * np.cos(ik) + dik_dt * np.cos(Omegak) * np.sin(ik) ) ) # Earth-fixed z velocity [m/s] zkDot = ykDash * dik_dt * np.cos(ik) + ykDashDot * np.sin(ik) # SV Acceleration # WGS 84 Earth equatorial radius [m] RE = 6378137.0 # Oblate Earth gravity coefficient J2 = 0.0010826262 # Oblate Earth acceleration factor F = -3 / 2 * J2 * mu / rk ** 2 * (RE / rk) ** 2 # Earth-fixed x acceleration [m/s^2] xkDotDot = ( -mu * xk / rk ** 3 + F * ((1 - 5 * (zk / rk) ** 2) * xk / rk) + 2 * ykDot * OmegaeDot + xk * OmegaeDot ** 2 ) # Earth-fixed y acceleration [m/s^2] ykDotDot = ( -mu * yk / rk ** 3 + F * ((1 - 5 * (zk / rk) ** 2) * yk / rk) - 2 * xkDot * OmegaeDot + yk * OmegaeDot ** 2 ) # Earth-fixed z acceleration [m/s^2] zkDotDot = -mu * zk / rk ** 3 + F * ((3 - 5 * (zk / rk) ** 2) * zk / rk) positions = np.array([xk, yk, zk]).T velocities = np.array([xkDot, ykDot, zkDot]).T accelerations = np.array([xkDotDot, ykDotDot, zkDotDot]).T else: # SBAS positions = 1.0e3 * np.array([eph[3], eph[6], eph[9]]).T velocities = 1.0e3 * np.array([eph[4], eph[7], eph[10]]).T accelerations = 1.0e3 * np.array([eph[5], eph[8], eph[11]]).T if isinstance(t, np.ndarray) and len(eph.shape) == 1: n_times = t.shape[0] positions = np.tile(positions, (n_times, 1)) velocities = np.tile(velocities, (n_times, 1)) accelerations = np.tile(accelerations, (n_times, 1)) return positions, velocities, accelerations def get_sat_pos_vel(t, eph): """Calculate positions and velocities of satellites. Accepts arrays for t / eph, i.e., can calculate multiple points in time / multiple satellites at once. Does not interpolate GLONASS. Implemented according to Thompson, <NAME>., et al. “Computing GPS Satellite Velocity and Acceleration from the Broadcast Navigation Message.” Annual of Navigation, vol. 66, no. 4, 2019, pp. 769–779. https://www.gps.gov/technical/icwg/meetings/2019/09/GPS-SV-velocity-and-acceleration.pdf Inputs: t - GPS time(s) [s] (ignored for SBAS) eph - Ephemeris as array(s) Outputs: positions - Satellite position(s) in ECEF XYZ as array(s) [m] velocities - Satellite velocity/ies in ECEF XYZ as array(s) [m/s] Author: <NAME> """ if not np.isnan(eph[2]).any(): # No SBAS / GLONASS t = np.mod(t, 7 * 24 * 60 * 60) cic = eph[13] # "cic"] crs = eph[10] # "crs"] Omega0 = eph[15] # "Omega0"] Deltan = eph[4] # "Deltan"] cis = eph[14] # "cis"] M0 = eph[2] # "M0"] i0 = eph[11] # "i0"] cuc = eph[7] # "cuc"] crc = eph[9] # "crc"] e = eph[5] # "e"] Omega = eph[6] # "Omega"] cus = eph[8] # "cus"] OmegaDot = eph[16] # "OmegaDot"] sqrtA = eph[3] # "sqrtA"] IDOT = eph[12] # "IDOT"] toe = eph[20] # "toe"] # Broadcast Navigation User Equations # WGS 84 value of the earth’s gravitational constant for GPS user [m^3/s^2] mu = 3.986005e14 # WGS 84 value of the earth’s rotation rate [rad/s] OmegaeDot = 7.2921151467e-5 # Semi-major axis A = sqrtA ** 2 # Computed mean motion [rad/s] n0 = np.sqrt(mu / A ** 3) # Time from ephemeris reference epoch tk = np.array(t - toe) # t is GPS system time at time of transmission, i.e., GPS time corrected # for transit time (range/speed of light). Furthermore, tk shall be the # actual total time difference between the time t and the epoch time toe, # and must account for beginning or end of week crossovers. That is, if tk # is greater than 302,400 seconds, subtract 604,800 seconds from tk. If tk # is less than -302,400 seconds, add 604,800 seconds to tk. with np.nditer(tk, op_flags=["readwrite"]) as it: for tk_i in it: if tk_i > 302400: tk_i[...] = tk_i - 604800 elif tk_i < -302400: tk_i[...] = tk_i + 604800 # Corrected mean motion n = n0 + Deltan # Mean anomaly Mk = M0 + n * tk # Kepler’s equation (Mk = Ek - e*np.sin(Ek)) solved for eccentric anomaly # (Ek) by iteration: # Initial value [rad] Ek = Mk # Refined value, three iterations, (j = 0,1,2) for j in range(3): Ek = Ek + (Mk - Ek + e * np.sin(Ek)) / (1 - e * np.cos(Ek)) # True anomaly (unambiguous quadrant) nuk = 2 * np.arctan(np.sqrt((1 + e) / (1 - e)) * np.tan(Ek / 2)) # Argument of Latitude Phik = nuk + Omega # Argument of Latitude Correction deltauk = cus * np.sin(2 * Phik) + cuc * np.cos(2 * Phik) # Radius Correction deltark = crs * np.sin(2 * Phik) + crc * np.cos(2 * Phik) # Inclination Correction deltaik = cis * np.sin(2 * Phik) + cic * np.cos(2 * Phik) # Corrected Argument of Latitude uk = Phik + deltauk # Corrected Radius rk = A * (1 - e * np.cos(Ek)) + deltark # Corrected Inclination ik = i0 + deltaik + IDOT * tk # Positions in Orbital Plane xkDash = rk * np.cos(uk) ykDash = rk * np.sin(uk) # Corrected longitude of ascending node Omegak = Omega0 + (OmegaDot - OmegaeDot) * tk - OmegaeDot * toe # Earth-fixed coordinates xk = xkDash * np.cos(Omegak) - ykDash * np.cos(ik) * np.sin(Omegak) yk = xkDash * np.sin(Omegak) + ykDash * np.cos(ik) * np.cos(Omegak) zk = ykDash * np.sin(ik) # SV Velocity # Eccentric anomaly rate EkDot = n / (1 - e * np.cos(Ek)) # True anomaly rate nukDot = EkDot * np.sqrt(1 - e ** 2) / (1 - e * np.cos(Ek)) # Corrected Inclination rate dik_dt = IDOT + 2 * nukDot * ( cis * np.cos(2 * Phik) - cic * np.sin(2 * Phik) ) # Corrected Argument of Latitude rate ukDot = nukDot + 2 * nukDot * ( cus * np.cos(2 * Phik) - cuc * np.sin(2 * Phik) ) # Corrected Radius rate rkDot = e * A * EkDot * np.sin(Ek) + 2 * nukDot * ( crs * np.cos(2 * Phik) - crc * np.sin(2 * Phik) ) # Longitude of ascending node rate OmegakDot = OmegaDot - OmegaeDot # In-plane x velocity xkDashDot = rkDot * np.cos(uk) - rk * ukDot * np.sin(uk) # In-plane y velocity ykDashDot = rkDot * np.sin(uk) + rk * ukDot * np.cos(uk) # Earth-fixed x velocity [m/s] xkDot = ( -xkDash * OmegakDot * np.sin(Omegak) + xkDashDot * np.cos(Omegak) - ykDashDot * np.sin(Omegak) * np.cos(ik) - ykDash * ( OmegakDot * np.cos(Omegak) * np.cos(ik) - dik_dt * np.sin(Omegak) * np.sin(ik) ) ) # Earth-fixed y velocity [m/s] ykDot = ( xkDash * OmegakDot * np.cos(Omegak) + xkDashDot * np.sin(Omegak) + ykDashDot * np.cos(Omegak) * np.cos(ik) - ykDash * ( OmegakDot * np.sin(Omegak) * np.cos(ik) + dik_dt * np.cos(Omegak) * np.sin(ik) ) ) # Earth-fixed z velocity [m/s] zkDot = ykDash * dik_dt * np.cos(ik) + ykDashDot * np.sin(ik) positions = np.array([xk, yk, zk]).T velocities = np.array([xkDot, ykDot, zkDot]).T else: # SBAS positions = 1.0e3 * np.array([eph[3], eph[6], eph[9]]).T velocities = 1.0e3 * np.array([eph[4], eph[7], eph[10]]).T if isinstance(t, np.ndarray) and len(eph.shape) == 1: n_times = t.shape[0] positions = np.tile(positions, (n_times, 1)) velocities = np.tile(velocities, (n_times, 1)) return positions, velocities def get_sat_pos(t, eph): """Calculate positions of satellites. Accepts arrays for t / eph, i.e., can calculate multiple points in time / multiple satellites at once. Does not interpolate GLONASS. Implemented according to Thompson, <NAME>., et al. “Computing GPS Satellite Velocity and Acceleration from the Broadcast Navigation Message.” Annual of Navigation, vol. 66, no. 4, 2019, pp. 769–779. https://www.gps.gov/technical/icwg/meetings/2019/09/GPS-SV-velocity-and-acceleration.pdf Inputs: t - GPS time(s) [s] (ignored for SBAS) eph - Ephemeris as array(s) Outputs: positions - Satellite position(s) in ECEF XYZ as array(s) [m] Author: <NAME> """ if not np.isnan(eph[2]).any(): # No SBAS / GLONASS t = np.mod(t, 7 * 24 * 60 * 60) cic = eph[13] # "cic"] crs = eph[10] # "crs"] Omega0 = eph[15] # "Omega0"] Deltan = eph[4] # "Deltan"] cis = eph[14] # "cis"] M0 = eph[2] # "M0"] i0 = eph[11] # "i0"] cuc = eph[7] # "cuc"] crc = eph[9] # "crc"] e = eph[5] # "e"] Omega = eph[6] # "Omega"] cus = eph[8] # "cus"] OmegaDot = eph[16] # "OmegaDot"] sqrtA = eph[3] # "sqrtA"] IDOT = eph[12] # "IDOT"] toe = eph[20] # "toe"] # Broadcast Navigation User Equations # WGS 84 value of the earth’s gravitational constant for GPS user [m^3/s^2] mu = 3.986005e14 # WGS 84 value of the earth’s rotation rate [rad/s] OmegaeDot = 7.2921151467e-5 # Semi-major axis A = sqrtA ** 2 # Computed mean motion [rad/s] n0 = np.sqrt(mu / A ** 3) # Time from ephemeris reference epoch tk = np.array(t - toe) # t is GPS system time at time of transmission, i.e., GPS time corrected # for transit time (range/speed of light). Furthermore, tk shall be the # actual total time difference between the time t and the epoch time toe, # and must account for beginning or end of week crossovers. That is, if tk # is greater than 302,400 seconds, subtract 604,800 seconds from tk. If tk # is less than -302,400 seconds, add 604,800 seconds to tk. try: with np.nditer(tk, op_flags=["readwrite"]) as it: for tk_i in it: if tk_i > 302400: tk_i[...] = tk_i - 604800 elif tk_i < -302400: tk_i[...] = tk_i + 604800 except TypeError: for idx in np.arange(tk.shape[0]): if tk[idx] > 302400: tk[idx] = tk[idx] - 604800 elif tk[idx] < -302400: tk[idx] = tk[idx] + 604800 # Corrected mean motion n = n0 + Deltan # Mean anomaly Mk = M0 + n * tk # Kepler’s equation (Mk = Ek - e*np.sin(Ek)) solved for eccentric anomaly # (Ek) by iteration: # Initial value [rad] Ek = Mk # Refined value, three iterations, (j = 0,1,2) for j in range(3): Ek = Ek + (Mk - Ek + e * np.sin(Ek)) / (1 - e * np.cos(Ek)) # True anomaly (unambiguous quadrant) nuk = 2 * np.arctan(np.sqrt((1 + e) / (1 - e)) * np.tan(Ek / 2)) # Argument of Latitude Phik = nuk + Omega # Argument of Latitude Correction deltauk = cus * np.sin(2 * Phik) + cuc * np.cos(2 * Phik) # Radius Correction deltark = crs * np.sin(2 * Phik) + crc * np.cos(2 * Phik) # Inclination Correction deltaik = cis * np.sin(2 * Phik) + cic * np.cos(2 * Phik) # Corrected Argument of Latitude uk = Phik + deltauk # Corrected Radius rk = A * (1 - e * np.cos(Ek)) + deltark # Corrected Inclination ik = i0 + deltaik + IDOT * tk # Positions in Orbital Plane xkDash = rk * np.cos(uk) ykDash = rk * np.sin(uk) # Corrected longitude of ascending node Omegak = Omega0 + (OmegaDot - OmegaeDot) * tk - OmegaeDot * toe # Earth-fixed coordinates xk = xkDash * np.cos(Omegak) - ykDash * np.cos(ik) * np.sin(Omegak) yk = xkDash * np.sin(Omegak) + ykDash * np.cos(ik) * np.cos(Omegak) zk = ykDash * np.sin(ik) positions = np.array([xk, yk, zk]).T else: # SBAS positions = 1.0e3 * np.array([eph[3], eph[6], eph[9]]).T if isinstance(t, np.ndarray) and len(eph.shape) == 1: n_times = t.shape[0] positions = np.tile(positions, (n_times, 1)) return positions def get_sat_pos_sp3(gps_time, sp3, sv_list, system=None): """Calculate positions of satellites from precise orbits (SP3 file). Inputs: gps_time - GPS times [s] as numpy array sp3 - Precise orbit supporting points as pandas.DataFrame from read_sp3 sv_list - Satellite indices (PRNs) system - Character representing satellite navigation system: 'G' - GPS 'S' - SBAS 'R' - GLONASS 'E' - Galileo 'C' - BeiDou 'J' - QZSS 'I' - NavIC None - Use character of 1st SP3 entry (default) Output: position - Satellite positions in ECEF XYZ as Nx3 array [m] Author: <NAME> Based on https://github.com/GNSSpy-Project/gnsspy/blob/fce079af37d585dc757c56539a98cc0dfe66f9de/gnsspy/position/interpolation.py """ def coord_interp(parameter): """ Interpolation of SP3 coordinates. Fit polynomial to 4 hours (14400 seconds) period of SP3 Cartesian coordinates and return to the interpolated coordinates. Input: parameter - Polynomial coefficients from numpy polyfit function (numpy array) Output: interp_coord - Interpolated coordinates (numpy array) """ epoch = 0.0 time = np.array([ epoch**deg for deg in range(len(parameter)-1, -1, -1) ]) return np.matmul(parameter, time) import pandas as pd # Degree of polynomial interpolation, lower than 11 not recommended, above # 16 not applicable for 15 minute intervals poly_degree = 16 # Convert time referenceDate = np.datetime64('1980-01-06') # GPS reference date utc = np.timedelta64(int((gps_time[0]) * 1e9), 'ns') + referenceDate # Check if numpy array has been passed for sv_list if isinstance(sv_list, np.ndarray): # Convert numpy array to list sv_list = sv_list.astype(int).tolist() # Check if system character must be read from SP3 if system is None: # Use system character of 1st entry system = sp3.index[0][1][0] # Convert sv_list to strings sv_list = [system + "{:02d}".format(sv) for sv in sv_list] # Get time stamps epoch_values = sp3.index.get_level_values("Epoch").unique() # Difference between 2 time stamps deltaT = epoch_values[1]-epoch_values[0] # Get 17 data points epoch_start = utc - np.timedelta64(2, 'h') epoch_stop = utc + np.timedelta64(2, 'h') + deltaT sp3_temp = sp3.loc[(slice(epoch_start, epoch_stop))].copy() sp3_temp = sp3_temp.reorder_levels(["SV", "Epoch"]) # Initialize result epoch_interp_List = np.zeros(shape=(len(sv_list), 3)) # Iterate over all satellites for svIndex, sv in enumerate(sv_list): fitTime = np.array([ (np.datetime64(t) - referenceDate) / np.timedelta64(1, 's') - gps_time[svIndex] for t in sp3_temp.loc[sv_list[0]].index.get_level_values("Epoch") ]) epoch_number = len(sp3_temp.loc[sv]) if epoch_number <= poly_degree: print("Warning: Not enough epochs to predict for satellite", sv, "| Epoch Count:", epoch_number, " - Polynomial Degree:", poly_degree) epoch_interp_List[svIndex, :] = np.full(shape=3, fill_value=None) continue # if epoch_number != 17: # fitTime = [(sp3_temp.loc[sv].index[t] # - sp3_temp.loc[sv].index[0]).seconds # for t in range(epoch_number)] # Fit sp3 coordinates to 16 deg polynomial fitX = np.polyfit(fitTime, sp3_temp.loc[sv].X.copy(), deg=poly_degree) fitY = np.polyfit(fitTime, sp3_temp.loc[sv].Y.copy(), deg=poly_degree) fitZ = np.polyfit(fitTime, sp3_temp.loc[sv].Z.copy(), deg=poly_degree) # sidereal_day = 0.99726956634 # period = sidereal_day # P0 = 2.0*np.pi / period # gps_day_sec = np.mod(gps_time, 24*60*60) # gps_rel_time = gps_day_sec / 86400.0 # Timei = fitTime + gps_day_sec # Timei = Timei / 86400.0 # Xi = sp3_temp.loc[sv].X.copy() # Yi = sp3_temp.loc[sv].Y.copy() # Zi = sp3_temp.loc[sv].Z.copy() # A = np.zeros((poly_degree+1, poly_degree+1)) # A[:, 0] = np.ones(poly_degree+1) # B = np.zeros(poly_degree+1) # B[0] = 1.0 # ND = np.int((poly_degree) / 2) # for i in np.arange(ND): # kk = 1 + i*2 # P = P0 * (i+1) # A[:, kk] = np.sin(P*Timei) # A[:, kk+1] = np.cos(P*Timei) # B[kk] = np.sin(P*gps_rel_time) # B[kk+1] = np.cos(P*gps_rel_time) # XCoeffs = np.linalg.lstsq(A, Xi, rcond=None)[0] # YCoeffs = np.linalg.lstsq(A, Yi, rcond=None)[0] # ZCoeffs = np.linalg.lstsq(A, Zi, rcond=None)[0] # epoch_interp_List[svIndex, :] = 1000.0*np.array( # [B@XCoeffs, B@YCoeffs, B@ZCoeffs] # ) # Interpolate coordinates x_interp = coord_interp(fitX) * 1000 # km to m # x_velocity = _np.array([(x_interp[i+1]-x_interp[i])/interval if (i+1)<len(x_interp) else 0 for i in range(len(x_interp))]) y_interp = coord_interp(fitY) * 1000 # km to m # y_velocity = _np.array([(y_interp[i+1]-y_interp[i])/interval if (i+1)<len(y_interp) else 0 for i in range(len(y_interp))]) z_interp = coord_interp(fitZ) * 1000 # km to m # z_velocity = _np.array([(z_interp[i+1]-z_interp[i])/interval if (i+1)<len(z_interp) else 0 for i in range(len(z_interp))]) sv_interp = np.vstack((x_interp, y_interp, z_interp)) epoch_interp_List[svIndex, :] = sv_interp[:, 0] # Restore original fitTime in case it has changed # fitTime = np.linspace(0.0, deltaT.seconds*16.0, 17) return epoch_interp_List def find_eph(eph, sv, time): """Find the proper column in ephemeris array. Inputs: eph - Ephemeris array sv - Satellite index (PRNs) time - GPS time of week [s] Output: icol - Column index, NaN if ephemeris does not contain satellite """ icol = 0 isat = np.where(eph[0] == sv)[0] n = isat.size if n == 0: return np.NaN icol = isat[0] dtmin = eph[20, icol] - time for t in isat: dt = eph[20, t] - time if dt < 0: if abs(dt) < abs(dtmin): icol = t dtmin = dt return icol def check_t(time): """Account for beginning or end of week crossover. Input: time - Time [s] Output: corrTime - Corrected time [s] """ half_week = 302400 # [s] corrTime = time if time > half_week: corrTime = time - 2 * half_week elif time < -half_week: corrTime = time + 2 * half_week return corrTime def check_t_vectorized(time): """Account for beginning or end of week crossover. Input: time - Time [s], numpy.ndarray Output: corrTime - Corrected time [s] """ half_week = 302400 # [s] corrTime = time corrTime[time > half_week] = time[time > half_week] - 2 * half_week corrTime[time < -half_week] = corrTime[time < -half_week] + 2 * half_week return corrTime def get_sat_clk_corr(transmit_time, prn, eph): """Compute satellite clock correction time. Without relativistic correction. Ephemeris provided as array. Inputs: transmit_time - Actual time when signal was transmitted [s] prn - Satellite's PRN index (array) eph - Ephemeris array Output: satClockCorr - Satellite clock corrections [s] Author: <NAME> """ # GPS time with respect to 1980 to time of week (TOW) transmit_time = np.mod(transmit_time, 7 * 24 * 60 * 60) # Get ephemerides (find column of ephemeris matrix that matches satellite # index and time) if eph.ndim > 1 and eph.shape[1] != prn.shape[0]: col = np.array([find_eph(eph, prn_i, transmit_time) for prn_i in prn]) eph = eph[:, col] # Extract column # Find initial satellite clock correction # Find time difference dt = np.array([check_t(transmit_time - eph_20) for eph_20 in eph[20]]) # Calculate clock correction satClkCorr = (eph[1] * dt + eph[19]) * dt + eph[19] # - eph.T_GD # Apply correction time = transmit_time - satClkCorr # Find time difference dt = np.array([check_t(t_eph_20) for t_eph_20 in time - eph[20]]) # Calculate clock correction return (eph[1] * dt + eph[19]) * dt + eph[18] # - eph.T_GD def get_sat_clk_corr_vectorized(transmit_time, prn, eph): """Compute satellite clock correction time. Without relativistic correction. Navigation data provided as 2D NumPy array; transmission time and PRNs provided as 1D NumPy array. Inputs: transmit_time - Actual times when signals were transmitted [s] (Nx1 array) prn - Satellite's PRN indices (Nx1 array) eph - Matching navigation data (21xN array) Output: sat_clock_corr - Satellite clock corrections [s] (Nx1 array) Author: <NAME> """ # GPS time with respect to 1980 to time of week (TOW) transmit_time = np.mod(transmit_time, 7 * 24 * 60 * 60) # Get ephemerides (find column of ephemeris matrix that matches satellite # index and time) if eph.shape[1] != prn.shape[0]: col = np.array([find_eph(eph, prn_i, transmit_time) for prn_i in prn]) eph = eph[:, col] # Extract column # Find initial satellite clock correction # Find time difference dt = check_t_vectorized(transmit_time - eph[20]) # Calculate clock correction satClkCorr = (eph[1] * dt + eph[19]) * dt + eph[19] # - eph.T_GD # Apply correction time = transmit_time - satClkCorr # Find time difference dt = check_t_vectorized(time - eph[20]) # Calculate clock correction return (eph[1] * dt + eph[19]) * dt + eph[18] # - eph.T_GD def get_visible_sats(ht, p, eph, elev_mask=0, prn_list=range(1, 33)): """Estimate set of visible satellites. Ephemeris provided as array. Inputs: ht - Receiver time hypothesis [s] p - Receiver position hypothesis (latitude, longitude, elevation) eph - Ephemeris as matrix elev_mask - [Optional] Elevation mask: minimum elevation for satellite to be considered to be visible [degrees], default 0 prn_list - [Optional] PRNs of satellites to search for, default 1-32 Output: visSat - Indices of visible satellites Author: <NAME> """ ht = np.mod(ht, 7 * 24 * 60 * 60) # Crude transmit time estimate [s] t = ht - 76.5e-3 # Empty array for result visSat = np.array([], dtype=int) # Loop over all satellite indices for prn in prn_list: col = find_eph(eph, prn, t) if not np.isnan(col): ephSat = eph[:, col] # Get satellite position at estimated transmit time satPos = get_sat_pos(t, ephSat) if not np.isnan(satPos).any(): az, elev, slantRange = pm.ecef2aer( satPos[0], satPos[1], satPos[2], p[0], p[1], p[2] ) # Satellites with elevation larger than threshold if elev > elev_mask: # Add satellite index to result visSat = np.append(visSat, prn) return visSat def get_doppler(ht, R, k, eph): """Calculate expected Doppler [Hz] for given time and position hypothesis. Inputs: ht - Time hypothesis (receiver) [s] R - Receiver position (ECEF) [m,m,m] k - Satellite index (PRN) eph - Ephemeris Output: D - Doppler shift frequency [Hz] Author: <NAME> """ # Speed of light [m/s] c = 299792458 # Crude transmit time estimate [s] t = ht - 76.5e-3 # GPS time with respect to 1980 to time of week (TOW) tow = np.mod(t, 7 * 24 * 60 * 60) # Find column of ephemeris matrix that matches satellite index and time col = find_eph(eph, k, tow) if np.isnan(col): return np.NaN else: # Extract column eph = eph[:, col] for it in range(2): # 2 iterations to refine transmit time estimate p = get_sat_pos(t, eph) # Satellite position estimate [m,m,m] d = np.linalg.norm(R - p) / c # Propagation delay estimate [s] t = ht - d # Transmit time estimate [s] L1 = 1575.42e6 # GPS signal frequency [Hz] P, V = get_sat_pos_vel(t, eph) # Satellite velocity [m/s,m/s,m/s] lambd = c / L1 # Wave length of transmitted signal # Doppler shift (cf. 'Cycle slip detection in single frequency GPS carrier # phase observations using expected Doppler shift') return (np.dot((R - P) / np.linalg.norm(R - P), V) / lambd) def generate_ca_code(PRN): """Generate one of the GPS, EGNOS, or WAAS satellite C/A codes. Input: PRN - PRN number of the sequence Output: CAcode - Array containing the desired C/A code sequence (chips) Author: <NAME> """ # Make the code shift array; the shift depends on the PRN number # The g2s vector holds the appropriate shift of the g2 code to generate # the C/A code (ex. for SV#19 - use a G2 shift of g2s(19) = 471) g2s = [ 5, 6, 7, 8, 17, 18, 139, 140, 141, 251, 252, 254, 255, 256, 257, 258, 469, 470, 471, 472, 473, 474, 509, 512, 513, 514, 515, 516, 859, 860, 861, 862, # End of shifts for GPS satellites 145, 175, 52, 21, 237, 235, 886, 657, 634, 762, 355, 1012, 176, 603, 130, 359, 595, 68, 386 # End of shifts for EGNOS and WAAS satellites ] # For EGNOS and WAAS, subtract 87 from the PRN # Adjust EGNOS and WAAS PRNs if PRN >= 120: PRN = PRN - 87 if PRN > len(g2s): raise Exception( "Provided PRN out of range. Only 1-32 and 120-139 supported.") # Pick right shift for the given PRN number g2shift = g2s[PRN - 1] # Generate G1 code # Initialize g1 output to speed up the function g1 = np.zeros(1023) # Load shift register reg = -1 * np.ones(10) # Generate all G1 signal chips based on the G1 feedback polynomial ----- for i in range(1023): g1[i] = reg[9] saveBit = reg[2] * reg[9] reg[1:10] = reg[0:9] reg[0] = saveBit # Generate G2 code # Initialize g2 output to speed up the function g2 = np.zeros(1023) # Load shift register reg = -1 * np.ones(10) # Generate all G2 signal chips based on the G2 feedback polynomial for i in range(1023): g2[i] = reg[9] saveBit = reg[1] * reg[2] * reg[5] * reg[7] * reg[8] * reg[9] reg[1:10] = reg[0:9] reg[0] = saveBit # Shift G2 code # The idea: g2 = concatenate[ g2_right_part, g2_left_part ] g2 = np.concatenate((g2[1023 - g2shift: 1023], g2[0: 1023 - g2shift])) # Form single sample C/A code by multiplying G1 and G2 return -(g1 * g2) def generate_e1_code(prn, fs, pilot=False): """Generate and sample Galileo signal that is transmitted in E1 band. Inputs: prn - Index of satellite (1-50) fs - Sampling rate [Hz] pilot - Flag if data component E1B (pilot=False) or primary pilot component E1C (pilot=True) is returned, default=False. Output: replica - Binary sampled E1 Open Service data signal Author: <NAME> """ # chip_rate = 1023000 # Number of samples per code sequence n = fs * 4e-3 # Number of chips per code sequence code_length = 4092.0 # Distance in chips between two samples (increment) incr = code_length / n if not pilot: # Obtain E1B (data) code c = e1b(prn) else: # Obtain primary E1C (pilot) code c = e1c(prn) # Find indices of samples in E1-B / E1-C code idx = incr * np.arange(int(n)) idx = np.floor(idx) idx = np.mod(idx, code_length).astype('int') # Sample E1-B code x = c[idx] e1_code = - 1.0 + 2.0 * x # Obtain sampled BOC(1,1) boc = boc11(incr, int(n)) # Multiply both signals return e1_code * boc def boc11(incr, n): """Generate and sample binary offset carrier (BOC) of Galileo satellite. Inputs: incr - Increment; difference in chips between two consecutive samples n - Number of samples per code sequence Output: boc - Sampled binary offset carrier Adapted by <NAME> from https://github.com/pmonta/GNSS-DSP-tools/blob/master/gnsstools/nco.py written by <NAME>. """ c = np.array([-1, 1]) boc11_length = 2 idx = incr * np.arange(n) idx = idx * 2 idx = np.floor(idx).astype('int') idx = np.mod(idx, boc11_length) return c[idx] e1b_codes = {} def e1b(prn): """Generate unsampled E1B code of Galileo satellite. Input: prn - Index of satellite Output: y - E1B code Adapted by <NAME> from https://github.com/pmonta/GNSS-DSP-tools/blob/master/gnsstools/galileo/e1b.py written by <NAME>. """ import e1_strings as es if prn not in e1b_codes: s = es.e1b_strings[prn] n = 4092 y = np.zeros(n) for i in range(n): nib = i // 4 bit = 3 - (i % 4) y[i] = (int(s[nib], 16) >> bit) & 1 e1b_codes[prn] = y return e1b_codes[prn] e1c_codes = {} def e1c(prn): """Generate unsampled E1C code of Galileo satellite. Neglect secondary code. Input: prn - Index of satellite Output: y - E1C code Adapted by <NAME> from https://github.com/pmonta/GNSS-DSP-tools/blob/master/gnsstools/galileo/e1c.py written by <NAME>. """ # secondary_code = np.array([0,0,1,1,1,0,0,0,0,0,0,0,1,0,1,0,1,1,0,1,1,0,0,1,0]) # secondary_code = 1.0 - 2.0*secondary_code import e1_strings as es if prn not in e1c_codes: s = es.e1c_strings[prn] n = 4092 y = np.zeros(n) for i in range(n): nib = i // 4 bit = 3 - (i % 4) y[i] = (int(s[nib], 16) >> bit) & 1 e1c_codes[prn] = y return e1c_codes[prn] def generate_b1c_code(prn, fs, pilot=False): """Generate and sample BeiDou signal that is transmitted in B1C band. Inputs: prn - Index of satellite (1-63) fs - Sampling rate [Hz] pilot - Flag if data component (pilot=False) or primary pilot component (pilot=True) is returned, default=False. Output: s_b1c - B1C signal, length of 10230 chips at 1.023 MHz chip rate Author: <NAME> """ # Number of samples per code sequence n = fs * 10.0e-3 # Number of chips per code sequence code_length = 10230.0 # Distance in chips between two samples (increment) incr = code_length / n if not pilot: # Obtain B1C_data code c = b1c_data(prn) else: # Obtain primary B1C_pilot code c = b1c_pilot(prn) # Find indices of samples in B1C_data code idx = incr * np.arange(int(n)) idx = np.floor(idx) idx = np.mod(idx, code_length).astype('int') # Sample B1C_data code x = c[idx] b1c_code = - 1.0 + 2.0 * x # Obtain sampled BOC boc = boc11(incr, int(n)) # Multiply both signals return b1c_code * boc b1cd_codes = {} def b1c_data(prn): """Generate unsampled BeiDou B1C_data signal. Input: prn - Index of satellite (1-63) Output: y - B1C_data, length of 10230 chips at 1.023 MHz chip rate Adapted by <NAME> from https://github.com/pmonta/GNSS-DSP-tools/blob/master/gnsstools/beidou/b1cd.py written by <NAME>. """ from sympy.ntheory import legendre_symbol if prn not in b1cd_codes: # chip_rate = 1023000 code_length = 10230 b1cd_params = { 1: (2678,699), 2: (4802,694), 3: (958,7318), 4: (859,2127), 5: (3843,715), 6: (2232,6682), 7: (124,7850), 8: (4352,5495), 9: (1816,1162), 10: (1126,7682), 11: (1860,6792), 12: (4800,9973), 13: (2267,6596), 14: (424,2092), 15: (4192,19), 16: (4333,10151), 17: (2656,6297), 18: (4148,5766), 19: (243,2359), 20: (1330,7136), 21: (1593,1706), 22: (1470,2128), 23: (882,6827), 24: (3202,693), 25: (5095,9729), 26: (2546,1620), 27: (1733,6805), 28: (4795,534), 29: (4577,712), 30: (1627,1929), 31: (3638,5355), 32: (2553,6139), 33: (3646,6339), 34: (1087,1470), 35: (1843,6867), 36: (216,7851), 37: (2245,1162), 38: (726,7659), 39: (1966,1156), 40: (670,2672), 41: (4130,6043), 42: (53,2862), 43: (4830,180), 44: (182,2663), 45: (2181,6940), 46: (2006,1645), 47: (1080,1582), 48: (2288,951), 49: (2027,6878), 50: (271,7701), 51: (915,1823), 52: (497,2391), 53: (139,2606), 54: (3693,822), 55: (2054,6403), 56: (4342,239), 57: (3342,442), 58: (2592,6769), 59: (1007,2560), 60: (310,2502), 61: (4203,5072), 62: (455,7268), 63: (4318,341), } N = 10243 L = np.array([legendre_symbol(i, N) for i in range(N)]) L[L == -1] = 0 L[0] = 0 w, p = b1cd_params[prn] W = np.array([L[k] ^ L[(k+w) % N] for k in range(N)]) c = np.array([W[(n+p-1) % N] for n in range(code_length)]) b1cd_codes[prn] = c return b1cd_codes[prn] b1cp_codes = {} b1cp_secondary_codes = {} def b1c_pilot(prn, secondary=False): """Generate unsampled BeiDou B1C_pilot signal. Input: prn - Index of satellite (1-63) secondary - Flag if primary code (secondary=False) or secondary code (secondary=True) is returned, default=False Output: y - Primary or secondary B1C_pilot, length of 10230 chips at 1.023 MHz chip rate and length of 1800 at xxx chip rate, respectively. Adapted by <NAME> from https://github.com/pmonta/GNSS-DSP-tools/blob/master/gnsstools/beidou/b1cp.py written by <NAME>. """ from sympy.ntheory import legendre_symbol if not secondary: if prn not in b1cp_codes: # chip_rate = 1023000 code_length = 10230 b1cp_params = { 1: (796,7575), 2: (156,2369), 3: (4198,5688), 4: (3941,539), 5: (1374,2270), 6: (1338,7306), 7: (1833,6457), 8: (2521,6254), 9: (3175,5644), 10: (168,7119), 11: (2715,1402), 12: (4408,5557), 13: (3160,5764), 14: (2796,1073), 15: (459,7001), 16: (3594,5910), 17: (4813,10060), 18: (586,2710), 19: (1428,1546), 20: (2371,6887), 21: (2285,1883), 22: (3377,5613), 23: (4965,5062), 24: (3779,1038), 25: (4547,10170), 26: (1646,6484), 27: (1430,1718), 28: (607,2535), 29: (2118,1158), 30: (4709,526), 31: (1149,7331), 32: (3283,5844), 33: (2473,6423), 34: (1006,6968), 35: (3670,1280), 36: (1817,1838), 37: (771,1989), 38: (2173,6468), 39: (740,2091), 40: (1433,1581), 41: (2458,1453), 42: (3459,6252), 43: (2155,7122), 44: (1205,7711), 45: (413,7216), 46: (874,2113), 47: (2463,1095), 48: (1106,1628), 49: (1590,1713), 50: (3873,6102), 51: (4026,6123), 52: (4272,6070), 53: (3556,1115), 54: (128,8047), 55: (1200,6795), 56: (130,2575), 57: (4494,53), 58: (1871,1729), 59: (3073,6388), 60: (4386,682), 61: (4098,5565), 62: (1923,7160), 63: (1176,2277), } N = 10243 L = np.array([legendre_symbol(i, N) for i in range(N)]) L[L == -1] = 0 L[0] = 0 w, p = b1cp_params[prn] W = np.array([L[k] ^ L[(k+w) % N] for k in range(N)]) c = np.array([W[(n+p-1) % N] for n in range(code_length)]) b1cp_codes[prn] = c return b1cp_codes[prn] else: if prn not in b1cp_secondary_codes: b1cp_secondary_params = { 1: (269,1889), 2: (1448,1268), 3: (1028,1593), 4: (1324,1186), 5: (822,1239), 6: (5,1930), 7: (155,176), 8: (458,1696), 9: (310,26), 10: (959,1344), 11: (1238,1271), 12: (1180,1182), 13: (1288,1381), 14: (334,1604), 15: (885,1333), 16: (1362,1185), 17: (181,31), 18: (1648,704), 19: (838,1190), 20: (313,1646), 21: (750,1385), 22: (225,113), 23: (1477,860), 24: (309,1656), 25: (108,1921), 26: (1457,1173), 27: (149,1928), 28: (322,57), 29: (271,150), 30: (576,1214), 31: (1103,1148), 32: (450,1458), 33: (399,1519), 34: (241,1635), 35: (1045,1257), 36: (164,1687), 37: (513,1382), 38: (687,1514), 39: (422,1), 40: (303,1583), 41: (324,1806), 42: (495,1664), 43: (725,1338), 44: (780,1111), 45: (367,1706), 46: (882,1543), 47: (631,1813), 48: (37,228), 49: (647,2871), 50: (1043,2884), 51: (24,1823), 52: (120,75), 53: (134,11), 54: (136,63), 55: (158,1937), 56: (214,22), 57: (335,1768), 58: (340,1526), 59: (661,1402), 60: (889,1445), 61: (929,1680), 62: (1002,1290), 63: (1149,1245), } sec_N = 3607 sec_L = np.array([legendre_symbol(i, sec_N) for i in range(sec_N)]) sec_L[sec_L == -1] = 0 sec_L[0] = 0 sec_code_length = 1800 w, p = b1cp_secondary_params[prn] W = np.array([sec_L[k] ^ sec_L[(k+w) % sec_N] for k in range(sec_N)]) c = np.array([W[(n+p-1) % sec_N] for n in range(sec_code_length)]) b1cp_secondary_codes[prn] = c return b1cp_secondary_codes[prn] def generate_l1c_code(prn, fs, pilot=False): """Generate and sample GPS signal that is transmitted in L1C band. Inputs: prn - Index of satellite (1-210) fs - Sampling rate [Hz] pilot - Flag if data component (pilot=False) or primary pilot component (pilot=True) is returned, default=False. Output: s_l1c - L1C signal, length of 10230 chips at 1.023 MHz chip rate Author: <NAME> """ # Number of samples per code sequence n = fs * 10.0e-3 # Number of chips per code sequence code_length = 10230.0 # Distance in chips between two samples (increment) incr = code_length / n if not pilot: # Obtain L1C_data code c = l1c_data(prn) else: # Obtain L1C_pilot code c = l1c_pilot(prn) # Find indices of samples in L1C_data code idx = incr * np.arange(int(n)) idx = np.floor(idx) idx = np.mod(idx, code_length).astype('int') # Sample L1C_data code x = c[idx] l1c_code = - 1.0 + 2.0 * x # Obtain sampled BOC boc = boc11(incr, int(n)) # Multiply both signals return l1c_code * boc l1cd_codes = {} def l1c_data(prn): """Generate unsampled GPS L1C_data signal. Input: prn - Index of satellite (1-210) Output: y - L1C_data, length of 10230 chips at 1.023 MHz chip rate Adapted by <NAME> from https://github.com/pmonta/GNSS-DSP-tools/blob/master/gnsstools/gps/l1cd.py written by <NAME>. """ from sympy.ntheory import legendre_symbol if prn not in l1cd_codes: # chip_rate = 1023000 # code_length = 10230 l1cd_params = { 1: (5097,181), 2: (5110,359), 3: (5079,72), 4: (4403,1110), 5: (4121,1480), 6: (5043,5034), 7: (5042,4622), 8: (5104,1), 9: (4940,4547), 10: (5035,826), 11: (4372,6284), 12: (5064,4195), 13: (5084,368), 14: (5048,1), 15: (4950,4796), 16: (5019,523), 17: (5076,151), 18: (3736,713), 19: (4993,9850), 20: (5060,5734), 21: (5061,34), 22: (5096,6142), 23: (4983,190), 24: (4783,644), 25: (4991,467), 26: (4815,5384), 27: (4443,801), 28: (4769,594), 29: (4879,4450), 30: (4894,9437), 31: (4985,4307), 32: (5056,5906), 33: (4921,378), 34: (5036,9448), 35: (4812,9432), 36: (4838,5849), 37: (4855,5547), 38: (4904,9546), 39: (4753,9132), 40: (4483,403), 41: (4942,3766), 42: (4813,3), 43: (4957,684), 44: (4618,9711), 45: (4669,333), 46: (4969,6124), 47: (5031,10216), 48: (5038,4251), 49: (4740,9893), 50: (4073,9884), 51: (4843,4627), 52: (4979,4449), 53: (4867,9798), 54: (4964,985), 55: (5025,4272), 56: (4579,126), 57: (4390,10024), 58: (4763,434), 59: (4612,1029), 60: (4784,561), 61: (3716,289), 62: (4703,638), 63: (4851,4353), 64: (4955,9899), 65: (5018,4629), 66: (4642,669), 67: (4840,4378), 68: (4961,4528), 69: (4263,9718), 70: (5011,5485), 71: (4922,6222), 72: (4317,672), 73: (3636,1275), 74: (4884,6083), 75: (5041,5264), 76: (4912,10167), 77: (4504,1085), 78: (4617,194), 79: (4633,5012), 80: (4566,4938), 81: (4702,9356), 82: (4758,5057), 83: (4860,866), 84: (3962,2), 85: (4882,204), 86: (4467,9808), 87: (4730,4365), 88: (4910,162), 89: (4684,367), 90: (4908,201), 91: (4759,18), 92: (4880,251), 93: (4095,10167), 94: (4971,21), 95: (4873,685), 96: (4561,92), 97: (4588,1057), 98: (4773,3), 99: (4997,5756), 100: (4583,14), 101: (4900,9979), 102: (4574,9569), 103: (4629,515), 104: (4676,753), 105: (4181,1181), 106: (5057,9442), 107: (4944,669), 108: (4401,4834), 109: (4586,541), 110: (4699,9933), 111: (3676,6683), 112: (4387,4828), 113: (4866,9710), 114: (4926,10170), 115: (4657,9629), 116: (4477,260), 117: (4359,86), 118: (4673,5544), 119: (4258,923), 120: (4447,257), 121: (4570,507), 122: (4486,4572), 123: (4362,4491), 124: (4481,341), 125: (4322,130), 126: (4668,79), 127: (3967,1142), 128: (4374,448), 129: (4553,875), 130: (4641,555), 131: (4215,1272), 132: (3853,5198), 133: (4787,9529), 134: (4266,4459), 135: (4199,10019), 136: (4545,9353), 137: (4208,9780), 138: (4485,375), 139: (3714,503), 140: (4407,4507), 141: (4182,875), 142: (4203,1246), 143: (3788,1), 144: (4471,4534), 145: (4691,8), 146: (4281,9549), 147: (4410,6240), 148: (3953,22), 149: (3465,5652), 150: (4801,10069), 151: (4278,4796), 152: (4546,4980), 153: (3779,27), 154: (4115,90), 155: (4193,9788), 156: (3372,715), 157: (3786,9720), 158: (3491,301), 159: (3812,5450), 160: (3594,5215), 161: (4028,13), 162: (3652,1147), 163: (4224,4855), 164: (4334,1190), 165: (3245,1267), 166: (3921,1302), 167: (3840,1), 168: (3514,5007), 169: (2922,549), 170: (4227,368), 171: (3376,6300), 172: (3560,5658), 173: (4989,4302), 174: (4756,851), 175: (4624,4353), 176: (4446,9618), 177: (4174,9652), 178: (4551,1232), 179: (3972,109), 180: (4399,10174), 181: (4562,6178), 182: (3133,1851), 183: (4157,1299), 184: (5053,325), 185: (4536,10206),186: (5067,9968), 187: (3905,10191), 188: (3721,5438), 189: (3787,10080),190: (4674,219), 191: (3436,758), 192: (2673,2140), 193: (4834,9753), 194: (4456,4799), 195: (4056,10126), 196: (3804,241), 197: (3672,1245), 198: (4205,1274), 199: (3348,1456), 200: (4152,9967), 201: (3883,235), 202: (3473,512), 203: (3669,1078), 204: (3455,1078), 205: (2318,953), 206: (2945,5647), 207: (2947,669), 208: (3220,1311), 209: (4052,5827), 210: (2953,15), } N = 10243 L = np.array([legendre_symbol(i, N) for i in range(N)]) L[L == -1] = 0 L[0] = 0 w, p = l1cd_params[prn] W = np.array([L[k] ^ L[(k+w) % N] for k in range(N)]) expansion = np.array([0, 1, 1, 0, 1, 0, 0]) c = np.concatenate((W[0:p-1], expansion, W[p-1:N])) l1cd_codes[prn] = c return l1cd_codes[prn] l1cp_codes = {} l1cp_secondary_codes = {} def l1c_pilot(prn, secondary=False): """Generate unsampled GPS L1C_pilot signal. Input: prn - Index of satellite (1-210) secondary - Flag if primary code (secondary=False) or secondary code (secondary=True) is returned, default=False Output: y - Primary or secondary B1C_pilot, length of 10230 chips at 1.023 MHz chip rate and length of 1800 at xxx chip rate, respectively. Adapted by <NAME> from https://github.com/pmonta/GNSS-DSP-tools/blob/master/gnsstools/gps/l1cp.py written by <NAME>. """ from sympy.ntheory import legendre_symbol if not secondary: if prn not in l1cp_codes: # chip_rate = 1023000 # code_length = 10230 l1cp_params = { 1: (5111,412), 2: (5109,161), 3: (5108,1), 4: (5106,303), 5: (5103,207), 6: (5101,4971), 7: (5100,4496), 8: (5098,5), 9: (5095,4557), 10: (5094,485), 11: (5093,253), 12: (5091,4676), 13: (5090,1), 14: (5081,66), 15: (5080,4485), 16: (5069,282), 17: (5068,193), 18: (5054,5211), 19: (5044,729), 20: (5027,4848), 21: (5026,982), 22: (5014,5955), 23: (5004,9805), 24: (4980,670), 25: (4915,464), 26: (4909,29), 27: (4893,429), 28: (4885,394), 29: (4832,616), 30: (4824,9457), 31: (4591,4429), 32: (3706,4771), 33: (5092,365), 34: (4986,9705), 35: (4965,9489), 36: (4920,4193), 37: (4917,9947), 38: (4858,824), 39: (4847,864), 40: (4790,347), 41: (4770,677), 42: (4318,6544), 43: (4126,6312), 44: (3961,9804), 45: (3790,278), 46: (4911,9461), 47: (4881,444), 48: (4827,4839), 49: (4795,4144), 50: (4789,9875), 51: (4725,197), 52: (4675,1156), 53: (4539,4674), 54: (4535,10035), 55: (4458,4504), 56: (4197,5), 57: (4096,9937), 58: (3484,430), 59: (3481,5), 60: (3393,355), 61: (3175,909), 62: (2360,1622), 63: (1852,6284), 64: (5065,9429), 65: (5063,77), 66: (5055,932), 67: (5012,5973), 68: (4981,377), 69: (4952,10000), 70: (4934,951), 71: (4932,6212), 72: (4786,686), 73: (4762,9352), 74: (4640,5999), 75: (4601,9912), 76: (4563,9620), 77: (4388,635), 78: (3820,4951), 79: (3687,5453), 80: (5052,4658), 81: (5051,4800), 82: (5047,59), 83: (5039,318), 84: (5015,571), 85: (5005,565), 86: (4984,9947), 87: (4975,4654), 88: (4974,148), 89: (4972,3929), 90: (4962,293), 91: (4913,178), 92: (4907,10142), 93: (4903,9683), 94: (4833,137), 95: (4778,565), 96: (4721,35), 97: (4661,5949), 98: (4660,2), 99: (4655,5982), 100: (4623,825), 101: (4590,9614), 102: (4548,9790), 103: (4461,5613), 104: (4442,764), 105: (4347,660), 106: (4259,4870), 107: (4256,4950), 108: (4166,4881), 109: (4155,1151), 110: (4109,9977), 111: (4100,5122), 112: (4023,10074),113: (3998,4832), 114: (3979,77), 115: (3903,4698), 116: (3568,1002), 117: (5088,5549), 118: (5050,9606), 119: (5020,9228), 120: (4990,604), 121: (4982,4678), 122: (4966,4854), 123: (4949,4122), 124: (4947,9471), 125: (4937,5026), 126: (4935,272), 127: (4906,1027), 128: (4901,317), 129: (4872,691), 130: (4865,509), 131: (4863,9708), 132: (4818,5033), 133: (4785,9938), 134: (4781,4314), 135: (4776,10140), 136: (4775,4790), 137: (4754,9823), 138: (4696,6093), 139: (4690,469), 140: (4658,1215), 141: (4607,799), 142: (4599,756), 143: (4596,9994), 144: (4530,4843), 145: (4524,5271), 146: (4451,9661), 147: (4441,6255), 148: (4396,5203), 149: (4340,203), 150: (4335,10070),151: (4296,30), 152: (4267,103), 153: (4168,5692), 154: (4149,32), 155: (4097,9826), 156: (4061,76), 157: (3989,59), 158: (3966,6831), 159: (3789,958), 160: (3775,1471), 161: (3622,10070), 162: (3523,553), 163: (3515,5487), 164: (3492,55), 165: (3345,208), 166: (3235,645), 167: (3169,5268), 168: (3157,1873), 169: (3082,427), 170: (3072,367), 171: (3032,1404), 172: (3030,5652), 173: (4582,5), 174: (4595,368), 175: (4068,451), 176: (4871,9595), 177: (4514,1030), 178: (4439,1324), 179: (4122,692), 180: (4948,9819), 181: (4774,4520), 182: (3923,9911), 183: (3411,278), 184: (4745,642), 185: (4195,6330), 186: (4897,5508), 187: (3047,1872), 188: (4185,5445), 189: (4354,10131), 190: (5077,422), 191: (4042,4918), 192: (2111,787), 193: (4311,9864), 194: (5024,9753), 195: (4352,9859), 196: (4678,328), 197: (5034,1), 198: (5085,4733), 199: (3646,164), 200: (4868,135), 201: (3668,174), 202: (4211,132), 203: (2883,538), 204: (2850,176), 205: (2815,198), 206: (2542,595), 207: (2492,574), 208: (2376,321), 209: (2036,596), 210: (1920,491), } N = 10223 L = np.array([legendre_symbol(i, N) for i in range(N)]) L[L == -1] = 0 L[0] = 0 w, p = l1cp_params[prn] W = np.array([L[k] ^ L[(k+w) % N] for k in range(N)]) expansion = np.array([0, 1, 1, 0, 1, 0, 0]) c = np.concatenate((W[0:p-1], expansion, W[p-1:N])) l1cp_codes[prn] = c return l1cp_codes[prn] else: if prn not in l1cp_secondary_codes: l1cp_secondary_params = { 1: (0o5111,0o3266), 2: (0o5421,0o2040), 3: (0o5501,0o1527), 4: (0o5403,0o3307), 5: (0o6417,0o3756), 6: (0o6141,0o3026), 7: (0o6351,0o0562), 8: (0o6501,0o0420), 9: (0o6205,0o3415), 10: (0o6235,0o0337), 11: (0o7751,0o0265), 12: (0o6623,0o1230), 13: (0o6733,0o2204), 14: (0o7627,0o1440), 15: (0o5667,0o2412), 16: (0o5051,0o3516), 17: (0o7665,0o2761), 18: (0o6325,0o3750), 19: (0o4365,0o2701), 20: (0o4745,0o1206), 21: (0o7633,0o1544), 22: (0o6747,0o1774), 23: (0o4475,0o0546), 24: (0o4225,0o2213), 25: (0o7063,0o3707), 26: (0o4423,0o2051), 27: (0o6651,0o3650), 28: (0o4161,0o1777), 29: (0o7237,0o3203), 30: (0o4473,0o1762), 31: (0o5477,0o2100), 32: (0o6163,0o0571), 33: (0o7223,0o3710), 34: (0o6323,0o3535), 35: (0o7125,0o3110), 36: (0o7035,0o1426), 37: (0o4341,0o0255), 38: (0o4353,0o0321), 39: (0o4107,0o3124), 40: (0o5735,0o0572), 41: (0o6741,0o1736), 42: (0o7071,0o3306), 43: (0o4563,0o1307), 44: (0o5755,0o3763), 45: (0o6127,0o1604), 46: (0o4671,0o1021), 47: (0o4511,0o2624), 48: (0o4533,0o0406), 49: (0o5357,0o0114), 50: (0o5607,0o0077), 51: (0o6673,0o3477), 52: (0o6153,0o1000), 53: (0o7565,0o3460), 54: (0o7107,0o2607), 55: (0o6211,0o2057), 56: (0o4321,0o3467), 57: (0o7201,0o0706), 58: (0o4451,0o2032), 59: (0o5411,0o1464), 60: (0o5141,0o0520), 61: (0o7041,0o1766), 62: (0o6637,0o3270), 63: (0o4577,0o0341), 64: (0o5111,0o1740,0o3035), 65: (0o5111,0o3664,0o1557), 66: (0o5111,0o1427,0o0237), 67: (0o5111,0o2627,0o2527), 68: (0o5111,0o0701,0o3307), 69: (0o5111,0o3460,0o1402), 70: (0o5111,0o1373,0o1225), 71: (0o5111,0o2540,0o0607), 72: (0o5111,0o2004,0o0351), 73: (0o5111,0o2274,0o3724), 74: (0o5111,0o1340,0o1675), 75: (0o5111,0o0602,0o2625), 76: (0o5111,0o2502,0o1030), 77: (0o5111,0o0327,0o1443), 78: (0o5111,0o2600,0o3277), 79: (0o5111,0o0464,0o1132), 80: (0o5111,0o3674,0o0572), 81: (0o5111,0o3040,0o1241), 82: (0o5111,0o1153,0o0535), 83: (0o5111,0o0747,0o1366), 84: (0o5111,0o1770,0o0041), 85: (0o5111,0o3772,0o0561), 86: (0o5111,0o1731,0o0122), 87: (0o5111,0o1672,0o1205), 88: (0o5111,0o1333,0o3753), 89: (0o5111,0o2705,0o2543), 90: (0o5111,0o2713,0o3031), 91: (0o5111,0o3562,0o2260), 92: (0o5111,0o3245,0o3773), 93: (0o5111,0o3770,0o3156), 94: (0o5111,0o3202,0o2215), 95: (0o5111,0o3521,0o0146), 96: (0o5111,0o3250,0o2413), 97: (0o5111,0o2117,0o2564), 98: (0o5111,0o0530,0o3310), 99: (0o5111,0o3021,0o2267), 100: (0o5421,0o2511,0o3120), 101: (0o5421,0o1562,0o0064), 102: (0o5421,0o1067,0o1042), 103: (0o5421,0o0424,0o0476), 104: (0o5421,0o3402,0o1020), 105: (0o5421,0o1326,0o0431), 106: (0o5421,0o2142,0o0216), 107: (0o5421,0o0733,0o2736), 108: (0o5421,0o0504,0o2527), 109: (0o5421,0o1611,0o2431), 110: (0o5421,0o2724,0o1013), 111: (0o5421,0o0753,0o0524), 112: (0o5421,0o3724,0o0726), 113: (0o5421,0o2652,0o1042), 114: (0o5421,0o1743,0o3362), 115: (0o5421,0o0013,0o1364), 116: (0o5421,0o3464,0o3354), 117: (0o5421,0o2300,0o0623), 118: (0o5421,0o1334,0o0145), 119: (0o5421,0o2175,0o0214), 120: (0o5421,0o2564,0o0223), 121: (0o5421,0o3075,0o0151), 122: (0o5421,0o3455,0o2405), 123: (0o5421,0o3627,0o2522), 124: (0o5421,0o0617,0o3235), 125: (0o5421,0o1324,0o0452), 126: (0o5421,0o3506,0o2617), 127: (0o5421,0o2231,0o1300), 128: (0o5421,0o1110,0o1430), 129: (0o5421,0o1271,0o0773), 130: (0o5421,0o3740,0o0772), 131: (0o5421,0o3652,0o3561), 132: (0o5421,0o1644,0o0607), 133: (0o5421,0o3635,0o0420), 134: (0o5421,0o3436,0o0527), 135: (0o5421,0o3076,0o3770), 136: (0o5421,0o0434,0o2536), 137: (0o5421,0o3340,0o2233), 138: (0o5421,0o0054,0o3366), 139: (0o5403,0o2446,0o3766), 140: (0o5403,0o0025,0o3554), 141: (0o5403,0o0150,0o2060), 142: (0o5403,0o2746,0o2070), 143: (0o5403,0o2723,0o0713), 144: (0o5403,0o2601,0o3366), 145: (0o5403,0o3440,0o3247), 146: (0o5403,0o1312,0o2776), 147: (0o5403,0o0544,0o1244), 148: (0o5403,0o2062,0o2102), 149: (0o5403,0o0176,0o1712), 150: (0o5403,0o3616,0o1245), 151: (0o5403,0o1740,0o3344), 152: (0o5403,0o3777,0o1277), 153: (0o5403,0o0432,0o0165), 154: (0o5403,0o2466,0o2131), 155: (0o5403,0o1667,0o3623), 156: (0o5403,0o3601,0o0141), 157: (0o5403,0o2706,0o0421), 158: (0o5403,0o2022,0o3032), 159: (0o5403,0o1363,0o2065), 160: (0o5403,0o2331,0o3024), 161: (0o5403,0o3556,0o2663), 162: (0o5403,0o2205,0o2274), 163: (0o5403,0o3734,0o2114), 164: (0o5403,0o2115,0o1664), 165: (0o5403,0o0010,0o0413), 166: (0o5403,0o2140,0o1512), 167: (0o5403,0o3136,0o0135), 168: (0o5403,0o0272,0o2737), 169: (0o5403,0o3264,0o1015), 170: (0o5403,0o2017,0o1075), 171: (0o5403,0o2505,0o1255), 172: (0o5403,0o3532,0o3473), 173: (0o5403,0o0647,0o2716), 174: (0o5403,0o1542,0o0101), 175: (0o5403,0o2154,0o1105), 176: (0o5403,0o3734,0o1407), 177: (0o5403,0o2621,0o3407), 178: (0o5403,0o2711,0o1046), 179: (0o5403,0o0217,0o3237), 180: (0o5403,0o3503,0o0154), 181: (0o5403,0o3457,0o3010), 182: (0o5403,0o3750,0o2245), 183: (0o5403,0o2525,0o2051), 184: (0o5403,0o0113,0o2144), 185: (0o5403,0o0265,0o1743), 186: (0o5403,0o1711,0o2511), 187: (0o5403,0o0552,0o3410), 188: (0o5403,0o0675,0o1414), 189: (0o5403,0o1706,0o1275), 190: (0o5403,0o3513,0o2257), 191: (0o5403,0o1135,0o2331), 192: (0o5403,0o0566,0o0276), 193: (0o5403,0o0500,0o3261), 194: (0o5403,0o0254,0o1760), 195: (0o5403,0o3445,0o0430), 196: (0o5403,0o2542,0o3477), 197: (0o5403,0o1257,0o1676), 198: (0o6501,0o0211,0o1636), 199: (0o6501,0o0534,0o2411), 200: (0o6501,0o1420,0o1473), 201: (0o6501,0o3401,0o2266), 202: (0o6501,0o0714,0o2104), 203: (0o6501,0o0613,0o2070), 204: (0o6501,0o2475,0o1766), 205: (0o6501,0o2572,0o0711), 206: (0o6501,0o3265,0o2533), 207: (0o6501,0o1250,0o0353), 208: (0o6501,0o1711,0o1744), 209: (0o6501,0o2704,0o0053), 210: (0o6501,0o0135,0o2222), } sec_code_length = 1800 def int2list(x, n): y = [] for i in range(n): y.append((x >> i) & 1) return y def xorprod(a, b): t = 0 for x, y in zip(a, b): t = t ^ (x*y) return t def s_shift(x, p): return [xorprod(x, p)] + x[0:-1] p, init = l1cp_secondary_params[prn] p = int2list(p//2, 11) x = int2list(init, 11) c = np.zeros(sec_code_length) for i in range(sec_code_length): c[i] = x[10] x = s_shift(x, p) l1cp_secondary_codes[prn] = c return l1cp_secondary_codes[prn] glonass_l1_code = {} def generate_ca_code_glonass(): """Generate GLONASS signal that is transmitted in L1 band. Inputs: prn - Index of satellite (1-210) fs - Sampling rate [Hz] pilot - Flag if data component (pilot=False) or primary pilot component (pilot=True) is returned, default=False. Output: glonass_l1_code - L1 C/A code, length of 511 chips at 0.511 MHz chip rate Adapted by <NAME> from https://github.com/pmonta/GNSS-DSP-tools/blob/master/gnsstools/glonass/ca.py written by <NAME>. """ global glonass_l1_code # Check if C/A code must be generated if len(glonass_l1_code) == 0: # chip_rate = 511000 code_length = 511 x = [1, 1, 1, 1, 1, 1, 1, 1, 1] glonass_l1_code = np.zeros(code_length) for i in range(code_length): glonass_l1_code[i] = x[6] x = [x[8] ^ x[4]] + x[0:8] return glonass_l1_code def rinexe(ephemerisfile, system=None): """Read a RINEX Navigation Message file and reformat the data. Reformat the data into a 2D NumPy array with 21 rows and a column for each satellite. Units are either seconds, meters, or radians Typical calls: rinexe("brdc1310.20n") rinexe("BRDC00IGS_R_20203410000_01D_MN.rnx", system='S') Inputs: ephemerisfile - Path to RINEX Navigation Message file system - Character of system to consider, only in RINEX version 3. 'G' - GPS 'S' - SBAS 'R' - GLONASS 'E' - Galileo 'C' - BeiDou 'J' - QZSS 'I' - NavIC None - Only one GNSS is assumed to be present (default) Author: <NAME> """ with open(ephemerisfile, "r") as fide: try: line = fide.readline() version = int(line[5]) except ValueError: raise ValueError('Could not find RINEX version in first line of file.') head_lines = 1 answer = -1 leap_seconds = 18 # Use default leap seconds if they are not in header while answer < 0: # Skip header head_lines = head_lines + 1 line = fide.readline() if line.find("LEAP SECONDS") >= 0 and (system == 'S' or system == 'R'): # Read leap seconds for SBAS or GLONASS leap_seconds = int(line[4:6]) leap_seconds = np.timedelta64(leap_seconds, 's') answer = line.find("END OF HEADER") line = "init" if version == 2: noeph = -1 while not line == "": noeph = noeph + 1 line = fide.readline() # if not sbas: noeph = int(noeph / 8) # else: # noeph = int(noeph / 4) elif version == 3: noeph = 0 while not line == "": line = fide.readline() if not line == "" and not line[0] == " " and ( system is None or line[0] == system): noeph = noeph + 1 else: raise ValueError("Found unsupported RINEX version, use 2 or 3.xx.") fide.seek(0) for i in range(head_lines): line = fide.readline() # Set aside memory for the input svprn = np.zeros(noeph) # weekno = np.zeros(noeph) # t0c = np.zeros(noeph) # tgd = np.zeros(noeph) # aodc = np.zeros(noeph) toe = np.zeros(noeph) af2 = np.zeros(noeph) af1 = np.zeros(noeph) af0 = np.zeros(noeph) # aode = np.zeros(noeph) deltan = np.zeros(noeph) M0 = np.zeros(noeph) ecc = np.zeros(noeph) roota = np.zeros(noeph) toe = np.zeros(noeph) cic = np.zeros(noeph) crc = np.zeros(noeph) cis = np.zeros(noeph) crs = np.zeros(noeph) cuc = np.zeros(noeph) cus = np.zeros(noeph) Omega0 = np.zeros(noeph) omega = np.zeros(noeph) i0 = np.zeros(noeph) Omegadot = np.zeros(noeph) idot = np.zeros(noeph) # tom = np.zeros(noeph) # accuracy = np.zeros(noeph) # health = np.zeros(noeph) # fit = np.zeros(noeph) if not system == 'S' and not system == 'R': if version == 2: for i in range(noeph): line = fide.readline() svprn[i] = int(line[0:2].replace("D", "E")) # year = line[2:6] # month = line[6:9] # day = line[9:12] # hour = line[12:15] # minute = line[15:18] # second = line[18:22] af0[i] = float(line[22:41].replace("D", "E")) af1[i] = float(line[41:60].replace("D", "E")) af2[i] = float(line[60:79].replace("D", "E")) line = fide.readline() # IODE = line[3:22] crs[i] = float(line[22:41].replace("D", "E")) deltan[i] = float(line[41:60].replace("D", "E")) M0[i] = float(line[60:79].replace("D", "E")) line = fide.readline() cuc[i] = float(line[3:22].replace("D", "E")) ecc[i] = float(line[22:41].replace("D", "E")) cus[i] = float(line[41:60].replace("D", "E")) roota[i] = float(line[60:79].replace("D", "E")) line = fide.readline() toe[i] = float(line[3:22].replace("D", "E")) cic[i] = float(line[22:41].replace("D", "E")) Omega0[i] = float(line[41:60].replace("D", "E")) cis[i] = float(line[60:79].replace("D", "E")) line = fide.readline() i0[i] = float(line[3:22].replace("D", "E")) crc[i] = float(line[22:41].replace("D", "E")) omega[i] = float(line[41:60].replace("D", "E")) Omegadot[i] = float(line[60:79].replace("D", "E")) line = fide.readline() idot[i] = float(line[3:22].replace("D", "E")) # codes = float(line[22:41].replace("D", "E")) # weekno = float(line[41:60].replace("D", "E")) # L2flag = float(line[60:79].replace("D", "E")) line = fide.readline() # svaccur = float(line[3:22].replace("D", "E")) # svhealth = float(line[22:41].replace("D", "E")) # tgd[i] = float(line[41:60].replace("D", "E")) # iodc = line[60:79] line = fide.readline() # tom[i] = float(line[3:22].replace("D", "E")) # spare = line[22:41] # spare = line[41:60] # spare = line[60:79] elif version == 3: for i in range(noeph): if system is not None: # Multiple systems might be present # Skip lines until desired one is found line = "init" while not line[0] == system: line = fide.readline() else: line = fide.readline() svprn[i] = int(line[1:3]) af0[i] = float(line[23:42]) af1[i] = float(line[42:61]) af2[i] = float(line[61:80]) line = fide.readline() crs[i] = float(line[23:42]) deltan[i] = float(line[42:61]) M0[i] = float(line[61:80]) line = fide.readline() cuc[i] = float(line[4:23]) ecc[i] = float(line[23:42]) cus[i] = float(line[42:61]) roota[i] = float(line[61:80]) line = fide.readline() toe[i] = float(line[4:23]) cic[i] = float(line[23:42]) Omega0[i] = float(line[42:61]) cis[i] = float(line[61:80]) line = fide.readline() i0[i] = float(line[4:23]) crc[i] = float(line[23:42]) omega[i] = float(line[42:61]) Omegadot[i] = float(line[61:80]) line = fide.readline() idot[i] = float(line[4:23]) line = fide.readline() # tgd[i] = float(line[42:61]) line = fide.readline() # tom[i] = float(line[4:23]) else: raise ValueError( "Found unsupported RINEX version, use 2 or 3.xx.") else: # SBAS / GLONASS navigation message format if version == 2: raise ValueError( "RINEX version 2 not supported for SBAS and GLONASS.") elif version == 3: # Set aside memory for the input pos_x = np.zeros(noeph) vel_x = np.zeros(noeph) acc_x = np.zeros(noeph) pos_y = np.zeros(noeph) vel_y = np.zeros(noeph) acc_y = np.zeros(noeph) pos_z = np.zeros(noeph) vel_z = np.zeros(noeph) acc_z = np.zeros(noeph) for i in range(noeph): # Multiple systems might be present # Skip lines until desired one is found line = "init" while not line[0] == system: line = fide.readline() if line[0] == 'S': # Satellite number svprn[i] = 100 + int(line[1:3]) # Time of Ephemeris (sec of BDT week) year = line[4:8] month = line[9:11] day = line[12:14] hour = line[15:17] minute = line[18:20] second = line[21:23] time_utc = np.datetime64(year + '-' + month + '-' + day + 'T' + hour + ':' + minute + ':' + second) time_bds = ( time_utc - np.datetime64('1980-01-06') + leap_seconds ) / np.timedelta64(1, 's') # time_bds = utc_2_gps_time(time_utc) toe[i] = np.mod(time_bds, 7 * 24 * 60 * 60) # SV clock bias [s] (aGf0) af0[i] = float(line[23:42]) # Transmission time in GPS seconds of week # tom[i] = float(line[42:61]) line = fide.readline() pos_x[i] = float(line[4:23]) vel_x[i] = float(line[23:42]) acc_x[i] = float(line[42:61]) line = fide.readline() pos_y[i] = float(line[4:23]) vel_y[i] = float(line[23:42]) acc_y[i] = float(line[42:61]) line = fide.readline() pos_z[i] = float(line[4:23]) vel_z[i] = float(line[23:42]) acc_z[i] = float(line[42:61]) else: raise ValueError( "Found unsupported RINEX version, use 2 or 3.xx.") # Description of variable eph if not system == 'S' and not system == 'R': return np.array( [ svprn, af2, M0, roota, deltan, ecc, omega, cuc, cus, crc, crs, i0, idot, cic, cis, Omega0, Omegadot, toe, af0, af1, toe ] ) else: # SBAS / GLONASS return np.array( [ svprn, af2, np.empty(noeph) * np.nan, pos_x, vel_x, acc_x, pos_y, vel_y, acc_y, pos_z, vel_z, acc_z, np.empty(noeph) * np.nan, np.empty(noeph) * np.nan, np.empty(noeph) * np.nan, np.empty(noeph) * np.nan, np.empty(noeph) * np.nan, toe, af0, af1, toe ] ) def gps_ionosphere_parameters_from_rinex(rinexfile): """Read ionospheric correction parameters and leap sec. for GPS from RINEX. Input: rinexfile - Path to RINEX Navigation Message file Outputs: alpha - Coefficients of a cubic equation representing the amplitude of the vertical delay (4 coefficients, numpy array) beta - Coefficients of a cubic equation representing the period of the model (4 coefficients, numpy array) leap_seconds - GPS leap seconds w.r.t. to UTC Author: <NAME> """ # Open file in read mode file_id = open(rinexfile, "r") # Initialize results alpha = np.full(4, np.nan) beta = np.full(4, np.nan) leap_seconds = np.nan # Search in header for desired parameters end_of_header = False while not end_of_header: # Read single line line = file_id.readline() # Search line for key words if line.find("ION ALPHA") >= 0: # Alpha parameters, RINEX 2 for idx in np.arange(4): start_char = 3 + idx * 12 end_char = 3 + (idx+1) * 12 - 1 alpha[idx] = float(line[start_char:end_char].replace("D", "E")) elif line.find("ION BETA") >= 0: # Beta parameters, RINEX 2 for idx in np.arange(4): start_char = 3 + idx * 12 end_char = 3 + (idx+1) * 12 - 1 beta[idx] = float(line[start_char:end_char].replace("D", "E")) elif line.find("GPSA") >= 0: # Alpha parameters, RINEX 3 for idx in np.arange(4): start_char = 6 + idx * 12 end_char = 6 + (idx+1) * 12 - 1 alpha[idx] = float(line[start_char:end_char]) elif line.find("GPSB") >= 0: # Beta parameters, RINEX 3 for idx in np.arange(4): start_char = 6 + idx * 12 end_char = 6 + (idx+1) * 12 - 1 beta[idx] = float(line[start_char:end_char]) elif line.find("LEAP SECONDS") >= 0: # Leap seconds start_char = 4 end_char = 6 leap_seconds = float(line[start_char:end_char]) # Check if end of header or end of file has been reached end_of_header = line.find("END OF HEADER") >= 0 or line == "" # Close RINEX file file_id.close() # Return tuple return alpha, beta, leap_seconds def read_sp3(file_name): """Read final precise orbits from SP3 file. Requires to install package GNSSpy first, e.g., by executing 'python setup.py install' in the directory '../3rd_party/gnsspy'. Input: file_name - Path to SP3 file Output: sp3 - Supporting points of orbits as pandas.DataFrame Author: <NAME> Based on https://github.com/GNSSpy-Project/gnsspy/blob/fce079af37d585dc757c56539a98cc0dfe66f9de/gnsspy/position/interpolation.py """ import pandas as pd from gnsspy.io import readFile sp3 = readFile.read_sp3File(file_name) sp3 = sp3.dropna(subset=["deltaT"]) sp3 = sp3.reorder_levels(["Epoch", "SV"]) return sp3 def interpolate_code_phase(corr, mode="quadratic"): """Interpolate code phase value based on correlogram. Necessary to obtain fractional code phases with a resolution that is not limited by the sampling frequency. Input: corr - 1D correlogram, correlation over code phase for one satellite mode - [Optional] type of interpolation 'none' - No interpolation 'linear' - Linear interpolation 'quadratic' - [Default] quadratic interpol. based on 3 points 'quadratic5' - Quadratic interpolation based on 5 points Output: codePhase - Interpolated code phase (in samples) Author: <NAME> """ maxInd = np.argmax(corr) if mode == "none": return maxInd + 1.0 maxVal = corr[maxInd] leftInd = maxInd - 1 rightInd = np.mod(maxInd + 1, corr.shape[0]) leftVal = corr[leftInd] rightVal = corr[rightInd] if mode == "linear": return ((maxInd - 1) * leftVal + maxInd * maxVal + (maxInd + 1) * rightVal) / (leftVal + maxVal + rightVal) + 1.0 if mode == "quadratic": # Algorithm from Chapter 8.12 of # Tsui, <NAME>. Fundamentals of global positioning system # receivers: a software approach. Vol. 173. <NAME> & Sons, 2005. # http://twanclik.free.fr/electricity/electronic/pdfdone7/Fundamentals%20of%20Global%20Positioning%20System%20Receivers.pdf x1 = -1.0 x2 = 0.0 x3 = 1.0 y1 = leftVal y2 = maxVal y3 = rightVal Y = np.array([y1, y2, y3]) X = np.array([[x1**2, x1, 1.0], [x2**2, x2, 1.0], [x3**2, x3, 1.0]]) A = np.linalg.lstsq(X, Y, rcond=None)[0] a = A[0] b = A[1] # c = A[2] x = -b / 2.0 / a return maxInd + x + 1.0 if mode == "quadratic5": leftLeftInd = maxInd - 2 rightRightInd = np.mod(maxInd + 2, corr.shape[0]) leftLeftVal = corr[leftLeftInd] rightRightVal = corr[rightRightInd] # Algorithm from Chapter 8.12 of # Tsui, <NAME>. Fundamentals of global positioning system # receivers: a software approach. Vol. 173. <NAME> & Sons, 2005. # http://twanclik.free.fr/electricity/electronic/pdfdone7/Fundamentals%20of%20Global%20Positioning%20System%20Receivers.pdf x1 = -2.0 x2 = -1.0 x3 = 0.0 x4 = 1.0 x5 = 2.0 y1 = leftLeftVal y2 = leftVal y3 = maxVal y4 = rightVal y5 = rightRightVal Y = np.array([y1, y2, y3, y4, y5]) X = np.array([[x1**2, x1, 1.0], [x2**2, x2, 1.0], [x3**2, x3, 1.0], [x4**2, x4, 1.0], [x5**2, x5, 1.0]]) A = np.linalg.lstsq(X, Y, rcond=None)[0] a = A[0] b = A[1] # c = A[2] x = -b / 2.0 / a return maxInd + x + 1.0 def gps_time_2_utc(gps_time_sec, leapSeconds=None): """Convert time from seconds since GPS start into UTC. 18 leap seconds, i.e., -18 s, for all dates after 2016-12-31. Inputs: gps_time_sec - Time in seconds since GPS reference date & time [s] leapSeconds - GPS leap seconds w.r.t. UTC; if None, then leap seconds are calculated from date; default=None Output: utc - UTC (datetime format) Author: <NAME> """ if leapSeconds is None or not np.isfinite(leapSeconds): stepDates = np.array( [46828800.0, 78364801.0, 109900802.0, 173059203.0, 252028804.0, 315187205.0, 346723206.0, 393984007.0, 425520008.0, 457056009.0, 504489610.0, 551750411.0, 599184012.0, 820108813.0, 914803214.0, 1025136015.0, 1119744016.0, 1167177617] ) leapSeconds = 0 while leapSeconds < 18 and gps_time_sec > stepDates[leapSeconds]: leapSeconds = leapSeconds + 1 referenceDate = np.datetime64('1980-01-06') # GPS reference date return (np.timedelta64(int((gps_time_sec - leapSeconds) * 1e9), 'ns') + referenceDate) def utc_2_gps_time(utc, leapSeconds=None): """Convert time from UTC to seconds since GPS start. 18 leap seconds, i.e., +18 s, for all dates after 2016-12-31. Inputs: utc - UTC (numpy.datetime64) leapSeconds - GPS leap seconds w.r.t. UTC; if None, then leap seconds are calculated from date; default=None Output: gps_time - Time in seconds since GPS reference date & time [s] Author: <NAME> """ if leapSeconds is None or not np.isfinite(leapSeconds): stepDates = np.array([ np.datetime64('1981-07-01'), np.datetime64('1982-07-01'), np.datetime64('1983-07-01'), np.datetime64('1985-07-01'), np.datetime64('1988-01-01'), np.datetime64('1990-01-01'), np.datetime64('1991-01-01'), np.datetime64('1992-07-01'), np.datetime64('1993-07-01'), np.datetime64('1994-07-01'), np.datetime64('1996-01-01'), np.datetime64('1997-07-01'), np.datetime64('1999-01-01'), np.datetime64('2006-01-01'), np.datetime64('2009-01-01'), np.datetime64('2012-07-01'), np.datetime64('2015-07-01'), np.datetime64('2016-12-31')]) leapSeconds = 0 while leapSeconds < 18 and utc > stepDates[leapSeconds]: leapSeconds = leapSeconds + 1 referenceDate = np.datetime64('1980-01-06') # GPS reference date leapSeconds = np.timedelta64(leapSeconds, 's') return (utc - referenceDate + leapSeconds) / np.timedelta64(1, 's') def gps_time_2_beidou_time(gps_time_sec): """Convert time from seconds since GPS start into BeiDou time (BDT). Input: gps_time_sec - Time in seconds since GPS reference date & time [s] Output: bdt - BeiDou time [s] (time in seconds since BeiDou time reference) Author: <NAME> """ return gps_time_sec - 820108814.0 def predict_pseudoranges(sats, eph, coarse_time, rec_pos, common_bias, trop=False): """Predict pseudoranges to satellites for given time and receiver position. Inputs: sats - Indices of satellites (PRNs) eph - Ephemeris as matrix coarse_time - Coarse GPS time [s] rec_pos - Receiver position in ECEF XYZ coordinates [m,m,m] common_bias - Common bias in all pseudoranges [m] trop - [Optional] flag indicating if troposheric correction is applied; default = True Output: predictedPR - Predicted pseudoranges [m] Author: <NAME> Algorithm from Chapter 4.4.2 of <NAME>, A-GPS: Assisted GPS, GNSS, and SBAS, 2009. """ # Speed of light [m/s] c = 299792458.0 # Number of satellites nSats = sats.shape[0] # GPS time since 1980 to time of week (TOW) [s] coarseTimeTOW = np.mod(coarse_time, 7 * 24 * 60 * 60) # Identify matching columns in ephemeris matrix, closest column in time # for each satellite if nSats < eph.shape[1]: col = np.array([find_eph(eph, s_i, coarseTimeTOW) for s_i in sats]) if col.size == 0: raise IndexError("Cannot find satellite in navigation data.") # Extract matching columns eph = eph[:, col] # Find satellite positions at coarse transmission time txGPS = coarseTimeTOW - get_sat_clk_corr(coarseTimeTOW, sats, eph) satPosCoarse = get_sat_pos(txGPS, eph) # Find closest one (alternatively, find highest) distancesCoarse = np.sqrt(np.sum((rec_pos - satPosCoarse)**2, axis=-1)) satByDistance = np.argsort(distancesCoarse) # Assign integer ms-part of distances Ns = np.zeros(nSats) # Time equivalent to distance [ms] distancesCoarse = distancesCoarse / c / 1e-3 # Index of 1st satellite (reference satellite) N0Inx = satByDistance[0] # Initial guess Ns[N0Inx] = np.floor(distancesCoarse[N0Inx]) # Time error [ms] deltaT = eph[18] * 1e3 # Update considering time error for i in range(1, nSats): k = satByDistance[i] Ns[k] = np.round(Ns[N0Inx] + (distancesCoarse[k] - deltaT[k]) - (distancesCoarse[N0Inx] - deltaT[N0Inx])) # Find integer ms-part difference to reference satellite Ks = Ns - Ns[N0Inx] # Correct for satellite clock error tCorr = np.empty(nSats) for i in range(nSats): k = np.array([sats[i]]) tCorr[i] = get_sat_clk_corr(coarseTimeTOW - Ks[i] * 1e-3, k, eph[:, i, np.newaxis]) txGPS = coarseTimeTOW - Ks * 1e-3 - tCorr # Get satellite position at corrected transmission time satPos = get_sat_pos(txGPS, eph) # Calculate rough propagation delay travelTime = np.linalg.norm(satPos - rec_pos, axis=1) / c # Initialize array rotSatPos = np.empty((nSats, 3)) for i in range(nSats): k = satByDistance[i] # Rotate satellite ECEF coordinates due to earth rotation during signal # travel time OmegaEdot = 7.292115147e-5 # Earth's angular velocity [rad/s] omegaTau = OmegaEdot * travelTime[k] # Angle [rad] R3 = np.array([[np.cos(omegaTau), np.sin(omegaTau), 0.0], [-np.sin(omegaTau), np.cos(omegaTau), 0.0], [0.0, 0.0, 1.0]]) # Rotation matrix rotSatPos[k] = R3 @ satPos[k] # Apply rotation if trop: # Initialize array trop = np.empty(nSats) for i in range(nSats): k = satByDistance[i] # Transform into topocentric coordinate system az, el, rng = topocent(rec_pos, rotSatPos[k]) # Elevation of satellite w.r.t. receiver [deg] # Tropospheric correction trop[k] = tropo(np.sin(el*np.pi/180.0), 0.0, 1013.0, 293.0, 50.0, 0.0, 0.0, 0.0) else: trop = 0.0 # Correct for common bias, satellite clock offset, tropospheric delay return (np.linalg.norm(rotSatPos - rec_pos, axis=1) + common_bias - tCorr*c + trop) # [m] def get_code_phase(ht, hp, hb, prn, eph, code_duration=1e-3, corr=True, corr_type=0, alpha=np.array([0.1676e-07, 0.1490e-07, -0.1192e-06, -0.5960e-07]), beta=np.array([0.1085e+06, 0.3277e+05, -0.2621e+06, -0.6554e+05])): """Calculate expected code phase [s] for given time and position. Precision comparable to predict_pseudoranges(...) but faster. Inputs: ht - time hypothesis (received time) [s] hp - position hypothesis [m,m,m] hb - common bias hypothesis [m] prn - satellite index eph - Ephemeris as matrix code_duration - Duration of the code [s], 1e-3 for GPS' C/A code, 4e-3 for Galileo's E1BC code, default=1e-3 corr - Switch for atmospheric correction, default=True corr_type - Type of atmospheric correction, default=0 0 - Tropospheric correction according to Goad et al. using default parameters 1 - Tropospheric correction according to Hopfield using default parameters, ionospheric correction according to Klobuchar alpha - Parameters from navigation message for ionospheric correction if corr_type=1 beta - Parameters from navigation message for ionospheric correction if corr_type=1 Output: phi - code phase [s]; add code_duration - phi if using with DPE Author: <NAME> Inspired by Bissig, Pascal, et al. “Fast and Robust GPS Fix Using One Millisecond of Data.” Proceedings of the 16th ACM/IEEE International Conference on Information Processing in Sensor Networks, 2017, pp. 223–233. https://tik-old.ee.ethz.ch/file/f65e5d021e6daee3344591d433b49e83/paper.pdf """ # Speed of light [m/s] c = 299792458.0 # Receiver position in geodetic coordinates lat, lon, h = pm.ecef2geodetic(hp[0], hp[1], hp[2]) # Crude transmit time estimate [s] t = ht - 76.5e-3 # GPS time with respect to 1980 to time of week (TOW) tow = np.mod(t, 7 * 24 * 60 * 60) if prn.shape[0] < eph.shape[1]: # Find column of ephemeris matrix that matches satellite index and time col = np.array([find_eph(eph, prn_i, tow) for prn_i in prn]) # Extract matching columns eph = eph[:, col] # 2 iterations to refine transmit time estimate for it in range(2): # Satellite position estimate [m,m,m] p = get_sat_pos(t, eph) # Propagation delay estimate [s] d = np.linalg.norm(hp - p, axis=1) / c # Apply common bias d = d + hb / c # Transmit time estimate [s] t = ht - d # Satellite clock error [s] tCorr = get_sat_clk_corr(ht, prn, eph) # Apply satellite clock error to transmission delay d = d - tCorr if corr: if corr_type == 0: # Satellite elevation az, elev, dist = pm.ecef2aer(p[:, 0], p[:, 1], p[:, 2], lat, lon, h) ddr = np.array([tropo(np.sin(elev_i * np.pi / 180), 0.0, 1013.0, 293.0, 50.0, 0.0, 0.0, 0.0) for elev_i in elev]) # Tropospheric correction tropoDelay = ddr / c # Apply tropospheric correction d = d + tropoDelay else: # Ionospheric error non-iterative iono_T = ionospheric_klobuchar(hp, p, np.mod(t[0], 7 * 24 * 60 * 60), alpha, beta) # [s] # Tropospheric time trop_T_equiv = tropospheric_hopfield(hp, p) / c d = d + iono_T + trop_T_equiv # Code phase [s] return np.mod(d, code_duration) def acquisition(longsignal, IF, Fs, freq_step=500, ms_to_process=1, prn_list=np.arange(1, 33), expected_doppler=0.0, max_doppler_err=5000.0, code_phase_interp='quadratic', fine_freq=True, gnss='gps', channel='combined', channel_coherent=False, l1c=False, ms_coherent_integration=None, snr_threshold=18.0, database=None): """Perform signal acquisition using parallel code phase search. Secondary codes are ignored. Inputs: longsignal - Binary GPS signal IF - Intermediate frequency [Hz] Fs - Sampling frequency [Hz] freq_step - Width of frequency bins for coarse acquisition [Hz], choose approximately 1 kHz / ms_to_process [default=500] freq_min - Minimum Doppler frequency [Hz], choose dependent on maximum expected receiver velocity [default=-5000] ms_to_process - Number of milliseconds to use [default=1] prn_list - Indices of satellites to use (PRNs), i.e., satellites that are expected to be visible [default=1:32] expected_doppler - Expected Doppler shifts of satellites, which are expected to be visible [Hz] [default=[0, ... 0]] max_doppler_err - Maximum expected absolute deviation of true Doppler shifts from expected ones [Hz] [default=5000] code_phase_interpolation - Type of code-phase interpolation ('none', 'linear', 'quadratic', 'quadratic5') fine_freq - Enable fine frequency calculation [default=True], not tested for Galileo yet, not present for BeiDou and GPS L1C gnss - Type of navigation satellite system, 'gps', 'sbas', 'galileo', or 'beidou' [default='gps'] channel - Signal channels to use, 'data', 'pilot', or 'combined', Galileo and BeiDou only [default='combined'] channel_coherent - Coherent or non-coherent acqusition of channels if channel='combined' [default=False] l1c - Use GPS L1C signal instead of GPS L1 C/A codes [default=False] ms_coherent_integration - Integration time for single coherent integration [ms], less or equal than smallest code duration, if None, then code duration is used [default=None] snr_threshold - Minimum signal-to-noise ratio (SNR) to acquire a satellite [dB] [default=18.0] database - Database with pre-sampled satellite code replicas; object of type CodeDB; if present, then replicas are be taken from database instead of created online [default=None] Outputs: acquired_sv - PRNs of acquired satellites acquired_snr - Signal-to-noise ratio of all acquired satellites acquired_doppler - Coarse Doppler shift of all acquired satellites [Hz] acquired_codedelay - C/A code delay of all acquired satellites [number of samples] acquired_fine_freq - Fine carrier wave frequency of all acquired satellites [Hz] results_doppler - Coarse or fine Doppler shift of all satellites [Hz] results_code_phase - C/A code phase of all satellites [num. of samples] results_peak_metric - Signal-to-noise ratio of all satellites Author: <NAME> """ if gnss == 'gps': if not l1c: # L1 n_prn = 32 code_duration = 1e-3 else: # L1C n_prn = 210 code_duration = 10e-3 fine_freq = False elif gnss == 'sbas': n_prn = 138 code_duration = 1e-3 elif gnss == 'galileo': n_prn = 50 code_duration = 4e-3 elif gnss == 'beidou' or gnss == 'bds': gnss = 'beidou' n_prn = 63 code_duration = 10e-3 fine_freq = False else: raise Exception( "Chosen GNSS not supported, select 'gps', 'sbas', 'galileo', or " + "'beidou'.") # Set number of signal channels if (gnss == 'gps' and not l1c) or gnss == 'sbas' \ or channel == 'data' or channel == 'pilot': n_channels = 1 elif channel == 'combined': n_channels = 2 else: raise Exception( "Chosen signal channel not supported, select 'data', 'pilot', or " + "'combined'.") # Check if scalar is passed as expected Doppler if not hasattr(expected_doppler, "__len__"): expected_doppler = expected_doppler * np.ones(prn_list.shape) if prn_list.shape[0] is not expected_doppler.shape[0]: raise Exception( "prn_list and expected_doppler do not have the same shape.") # Number of code sequences in ms_to_process n_codes = int(np.ceil(ms_to_process / code_duration * 1e-3)) # Maximum number of samples to read max_samp = longsignal.shape[0] # Samples per C/A code sequence sample = int(np.ceil(Fs * code_duration)) sampleindex = np.arange(1, sample + 1) # C/A code frequency codeFreqBasis = 1.023e6 # Length of C/A code sequence codelength = codeFreqBasis * code_duration # Check if integration interval other than code duration shall be used if ms_coherent_integration is not None \ and ms_coherent_integration < code_duration / 1e-3: # Number of samples per integration interval samples_per_integration = int(np.round(ms_coherent_integration * 1e-3 * Fs)) idx = 0 extended_signal = np.empty(0) while idx * samples_per_integration < max_samp: # Extract signal chunk rawsignal = longsignal[idx * samples_per_integration: np.min([(idx + 1) * samples_per_integration, max_samp])] # Zero-pad signal chunk to same length as code extended_signal = np.concatenate((extended_signal, rawsignal, np.zeros(sample))) idx = idx + 1 longsignal = extended_signal # Number of code sequences n_codes = idx # Maximum number of samples to read max_samp = longsignal.shape[0] # Initialization acquired_sv = np.empty(0, dtype=int) acquired_snr = np.empty(0) acquired_doppler = np.empty(0) acquired_codedelay = np.empty(0, dtype=int) acquired_fine_freq = np.empty(0) results_doppler = np.full(n_prn, np.nan) results_code_phase = np.full(n_prn, np.nan) results_peak_metric = np.full(n_prn, np.nan) # Minimum Doppler frequencies to start search freq_min = expected_doppler - max_doppler_err # Number of frequency bins freqNum = 2 * int(np.abs(max_doppler_err) / freq_step) + 1 # Generate carrier wave replica carrier = np.empty((prn_list.shape[0], freqNum, sample), dtype=complex) for prn_idx in range(prn_list.shape[0]): for freqband in range(freqNum): dopplershift = freq_min[prn_idx] + freq_step * freqband carrier[prn_idx, freqband] = np.exp( 1j * 2.0 * np.pi * (IF + dopplershift) * sampleindex / Fs) # Loop over all satellites that are expected to be visible for prn_idx in range(prn_list.shape[0]): svindex = prn_list[prn_idx] # Initialize correlogram correlation = np.zeros((freqNum, sample)) # Iterate over channels for channel_idx in range(n_channels): if (gnss == 'gps' and not l1c) or gnss == 'sbas': if database is None: # Generate C/A code replica ocode = generate_ca_code(svindex) ocode = np.concatenate((ocode, ocode)) scode = ocode[np.ceil(sampleindex * codeFreqBasis / Fs ).astype(int) - 1] replica = scode else: # Get C/A code replica from database replica = database.query_db(gnss, svindex) elif (gnss == 'gps' and l1c) or gnss == 'galileo' \ or gnss == 'beidou': # Generate E1 / B1C / L1C code replica if not channel == 'combined' or not channel_coherent: # Non-coherent acqusition of channels # -> Either data or pilot signal if channel_idx == 0 and channel != 'pilot': # Acqusition for data channel E1B / B1C_data / L1C_d pilot = False else: # Acqusition for pilot channel E1C / B1C_pilot / L1C_p pilot = True if database is None: # Generate code replica if gnss == 'galileo': # E1 code replica = generate_e1_code(svindex, Fs, pilot=pilot) elif gnss == 'beidou': # B1C code replica = generate_b1c_code(svindex, Fs, pilot=pilot) elif gnss == 'gps' and l1c: # L1C code replica = generate_l1c_code(svindex, Fs, pilot=pilot) else: # Get code replica from database replica = database.query_db(gnss, svindex, pilot) else: # Coherent acqusition of channels # -> Combine both channels if channel_idx == 0: if database is None: if gnss == 'galileo': replica_data = generate_e1_code(svindex, Fs, pilot=False) replica_pilot = generate_e1_code(svindex, Fs, pilot=True) elif gnss == 'beidou': replica_data = generate_b1c_code(svindex, Fs, pilot=False) replica_pilot = generate_b1c_code(svindex, Fs, pilot=True) elif gnss == 'gps' and l1c: replica_data = generate_l1c_code(svindex, Fs, pilot=False) replica_pilot = generate_l1c_code(svindex, Fs, pilot=True) else: replica_data = database.query_db(gnss, svindex, pilot=False) replica_pilot = database.query_db(gnss, svindex, pilot=True) # Add data signal to pilot signal replica = replica_data + replica_pilot else: # Subtract data signal from pilot signal replica = - replica_data + replica_pilot # Correlation in frequency domain temp3 = fft_lib.fft(replica) for idx in range(n_codes): # Process each code sequence # Extract signal chunk rawsignal = longsignal[idx * sample: np.min([(idx + 1) * sample, max_samp])] # Zero padding to adjust for code sequence length rawsignal = np.concatenate((rawsignal, np.zeros( sampleindex.shape[0] - rawsignal.shape[0]))) for freqband in range(freqNum): temp1 = rawsignal \ * carrier[prn_idx, freqband] temp2 = np.conj(fft_lib.fft(temp1)) correlation[freqband] = correlation[freqband] \ + np.abs(fft_lib.ifft(temp3 * temp2))**2 if channel == 'combined' and channel_coherent: correlation_0 = correlation correlation = np.zeros((freqNum, sample)) # Normalize correlation = correlation * ms_to_process * code_duration / 4e-3 if not channel == 'combined' or not channel_coherent: # Normalize correlation = correlation / n_channels else: # Take max correlation = np.maximum(np.abs(correlation_0), np.abs(correlation)) # Find peak fbin = np.argmax(np.max(np.abs(correlation), axis=1)) codePhase = np.argmax(np.max(np.abs(correlation), axis=0)) peak = correlation[fbin, codePhase] # Doppler shift Doppler = freq_min[prn_idx] + freq_step * fbin # Signal-to-noise ration (SNR) codechipshift = np.ceil(Fs / codeFreqBasis) ind_snr = np.concatenate((np.arange(codePhase - codechipshift), np.arange(codePhase + codechipshift - 1, sample))) corr_snr = correlation[fbin, ind_snr.astype(int)] # import matplotlib.pyplot as plt # plt.plot(correlation[fbin]) SNR = 10.0 * np.log10(peak**2 / (np.sum(corr_snr**2) / corr_snr.shape[0])) # SNR = 10.0 * np.log10(peak / # np.mean(corr_snr)) # # SNR = peak / np.max(corr_snr) # plt.title(gnss + " PRN " + str(svindex) + ", SNR = " + str(np.round(SNR,1))) # plt.show() # Acquisition threshold if SNR >= snr_threshold: acquired_sv = np.append(acquired_sv, svindex) acquired_snr = np.append(acquired_snr, SNR) acquired_doppler = np.append(acquired_doppler, Doppler) acquired_codedelay = np.append(acquired_codedelay, codePhase) results_peak_metric[svindex - 1] = SNR codePhase = interpolate_code_phase(correlation[fbin], mode=code_phase_interp) results_code_phase[svindex - 1] = sample - codePhase + 1.0 results_doppler[svindex - 1] = Doppler # Fine frequency calculation if fine_freq: # Number of ms to perform FFT acq_L = 10 longSignalIndex = np.mod(np.arange(1, sample * (acq_L + int( code_duration / 1e-3))), sample) longSignalIndex[longSignalIndex == 0] = sample if longSignalIndex.shape[0] > rawsignal.shape[0]: longsignal = np.concatenate((longsignal, np.zeros( longSignalIndex.shape[0] - rawsignal.shape[0]))) longrawsignal = longsignal[longSignalIndex - 1] for svindex in range(acquired_sv.shape[0]): if (gnss == 'gps' and not l1c) or gnss == 'sbas': caCode = generate_ca_code(acquired_sv[svindex]) codeValueIndex = np.floor((1.0 / Fs * (np.arange(acq_L * sample) + 1.0)) / (1.0 / codeFreqBasis)) longCaCode = caCode[np.mod(codeValueIndex, codelength).astype( int)] elif gnss == 'galileo': caCode = generate_e1_code(acquired_sv[svindex], Fs) codeValueIndex = np.floor((1.0 / Fs * (np.arange(acq_L * sample) + 1.0)) / (1.0 / codeFreqBasis)) longCaCode = np.tile(caCode, acq_L) CarrSignal = longrawsignal[ (sample - acquired_codedelay[svindex] - 1): (sample - acquired_codedelay[svindex]) + acq_L * sample - 1] * longCaCode fftlength = CarrSignal.shape[0] * 20 fftSignal = np.abs(fft_lib.fft(CarrSignal, fftlength)) # Find acquired satellite in original RPN list prn_idx = np.where(prn_list == acquired_sv[svindex])[0][0] # Get frequency index range for this satellite maxDoppler = -freq_min[prn_idx] # [Hz] minFreq = IF - maxDoppler maxFreq = IF + maxDoppler minIndex = np.ceil(minFreq / Fs * fftlength).astype(int) minIndex = np.max([1, minIndex]) maxIndex = np.ceil(maxFreq / Fs * fftlength).astype(int) maxIndex = np.min([fftlength, maxIndex]) FreqPeakIndex = np.argmax(fftSignal[minIndex-1:maxIndex]) FreqPeakIndex = FreqPeakIndex + minIndex fineDoppler = FreqPeakIndex * Fs / fftlength acquired_fine_freq = np.append(acquired_fine_freq, fineDoppler) results_doppler[acquired_sv[svindex] - 1] = fineDoppler - IF return acquired_sv, acquired_snr, acquired_doppler, acquired_codedelay,\ acquired_fine_freq, results_doppler, results_code_phase,\ results_peak_metric def acquisition_simplified(signals, utc, pos_geo, rinex_file=None, eph=None, system_identifier='G', elev_mask=15, intermediate_frequency=4092000.0, frequency_bins=np.array([0])): """Satellite acquisition for snapper with parallel code phase search (PCPS). Sampling frequency and snapshot duration fixed to snapper parameters. Includes prediction of set of visible satellites. Acquisition of all potentially visible satellites of one satellite system. Can process a batch of snapshots. Non-coherent integration over time and across satellite signal channels. Quadratic code-phase interpolation based on three points. Core computations in single precision. GPS and SBAS: L1 C/A signal Galileo: E1 signal with data and primary pilot channel BeiDou: B1C signal with data and primary pilot channel Reads pre-sampled satellite signal replicas from 'codes_X.npy'. Inputs: signals - Binary signal snapshots {-1,+1}, Nx49104 NumPy array utc - Time stamps of snapshots in UTC, NumPy array of numpy.datetime64 pos_geo - Initial geodetic position (latitude [deg], longitude [deg], height [m]), NumPy array rinex_file - Path to RINEX navigation file, default=None eph - Navigation data for desired time interval and satellite system, 2D numpy array with 21 rows, default=None, either 'rinex_file' or 'eph' must be provided, 'eph' is recommended system_identifier - 'G' for GPS, 'S' for SBAS, 'E' for Galileo, or 'C' for BeiDou, default='G' elev_mask - Satellite elevation threshold [deg], default=15 intermediate_frequency - (Offset corrected) intermediate frequency, default=4092000.0 frequency_bins - Centres of acquisition frequency bins relative to intermediate frequency for PCPS, 1D NumPy array, default=np.array([0]) Outputs: snapshot_idx_vec - Index of snapshot to which the following results belong, 1D NumPy array prn_vec - PRN of satellite to which the following results belong, all potentially visible satellites are included, 1D NumPy array code_phase_vec - Code phase estimates [ms] of all potentially visible satellites in the convention that is used in coarse_time_navigation.py, 1D NumPy array snr_vec - Something like the signal-to-noise ratio [dB] that can be used by the classifier in bayes_classifier_snr.npy to assess satellite reliability, 1D NumPy array eph_idx_vec - Column indices of the potentially visble satellites in the navigation data matrix, 1D NumPy array frequency_vec - Carrier frequency estimates [Hz] w.r.t. intermediate frequency for all potentially visible satellites, 1D NumPy array frequency_error_vec - Differences between estimated carrier frequencies and predicted Doppler shifts [Hz], 1D Numpy array Author: <NAME> """ # Remove signal mean to avoid DC artefacts in the frequency domain signals = signals.astype(np.float32) signals = signals - np.mean(signals, axis=-1, keepdims=True) # Sampling frequency sampling_frequency = 4092000.0 # Snapshot duration (12 ms) snapshot_duration = 12e-3 # Check some inputs if not isinstance(signals, np.ndarray) or signals.ndim != 2: raise Exception( "'signals' must be a 2D NumPy array.") if signals.shape[1] != int(sampling_frequency*snapshot_duration): raise Exception( "The second axis of 'signals' must have a length of {}.".format( int(sampling_frequency*snapshot_duration) )) if not isinstance(utc, np.ndarray) or utc.ndim != 1: raise Exception( "'utc' must be a 1D NumPy array.") if not isinstance(pos_geo, np.ndarray) or pos_geo.ndim != 1 \ or pos_geo.shape[0] != 3: raise Exception( "'pos_geo' must be a 1D NumPy array with three elements.") if not isinstance(frequency_bins, np.ndarray) or pos_geo.ndim != 1: raise Exception( "'frequency_bins' must be a 1D NumPy array.") if signals.shape[0] != utc.shape[0]: raise Exception( "The first dimensions of 'signals' and 'utc' must have the same " \ "size, but 'signals' has {} elements and 'utc' has {} elements.".format( signals.shape[0], utc.shape[0]) ) if rinex_file is None and eph is None: raise Exception( "Either 'eph' or 'rinex_file' must be provided, but both are 'None'." ) if eph is not None and (not isinstance(eph, np.ndarray) or eph.ndim != 2): raise Exception( "'eph' must be a 2D NumPy array." ) if eph is not None and eph.shape[0] != 21: raise Exception( "'eph' must have 21 rows, i.e., its first dimension must have size 21." ) # Convert geodetic coordinates to ECEF (Cartesian XYZ) pos_ecef = np.empty(3) pos_ecef[0], pos_ecef[1], pos_ecef[2] = pm.geodetic2ecef( pos_geo[0], pos_geo[1], pos_geo[2] ) if eph is None: # Read navigation data file try: eph = rinexe(rinex_file, system_identifier) except: raise Exception( "Could not read RINEX navigation data file.") # Check which PRNs are present in navigation data file prn = np.unique(eph[0]).astype(int) if prn.shape[0] == 0: raise Exception( "Could not find any satellites of the selected system in RINEX navigation data file.") # Set satellite signal code period depending on system if system_identifier == 'G' or system_identifier == 'S': code_period = 1e-3 # C/A codes have a period of 1 ms elif system_identifier == 'E': code_period = 4e-3 # E1 codes have a period of 4 ms elif system_identifier == 'C': code_period = 10e-3 # B1C codes have a period of 10 ms else: raise Exception( "Chosen GNSS not supported. Select 'G' for GPS, 'S' for SBAS, 'E' " + "for Galileo, or 'C' for BeiDou as 'system_identifier'.") # Convert UTC to GPS time reference_date = np.datetime64('1980-01-06') # GPS reference date leap_seconds = np.timedelta64(18, 's') # Hardcoded 18 leap seconds time = (utc - reference_date + leap_seconds) / np.timedelta64(1, 's') if system_identifier == 'C': # Convert GPS time to BeiDou time, but keep the GPS week number time = time - 14.0 # - 820108814.0 (this would change to BeiDou weeks) # Absolute system time to time of week (TOW) tow = np.mod(time, 7 * 24 * 60 * 60) # Vectorize everything: one row for one satellite at one point in time prn_vec = np.tile(prn, tow.shape[0]) tow_vec = np.repeat(tow, prn.shape[0]) # Remember which snapshot belongs to which row snapshot_idx_vec = np.repeat(np.arange(tow.shape[0]), prn.shape[0]) # Find column for each satellite in ephemerides array # Initialize array to store column indices eph_idx_vec = np.empty(tow.shape[0] * prn.shape[0], dtype=int) # Time differences between ephemerides timestamps and snapshot timestamps if eph[20, -1] > 7 * 24 * 60 * 60: # eph[20] holds absolute GPS time differences = eph[20] - time.reshape(-1, 1) # Convert to time of week (TOW) [s] eph[20] = np.mod(eph[20], 7 * 24 * 60 * 60) else: # eph[20] holds time of week (TOW) differences = eph[20] - tow.reshape(-1, 1) # Ephemerides timestamp should be smaller than snapshot timestamp # So, ignore all rows with larger timestamp differences[differences > 0] = -np.inf # Iterate over all PRNs for sat_idx, sat_id in enumerate(prn): # Get column indices of this PRN eph_idx_sat = np.where(eph[0] == sat_id)[0] # Get time differences for this PRN differences_sat = differences[:, eph_idx_sat] # Find timestamps closest to zero eph_idx = eph_idx_sat[np.argmax(differences_sat, axis=-1)] # Store indices for this PRN eph_idx_vec[sat_idx::prn.shape[0]] = eph_idx # Crude transmit time estimate [s] transmit_time_vec = tow_vec - 76.5e-3 # Get satellite position at estimated transmit time sat_pos_vec, sat_vel_vec = get_sat_pos_vel(transmit_time_vec, eph[:, eph_idx_vec]) # Convert to elevation above horizon in degrees _, elev_vec, _ = pm.ecef2aer( sat_pos_vec[:, 0], sat_pos_vec[:, 1], sat_pos_vec[:, 2], pos_geo[0], pos_geo[1], pos_geo[2] ) # Predict visible satellites # Satellites with elevation larger than threshold vis_sat_idx = (elev_vec > elev_mask) prn_vec = prn_vec[vis_sat_idx] snapshot_idx_vec = snapshot_idx_vec[vis_sat_idx] sat_pos_vec = sat_pos_vec[vis_sat_idx] sat_vel_vec = sat_vel_vec[vis_sat_idx] # Estimate Doppler shifts c = 299792458.0 # Speed of light [m/s] L1 = 1575.42e6 # GPS signal frequency [Hz] wave_length = c / L1 # Wave length of transmitted signal # Doppler shift (cf. 'Cycle slip detection in single frequency GPS carrier # phase observations using expected Doppler shift') doppler_vec = (((pos_ecef - sat_pos_vec) / np.linalg.norm( pos_ecef - sat_pos_vec, axis=-1, keepdims=True )) * sat_vel_vec).sum(1) / wave_length # Use single precision doppler_vec = doppler_vec.astype(np.float32) # Account for search along frequency axis n_bins = frequency_bins.shape[0] frequency_bins = np.tile(frequency_bins, doppler_vec.shape[0]).astype(np.float32) doppler_vec = np.repeat(doppler_vec, n_bins) snapshot_idx_vec_f = np.repeat(snapshot_idx_vec, n_bins) doppler_vec += frequency_bins # Samples per C/A code sequence sample = int(sampling_frequency * code_period) sample_idx = np.arange(1, sample + 1) if np.isscalar(intermediate_frequency): intermediate_frequency_f = intermediate_frequency else: intermediate_frequency_f = intermediate_frequency[snapshot_idx_vec_f] # Generate carrier wave replicas carrier_vec = np.exp(np.complex64(1j * 2.0 * np.pi / sampling_frequency) * np.array([(intermediate_frequency_f + doppler_vec)], dtype=np.float32).T @ np.array([sample_idx], dtype=np.float32)) if system_identifier == 'C': # Zero Padding for BeiDou because 10 does not divide 12 signals = np.hstack((signals, np.zeros((signals.shape[0], int((2*code_period-snapshot_duration)*sampling_frequency)), dtype=np.float32))) snapshot_duration = 20e-3 # Number of code sequences n_codes = int(snapshot_duration / code_period) # Create signal chunks, 1 ms, 4 ms, or 10 ms each, new array dimension signals = np.array(np.hsplit(signals, n_codes), dtype=np.float32).transpose(1, 0, 2) signals = signals[snapshot_idx_vec_f] # Wipe-off carrier signals = signals * np.repeat(carrier_vec[:, np.newaxis, :], n_codes, axis=1) # Transform snapshot chunks into frequency domain signals = np.conj(fft_lib.fft(signals)) # Adjust SBAS PRNs if system_identifier == 'S': prn -= 100 prn_vec -= 100 # Set number of signal channels if system_identifier == 'G' or system_identifier == 'S': n_channels = 1 else: n_channels = 2 # Satellite code replicas with single precision replicas = np.load("codes_" + system_identifier + ".npy") # Transform relevant replicas into frequency domain replicas_f = np.empty_like(replicas, dtype=np.complex64) replicas_f[prn-1] = fft_lib.fft(replicas[prn-1]) # Get matching replica for each row replicas_f = replicas_f[prn_vec-1] # Repeat replica for each code chunk, new code chunk dimension replicas_f = np.repeat(replicas_f[:, np.newaxis, :, :], n_codes, axis=1) # Account for multiple channels, create channel dimension signals = np.repeat(signals[:, :, np.newaxis, :], n_channels, axis=2) # Correlate in frequency domain and transform back into time domain correlation = np.abs(fft_lib.ifft(np.repeat(replicas_f, n_bins, axis=0) * signals))**2 # Sum all channels and all signals chunks of one # snapshot (non-coherent integration) correlation = np.sum(correlation, axis=2) correlation = np.sum(correlation, axis=1) # Normalize correlation = correlation * np.float32(snapshot_duration * 1e3 * code_period / 4e-3 / n_channels) # Create new dimension for frequency search space correlation = correlation.reshape((int(correlation.shape[0] / n_bins), n_bins, correlation.shape[1])) # Find correlogram peaks bin_vec = np.argmax(np.max(correlation, axis=-1), axis=-1) code_phase_vec = np.argmax(np.max(correlation, axis=-2), axis=-1) correlation = correlation[np.arange(correlation.shape[0]), bin_vec, :] # Remove frequency dimension peak_vec = correlation[np.arange(code_phase_vec.shape[0]), code_phase_vec] doppler_vec = doppler_vec.reshape((int(doppler_vec.shape[0] / n_bins), n_bins)) frequency_vec = doppler_vec[np.arange(code_phase_vec.shape[0]), bin_vec] frequency_error_vec = frequency_bins[bin_vec] # Quadratically interpolate code phases # Algorithm from Chapter 8.12 of # Tsui, <NAME>. Fundamentals of Global Positioning System # receivers: a software approach. Vol. 173. <NAME> & Sons, 2005. # http://twanclik.free.fr/electricity/electronic/pdfdone7/Fundamentals%20of%20Global%20Positioning%20System%20Receivers.pdf Y = np.array([correlation[np.arange(code_phase_vec.shape[0]), code_phase_vec - 1], # y1 = left_val peak_vec, # y2 = max_val correlation[np.arange(code_phase_vec.shape[0]), np.mod(code_phase_vec + 1, sample)] # y3 = right_val ], dtype=np.float32) x1 = -1.0 x2 = 0.0 x3 = 1.0 X = np.array([[x1**2, x1, 1.0], [x2**2, x2, 1.0], [x3**2, x3, 1.0]]) A = np.linalg.lstsq(X, Y, rcond=None)[0] a = A[0] b = A[1] # c = A[2] x = -b / 2.0 / a code_phase_interp_vec = sample - code_phase_vec - x # Signal-to-noise ratio (SNR) code_freq_basis = 1.023e6 # C/A code frequency code_chip_shift = int(np.ceil(sampling_frequency / code_freq_basis)) # Remove peaks correlation[np.repeat(np.arange(code_phase_vec.shape[0]), 2*code_chip_shift+1), np.mod(np.linspace(code_phase_vec-code_chip_shift, code_phase_vec+code_chip_shift, 2*code_chip_shift+1, dtype=int).T.flatten(), sample)] = np.nan # SNR snr_vec = 10.0 * np.log10(peak_vec**2 / (np.nansum(correlation**2, axis=-1) / correlation.shape[1])) # Convert code phases and SNR to convention used by CTN function code_phase_vec = code_phase_interp_vec / sampling_frequency / 1.0e-3 # Adjust SBAS PRNs if system_identifier == 'S': prn_vec += 100 return snapshot_idx_vec, prn_vec, code_phase_vec, snr_vec, \ eph_idx_vec[vis_sat_idx], frequency_vec, frequency_error_vec def topocent(X, dx): """Transform dx into topocentric coordinate system with origin at X. Inputs: X - Origin in ECEF XYZ coordinates dx - Point in ECEF XYZ coordinates Outputs: az - Azimuth from north positive clockwise [deg] el - Elevation angle [deg] dist - Length in units like the input """ dtr = np.pi/180.0 lat, lon, h = pm.ecef2geodetic(X[0], X[1], X[2]) cl = np.cos(lon*dtr) sl = np.sin(lon*dtr) cb = np.cos(lat*dtr) sb = np.sin(lat*dtr) F = np.array([np.array([-sl, -sb*cl, cb*cl]), np.array([cl, -sb*sl, cb*sl]), np.array([0.0, cb, sb])]) local_vector = F.T@dx E = local_vector[0] N = local_vector[1] U = local_vector[2] hor_dis = np.sqrt(E**2+N**2) if hor_dis < 1.e-20: az = 0.0 el = 90.0 else: az = np.arctan2(E, N)/dtr el = np.arctan2(U, hor_dis)/dtr if az < 0.0: az = az+360.0 dist = np.sqrt(dx[0]**2+dx[1]**2+dx[2]**2) return az, el, dist def tropo(sinel, hsta, p, tkel, hum, hp, htkel, hhum): """Calculate tropospheric correction. The range correction ddr in m is to be subtracted from pseudoranges and carrier phases. Inputs: sinel - Sin of elevation angle of satellite hsta - Height of station in km p - Atmospheric pressure in mb at height hp tkel - Surface temperature in degrees Kelvin at height htkel hum - Humidity in % at height hhum hp - Height of pressure measurement in km htkel - Height of temperature measurement in km hhum - Height of humidity measurement in km Output: ddr - Range correction [m] Reference <NAME>. & <NAME>. (1974) A Modified Tropospheric Refraction Correction Model. Paper presented at the American Geophysical Union Annual Fall Meeting, San Francisco, December 12-17. Author: <NAME> """ a_e = 6378.137 # Semi-major axis of earth ellipsoid b0 = 7.839257e-5 tlapse = -6.5 tkhum = tkel + tlapse * (hhum - htkel) atkel = 7.5 * (tkhum - 273.15) / (237.3 + tkhum - 273.15) e0 = 0.0611 * hum * 10**atkel tksea = tkel - tlapse * htkel em = -978.77 / (2.8704e6 * tlapse * 1.0e-5) tkelh = tksea + tlapse * hhum e0sea = e0 * (tksea / tkelh)**(4 * em) tkelp = tksea + tlapse * hp psea = p * (tksea / tkelp)**em if sinel < 0.0: sinel = 0.0 tropo = 0.0 done = False refsea = 77.624e-6 / tksea htop = 1.1385e-5 / refsea refsea = refsea * psea ref = refsea * ((htop - hsta) / htop)**4 while True: rtop = (a_e + htop)**2 - (a_e + hsta)**2 * (1 - sinel**2) if rtop < 0.0: rtop = 0.0 # Check to see if geometry is crazy rtop = np.sqrt(rtop) - (a_e + hsta) * sinel a = -sinel / (htop - hsta) b = -b0 * (1.0 - sinel**2) / (htop - hsta) rn = np.zeros(8) for i in range(8): rn[i] = rtop**(i + 2) alpha = np.array([2 * a, 2 * a**2 + 4 * b / 3, a * (a**2 + 3 * b), a**4 / 5 + 2.4 * a**2 * b + 1.2 * b**2, 2 * a * b * (a**2 + 3 * b) / 3, b**2 * (6 * a**2 + 4 * b) * 1.428571e-1, 0, 0]) if b**2 > 1.0e-35: alpha[6] = a * b**3 / 2 alpha[7] = b**4 / 9 dr = rtop dr = dr + np.sum(alpha * rn) tropo = tropo + dr * ref * 1000 if done: return tropo done = True refsea = (371900.0e-6 / tksea - 12.92e-6) / tksea htop = 1.1385e-5 * (1255 / tksea + 0.05) / refsea ref = refsea * e0sea * ((htop - hsta) / htop)**4 def tropospheric_hopfield(pos_rcv, pos_sv, T_amb=20.0, P_amb=101.0, P_vap=0.86): """Approximate troposspheric group delay. Inputs: pos_rcv - XYZ position of reciever [m,m,m] pos_sv - XYZ matrix position of GPS satellites [m,m,m] T_amb - Temperature at reciever antenna location [deg. Celsius] P_amb - Air pressure at reciever antenna location [hPa] P_vap - Water vapore pressure at reciever antenna location [hPa] Output: Delta_R_Trop - Tropospheric error correction [m] Author: <NAME> Reference: "GPS Theory and application", edited by <NAME>, <NAME>. """ # Receiver position in geodetic coordinates lat, lon, h = pm.ecef2geodetic(pos_rcv[0], pos_rcv[1], pos_rcv[2], deg=False) # Azimuth [rad], elevation [rad] az, El, dist = pm.ecef2aer(pos_sv[:, 0], pos_sv[:, 1], pos_sv[:, 2], lat, lon, h, deg=False) # Zenith hydrostatic delay Kd = 1.55208e-4 * P_amb * (40136.0 + 148.72 * T_amb) / (T_amb + 273.16) # Zenith Wet Delay Kw = -0.282 * P_vap / (T_amb + 273.16) + 8307.2 * P_vap / (T_amb + 273.16)**2 Denom1 = np.sin(np.sqrt(El**2 + 1.904e-3)) Denom2 = np.sin(np.sqrt(El**2 + 0.6854e-3)) # Troposhpheric delay correctoion return Kd / Denom1 + Kw / Denom2 # Meter def tropospheric_tsui(elevation): """Troposheric delay. Input: elevation - Elevation angle between user and satellite [deg] Output: tropospheric_delay - Estimated troposheric delay [m] Author: <NAME> Reference: Tsui, <NAME>. Fundamentals of global positioning system receivers: a software approach. Vol. 173. John Wiley & Sons, 2005. """ return 2.47 / (np.sin(np.deg2rad(elevation)) + 0.0121) def ionospheric_klobuchar(r_pos, pos_sv, gps_time, alpha=np.array([0.1676e-07, 0.1490e-07, -0.1192e-06, -0.5960e-07]), beta=np.array([0.1085e+06, 0.3277e+05, -0.2621e+06, -0.6554e+05])): """Approximate ionospheric group delay. Compute an ionospheric range correction for the GPS L1 frequency from the parameters broadcasted in the GPS navigation message. Not validated yet. Inputs: r_pos - XYZ position of reciever [m] pos_sv - XYZ matrix position of GPS satellites [m] gps_time - Time of Week [s] alpha - Coefficients of a cubic equation representing the amplitude of the vertical delay (4 coefficients) beta - Coefficients of a cubic equation representing the period of the model (4 coefficients) Output: Delta_I - Ionospheric slant range correction for the L1 frequency [s] Author: <NAME> References: <NAME>., (1996) "Ionosphercic Effects on GPS", in Parkinson, Spilker (ed), "Global Positioning System Theory and Applications, pp. 513-514. ICD-GPS-200, Rev. C, (1997), pp. 125-128 NATO, (1991), "Technical Characteristics of the NAVSTAR GPS", pp. A-6-31 - A-6-33 """ # Semicircles, latitude, and longitude GPS_Rcv = np.array([0.0, 0.0, 0.0]) GPS_Rcv[0], GPS_Rcv[1], GPS_Rcv[2] = pm.ecef2geodetic(r_pos[0], r_pos[1], r_pos[2]) Lat = GPS_Rcv[0] / 180.0 Lon = GPS_Rcv[1] / 180.0 S = pos_sv.shape m = S[0] A0, El, dist = pm.ecef2aer(pos_sv[:, 0], pos_sv[:, 1], pos_sv[:, 2], GPS_Rcv[0], GPS_Rcv[1], GPS_Rcv[2]) # Semicircle elevation E = El / 180.0 # Semicircle azimuth A = A0 / 180.0 * np.pi # Calculate the earth-centered angle, Psi (semicircle) Psi = 0.0137 / (E + 0.11) - 0.022 # Compute the subionospheric latitude, Phi_L (semicircle) Phi_L = Lat + Psi * np.cos(A) Phi_L = np.clip(Phi_L, -0.416, 0.416) # Compute the subionospheric longitude, Lambda_L (semicircle) Lambda_L = Lon + (Psi * np.sin(A) / np.cos(Phi_L * np.pi)) # Find the geomagnetic latitude, Phi_m, of the subionospheric location # looking towards each GPS satellite: Phi_m = Phi_L + 0.064 * np.cos((Lambda_L - 1.617) * np.pi) # Find the local time, t, at the subionospheric point t = 4.23e4 * Lambda_L + gps_time # GPS_Time [s] for i in range(t.shape[0]): if t[i] > 86400: t[i] = t[i] - 86400.0 elif t[i] < 0: t[i] = t[i] + 86400.0 # Convert slant time delay, compute the slant factor, F F = 1.0 + 16.0 * (0.53 - E)**3 # Compute the ionospheric time delay T_iono by first computing x Per = beta[0] + beta[1] * Phi_m + beta[2] * Phi_m**2 + beta[3] * Phi_m**3 Per = np.clip(Per, 72000, None) # Period x = 2.0 * np.pi * (t - 50400.0) / Per # [rad] AMP = alpha[0] + alpha[1] * Phi_m + alpha[2] * Phi_m**2 + alpha[3] \ * Phi_m**3 AMP = np.clip(AMP, 0, None) T_iono = np.empty(m) for i in range(m): if np.abs(x[i]) > 1.57: T_iono[i] = F[i] * 5e-9 else: T_iono[i] = F[i] * (5e-9 + AMP[i] * (1.0 - x[i]**2 / 2.0 + x[i]**4 / 24)) return T_iono def ionospheric_tsui(elevation, azimuth, latitude, longitude, gps_time, alpha, beta): """Additional ionospheric delay time. Compute an ionospheric range correction for the GPS L1 frequency from the parameters broadcasted in the GPS navigation message. Inputs: elevation - Elevation angle between user and satellite [semicircles] azimuth - Azimuth angle between user and satellite, measured clockwise positive from true North [semicircles] latitude - User geodetic latitude [semicircle] longitude - User geodetic longitude [semicircle] gps_time - System time [s] alpha - Coefficients of a cubic equation representing the amplitude of the vertical delay (4 coefficients) beta - Coefficients of a cubic equation representing the period of the model (4 coefficients) Output: T_iono - Additional ionospheric dealy time estimate [s] Author: <NAME> Reference: Tsui, <NAME>. Fundamentals of global positioning system receivers: a software approach. Vol. 173. <NAME> & Sons, 2005. """ # Central angle [semicircle] (typos in the book) psi = 0.0137 / (elevation + 0.11) - 0.022 # Geomagnetic latitude[semicircle] phi_i = latitude + psi * np.cos(azimuth * np.pi) if phi_i > 0.416: phi_i = 0.416 elif phi_i < -0.416: phi_i = -0.416 # Geomagnetic latitude [semicircle] (typo in the book) lambda_i = longitude + psi * np.sin(azimuth*np.pi) /
np.cos(phi_i*np.pi)
numpy.cos
import random as aleas import matplotlib.pyplot as plt from scipy.signal import freqz import numpy as np """ random : pour generer des nombres aleatoires matplotlib.pyplot : pour generer des graphiques et gerer leur construction scipy.signal : pour avoir le TF de l'autocorrelation numpy : pour implementer les moyennes et les covariances """ #On commence par générer n données n=1536 # Sequences des parametres des 3 modeles AR du second ordre a=[ [1,-0.1344,0.9025], # coefficients du premier processus AR [1,-1.6674,0.9025], # Ccoefficients du second processus AR [1, 1.7820,0.8100] # coefficients du troisieme processus AR ] """ On génère une série temporelle (non-stationnaire globalement), et composée de 3 blocs stationnaires. Ensuite, on juxtapose les 3 blocs de largeur n/3 chacun. Ensuite, on trace la série globale. """ t=range(-2,n-1) y=[k*0 for k in t] for k in range(1,int(n/3)): y[k+1]=-a[0][1]*y[k]-a[0][2]*y[k-1]+aleas.gauss(0,1) for k in range(int(n/3)+1,2*int(n/3)): y[k+1]=-a[1][1]*y[k]-a[1][2]*y[k-1]+aleas.gauss(0,1) for k in range(2*int(n/3)+1,n): y[k+1]=-a[2][1]*y[k]-a[2][2]*y[k-1]+aleas.gauss(0,1) y=y[3:] # suppression des donnees transitoires t=t[3:] # Trace- de la serie plt.plot(t,y) plt.title("Data = juxtapososition de 3 sous-series stationnaires") plt.show() """" On utilise freqz pour calculer et tracer les spectres des trois sous-series. Puisqu'on connaît les coefficients, le calcul se fait directement à partir des coefficients et ne dépend donc pas du nombre d'échantillons. """ def spectre(*args): Np = 256 # nombre de points du spectre f=freqz(1,args[0],Np)[0] # recuperer les echantillons de frequences (abscisses) mag=[] # hauteurs des frequences observables correspondantes (ordonnees) for arg in args: mag.append(abs(freqz(1,arg,Np)[1])) # calcul du spectre de chaque sous-serie return (f,mag) f,mag=spectre(a[0],a[1],a[2]) ## Calcul des spectres des trois sous-series plt.semilogy( f,mag[0],'-g', f,mag[1],':b', f,mag[2],'--r' ) ## Traces des spectres des trois sous-series plt.show() """ On choisit de décrire y par un modèle AR d'ordre 3, puis d'ordre 4. """ # Estimation des coefficients des modeles AR d-ordres 3 et 4 def AR_model(debut, fin, serie, vrai_spectre): """ : parametre debut : debut de l'intervalle : parametre fin : fin de l'intervalle : parametre serie : nom de la serie à modéliser : parametre vrai_spectre : vrai spectre à comparer aux résultats : type debut : int : type fin : int : type serie : string : type vrai_spectre : spectre : return : la serie temporelle et la comparaison entre les spectres : type return : plt.show """ D = np.cov([ y[debut : fin] + [0, 0, 0, 0], [0] + y[debut : fin] + [0, 0, 0], [0, 0] + y[debut : fin] + [0, 0], [0, 0, 0] + y[debut : fin] + [0], [0, 0, 0, 0] + y[debut : fin]]) E = - np.linalg.inv(D[0:4, 0:4]) @ D[0, 1:5].reshape(4, 1) # car on veut l'avoir à l'ordre 4 H = - np.linalg.inv(D[0:3, 0:3]) @ D[0, 1:4].reshape(3, 1) # car on veut l'avoir à l'ordre 3 E1 = np.append([1], E) # vecteur de coefficients incluant a0(ordre 4) H1 =
np.append([1], H)
numpy.append
import sys from typing import Any import numpy as np class Index: def __index__(self) -> int: return 0 class SubClass(np.ndarray): pass def func(i: int, j: int, **kwargs: Any) -> SubClass: return B i8 = np.int64(1) A = np.array([1]) B = A.view(SubClass).copy() B_stack = np.array([[1], [1]]).view(SubClass) C = [1] if sys.version_info >= (3, 8): np.ndarray(Index()) np.ndarray([Index()]) np.array(1, dtype=float) np.array(1, copy=False)
np.array(1, order='F')
numpy.array
import numpy as np from scipy.stats import norm import pandas as pd import matplotlib.pyplot as plt # Function to estimate point of intersection of normal curves of two classes, at the point of intersection diff # is zero or a point where the difference changes it sign def intersection(f, g, x): d = f - g for i in range(len(d) - 1): if d[i] == 0. or d[i] * d[i + 1] < 0.: x_ = x[i] return x_ def FisherLDA(ds, s): row, col = ds.shape ds_0 = ds[ds[col-1] == 0].iloc[:, 0:-1].values ds_1 = ds[ds[col-1] == 1].iloc[:, 0:-1].values m0 = np.mean(ds_0, axis=0) m1 = np.mean(ds_1, axis=0) SW_0 = np.cov(np.transpose(ds_0)) SW_1 = np.cov(np.transpose(ds_1)) SW = SW_0 + SW_1 SW_inv =
np.linalg.inv(SW)
numpy.linalg.inv
# These are some graph learning functions implemented in UMAP, added here with modifications # for better speed and computational efficiency. # Originally implemented by <NAME> at https://github.com/lmcinnes/umap # License: BSD 3 clause # # For more information on the original UMAP implementation, please see: https://umap-learn.readthedocs.io/ # # BSD 3-Clause License # # Copyright (c) 2017, <NAME> # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import numpy as np from scipy.optimize import curve_fit from scipy.sparse import coo_matrix from sklearn.neighbors import KDTree from sklearn.neighbors import NearestNeighbors from topo.base import ann from topo.base import dists as dist from topo.spectral import _spectral, umap_layouts from topo.tpgraph import diffusion from topo.utils import umap_utils ts = umap_utils.ts csr_unique = umap_utils.csr_unique fast_knn_indices = umap_utils.fast_knn_indices optimize_layout_euclidean = umap_layouts.optimize_layout_euclidean optimize_layout_generic = umap_layouts.optimize_layout_generic optimize_layout_inverse = umap_layouts.optimize_layout_inverse try: import joblib except ImportError: # sklearn.externals.joblib is deprecated in 0.21, will be removed in 0.23. Try installing joblib. from sklearn.externals import joblib SMOOTH_K_TOLERANCE = 1e-5 MIN_K_DIST_SCALE = 1e-3 NPY_INFINITY = np.inf INT32_MIN = np.iinfo(np.int32).min + 1 INT32_MAX = np.iinfo(np.int32).max - 1 def fuzzy_simplicial_set_ann( X, n_neighbors=15, knn_indices=None, knn_dists=None, backend='hnswlib', metric='cosine', n_jobs=None, efC=50, efS=50, M=15, set_op_mix_ratio=1.0, local_connectivity=1.0, apply_set_operations=True, return_dists=False, verbose=False): """Given a set of data X, a neighborhood size, and a measure of distance compute the fuzzy simplicial set (here represented as a fuzzy graph in the form of a sparse matrix) associated to the data. This is done by locally approximating geodesic distance at each point, creating a fuzzy simplicial set for each such point, and then combining all the local fuzzy simplicial sets into a global one via a fuzzy union. Parameters ---------- X : array of shape (n_samples, n_features). The data to be modelled as a fuzzy simplicial set. n_neighbors : int. The number of neighbors to use to approximate geodesic distance. Larger numbers induce more global estimates of the manifold that can miss finer detail, while smaller values will focus on fine manifold structure to the detriment of the larger picture. backend : str (optional, default 'hnwslib'). Which backend to use to compute nearest-neighbors. Options for fast, approximate nearest-neighbors are 'hnwslib' (default) and 'nmslib'. For exact nearest-neighbors, use 'sklearn'. metric : str (optional, default 'cosine'). Distance metric for building an approximate kNN graph. Defaults to 'cosine'. Users are encouraged to explore different metrics, such as 'euclidean' and 'inner_product'. The 'hamming' and 'jaccard' distances are also available for string vectors. Accepted metrics include NMSLib*, HNSWlib** and sklearn metrics. Some examples are: -'sqeuclidean' (*, **) -'euclidean' (*, **) -'l1' (*) -'lp' - requires setting the parameter ``p`` (*) - similar to Minkowski -'cosine' (*, **) -'inner_product' (**) -'angular' (*) -'negdotprod' (*) -'levenshtein' (*) -'hamming' (*) -'jaccard' (*) -'jansen-shan' (*). n_jobs : int (optional, default 1). number of threads to be used in computation. Defaults to 1. The algorithm is highly scalable to multi-threading. M : int (optional, default 30). defines the maximum number of neighbors in the zero and above-zero layers during HSNW (Hierarchical Navigable Small World Graph). However, the actual default maximum number of neighbors for the zero layer is 2*M. A reasonable range for this parameter is 5-100. For more information on HSNW, please check https://arxiv.org/abs/1603.09320. HSNW is implemented in python via NMSlib. Please check more about NMSlib at https://github.com/nmslib/nmslib. efC : int (optional, default 100). A 'hnsw' parameter. Increasing this value improves the quality of a constructed graph and leads to higher accuracy of search. However this also leads to longer indexing times. A reasonable range for this parameter is 50-2000. efS : int (optional, default 100). A 'hnsw' parameter. Similarly to efC, increasing this value improves recall at the expense of longer retrieval time. A reasonable range for this parameter is 50-2000. knn_indices : array of shape (n_samples, n_neighbors) (optional). If the k-nearest neighbors of each point has already been calculated you can pass them in here to save computation time. This should be an array with the indices of the k-nearest neighbors as a row for each data point. knn_dists : array of shape (n_samples, n_neighbors) (optional). If the k-nearest neighbors of each point has already been calculated you can pass them in here to save computation time. This should be an array with the distances of the k-nearest neighbors as a row for each data point. set_op_mix_ratio : float (optional, default 1.0). Interpolate between (fuzzy) union and intersection as the set operation used to combine local fuzzy simplicial sets to obtain a global fuzzy simplicial sets. Both fuzzy set operations use the product t-norm. The value of this parameter should be between 0.0 and 1.0; a value of 1.0 will use a pure fuzzy union, while 0.0 will use a pure fuzzy intersection. local_connectivity : int (optional, default 1) The local connectivity required -- i.e. the number of nearest neighbors that should be assumed to be connected at a local level. The higher this value the more connected the manifold becomes locally. In practice this should be not more than the local intrinsic dimension of the manifold. verbose : bool (optional, default False) Whether to report information on the current progress of the algorithm. return_dists : bool or None (optional, default none) Whether to return the pairwise distance associated with each edge. Returns ------- fuzzy_simplicial_set : coo_matrix A fuzzy simplicial set represented as a sparse matrix. The (i, j) entry of the matrix represents the membership strength of the 1-simplex between the ith and jth sample points. """ if knn_indices is None or knn_dists is None: if verbose: print('Running fast approximate nearest neighbors with NMSLIB using HNSW...') if metric not in ['sqeuclidean', 'euclidean', 'l1', 'cosine', 'angular', 'negdotprod', 'levenshtein', 'hamming', 'jaccard', 'jansen-shan']: print('Please input a metric compatible with NMSLIB when use_nmslib is set to True') knn_indices, knn_dists = approximate_n_neighbors(X, n_neighbors=n_neighbors, metric=metric, backend=backend, n_jobs=n_jobs, efC=efC, efS=efS, M=M, verbose=verbose) knn_dists = knn_dists.astype(np.float32) knn_dists = knn_dists sigmas, rhos = smooth_knn_dist( knn_dists, float(n_neighbors), local_connectivity=float(local_connectivity), ) rows, cols, vals = compute_membership_strengths( knn_indices, knn_dists, sigmas, rhos ) result = coo_matrix( (vals, (rows, cols)), shape=(X.shape[0], X.shape[0]) ) result.eliminate_zeros() if apply_set_operations: transpose = result.transpose() prod_matrix = result.multiply(transpose) result = ( set_op_mix_ratio * (result + transpose - prod_matrix) + (1.0 - set_op_mix_ratio) * prod_matrix ) result.eliminate_zeros() if return_dists: return result, sigmas, rhos, knn_dists else: return result, sigmas, rhos def compute_diff_connectivities( data, n_components=100, n_neighbors=30, alpha=0.0, n_jobs=10, ann=True, ann_dist='cosine', M=30, efC=100, efS=100, knn_dist='euclidean', kernel_use='simple_adaptive', sensitivity=1, set_op_mix_ratio=1.0, local_connectivity=1.0, verbose=False ): """ Sklearn estimator for using fast anisotropic diffusion with an anisotropic adaptive algorithm as proposed by Setty et al, 2018, and optimized by Sidarta-Oliveira, 2020. This procedure generates diffusion components that effectivelly carry the maximum amount of information regarding the data geometric structure (structure components). These structure components then undergo a fuzzy-union of simplicial sets. This step is from umap.fuzzy_simplicial_set [McInnes18]_. Given a set of data X, a neighborhood size, and a measure of distance compute the fuzzy simplicial set (here represented as a fuzzy graph in the form of a sparse matrix) associated to the data. This is done by locally approximating geodesic distance at each point, creating a fuzzy simplicial set for each such point, and then combining all the local fuzzy simplicial sets into a global one via a fuzzy union. Parameters ---------- n_components : Number of diffusion components to compute. Defaults to 100. We suggest larger values if analyzing more than 10,000 cells. n_neighbors : Number of k-nearest-neighbors to compute. The adaptive kernel will normalize distances by each cell distance of its median neighbor. knn_dist : Distance metric for building kNN graph. Defaults to 'euclidean'. ann : Boolean. Whether to use approximate nearest neighbors for graph construction. Defaults to True. alpha : Alpha in the diffusion maps literature. Controls how much the results are biased by data distribution. Defaults to 1, which is suitable for normalized data. n_jobs : Number of threads to use in calculations. Defaults to all but one. sensitivity : Sensitivity to select eigenvectors if diff_normalization is set to 'knee'. Useful when dealing wit :returns: Diffusion components ['EigenVectors'], associated eigenvalues ['EigenValues'] and suggested number of resulting components to use during Multiscaling. Example ------------- import numpy as np from sklearn.datasets import load_digits from scipy.sparse import csr_matrix from topo.tpgraph.diffusion import Diffusor # Load the MNIST digits data, convert to sparse for speed digits = load_digits() data = csr_matrix(digits) # Fit the anisotropic diffusion process tpgraph = Diffusor().fit(data) # Find multiscale diffusion components mds = tpgraph.transform(data) """ from scipy.sparse import csr_matrix, issparse if issparse(data) == True: if verbose: print('Sparse input. Proceding without converting...') if isinstance(data, np.ndarray): data = csr_matrix(data) if issparse(data) == False: if verbose: print('Converting input to sparse...') import pandas as pd if isinstance(data, pd.DataFrame): data = csr_matrix(data.values.T) elif isinstance(data, np.ndarray): data = data diff = diffusion.Diffusor( n_components=n_components, n_neighbors=n_neighbors, alpha=alpha, n_jobs=n_jobs, ann=ann, ann_dist=ann_dist, M=M, efC=efC, efS=efS, knn_dist=knn_dist, kernel_use=kernel_use, sensitivity=sensitivity).fit(data) knn_indices, knn_distances, knn_grad, knn_graph = diff.ind_dist_grad(data, dense=False) if not issparse(knn_graph): knn_graph = csr_matrix(knn_graph) distances, connectivities, sigmas, rhos = fuzzy_simplicial_set_ann( knn_graph, n_neighbors, knn_indices=knn_indices, knn_dists=knn_distances, nmslib_metric=ann_dist, set_op_mix_ratio=set_op_mix_ratio, local_connectivity=local_connectivity, verbose=verbose ) if isinstance(connectivities, tuple): # In umap-learn 0.4, this returns (result, sigmas, rhos) connectivities = connectivities[0] if issparse(connectivities): if isinstance(connectivities, np.ndarray): connectivities = csr_matrix(connectivities) else: connectivities = connectivities.tocsr() return knn_graph, connectivities def get_sparse_matrix_from_indices_distances_dbmap(knn_indices, knn_dists, n_obs, n_neighbors): rows = np.zeros((n_obs * n_neighbors), dtype=np.int64) cols = np.zeros((n_obs * n_neighbors), dtype=np.int64) vals = np.zeros((n_obs * n_neighbors), dtype=np.float64) for i in range(knn_indices.shape[0]): for j in range(n_neighbors): if knn_indices[i, j] == -1: continue # We didn't get the full knn for i if knn_indices[i, j] == i: val = 0.0 else: val = knn_dists[i, j] rows[i * n_neighbors + j] = i cols[i * n_neighbors + j] = knn_indices[i, j] vals[i * n_neighbors + j] = val result = coo_matrix((vals, (rows, cols)), shape=(n_obs, n_obs)) result.eliminate_zeros() return result.tocsr() def approximate_n_neighbors(data, n_neighbors=15, metric='cosine', backend='hnswlib', n_jobs=10, efC=50, efS=50, M=15, p=11/16, dense=False, verbose=False ): """ Simple function using NMSlibTransformer from topodata.ann. This implements a very fast and scalable approximate k-nearest-neighbors graph on spaces defined by nmslib. Read more about nmslib and its various available metrics at https://github.com/nmslib/nmslib. Read more about dbMAP at https://github.com/davisidarta/dbMAP. Parameters ---------- n_neighbors : number of nearest-neighbors to look for. In practice, this should be considered the average neighborhood size and thus vary depending on your number of features, samples and data intrinsic dimensionality. Reasonable values range from 5 to 100. Smaller values tend to lead to increased graph structure resolution, but users should beware that a too low value may render granulated and vaguely defined neighborhoods that arise as an artifact of downsampling. Defaults to 15. Larger values can slightly increase computational time. backend : str (optional, default 'hnwslib') Which backend to use to compute nearest-neighbors. Options for fast, approximate nearest-neighbors are 'hnwslib' (default) and 'nmslib'. For exact nearest-neighbors, use 'sklearn'. metric : str (optional, default 'cosine') Distance metric for building an approximate kNN graph. Defaults to 'cosine'. Users are encouraged to explore different metrics, such as 'euclidean' and 'inner_product'. The 'hamming' and 'jaccard' distances are also available for string vectors. Accepted metrics include NMSLib*, HNSWlib** and sklearn metrics. Some examples are: -'sqeuclidean' (*, **) -'euclidean' (*, **) -'l1' (*) -'lp' - requires setting the parameter ``p`` (*) - similar to Minkowski -'cosine' (*, **) -'inner_product' (**) -'angular' (*) -'negdotprod' (*) -'levenshtein' (*) -'hamming' (*) -'jaccard' (*) -'jansen-shan' (*) p : int or float (optional, default 11/16 ) P for the Lp metric, when ``metric='lp'``. Can be fractional. The default 11/16 approximates an astroid norm with some computational efficiency (2^n bases are less painstakinly slow to compute). See https://en.wikipedia.org/wiki/Lp_space for some context. n_jobs : number of threads to be used in computation. Defaults to 10 (~5 cores). efC : increasing this value improves the quality of a constructed graph and leads to higher accuracy of search. However this also leads to longer indexing times. A reasonable range is 100-2000. Defaults to 100. efS : similarly to efC, improving this value improves recall at the expense of longer retrieval time. A reasonable range is 100-2000. M : defines the maximum number of neighbors in the zero and above-zero layers during HSNW (Hierarchical Navigable Small World Graph). However, the actual default maximum number of neighbors for the zero layer is 2*M. For more information on HSNW, please check https://arxiv.org/abs/1603.09320. HSNW is implemented in python via NMSLIB. Please check more about NMSLIB at https://github.com/nmslib/nmslib . Returns ------------- k-nearest-neighbors indices and distances. Can be customized to also return return the k-nearest-neighbors graph and its gradient. Example ------------- knn_indices, knn_dists = approximate_n_neighbors(data) """ if backend == 'hnswlib' and metric not in ['euclidean', 'sqeuclidean', 'cosine', 'inner_product']: if verbose: print('Metric ' + str( metric) + ' not compatible with \'hnslib\' backend. Changing to \'nmslib\' backend.') backend = 'nmslib' if backend == 'nmslib': # Construct an approximate k-nearest-neighbors graph anbrs = ann.NMSlibTransformer(n_neighbors=n_neighbors, metric=metric, p=p, method='hnsw', n_jobs=n_jobs, M=M, efC=efC, efS=efS, dense=dense, verbose=verbose).fit(data) knn_inds, knn_distances, grad, knn_graph = anbrs.ind_dist_grad(data) elif backend == 'hnwslib': anbrs = ann.HNSWlibTransformer(n_neighbors=n_neighbors, metric=metric, n_jobs=n_jobs, M=M, efC=efC, efS=efS, verbose=verbose).fit(data) knn_inds, knn_distances, grad, knn_graph = anbrs.ind_dist_grad(data) else: # Construct a k-nearest-neighbors graph nbrs = NearestNeighbors(n_neighbors=int(n_neighbors), metric=metric, n_jobs=n_jobs).fit( data) knn_distances, knn_inds = nbrs.kneighbors(data) return knn_inds, knn_distances def compute_membership_strengths(knn_indices, knn_dists, sigmas, rhos): """Construct the membership strength data for the 1-skeleton of each local fuzzy simplicial set -- this is formed as a sparse matrix where each row is a local fuzzy simplicial set, with a membership strength for the 1-simplex to each other data point. Parameters ---------- knn_indices: array of shape (n_samples, n_neighbors) The indices on the ``n_neighbors`` closest points in the dataset. knn_dists: array of shape (n_samples, n_neighbors) The distances to the ``n_neighbors`` closest points in the dataset. sigmas: array of shape(n_samples) The normalization factor derived from the metric tensor approximation. rhos: array of shape(n_samples) The local connectivity adjustment. Returns ------- rows: array of shape (n_samples * n_neighbors) Row data for the resulting sparse matrix (coo format) cols: array of shape (n_samples * n_neighbors) Column data for the resulting sparse matrix (coo format) vals: array of shape (n_samples * n_neighbors) Entries for the resulting sparse matrix (coo format) """ n_samples = knn_indices.shape[0] n_neighbors = knn_indices.shape[1] rows = np.zeros(knn_indices.size, dtype=np.int32) cols = np.zeros(knn_indices.size, dtype=np.int32) vals =
np.zeros(knn_indices.size, dtype=np.float32)
numpy.zeros
#!/usr/bin/env python import numpy as np def bezier(t, p0, p1, p2, p3): return p0 * (1 - t) ** 3 \ + 3 * p1 * t * (1 - t) ** 2 \ + 3 * p2 * t ** 2 * (1 - t) \ + p3 * t ** 3 def angle_deg(a1, a2): return np.mod(a1 + a2 + 3*180.0, 360) - 180 def angle_rad(a1, a2): return np.mod(a1 + a2 + 3*np.pi, 2*np.pi) - np.pi def homothetie_vec(vec, theta, x, y): # Rotation matrix R = np.array([[np.cos(theta), -np.sin(theta), x], [
np.sin(theta)
numpy.sin
import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import os from collections import deque import numpy as np import SimpleITK as sitk from net import Network class Subject(object): def __init__(self, file): self.file = file self.segm_file = self.file[:-4] + '_segm.vtk' self.sitk_img = sitk.ReadImage(file) self.img = sitk.GetArrayFromImage(self.sitk_img) self.img = self.img / np.max(self.img) self.img = self.img[self.img.shape[0]//2:self.img.shape[0]//2+1] if os.path.isfile(self.segm_file): img = sitk.ReadImage(self.segm_file) self.segm = sitk.GetArrayFromImage(img) else: self.segm = None def save(self): pass #img = sitk.GetImageFromArray(self.segm) #img.CopyInformation(self.sitk_img) #sitk.WriteImage(img, self.segm_file) class SubjectView(object): def __init__(self, subject): self.subject = subject self.initialize() def initialize(self): self.slices = [] self.segms = [] img = self.subject.img segm = self.subject.segm shape = img.shape img_max = np.max(img) for z in range(shape[0]): qi = QImage((255*img[z]/img_max).astype(np.uint8), shape[2], shape[1], shape[2], QImage.Format_Grayscale8) self.slices.append(qi) qi = QImage(segm[z].astype(np.uint8), shape[2], shape[1], shape[2], QImage.Format_Alpha8) self.segms.append(qi) def save(self): """ Write changes (in QImage) to numpy array """ shape = self.subject.img.shape for z in range(shape[0]): segm = self.segms[z] # Seems like we cant trust that QImage.bytesPerLine() == BPP*QImage.width() # so we'll need to copy line by line for y in range(segm.height()): b = segm.constScanLine(y) b.setsize(segm.width()) self.subject.segm[z,y] = np.array(b) self.subject.save() def clear(self): """ Clears the segmentation completely """ self.subject.segm = np.zeros(self.subject.segm.shape, dtype=np.uint8) self.initialize() class DataLoader(object): def __init__(self, files, buffer_size=30): self.files = files self.next_idx = 0 self.buffer = deque(maxlen=buffer_size) def next(self): if self.next_idx >= len(self.files): return f = self.files[self.next_idx] self.next_idx += 1 subject = Subject(f) self.buffer.append(subject) return subject class App(QWidget): DRAW_NONE = 0 DRAW_ADD = 1 DRAW_REMOVE = 2 def __init__(self, files): super().__init__() self.network = Network() self.loader = DataLoader(files) self.subject_view = None self.num_trained = 0 self.previous = [] self.draw_mode = App.DRAW_NONE self.setGeometry(100, 100, 500, 500) self.path = None self.next() def next(self): self.save() subject = self.loader.next() if not subject: return if subject.segm is None: if self.num_trained < 1: subject.segm = np.zeros(subject.img.shape, dtype=np.uint8) else: subject.segm = (255*self.network.predict(subject.img)).astype(np.uint8) self.subject_view = SubjectView(subject) self.slice_index = len(self.subject_view.slices)//2 self.update() def save(self): if not self.subject_view: return self.subject_view.save() subject = self.subject_view.subject amax = np.max(subject.segm.reshape(subject.segm.shape[0], -1), axis=1) ids =
np.where(amax > 0)
numpy.where
""" .. role:: bash(code) :language: bash This is the test module for the SNR evaluation of the reconstructed signal. |br| It tests the SNR evaluator with the number of test cases, and analyzes the results. In every case random multitone signals are generated with a specified level of noise. The Random Multitone Signal Generator is used to generate the signals. The non noisy signal from the generator is treated as the orignal signal, the noisy signal is treated as the reconstructed signal. |br| The following tests are performed on the results of evaluation: - if the measured level of noise for every signal is correct? - if the measured average level of noise is correct? - if the measured success ratio of the reconsteruction is correct? To start the test run this module directly as a script: :bash:`$ python SNR_test.py` when in *rxcs/test/analysis* directory. The results are then printed to the console. |br| *Author*: <NAME>, Aalborg University, Denmark. <<EMAIL>> *Version*: 0.1 | 20-MAY-2014 : * Initial version. |br| 0.2 | 21-MAY-2014 : * Success Ratio check added. |br| 0.3 | 21-MAY-2014 : * Docstrings added. |br| 0.4 | 21-MAY-2014 : * UUT now configured with a dicionary. |br| 1.0 | 21-MAY-2014 : * Version 1.0 released. |br| 2.0 | 21-AUG-2015 : * Adjusted to SNR analysis v2.0 (objectified) |br| *License*: BSD 2-Clause """ from __future__ import division import numpy as np import rxcs # ===================================================================== # Main function of the test # ===================================================================== def _SNR_test(): """ This is main function of the test. It runs the test case functions. An info that a test was passed is printed to the console if a case function returns. Args: None Returns: Nothing """ # Print out the header of the signal generator test print('') rxcs.console.progress('Function under test', 'SNR evaluation of the reconstructed signal') # ----------------------------------------------------------------- # Tests start here: # Tolerance of expected vs measured is 0.1% iTolerance = 0.1 * 1e-2 _TestCase1(iTolerance) rxcs.console.info('case 1 OK!') _TestCase2(iTolerance) rxcs.console.info('case 2 OK!') _TestCase3(iTolerance) rxcs.console.info('case 3 OK!') _TestCase4(iTolerance) rxcs.console.info('case 4 OK!') _TestCase5(iTolerance) rxcs.console.info('case 5 OK!') # ===================================================================== # Test case 1 # ===================================================================== def _TestCase1(iTolerance): """ This is test case function #1. |br| The function sets up the configuration dictionary for the Random Multitone Signal Generator and runs the engine of the test. Args: iTolerance: maximum tolerance of a difference between an expected value and a real value Returns: Nothing """ # Put the generator on board gen = rxcs.sig.randMult() gen.tS = 1e-3 # Time of the signal is 1 ms gen.fR = 2e4 # The signal representation sampling frequency is 20 kHz gen.fMax = 8e3 # The highest possible frequency in the signal is 8 kHz gen.fRes = 1e3 # The signal spectrum resolution is 1 kHz gen.iSNR = 30 # Signal noise gen.iP = 2 # Signal power adjustments gen.vFrqs = np.array([2e3, np.nan, 4e3]) # Vector with given frequencies gen.vAmps = np.array([np.nan, 1, np.nan]) # Vector with given amplitudes gen.vPhs = np.array([np.nan, np.nan, 90]) # Vector with given phases # The number of random tones gen.nTones = 2 # Amplitude and phase parameters of ranimd tones: gen.iMinAmp = 0.1 # Minimum amplitude gen.iGraAmp = 0.1 # Gradation of amplitude gen.iMaxAmp = 1.0 # Maximum amplitude gen.iMinPhs = 0 # Minimum phase of additional tones gen.iGraPhs = 2 # Gradation of phase of additional tones gen.iMaxPhs = 90 # Maximum phase of additional tones gen.nSigs = int(1e5) # The number of signals to be generated gen.bMute = 1 # Mute the output from the gneerator # ----------------------------------------------------------------- # ENGINE OF THE TEST: # Generate signals with a given SNR, measure the SNR and check if # the measured value is correct _checkSNR(gen, iTolerance) return # ===================================================================== # Test case 2 # ===================================================================== def _TestCase2(iTolerance): """ This is test case function #2. |br| The function sets up the configuration dictionary for the Random Multitone Signal Generator and runs the engine of the test. Args: iTolerance: maximum tolerance of a difference between an expected value and a real value Returns: Nothing """ # Put the generator on board gen = rxcs.sig.randMult() gen.tS = 1e-1 # Time of the signal is 100 ms gen.fR = 1e6 # The signal representation sampling frequency is 1 MHz gen.fMax = 100e3 # The highest possible frequency in the signal is 100 kHz gen.fRes = 1e3 # The signal spectrum resolution is 1 kHz gen.iSNR = 100 # Signal noise gen.iP = 10 # Signal power adjustments gen.vFrqs = np.array([1e3]) # Vector with given frequencies gen.vAmps =
np.array([0.5])
numpy.array
#!/usr/bin/env python # # This code calculates LQR gains for a drone system whose reference signal is obtained # by differential flatness. The input to the system is the body frame thrust and body # frame angular velocities, and output is the world frame position, velocity and # angular position given by euler angles. # # For reference please see: # Differential Flatness Based Control of a Rotorcraft For Aggressive Maneuvers BYU ScholarsArchive Citation Differential Flatness Based Control of a Rotorcraft For # Aggressive Maneuvers, (September), 2688-2693. Retrieved from https://scholarsarchive.byu.edu/facpub%0Ahttps://scholarsarchive.byu.edu/facpub/1949 # # For a reference of the differential flatness proof for the drone dynamics refer # to: <NAME>., <NAME>. (2011). Minimum snap trajectory generation and control for quadrotors. Proceedings - IEEE International Conference on Robotics and # Automation, 2520-2525. https://doi.org/10.1109/ICRA.2011.5980409 # # And this paper for important corrections on the demostration done in the previous paper: # <NAME>., <NAME>., & <NAME>. (2017). Differential Flatness of Quadrotor Dynamics Subject to Rotor Drag for Accurate Tracking of High-Speed Trajectories. # https://doi.org/10.1109/LRA.2017.2776353 # # # The system is x2_dot = A*x_2 + B*u_2 # # x2 = [x,y,z,v_x,v_y,v_z,phi,theta,psi].T # # u_2 =[u_2a, u_2b].T # # A = [[0_3x3, I_3x3, 0_3x3], # [0_3x3, 0_3x3, 0_3x3], # [0_3x3, 0_3x3, 0_3x3]] # # B = [[0_3x3, 0_3x3], # [I_3x3, 0_3x3], # [0_3x3, I_3x3]] # # The dynamics of this system can be divided as follows, which eases computation and allows # use of the python control library. # __ # [x_dot ] = [0 1][ x ] + [0][u_2a_x] | # [v_x_dot] [0 0][v_x] [1] | # | # [y_dot ] = [0 1][ y ] + [0][u_2a_y] | # [v_y_dot] [0 0][v_y] [1] |---- translation dynamics # | # [z_dot ] = [0 1][ z ] + [0][u_2a_z] | # [v_z_dot] [0 0][v_z] [1] | # __| # # __ # [phi_dot ] = [0][phi] + [0][u_2b_x] | # | # [theta_dot ] = [0][theta] + [0][u_2b_y] |---- rotational dynamics # | # [psi_dot ] = [0][psi] + [0][u_2b_z] | # __| # # System division that we use to compute constants in a simpler manner. import rl_quad.conventional_control as ctl print(ctl) import numpy as np # In general u = Nu*r - K(x -Nx*r) = -K*x + (Nu + K*Nx)*r # where K are the LQR gains, Nu and Nx are reference input matrices. # See more at p.493 "Feedback Control of Dynamic Systems, <NAME>, # Powell, <NAME>, Abbas" # This method calculates Nu and Nx matrices for given A,B,C,D matrices. def getInputMatrices(A_,B_,C_,D_): aug1 = np.concatenate((A_,B_), axis = 1) aug2 = np.concatenate((C_,D_), axis = 1) # create [[A,B],[C,D]] matrix inp = np.concatenate((aug1,aug2), axis = 0) #print(inp) # create multiplying matrix mult = np.zeros((inp.shape[0],1)) mult[mult.shape[0]-1] = 1.0 # compute inv(inp)*mult inp = np.linalg.inv(inp)*mult # nx is all values but last, nu is simply last value n_x = inp[0:(inp.shape[0]-1)] n_u = inp[-1] return n_u, n_x # Q should be nxn diagonal np.array, where n is dim(A). Diagonal elements should be # the output performance weights # R should be mxm np.array where m is dim(B). The diagonal values should be input # effort weights. # # Example: # output performance matrix for translation variables # Qt = np.diag([100.0,1.0]) # input effort matrix for translation variables # Rt = np.array([1.0]) def calculate_LQR_gains(A,B,C,D,Q,R): # calculate LQR gains (K, X, E) = ctl.lqr(A, B, Q, R) # calculate Nu, Nx matrices for including reference input Nu, Nx = getInputMatrices(A,B,C,D) return K, Nu, Nx # Calculate the gain matrix K required for the poles of a system # x_dot = Ax + Bu, with u = -Kx # to be equal to the pole array passed in the argument dp. # dp is an np.array 1xm where m is dim(A) # # For the system to be stable, all elements in dp should be < 0 def calculate_pp_gains(A,B,C,D,dp): # pole placement via ackermann's formula K = ctl.acker(A,B,dp) # calculate Nu, Nx matrices for including reference input Nu, Nx = getInputMatrices(A,B,C,D) return K, Nu, Nx # define system matrix for translation variables # (It is the result of linearization with computer-torque method) At = np.matrix( [[0.0,1.0], [0.0,0.0]]) # input matrices Bt = np.matrix( [[0.0], [1.0]]) # output matrices Ct = np.matrix([1.0,0.0]) #np.matrix() # system matrix for rotational variables Ar =
np.matrix([0.0])
numpy.matrix
import random from collections import namedtuple, deque, Iterable import numpy as np import torch Experience = namedtuple("Experience", field_names=["state", "action", "reward", "next_state", "done", "action_prob", "user_value"]) class ReplayBuffer: """Fixed-size buffer to store experience tuples.""" def __init__(self, action_size, buffer_size, batch_size, device): """Initialize a ReplayBuffer object. Params ====== action_size (int): dimension of each action buffer_size (int): maximum size of buffer batch_size (int): size of each training batch """ self.action_size = action_size self.memory = deque(maxlen=buffer_size) self.batch_size = batch_size self.device = device def add(self, state, action, reward, next_state, done, action_prob=0.0, user_value=0.0): """Add a new experience to memory.""" e = Experience(np.expand_dims(state, 0), action, reward,
np.expand_dims(next_state, 0)
numpy.expand_dims
"""Tests for ExtendedNonlocalGame class.""" import unittest import numpy as np from toqito.states import basis from toqito.nonlocal_games.extended_nonlocal_game import ExtendedNonlocalGame class TestExtendedNonlocalGame(unittest.TestCase): """Unit test for ExtendedNonlocalGame.""" @staticmethod def bb84_extended_nonlocal_game(): """Define the BB84 extended nonlocal game.""" e_0, e_1 = basis(2, 0), basis(2, 1) e_p = (e_0 + e_1) / np.sqrt(2) e_m = (e_0 - e_1) / np.sqrt(2) dim = 2 num_alice_out, num_bob_out = 2, 2 num_alice_in, num_bob_in = 2, 2 pred_mat = np.zeros([dim, dim, num_alice_out, num_bob_out, num_alice_in, num_bob_in]) pred_mat[:, :, 0, 0, 0, 0] = e_0 * e_0.conj().T pred_mat[:, :, 0, 0, 1, 1] = e_p * e_p.conj().T pred_mat[:, :, 1, 1, 0, 0] = e_1 * e_1.conj().T pred_mat[:, :, 1, 1, 1, 1] = e_m * e_m.conj().T prob_mat = 1 / 2 * np.identity(2) return prob_mat, pred_mat @staticmethod def chsh_extended_nonlocal_game(): """Define the CHSH extended nonlocal game.""" dim = 2 num_alice_out, num_bob_out = 2, 2 num_alice_in, num_bob_in = 2, 2 pred_mat = np.zeros([dim, dim, num_alice_out, num_bob_out, num_alice_in, num_bob_in]) pred_mat[:, :, 0, 0, 0, 0] = np.array([[1, 0], [0, 0]]) pred_mat[:, :, 0, 0, 0, 1] = np.array([[1, 0], [0, 0]]) pred_mat[:, :, 0, 0, 1, 0] = np.array([[1, 0], [0, 0]]) pred_mat[:, :, 1, 1, 0, 0] = np.array([[0, 0], [0, 1]]) pred_mat[:, :, 1, 1, 0, 1] = np.array([[0, 0], [0, 1]]) pred_mat[:, :, 1, 1, 1, 0] = np.array([[0, 0], [0, 1]]) pred_mat[:, :, 0, 1, 1, 1] = 1 / 2 * np.array([[1, 1], [1, 1]]) pred_mat[:, :, 1, 0, 1, 1] = 1 / 2 * np.array([[1, -1], [-1, 1]]) prob_mat = np.array([[1 / 4, 1 / 4], [1 / 4, 1 / 4]]) return prob_mat, pred_mat @staticmethod def moe_mub_4_in_3_out_game(): """Define the monogamy-of-entanglement game defined by MUBs.""" prob_mat = 1 / 4 * np.identity(4) dim = 3 e_0, e_1, e_2 = basis(dim, 0), basis(dim, 1), basis(dim, 2) eta = np.exp((2 * np.pi * 1j) / dim) mub_0 = [e_0, e_1, e_2] mub_1 = [ (e_0 + e_1 + e_2) / np.sqrt(3), (e_0 + eta ** 2 * e_1 + eta * e_2) / np.sqrt(3), (e_0 + eta * e_1 + eta ** 2 * e_2) / np.sqrt(3), ] mub_2 = [ (e_0 + e_1 + eta * e_2) / np.sqrt(3), (e_0 + eta ** 2 * e_1 + eta ** 2 * e_2) / np.sqrt(3), (e_0 + eta * e_1 + e_2) / np.sqrt(3), ] mub_3 = [ (e_0 + e_1 + eta ** 2 * e_2) / np.sqrt(3), (e_0 + eta ** 2 * e_1 + e_2) / np.sqrt(3), (e_0 + eta * e_1 + eta * e_2) / np.sqrt(3), ] # List of measurements defined from mutually unbiased basis. mubs = [mub_0, mub_1, mub_2, mub_3] num_in = 4 num_out = 3 pred_mat = np.zeros([dim, dim, num_out, num_out, num_in, num_in], dtype=complex) pred_mat[:, :, 0, 0, 0, 0] = mubs[0][0] * mubs[0][0].conj().T pred_mat[:, :, 1, 1, 0, 0] = mubs[0][1] * mubs[0][1].conj().T pred_mat[:, :, 2, 2, 0, 0] = mubs[0][2] * mubs[0][2].conj().T pred_mat[:, :, 0, 0, 1, 1] = mubs[1][0] * mubs[1][0].conj().T pred_mat[:, :, 1, 1, 1, 1] = mubs[1][1] * mubs[1][1].conj().T pred_mat[:, :, 2, 2, 1, 1] = mubs[1][2] * mubs[1][2].conj().T pred_mat[:, :, 0, 0, 2, 2] = mubs[2][0] * mubs[2][0].conj().T pred_mat[:, :, 1, 1, 2, 2] = mubs[2][1] * mubs[2][1].conj().T pred_mat[:, :, 2, 2, 2, 2] = mubs[2][2] * mubs[2][2].conj().T pred_mat[:, :, 0, 0, 3, 3] = mubs[3][0] * mubs[3][0].conj().T pred_mat[:, :, 1, 1, 3, 3] = mubs[3][1] * mubs[3][1].conj().T pred_mat[:, :, 2, 2, 3, 3] = mubs[3][2] * mubs[3][2].conj().T return prob_mat, pred_mat def test_bb84_unentangled_value(self): """Calculate the unentangled value of the BB84 game.""" prob_mat, pred_mat = self.bb84_extended_nonlocal_game() bb84 = ExtendedNonlocalGame(prob_mat, pred_mat) res = bb84.unentangled_value() expected_res = np.cos(np.pi / 8) ** 2 self.assertEqual(np.isclose(res, expected_res), True) def test_bb84_unentangled_value_rep_2(self): """Calculate the unentangled value for BB84 game for 2 repetitions.""" prob_mat, pred_mat = self.bb84_extended_nonlocal_game() bb84_2 = ExtendedNonlocalGame(prob_mat, pred_mat, 2) res = bb84_2.unentangled_value() expected_res = np.cos(np.pi / 8) ** 4 self.assertEqual(np.isclose(res, expected_res), True) def test_bb84_quantum_value_lower_bound(self): """Calculate the lower bound for the quantum value of theBB84 game.""" prob_mat, pred_mat = self.bb84_extended_nonlocal_game() bb84 = ExtendedNonlocalGame(prob_mat, pred_mat) res = bb84.quantum_value_lower_bound() expected_res = np.cos(np.pi / 8) ** 2 self.assertLessEqual(np.isclose(res, expected_res), True) def test_bb84_nonsignaling_value(self): """Calculate the non-signaling value of the BB84 game.""" prob_mat, pred_mat = self.bb84_extended_nonlocal_game() bb84 = ExtendedNonlocalGame(prob_mat, pred_mat) res = bb84.nonsignaling_value() expected_res = np.cos(np.pi / 8) ** 2 self.assertEqual(np.isclose(res, expected_res, rtol=1e-03), True) def test_bb84_nonsignaling_value_rep_2(self): """Calculate the non-signaling value of the BB84 game for 2 reps.""" prob_mat, pred_mat = self.bb84_extended_nonlocal_game() bb84 = ExtendedNonlocalGame(prob_mat, pred_mat, 2) res = bb84.nonsignaling_value() expected_res = 0.73826 self.assertEqual(np.isclose(res, expected_res, rtol=1e-03), True) def test_chsh_unentangled_value(self): """Calculate the unentangled value of the CHSH game.""" prob_mat, pred_mat = self.chsh_extended_nonlocal_game() chsh = ExtendedNonlocalGame(prob_mat, pred_mat) res = chsh.unentangled_value() expected_res = 3 / 4 self.assertEqual(np.isclose(res, expected_res), True) def test_moe_mub_4_in_3_out_unentangled_value(self): """ Calculate the unentangled value of a monogamy-of-entanglement game. """ prob_mat, pred_mat = self.moe_mub_4_in_3_out_game() moe = ExtendedNonlocalGame(prob_mat, pred_mat) res = moe.unentangled_value() expected_res = (3 + np.sqrt(5)) / 8 self.assertEqual(
np.isclose(res, expected_res)
numpy.isclose
# Author: <NAME> (<EMAIL>) # Original paper: <NAME>., & <NAME>. (2004). # # Support Vector Data Description. Machine Learning, 54(1), 45–66. https://doi.org/10.1023/B:MACH.0000008084.60811.49 import numpy as np from scipy.spatial.distance import cdist from scipy.linalg import cholesky, LinAlgError from cvxopt import matrix, solvers import matplotlib.pyplot as plt import matplotlib.cm as cm from sklearn.base import BaseEstimator, ClassifierMixin class SVDD(BaseEstimator, ClassifierMixin): '''Support Vector Data Descriptor.''' def __init__(self, kernel_type='rbf', bandwidth=1, order=2, fracrej=np.array([0.1, 1])): self.kernel_type = kernel_type self.bandwidth = bandwidth self.order = order self.fracrej = fracrej def _more_tags(self): return {'binary_only': True} def compute_kernel(self, X, Z): """ Compute kernel for given data set. Parameters ---------- X : array data set (N samples by D features) Z : array data set (M samples by D features) type : str type of kernel, options: 'linear', 'polynomial', 'rbf', 'sigmoid' (def: 'linear') order : float degree for the polynomial kernel (def: 2.0) bandwidth : float kernel bandwidth (def: 1.0) Returns ------- array kernel matrix (N by M) """ # Data shapes # N, DX = X.shape # Only RBF kernel is implemented if self.kernel_type != 'rbf': raise NotImplementedError('Kernel not implemented yet.') else: # Radial basis function kernel return np.exp(-cdist(X, Z, 'sqeuclidean') / (self.bandwidth ** 2)) # These kernels are not implemented yet # # Select type of kernel to compute # if self.kernel_type == 'linear': # # Linear kernel is data outer product # return np.dot(X, Z.T) # elif self.kernel_type == 'polynomial': # # Polynomial kernel is an exponentiated data outer product # return (np.dot(X, Z.T) + 1) ** self.order # elif self.kernel_type == 'sigmoid': # # Sigmoidal kernel # return 1. / (1 + np.exp(np.dot(X, Z.T))) def optimize_SVDD(self, X, y, c): # Solve (quadratic) SVDD program. # Maximize Lagrangian by minimizing negation: # a'.T @ K @ a' - diag(K).T @ a' (Eq. 2.28) # Subject to 0 <= a' <= C (Box constraints, Eq. 2.20) # 1.T a' = 1 (Equality constraint, Eq. 2.6 and 2.18) # where a' = y * a (Eq. 2.22) # CVXOPT has following format: # https://github.com/cvxopt/cvxopt/blob/cc46cbd0cea40cdb8c6e272d3e709c268cd38468/src/python/coneprog.py#L4156 # Minimize (1/2) x.T P x + q.T x # # Subject to G x <= h # A x = b # TODO: wait, I am not actually substituting a' in the box constraints # TODO: Is this valid!!??? # Therefore, box constraints are rewritten to: # -I a' <= 0 # I a' <= C # Where I is the identity matrix # CVXOPT does not accept integers y = np.double(y) K = self.compute_kernel(X, X) # self.K = K N = K.shape[0] # Incorporate labels y in kernel matrix to rewrite in standard form (again, Eq. 2.22) P = np.outer(y, y) * K q = matrix(- y * np.diag(P)) # self.q = q # Regularize quadratic part if not positive definite i = -30 posdef_warning = False I_matrix = np.eye(N) while not self.is_pos_def(P + (10.0 ** i) * I_matrix): if not posdef_warning: print('Warning: matrix not positive definite. Started regularization') posdef_warning = True i = i + 1 P = P + (10.0 ** i) * I_matrix # self.P = P print("Finished regularization") P = matrix(2*P) lb = np.zeros(N) # Either assign C for every sample if len(c) > 2: ub = c # Or one for the inliers and outliers separately. else: ub = np.zeros(N) ub[y == 1] = c[0] ub[y == -1] = c[1] # Equality constraint A = matrix(y, (1, N), 'd') b = matrix(1.0) # Box constraints written as inequality constraints # With correct substitution of alpha incorporating labels # = matrix(np.vstack([-np.eye(N)*y, np.eye(N)*y]), (2 * N, N)) G = matrix(np.vstack([-np.eye(N), np.eye(N)]), (2 * N, N)) h = matrix(np.hstack([lb, ub]), (2 * N, 1)) # Find optimal alphas solvers.options['show_progress'] = False res = solvers.qp(P, q, G, h, A, b) alfs = np.array(res['x']).ravel() # TODO: Figure out if the multiplication by one in the paper is valid # % Important: change sign for negative examples: alfs = y * alfs # The support vectors: SV_inds = np.where(abs(alfs) > 1e-8)[0] # Eq. 2.12, second term: Distance to center of the sphere (ignoring the offset): self.Dx = -2 * np.sum(np.outer(np.ones(N), alfs) * K, axis=1) # Support vectors where 0 < alpha_i < C_i for every i borderx = SV_inds[np.where((alfs[SV_inds] < ub[SV_inds]) & (alfs[SV_inds] > 1e-8))[0]] if np.shape(borderx)[0] < 1: borderx = SV_inds # Although all support vectors should give the same results, sometimes # they do not. self.R2 = np.mean(self.Dx[borderx]) # Set all nonl-support-vector alpha to 0 alfs[abs(alfs) < 1e-8] = 0.0 return (alfs, self.R2, self.Dx, SV_inds) def fit(self, X, y): # Setup the appropriate C's self.C =
np.zeros(2)
numpy.zeros
""" ******** Geodetic ******** The library provides utilities to manage geodetic coordinates. There are other more exhaustive libraries that manage this domain, but some C++ objects need to receive this information from the Python code. This is why these objects have been developed. World Geodetic System (WGS) =========================== This class allows describing the geodetic coordinate system used in the calculation. By default, the class instantiates the WGS84 system. """ #%% import timeit import cartopy.crs import cartopy.feature import matplotlib.pyplot import numpy import pyinterp.geodetic wgs84 = pyinterp.geodetic.System() wgs84 #%% # You can instantiate other systems. grs80 = pyinterp.geodetic.System((6378137, 1 / 298.257222101)) grs80 #%% # World Geodetic Coordinates System # ================================= # # This class is used internally to perform conversions from geodetic latitude, # longitude, and altitude (LLA) coordinates to Earth-centered Earth-fixed (ECEF) # coordinates. You can instantiate it from the Python, to do conversions or # transformations. lon = numpy.random.uniform(-180.0, 180.0, 1000000) lat = numpy.random.uniform(-90.0, 90.0, 1000000) alt = numpy.random.uniform(-10000, 100000, 1000000) a = pyinterp.geodetic.Coordinates(wgs84) b = pyinterp.geodetic.Coordinates(grs80) elapsed = timeit.timeit("a.transform(b, lon, lat, alt, num_threads=0)", number=100, globals=dict(a=a, b=b, lon=lon, lat=lat, alt=alt)) print("transform: %f seconds" % (float(elapsed) / 100)) # %% # Geodetic Point # ============== # # This class represents a point determined by its longitude and latitude # expressed in degrees. paris = pyinterp.geodetic.Point(2.3488, 48.8534) new_york = pyinterp.geodetic.Point(-73.9385, 40.6643) # %% # It is possible to instantiate these objects from the representation in # Well-known text (WKT) format or to display it. print(paris.wkt()) print(pyinterp.geodetic.Point.read_wkt(paris.wkt()) == paris) # %% # It's possible to calculate the distances between the points using different # strategies. # print(paris.distance(new_york, strategy='thomas', wgs=wgs84)) print(paris.distance(new_york, strategy='andoyer', wgs=wgs84)) print(paris.distance(new_york, strategy='vincenty', wgs=wgs84)) # %% # It is possible to do the same calculation on a large number of coordinates # quickly. lon = numpy.arange(0, 360, 10) lat = numpy.arange(-90, 90.5, 10) mx, my = numpy.meshgrid(lon, lat) distances = pyinterp.geodetic.coordinate_distances(mx.ravel(), my.ravel(), mx.ravel() + 1, my.ravel() + 1, strategy="vincenty", wgs=wgs84, num_threads=1) distances = distances.reshape(mx.shape) print(distances[:, 0]) # %% # Geodetic Box & Polygon # ====================== # # This class represents a box made of two describing points. box = pyinterp.geodetic.Box(paris, new_york) print(box.wkt()) # %% # A box is a polygon, but it is more easily constructed. polygon = pyinterp.geodetic.Polygon.read_wkt(box.wkt()) print(polygon.wkt()) # %% # It's possible to use different algorithms on these objects. print(f"{polygon.area(wgs=wgs84) * 1e-3} km2") # %% # Transform this polygon into a bounding box polygon = pyinterp.geodetic.Polygon.read_wkt("POLYGON((0 0,0 7,4 2,2 0,0 0))") print(polygon.envelope()) # %% # It is possible to use these objects to select coordinates in an area of # interest. coordinates = [[-36.25, -54.9238], [-36.5, -54.9238], [-36.75, -54.9238], [-37, -54.9238], [-37.25, -54.9238], [-37.5, -54.9238], [-37.75, -54.9238], [-38, -54.9238], [-38.25, -54.9238], [-38.5, -54.9238], [-38.75, -54.9238], [-39, -54.9238], [-39.25, -54.9238], [-39.5, -54.9238], [-39.75, -54.9238], [-40, -54.9238], [-40.25, -54.9238], [-40.5, -54.9238], [-40.75, -54.9238], [-41, -54.9238], [-41.25, -54.9238], [-41.5, -54.9238], [-41.75, -54.9238], [-42, -54.9238], [-42.25, -54.9238], [-42.5, -54.9238], [-42.75, -54.9238], [-43, -54.9238], [-43.25, -54.9238], [-43.5, -54.9238], [-43.75, -54.9238], [-44, -54.9238], [-44.25, -54.9238], [-44.5, -54.9238], [-44.75, -54.9238], [-45, -54.9238], [-45.25, -54.9238], [-45.5, -54.9238], [-45.75, -54.9238], [-46, -54.9238], [-46.25, -54.9238], [-46.5, -54.9238], [-46.75, -54.9238], [-47, -54.9238], [-47.25, -54.9238], [-47.5, -54.9238], [-47.75, -54.9238], [-48, -54.9238], [-48.25, -54.9238], [-48.5, -54.9238], [-48.75, -54.9238], [-49, -54.9238], [-49.25, -54.9238], [-49.5, -54.9238], [-49.75, -54.9238], [-50, -54.9238], [-50.25, -54.9238], [-50.5, -54.9238], [-50.75, -54.9238], [-51, -54.9238], [-51.25, -54.9238], [-51.5, -54.9238], [-51.75, -54.9238], [-52, -54.9238], [-52.25, -54.9238], [-52.5, -54.9238], [-52.75, -54.9238], [-53, -54.9238], [-53.25, -54.9238], [-53.5, -54.9238], [-53.75, -54.9238], [-54, -54.9238], [-54.25, -54.9238], [-54.5, -54.9238], [-54.75, -54.9238], [-55, -54.9238], [-55.25, -54.9238], [-55.5, -54.9238], [-55.75, -54.9238], [-56, -54.9238], [-56.25, -54.9238], [-56.5, -54.9238], [-56.75, -54.9238], [-57, -54.9238], [-57.25, -54.9238], [-57.5, -54.9238], [-57.75, -54.9238], [-58, -54.9238], [-58.25, -54.9238], [-58.5, -54.9238], [-58.75, -54.9238], [-59, -54.9238], [-59.25, -54.9238], [-59.5, -54.9238], [-59.75, -54.9238], [-60, -54.9238], [-60.25, -54.9238], [-60.5, -54.9238], [-60.75, -54.9238], [-61, -54.9238], [-61.25, -54.9238], [-61.5, -54.9238], [-61.75, -54.9238], [-62, -54.9238], [-62.25, -54.9238], [-62.5, -54.9238], [-62.75, -54.9238], [-63, -54.9238], [-63.25, -54.9238], [-63.5, -54.9238], [-63.75, -54.9238], [-64, -54.9238], [-64.25, -54.9238], [-64.5, -54.9238], [-64.75, -54.9238], [-65, -54.9238], [-65.25, -54.9238], [-65.5, -54.9238], [-66.25, -54.4905], [-66.5, -54.345], [-67.25, -54.0525], [-67.5, -53.9055], [-67.75, -53.7579], [-68, -53.4613], [-69.25, -52.5588], [-69.25, -52.4066], [-69.25, -52.2538], [-69, -51.1695], [-69, -51.0125], [-69, -50.855], [-69, -50.6969], [-69, -50.5383], [-68.75, -50.3791], [-67.5, -49.0865], [-67.5, -46.3975], [-67.5, -46.2248], [-67.5, -46.0515], [-67.25, -45.7035], [-67, -45.3532], [-66.25, -45.0007], [-65.25, -43.7499], [-65, -42.1026], [-65, -41.9168], [-65, -41.7305], [-65, -41.5437], [-65, -41.3563], [-65, -41.1684], [-65, -40.9799], [-64.75, -40.9799], [-62.25, -39.0656], [-62, -39.0656], [-61.75, -39.0656], [-61.5, -39.0656], [-61.25, -39.0656], [-61, -39.0656], [-60, -38.8713], [-59.75, -38.8713], [-58.25, -34.4619], [-58.25, -34.2555], [-58, -34.2555], [-57, -34.6678], [-55.75, -34.8731], [-55.5, -34.8731], [-53.5, -34.0486], [-53.25, -33.8412], [-53, -33.6333], [-52.5, -33.0066], [-52.25, -32.3754], [-52, -32.164], [-51.75, -31.9522], [-51.5, -31.7398], [-51, -31.3136], [-50.25, -30.4554], [-50, -29.8068], [-49.5, -29.1539], [-49.25, -28.9353], [-48.5, -27.1704], [-48.5, -26.9478], [-48.5, -26.7247], [-48.5, -26.5012], [-48.5, -26.2772], [-48.5, -26.0528], [-48.5, -25.828], [-48.25, -25.3771], [-47.75, -24.9245], [-47, -24.4703], [-46.75, -24.2425], [-46, -23.7858], [-44.5, -23.0977], [-44.25, -23.0977], [-44, -23.0977], [-43.75, -23.0977], [-43.5, -23.0977], [-41.75, -22.4061], [-41, -21.4785], [-40.75, -21.0125], [-40.25, -20.3107], [-40, -19.8411], [-39.5, -18.424], [-39.5, -18.1867], [-39, -16.7559], [-39, -16.5164], [-39, -15.0731], [-39, -14.8315], [-39, -14.5897], [-39, -14.3477], [-39, -14.1053], [-38.75, -13.1335], [-37.5, -11.9132], [-37.25, -11.4236], [-37, -10.933], [-35.75, -9.70328], [-35, -8.71619], [-34.75, -7.72648], [-34.75, -7.47867], [-36.75, -4.99367], [-37.25, -4.74457], [-38, -4.24611], [-38.25, -3.99675], [-39.25, -3.24826], [-39.75, -2.99863], [-40.75, -2.74894], [-41, -2.74894], [-41.25, -2.74894], [-41.5, -2.74894], [-41.75, -2.74894], [-42, -2.74894], [-44.25, -2.74894], [-44.5, -2.74894], [-46.5, -0.999949], [-48.25, -0.999949], [-48.5, -0.999949], [-48.5, -0.749979], [-48.5, -0.499994], [-48.5, -0.249999], [-48.25, -0.249999], [-48, -0.249999], [-47.75, -0.249999], [-47.5, -0.249999], [-47.25, -0.249999], [-47, -0.249999], [-46.75, -0.249999], [-46.5, -0.249999], [-46.25, -0.249999], [-46, -0.249999], [-45.75, -0.249999], [-45.5, -0.249999], [-45.25, -0.249999], [-45, -0.249999], [-44.75, -0.249999], [-44.5, -0.249999], [-44.25, -0.249999], [-44, -0.249999], [-43.75, -0.249999], [-43.5, -0.249999], [-43.25, -0.249999], [-43, -0.249999], [-42.75, -0.249999], [-42.5, -0.249999], [-42.25, -0.249999], [-42, -0.249999], [-41.75, -0.249999], [-41.5, -0.249999], [-41.25, -0.249999], [-41, -0.249999], [-40.75, -0.249999], [-40.5, -0.249999], [-40.25, -0.249999], [-40, -0.249999], [-39.75, -0.249999], [-39.5, -0.249999], [-39.25, -0.249999], [-39, -0.249999], [-38.75, -0.249999], [-38.5, -0.249999], [-38.25, -0.249999], [-38, -0.249999], [-37.75, -0.249999], [-37.5, -0.249999], [-37.25, -0.249999], [-37, -0.249999], [-36.75, -0.249999], [-36.5, -0.249999], [-36.25, -0.249999], [-36, -0.249999], [-35.75, -0.249999], [-35.5, -0.249999], [-35.25, -0.249999], [-35, -0.249999], [-34.75, -0.249999], [-34.5, -0.249999], [-34.25, -0.249999], [-34, -0.249999], [-33.75, -0.249999], [-33.5, -0.249999], [-33.25, -0.249999], [-33, -0.249999], [-32.75, -0.249999], [-32.5, -0.249999], [-32.25, -0.249999], [-32, -0.249999], [-31.75, -0.249999], [-31.5, -0.249999], [-31.25, -0.249999], [-31, -0.249999], [-30.75, -0.249999], [-30.5, -0.249999], [-30.25, -0.249999], [-30, -0.249999], [-29.75, -0.249999], [-29.5, -0.249999], [-29.25, -0.249999], [-29, -0.249999], [-28.75, -0.249999], [-28.5, -0.249999], [-28.25, -0.249999], [-28, -0.249999], [-27.75, -0.249999], [-27.5, -0.249999], [-27.25, -0.249999], [-27, -0.249999], [-26.75, -0.249999], [-26.5, -0.249999], [-26.25, -0.249999], [-26, -0.249999], [-25.75, -0.249999], [-25.5, -0.249999], [-25.25, -0.249999], [-25, -0.249999], [-24.75, -0.249999], [-24.5, -0.249999], [-24.25, -0.249999], [-24, -0.249999], [-23.75, -0.249999], [-23.5, -0.249999], [-23.25, -0.249999], [-23, -0.249999], [-22.75, -0.249999], [-22.5, -0.249999], [-22.25, -0.249999], [-22, -0.249999], [-21.75, -0.249999], [-21.5, -0.249999], [-21.25, -0.249999], [-21, -0.249999], [-20.75, -0.249999], [-20.5, -0.249999], [-20.25, -0.249999], [-20, -0.249999], [-19.75, -0.249999], [-19.5, -0.249999], [-19.25, -0.249999], [-19, -0.249999], [-18.75, -0.249999], [-18.5, -0.249999], [-18.25, -0.249999], [-18, -0.249999], [-17.75, -0.249999], [-17.5, -0.249999], [-17.25, -0.249999], [-17, -0.249999], [-16.75, -0.249999], [-16.5, -0.249999], [-16.25, -0.249999], [-16, -0.249999], [-15.75, -0.249999], [-15.5, -0.249999], [-15.25, -0.249999], [-15, -0.249999], [-14.75, -0.249999], [-14.5, -0.249999], [-14.25, -0.249999], [-14, -0.249999], [-13.75, -0.249999], [-13.5, -0.249999], [-13.25, -0.249999], [-13, -0.249999], [-12.75, -0.249999], [-12.5, -0.249999], [-12.25, -0.249999], [-12, -0.249999], [-11.75, -0.249999], [-11.5, -0.249999], [-11.25, -0.249999], [-11, -0.249999], [-10.75, -0.249999], [-10.5, -0.249999], [-10.25, -0.249999], [-10, -0.249999], [-9.75, -0.249999], [-9.5, -0.249999], [-9.25, -0.249999], [-9, -0.249999], [-8.75, -0.249999], [-8.5, -0.249999], [-8.25, -0.249999], [-8, -0.249999], [-7.75, -0.249999], [-7.5, -0.249999], [-7.25, -0.249999], [-7, -0.249999], [-6.75, -0.249999], [-6.5, -0.249999], [-6.25, -0.249999], [-6, -0.249999], [-5.75, -0.249999], [-5.5, -0.249999], [-5.25, -0.249999], [-5, -0.249999], [-4.75, -0.249999], [-4.5, -0.249999], [-4.25, -0.249999], [-4, -0.249999], [-3.75, -0.249999], [-3.5, -0.249999], [-3.25, -0.249999], [-3, -0.249999], [-2.75, -0.249999], [-2.5, -0.249999], [-2.25, -0.249999], [-2, -0.249999], [-1.75, -0.249999], [-1.5, -0.249999], [-1.25, -0.249999], [-1, -0.249999], [-0.75, -0.249999], [-0.5, -0.249999], [-0.25, -0.249999], [0, -0.249999], [0.25, -0.249999], [0.5, -0.249999], [0.75, -0.249999], [1, -0.249999], [1.25, -0.249999], [1.5, -0.249999], [1.75, -0.249999], [2, -0.249999], [2.25, -0.249999], [2.5, -0.249999], [2.75, -0.249999], [3, -0.249999], [3.25, -0.249999], [3.5, -0.249999], [3.75, -0.249999], [4, -0.249999], [4.25, -0.249999], [4.5, -0.249999], [4.75, -0.249999], [5, -0.249999], [5.25, -0.249999], [5.5, -0.249999], [5.75, -0.249999], [6, -0.249999], [6.25, -0.249999], [6.5, -0.249999], [6.75, -0.249999], [7, -0.249999], [7.25, -0.249999], [7.5, -0.249999], [7.75, -0.249999], [8, -0.249999], [8.25, -0.249999], [8.5, -0.249999], [8.75, -0.249999], [9, -0.249999], [9.25, -0.249999], [9.75, -2.49921], [10.25, -2.99863], [10.75, -3.49783], [11.25, -3.99675], [11.75, -4.74457], [12, -5.24267], [12.25, -5.98906], [12.75, -6.98265], [13, -7.72648], [13.25, -8.22164], [13.25, -8.46899], [13.25, -8.71619], [13.5, -10.4417], [13.75, -10.933], [13.75, -11.1784], [13.75, -11.4236], [13.75, -11.6685], [13.75, -11.9132], [13.5, -12.402], [12.5, -13.6199], [12.25, -14.5897], [12, -15.5553], [11.75, -16.7559], [12.5, -19.1341], [12.75, -19.6058], [13, -20.0761], [13.25, -20.545], [13.5, -21.0125], [13.75, -21.4785], [14.25, -22.1747], [14.5, -22.637], [14.5, -22.8675], [14.5, -24.2425], [14.75, -24.9245], [14.75, -25.151], [14.75, -25.3771], [15, -26.5012], [16, -28.2769], [16.5, -28.7163], [16.75, -29.1539], [17, -29.8068], [17.25, -30.4554], [17.5, -30.8855], [18, -31.5269], [18.25, -31.9522], [18.25, -32.164], [18.25, -32.3754], [19.25, -34.4619], [19.75, -34.8731], [19.75, -35.078], [19.75, -35.2823], [19.75, -35.4861], [19.75, -35.6894], [19.75, -35.8922], [19.75, -36.0945], [19.75, -36.2962], [19.75, -36.4975], [19.75, -36.6982], [19.75, -36.8984], [19.75, -37.098], [19.75, -37.2972], [19.75, -37.4958], [19.75, -37.6939], [19.75, -37.8914], [19.75, -38.0885], [19.75, -38.285], [19.75, -38.4809], [19.75, -38.6764], [19.75, -38.8713], [19.75, -39.0656], [19.75, -39.2595], [19.75, -39.4528], [19.75, -39.6456], [19.75, -39.8378], [19.75, -40.0295], [19.75, -40.2206], [19.75, -40.4113], [19.75, -40.6013], [19.75, -40.7909], [19.75, -40.9799], [19.75, -41.1684], [19.75, -41.3563], [19.75, -41.5437], [19.75, -41.7305], [19.75, -41.9168], [19.75, -42.1026], [19.75, -42.2878], [19.75, -42.4725], [19.75, -42.6566], [19.75, -42.8402], [19.75, -43.0232], [19.75, -43.2057], [19.75, -43.3877], [19.75, -43.5691], [19.75, -43.7499], [19.75, -43.9303], [19.75, -44.11], [19.75, -44.2893], [19.75, -44.4679], [19.75, -44.6461], [19.75, -44.8237], [19.75, -45.0007], [19.75, -45.1772], [19.75, -45.3532], [19.75, -45.5286], [19.75, -45.7035], [19.75, -45.8778], [19.75, -46.0515], [19.75, -46.2248], [19.75, -46.3975], [19.75, -46.5696], [19.75, -46.7412], [19.75, -46.9123], [19.75, -47.0828], [19.75, -47.2527], [19.75, -47.4221], [19.75, -47.591], [19.75, -47.7593], [19.75, -47.9271], [19.75, -48.0944], [19.75, -48.2611], [19.75, -48.4273], [19.75, -48.5929], [19.75, -48.758], [19.75, -48.9225], [19.75, -49.0865], [19.75, -49.25], [19.75, -49.4129], [19.75, -49.5753], [19.75, -49.7371], [19.75, -49.8984], [19.75, -50.0592], [19.75, -50.2194], [19.75, -50.3791], [19.75, -50.5383], [19.75, -50.6969], [19.75, -50.855], [19.75, -51.0125], [19.75, -51.1695], [19.75, -51.326], [19.75, -51.482], [19.75, -51.6374], [19.75, -51.7923], [19.75, -51.9467], [19.75, -52.1005], [19.75, -52.2538], [19.75, -52.4066], [19.75, -52.5588], [19.75, -52.7106], [19.75, -52.8618], [19.75, -53.0124], [19.75, -53.1626], [19.75, -53.3122], [19.75, -53.4613], [19.75, -53.6099], [19.75, -53.7579], [19.75, -53.9055], [19.75, -54.0525], [19.75, -54.199], [19.75, -54.345], [19.75, -54.4905], [19.75, -54.6354], [19.75, -54.7799], [19.75, -54.9238], [19.5, -54.9238], [19.25, -54.9238], [19, -54.9238], [18.75, -54.9238], [18.5, -54.9238], [18.25, -54.9238], [18, -54.9238], [17.75, -54.9238], [17.5, -54.9238], [17.25, -54.9238], [17, -54.9238], [16.75, -54.9238], [16.5, -54.9238], [16.25, -54.9238], [16, -54.9238], [15.75, -54.9238], [15.5, -54.9238], [15.25, -54.9238], [15, -54.9238], [14.75, -54.9238], [14.5, -54.9238], [14.25, -54.9238], [14, -54.9238], [13.75, -54.9238], [13.5, -54.9238], [13.25, -54.9238], [13, -54.9238], [12.75, -54.9238], [12.5, -54.9238], [12.25, -54.9238], [12, -54.9238], [11.75, -54.9238], [11.5, -54.9238], [11.25, -54.9238], [11, -54.9238], [10.75, -54.9238], [10.5, -54.9238], [10.25, -54.9238], [10, -54.9238], [9.75, -54.9238], [9.5, -54.9238], [9.25, -54.9238], [9, -54.9238], [8.75, -54.9238], [8.5, -54.9238], [8.25, -54.9238], [8, -54.9238], [7.75, -54.9238], [7.5, -54.9238], [7.25, -54.9238], [7, -54.9238], [6.75, -54.9238], [6.5, -54.9238], [6.25, -54.9238], [6, -54.9238], [5.75, -54.9238], [5.5, -54.9238], [5.25, -54.9238], [5, -54.9238], [4.75, -54.9238], [4.5, -54.9238], [4.25, -54.9238], [4, -54.9238], [3.75, -54.9238], [3.5, -54.9238], [3.25, -54.9238], [3, -54.9238], [2.75, -54.9238], [2.5, -54.9238], [2.25, -54.9238], [2, -54.9238], [1.75, -54.9238], [1.5, -54.9238], [1.25, -54.9238], [1, -54.9238], [0.75, -54.9238], [0.5, -54.9238], [0.25, -54.9238], [-1.81899e-12, -54.9238], [-0.25, -54.9238], [-0.5, -54.9238], [-0.75, -54.9238], [-1, -54.9238], [-1.25, -54.9238], [-1.5, -54.9238], [-1.75, -54.9238], [-2, -54.9238], [-2.25, -54.9238], [-2.5, -54.9238], [-2.75, -54.9238], [-3, -54.9238], [-3.25, -54.9238], [-3.5, -54.9238], [-3.75, -54.9238], [-4, -54.9238], [-4.25, -54.9238], [-4.5, -54.9238], [-4.75, -54.9238], [-5, -54.9238], [-5.25, -54.9238], [-5.5, -54.9238], [-5.75, -54.9238], [-6, -54.9238], [-6.25, -54.9238], [-6.5, -54.9238], [-6.75, -54.9238], [-7, -54.9238], [-7.25, -54.9238], [-7.5, -54.9238], [-7.75, -54.9238], [-8, -54.9238], [-8.25, -54.9238], [-8.5, -54.9238], [-8.75, -54.9238], [-9, -54.9238], [-9.25, -54.9238], [-9.5, -54.9238], [-9.75, -54.9238], [-10, -54.9238], [-10.25, -54.9238], [-10.5, -54.9238], [-10.75, -54.9238], [-11, -54.9238], [-11.25, -54.9238], [-11.5, -54.9238], [-11.75, -54.9238], [-12, -54.9238], [-12.25, -54.9238], [-12.5, -54.9238], [-12.75, -54.9238], [-13, -54.9238], [-13.25, -54.9238], [-13.5, -54.9238], [-13.75, -54.9238], [-14, -54.9238], [-14.25, -54.9238], [-14.5, -54.9238], [-14.75, -54.9238], [-15, -54.9238], [-15.25, -54.9238], [-15.5, -54.9238], [-15.75, -54.9238], [-16, -54.9238], [-16.25, -54.9238], [-16.5, -54.9238], [-16.75, -54.9238], [-17, -54.9238], [-17.25, -54.9238], [-17.5, -54.9238], [-17.75, -54.9238], [-18, -54.9238], [-18.25, -54.9238], [-18.5, -54.9238], [-18.75, -54.9238], [-19, -54.9238], [-19.25, -54.9238], [-19.5, -54.9238], [-19.75, -54.9238], [-20, -54.9238], [-20.25, -54.9238], [-20.5, -54.9238], [-20.75, -54.9238], [-21, -54.9238], [-21.25, -54.9238], [-21.5, -54.9238], [-21.75, -54.9238], [-22, -54.9238], [-22.25, -54.9238], [-22.5, -54.9238], [-22.75, -54.9238], [-23, -54.9238], [-23.25, -54.9238], [-23.5, -54.9238], [-23.75, -54.9238], [-24, -54.9238], [-24.25, -54.9238], [-24.5, -54.9238], [-24.75, -54.9238], [-25, -54.9238], [-25.25, -54.9238], [-25.5, -54.9238], [-25.75, -54.9238], [-26, -54.9238], [-26.25, -54.9238], [-26.5, -54.9238], [-26.75, -54.9238], [-27, -54.9238], [-27.25, -54.9238], [-27.5, -54.9238], [-27.75, -54.9238], [-28, -54.9238], [-28.25, -54.9238], [-28.5, -54.9238], [-28.75, -54.9238], [-29, -54.9238], [-29.25, -54.9238], [-29.5, -54.9238], [-29.75, -54.9238], [-30, -54.9238], [-30.25, -54.9238], [-30.5, -54.9238], [-30.75, -54.9238], [-31, -54.9238], [-31.25, -54.9238], [-31.5, -54.9238], [-31.75, -54.9238], [-32, -54.9238], [-32.25, -54.9238], [-32.5, -54.9238], [-32.75, -54.9238], [-33, -54.9238], [-33.25, -54.9238], [-33.5, -54.9238], [-33.75, -54.9238], [-34, -54.9238], [-34.25, -54.9238], [-34.5, -54.9238], [-34.75, -54.9238], [-35, -54.9238], [-35.25, -54.9238], [-35.5, -54.9238], [-35.75, -54.9238], [-36, -54.9238], [-36.25, -54.9238]] # %% lon = numpy.arange(0, 360, 10) lat =
numpy.arange(-80, 90, 10)
numpy.arange
"""Filter design. """ from __future__ import division, print_function, absolute_import import warnings import numpy from numpy import (atleast_1d, poly, polyval, roots, real, asarray, allclose, resize, pi, absolute, logspace, r_, sqrt, tan, log10, arctan, arcsinh, sin, exp, cosh, arccosh, ceil, conjugate, zeros, sinh, append, concatenate, prod, ones, array) from numpy import mintypecode import numpy as np from scipy import special, optimize from scipy.special import comb from scipy.misc import factorial from numpy.polynomial.polynomial import polyval as npp_polyval import math __all__ = ['findfreqs', 'freqs', 'freqz', 'tf2zpk', 'zpk2tf', 'normalize', 'lp2lp', 'lp2hp', 'lp2bp', 'lp2bs', 'bilinear', 'iirdesign', 'iirfilter', 'butter', 'cheby1', 'cheby2', 'ellip', 'bessel', 'band_stop_obj', 'buttord', 'cheb1ord', 'cheb2ord', 'ellipord', 'buttap', 'cheb1ap', 'cheb2ap', 'ellipap', 'besselap', 'BadCoefficients', 'tf2sos', 'sos2tf', 'zpk2sos', 'sos2zpk', 'group_delay'] class BadCoefficients(UserWarning): """Warning about badly conditioned filter coefficients""" pass abs = absolute def findfreqs(num, den, N): """ Find array of frequencies for computing the response of an analog filter. Parameters ---------- num, den : array_like, 1-D The polynomial coefficients of the numerator and denominator of the transfer function of the filter or LTI system. The coefficients are ordered from highest to lowest degree. N : int The length of the array to be computed. Returns ------- w : (N,) ndarray A 1-D array of frequencies, logarithmically spaced. Examples -------- Find a set of nine frequencies that span the "interesting part" of the frequency response for the filter with the transfer function H(s) = s / (s^2 + 8s + 25) >>> from scipy import signal >>> signal.findfreqs([1, 0], [1, 8, 25], N=9) array([ 1.00000000e-02, 3.16227766e-02, 1.00000000e-01, 3.16227766e-01, 1.00000000e+00, 3.16227766e+00, 1.00000000e+01, 3.16227766e+01, 1.00000000e+02]) """ ep = atleast_1d(roots(den)) + 0j tz = atleast_1d(roots(num)) + 0j if len(ep) == 0: ep = atleast_1d(-1000) + 0j ez = r_['-1', numpy.compress(ep.imag >= 0, ep, axis=-1), numpy.compress((abs(tz) < 1e5) & (tz.imag >= 0), tz, axis=-1)] integ = abs(ez) < 1e-10 hfreq = numpy.around(numpy.log10(numpy.max(3 * abs(ez.real + integ) + 1.5 * ez.imag)) + 0.5) lfreq = numpy.around(numpy.log10(0.1 * numpy.min(abs(real(ez + integ)) + 2 * ez.imag)) - 0.5) w = logspace(lfreq, hfreq, N) return w def freqs(b, a, worN=None, plot=None): """ Compute frequency response of analog filter. Given the M-order numerator `b` and N-order denominator `a` of an analog filter, compute its frequency response:: b[0]*(jw)**M + b[1]*(jw)**(M-1) + ... + b[M] H(w) = ---------------------------------------------- a[0]*(jw)**N + a[1]*(jw)**(N-1) + ... + a[N] Parameters ---------- b : array_like Numerator of a linear filter. a : array_like Denominator of a linear filter. worN : {None, int, array_like}, optional If None, then compute at 200 frequencies around the interesting parts of the response curve (determined by pole-zero locations). If a single integer, then compute at that many frequencies. Otherwise, compute the response at the angular frequencies (e.g. rad/s) given in `worN`. plot : callable, optional A callable that takes two arguments. If given, the return parameters `w` and `h` are passed to plot. Useful for plotting the frequency response inside `freqs`. Returns ------- w : ndarray The angular frequencies at which `h` was computed. h : ndarray The frequency response. See Also -------- freqz : Compute the frequency response of a digital filter. Notes ----- Using Matplotlib's "plot" function as the callable for `plot` produces unexpected results, this plots the real part of the complex transfer function, not the magnitude. Try ``lambda w, h: plot(w, abs(h))``. Examples -------- >>> from scipy.signal import freqs, iirfilter >>> b, a = iirfilter(4, [1, 10], 1, 60, analog=True, ftype='cheby1') >>> w, h = freqs(b, a, worN=np.logspace(-1, 2, 1000)) >>> import matplotlib.pyplot as plt >>> plt.semilogx(w, 20 * np.log10(abs(h))) >>> plt.xlabel('Frequency') >>> plt.ylabel('Amplitude response [dB]') >>> plt.grid() >>> plt.show() """ if worN is None: w = findfreqs(b, a, 200) elif isinstance(worN, int): N = worN w = findfreqs(b, a, N) else: w = worN w = atleast_1d(w) s = 1j * w h = polyval(b, s) / polyval(a, s) if plot is not None: plot(w, h) return w, h def freqz(b, a=1, worN=None, whole=False, plot=None): """ Compute the frequency response of a digital filter. Given the M-order numerator `b` and N-order denominator `a` of a digital filter, compute its frequency response:: jw -jw -jwM jw B(e ) b[0] + b[1]e + .... + b[M]e H(e ) = ---- = ----------------------------------- jw -jw -jwN A(e ) a[0] + a[1]e + .... + a[N]e Parameters ---------- b : array_like numerator of a linear filter a : array_like denominator of a linear filter worN : {None, int, array_like}, optional If None (default), then compute at 512 frequencies equally spaced around the unit circle. If a single integer, then compute at that many frequencies. If an array_like, compute the response at the frequencies given (in radians/sample). whole : bool, optional Normally, frequencies are computed from 0 to the Nyquist frequency, pi radians/sample (upper-half of unit-circle). If `whole` is True, compute frequencies from 0 to 2*pi radians/sample. plot : callable A callable that takes two arguments. If given, the return parameters `w` and `h` are passed to plot. Useful for plotting the frequency response inside `freqz`. Returns ------- w : ndarray The normalized frequencies at which `h` was computed, in radians/sample. h : ndarray The frequency response. Notes ----- Using Matplotlib's "plot" function as the callable for `plot` produces unexpected results, this plots the real part of the complex transfer function, not the magnitude. Try ``lambda w, h: plot(w, abs(h))``. Examples -------- >>> from scipy import signal >>> b = signal.firwin(80, 0.5, window=('kaiser', 8)) >>> w, h = signal.freqz(b) >>> import matplotlib.pyplot as plt >>> fig = plt.figure() >>> plt.title('Digital filter frequency response') >>> ax1 = fig.add_subplot(111) >>> plt.plot(w, 20 * np.log10(abs(h)), 'b') >>> plt.ylabel('Amplitude [dB]', color='b') >>> plt.xlabel('Frequency [rad/sample]') >>> ax2 = ax1.twinx() >>> angles = np.unwrap(np.angle(h)) >>> plt.plot(w, angles, 'g') >>> plt.ylabel('Angle (radians)', color='g') >>> plt.grid() >>> plt.axis('tight') >>> plt.show() """ b, a = map(atleast_1d, (b, a)) if whole: lastpoint = 2 * pi else: lastpoint = pi if worN is None: N = 512 w = numpy.linspace(0, lastpoint, N, endpoint=False) elif isinstance(worN, int): N = worN w = numpy.linspace(0, lastpoint, N, endpoint=False) else: w = worN w = atleast_1d(w) zm1 = exp(-1j * w) h = polyval(b[::-1], zm1) / polyval(a[::-1], zm1) if plot is not None: plot(w, h) return w, h def group_delay(system, w=None, whole=False): r"""Compute the group delay of a digital filter. The group delay measures by how many samples amplitude envelopes of various spectral components of a signal are delayed by a filter. It is formally defined as the derivative of continuous (unwrapped) phase:: d jw D(w) = - -- arg H(e) dw Parameters ---------- system : tuple of array_like (b, a) Numerator and denominator coefficients of a filter transfer function. w : {None, int, array-like}, optional If None (default), then compute at 512 frequencies equally spaced around the unit circle. If a single integer, then compute at that many frequencies. If array, compute the delay at the frequencies given (in radians/sample). whole : bool, optional Normally, frequencies are computed from 0 to the Nyquist frequency, pi radians/sample (upper-half of unit-circle). If `whole` is True, compute frequencies from 0 to ``2*pi`` radians/sample. Returns ------- w : ndarray The normalized frequencies at which the group delay was computed, in radians/sample. gd : ndarray The group delay. Notes ----- The similar function in MATLAB is called `grpdelay`. If the transfer function :math:`H(z)` has zeros or poles on the unit circle, the group delay at corresponding frequencies is undefined. When such a case arises the warning is raised and the group delay is set to 0 at those frequencies. For the details of numerical computation of the group delay refer to [1]_. .. versionadded: 0.16.0 See Also -------- freqz : Frequency response of a digital filter References ---------- .. [1] <NAME>, "Understanding Digital Signal Processing, 3rd edition", p. 830. Examples -------- >>> from scipy import signal >>> b, a = signal.iirdesign(0.1, 0.3, 5, 50, ftype='cheby1') >>> w, gd = signal.group_delay((b, a)) >>> import matplotlib.pyplot as plt >>> plt.title('Digital filter group delay') >>> plt.plot(w, gd) >>> plt.ylabel('Group delay [samples]') >>> plt.xlabel('Frequency [rad/sample]') >>> plt.show() """ if w is None: w = 512 if isinstance(w, int): if whole: w = np.linspace(0, 2 * pi, w, endpoint=False) else: w = np.linspace(0, pi, w, endpoint=False) w = np.atleast_1d(w) b, a = map(np.atleast_1d, system) c = np.convolve(b, a[::-1]) cr = c * np.arange(c.size) z = np.exp(-1j * w) num = np.polyval(cr[::-1], z) den = np.polyval(c[::-1], z) singular = np.absolute(den) < 10 * EPSILON if np.any(singular): warnings.warn( "The group delay is singular at frequencies [{0}], setting to 0". format(", ".join("{0:.3f}".format(ws) for ws in w[singular])) ) gd = np.zeros_like(w) gd[~singular] = np.real(num[~singular] / den[~singular]) - a.size + 1 return w, gd def _cplxreal(z, tol=None): """ Split into complex and real parts, combining conjugate pairs. The 1D input vector `z` is split up into its complex (`zc`) and real (`zr`) elements. Every complex element must be part of a complex-conjugate pair, which are combined into a single number (with positive imaginary part) in the output. Two complex numbers are considered a conjugate pair if their real and imaginary parts differ in magnitude by less than ``tol * abs(z)``. Parameters ---------- z : array_like Vector of complex numbers to be sorted and split tol : float, optional Relative tolerance for testing realness and conjugate equality. Default is ``100 * spacing(1)`` of `z`'s data type (i.e. 2e-14 for float64) Returns ------- zc : ndarray Complex elements of `z`, with each pair represented by a single value having positive imaginary part, sorted first by real part, and then by magnitude of imaginary part. The pairs are averaged when combined to reduce error. zr : ndarray Real elements of `z` (those having imaginary part less than `tol` times their magnitude), sorted by value. Raises ------ ValueError If there are any complex numbers in `z` for which a conjugate cannot be found. See Also -------- _cplxpair Examples -------- >>> a = [4, 3, 1, 2-2j, 2+2j, 2-1j, 2+1j, 2-1j, 2+1j, 1+1j, 1-1j] >>> zc, zr = _cplxreal(a) >>> print zc [ 1.+1.j 2.+1.j 2.+1.j 2.+2.j] >>> print zr [ 1. 3. 4.] """ z = atleast_1d(z) if z.size == 0: return z, z elif z.ndim != 1: raise ValueError('_cplxreal only accepts 1D input') if tol is None: # Get tolerance from dtype of input tol = 100 * np.finfo((1.0 * z).dtype).eps # Sort by real part, magnitude of imaginary part (speed up further sorting) z = z[np.lexsort((abs(z.imag), z.real))] # Split reals from conjugate pairs real_indices = abs(z.imag) <= tol * abs(z) zr = z[real_indices].real if len(zr) == len(z): # Input is entirely real return array([]), zr # Split positive and negative halves of conjugates z = z[~real_indices] zp = z[z.imag > 0] zn = z[z.imag < 0] if len(zp) != len(zn): raise ValueError('Array contains complex value with no matching ' 'conjugate.') # Find runs of (approximately) the same real part same_real = np.diff(zp.real) <= tol * abs(zp[:-1]) diffs = numpy.diff(concatenate(([0], same_real, [0]))) run_starts = numpy.where(diffs > 0)[0] run_stops = numpy.where(diffs < 0)[0] # Sort each run by their imaginary parts for i in range(len(run_starts)): start = run_starts[i] stop = run_stops[i] + 1 for chunk in (zp[start:stop], zn[start:stop]): chunk[...] = chunk[np.lexsort([abs(chunk.imag)])] # Check that negatives match positives if any(abs(zp - zn.conj()) > tol * abs(zn)): raise ValueError('Array contains complex value with no matching ' 'conjugate.') # Average out numerical inaccuracy in real vs imag parts of pairs zc = (zp + zn.conj()) / 2 return zc, zr def _cplxpair(z, tol=None): """ Sort into pairs of complex conjugates. Complex conjugates in `z` are sorted by increasing real part. In each pair, the number with negative imaginary part appears first. If pairs have identical real parts, they are sorted by increasing imaginary magnitude. Two complex numbers are considered a conjugate pair if their real and imaginary parts differ in magnitude by less than ``tol * abs(z)``. The pairs are forced to be exact complex conjugates by averaging the positive and negative values. Purely real numbers are also sorted, but placed after the complex conjugate pairs. A number is considered real if its imaginary part is smaller than `tol` times the magnitude of the number. Parameters ---------- z : array_like 1-dimensional input array to be sorted. tol : float, optional Relative tolerance for testing realness and conjugate equality. Default is ``100 * spacing(1)`` of `z`'s data type (i.e. 2e-14 for float64) Returns ------- y : ndarray Complex conjugate pairs followed by real numbers. Raises ------ ValueError If there are any complex numbers in `z` for which a conjugate cannot be found. See Also -------- _cplxreal Examples -------- >>> a = [4, 3, 1, 2-2j, 2+2j, 2-1j, 2+1j, 2-1j, 2+1j, 1+1j, 1-1j] >>> z = _cplxpair(a) >>> print(z) [ 1.-1.j 1.+1.j 2.-1.j 2.+1.j 2.-1.j 2.+1.j 2.-2.j 2.+2.j 1.+0.j 3.+0.j 4.+0.j] """ z = atleast_1d(z) if z.size == 0 or np.isrealobj(z): return np.sort(z) if z.ndim != 1: raise ValueError('z must be 1-dimensional') zc, zr = _cplxreal(z, tol) # Interleave complex values and their conjugates, with negative imaginary # parts first in each pair zc = np.dstack((zc.conj(), zc)).flatten() z = np.append(zc, zr) return z def tf2zpk(b, a): r"""Return zero, pole, gain (z, p, k) representation from a numerator, denominator representation of a linear filter. Parameters ---------- b : array_like Numerator polynomial coefficients. a : array_like Denominator polynomial coefficients. Returns ------- z : ndarray Zeros of the transfer function. p : ndarray Poles of the transfer function. k : float System gain. Notes ----- If some values of `b` are too close to 0, they are removed. In that case, a BadCoefficients warning is emitted. The `b` and `a` arrays are interpreted as coefficients for positive, descending powers of the transfer function variable. So the inputs :math:`b = [b_0, b_1, ..., b_M]` and :math:`a =[a_0, a_1, ..., a_N]` can represent an analog filter of the form: .. math:: H(s) = \frac {b_0 s^M + b_1 s^{(M-1)} + \cdots + b_M} {a_0 s^N + a_1 s^{(N-1)} + \cdots + a_N} or a discrete-time filter of the form: .. math:: H(z) = \frac {b_0 z^M + b_1 z^{(M-1)} + \cdots + b_M} {a_0 z^N + a_1 z^{(N-1)} + \cdots + a_N} This "positive powers" form is found more commonly in controls engineering. If `M` and `N` are equal (which is true for all filters generated by the bilinear transform), then this happens to be equivalent to the "negative powers" discrete-time form preferred in DSP: .. math:: H(z) = \frac {b_0 + b_1 z^{-1} + \cdots + b_M z^{-M}} {a_0 + a_1 z^{-1} + \cdots + a_N z^{-N}} Although this is true for common filters, remember that this is not true in the general case. If `M` and `N` are not equal, the discrete-time transfer function coefficients must first be converted to the "positive powers" form before finding the poles and zeros. """ b, a = normalize(b, a) b = (b + 0.0) / a[0] a = (a + 0.0) / a[0] k = b[0] b /= b[0] z = roots(b) p = roots(a) return z, p, k def zpk2tf(z, p, k): """ Return polynomial transfer function representation from zeros and poles Parameters ---------- z : array_like Zeros of the transfer function. p : array_like Poles of the transfer function. k : float System gain. Returns ------- b : ndarray Numerator polynomial coefficients. a : ndarray Denominator polynomial coefficients. """ z = atleast_1d(z) k = atleast_1d(k) if len(z.shape) > 1: temp = poly(z[0]) b = zeros((z.shape[0], z.shape[1] + 1), temp.dtype.char) if len(k) == 1: k = [k[0]] * z.shape[0] for i in range(z.shape[0]): b[i] = k[i] * poly(z[i]) else: b = k * poly(z) a = atleast_1d(poly(p)) # Use real output if possible. Copied from numpy.poly, since # we can't depend on a specific version of numpy. if issubclass(b.dtype.type, numpy.complexfloating): # if complex roots are all complex conjugates, the roots are real. roots = numpy.asarray(z, complex) pos_roots = numpy.compress(roots.imag > 0, roots) neg_roots = numpy.conjugate(numpy.compress(roots.imag < 0, roots)) if len(pos_roots) == len(neg_roots): if numpy.all(numpy.sort_complex(neg_roots) == numpy.sort_complex(pos_roots)): b = b.real.copy() if issubclass(a.dtype.type, numpy.complexfloating): # if complex roots are all complex conjugates, the roots are real. roots = numpy.asarray(p, complex) pos_roots = numpy.compress(roots.imag > 0, roots) neg_roots = numpy.conjugate(numpy.compress(roots.imag < 0, roots)) if len(pos_roots) == len(neg_roots): if numpy.all(numpy.sort_complex(neg_roots) == numpy.sort_complex(pos_roots)): a = a.real.copy() return b, a def tf2sos(b, a, pairing='nearest'): """ Return second-order sections from transfer function representation Parameters ---------- b : array_like Numerator polynomial coefficients. a : array_like Denominator polynomial coefficients. pairing : {'nearest', 'keep_odd'}, optional The method to use to combine pairs of poles and zeros into sections. See `zpk2sos`. Returns ------- sos : ndarray Array of second-order filter coefficients, with shape ``(n_sections, 6)``. See `sosfilt` for the SOS filter format specification. See Also -------- zpk2sos, sosfilt Notes ----- It is generally discouraged to convert from TF to SOS format, since doing so usually will not improve numerical precision errors. Instead, consider designing filters in ZPK format and converting directly to SOS. TF is converted to SOS by first converting to ZPK format, then converting ZPK to SOS. .. versionadded:: 0.16.0 """ return zpk2sos(*tf2zpk(b, a), pairing=pairing) def sos2tf(sos): """ Return a single transfer function from a series of second-order sections Parameters ---------- sos : array_like Array of second-order filter coefficients, must have shape ``(n_sections, 6)``. See `sosfilt` for the SOS filter format specification. Returns ------- b : ndarray Numerator polynomial coefficients. a : ndarray Denominator polynomial coefficients. Notes ----- .. versionadded:: 0.16.0 """ sos = np.asarray(sos) b = [1.] a = [1.] n_sections = sos.shape[0] for section in range(n_sections): b = np.polymul(b, sos[section, :3]) a = np.polymul(a, sos[section, 3:]) return b, a def sos2zpk(sos): """ Return zeros, poles, and gain of a series of second-order sections Parameters ---------- sos : array_like Array of second-order filter coefficients, must have shape ``(n_sections, 6)``. See `sosfilt` for the SOS filter format specification. Returns ------- z : ndarray Zeros of the transfer function. p : ndarray Poles of the transfer function. k : float System gain. Notes ----- .. versionadded:: 0.16.0 """ sos = np.asarray(sos) n_sections = sos.shape[0] z = np.empty(n_sections*2, np.complex128) p = np.empty(n_sections*2, np.complex128) k = 1. for section in range(n_sections): zpk = tf2zpk(sos[section, :3], sos[section, 3:]) z[2*section:2*(section+1)] = zpk[0] p[2*section:2*(section+1)] = zpk[1] k *= zpk[2] return z, p, k def _nearest_real_complex_idx(fro, to, which): """Get the next closest real or complex element based on distance""" assert which in ('real', 'complex') order = np.argsort(np.abs(fro - to)) mask = np.isreal(fro[order]) if which == 'complex': mask = ~mask return order[np.where(mask)[0][0]] def zpk2sos(z, p, k, pairing='nearest'): """ Return second-order sections from zeros, poles, and gain of a system Parameters ---------- z : array_like Zeros of the transfer function. p : array_like Poles of the transfer function. k : float System gain. pairing : {'nearest', 'keep_odd'}, optional The method to use to combine pairs of poles and zeros into sections. See Notes below. Returns ------- sos : ndarray Array of second-order filter coefficients, with shape ``(n_sections, 6)``. See `sosfilt` for the SOS filter format specification. See Also -------- sosfilt Notes ----- The algorithm used to convert ZPK to SOS format is designed to minimize errors due to numerical precision issues. The pairing algorithm attempts to minimize the peak gain of each biquadratic section. This is done by pairing poles with the nearest zeros, starting with the poles closest to the unit circle. *Algorithms* The current algorithms are designed specifically for use with digital filters. (The output coefficents are not correct for analog filters.) The steps in the ``pairing='nearest'`` and ``pairing='keep_odd'`` algorithms are mostly shared. The ``nearest`` algorithm attempts to minimize the peak gain, while ``'keep_odd'`` minimizes peak gain under the constraint that odd-order systems should retain one section as first order. The algorithm steps and are as follows: As a pre-processing step, add poles or zeros to the origin as necessary to obtain the same number of poles and zeros for pairing. If ``pairing == 'nearest'`` and there are an odd number of poles, add an additional pole and a zero at the origin. The following steps are then iterated over until no more poles or zeros remain: 1. Take the (next remaining) pole (complex or real) closest to the unit circle to begin a new filter section. 2. If the pole is real and there are no other remaining real poles [#]_, add the closest real zero to the section and leave it as a first order section. Note that after this step we are guaranteed to be left with an even number of real poles, complex poles, real zeros, and complex zeros for subsequent pairing iterations. 3. Else: 1. If the pole is complex and the zero is the only remaining real zero*, then pair the pole with the *next* closest zero (guaranteed to be complex). This is necessary to ensure that there will be a real zero remaining to eventually create a first-order section (thus keeping the odd order). 2. Else pair the pole with the closest remaining zero (complex or real). 3. Proceed to complete the second-order section by adding another pole and zero to the current pole and zero in the section: 1. If the current pole and zero are both complex, add their conjugates. 2. Else if the pole is complex and the zero is real, add the conjugate pole and the next closest real zero. 3. Else if the pole is real and the zero is complex, add the conjugate zero and the real pole closest to those zeros. 4. Else (we must have a real pole and real zero) add the next real pole closest to the unit circle, and then add the real zero closest to that pole. .. [#] This conditional can only be met for specific odd-order inputs with the ``pairing == 'keep_odd'`` method. .. versionadded:: 0.16.0 Examples -------- Design a 6th order low-pass elliptic digital filter for a system with a sampling rate of 8000 Hz that has a pass-band corner frequency of 1000 Hz. The ripple in the pass-band should not exceed 0.087 dB, and the attenuation in the stop-band should be at least 90 dB. In the following call to `signal.ellip`, we could use ``output='sos'``, but for this example, we'll use ``output='zpk'``, and then convert to SOS format with `zpk2sos`: >>> from scipy import signal >>> z, p, k = signal.ellip(6, 0.087, 90, 1000/(0.5*8000), output='zpk') Now convert to SOS format. >>> sos = signal.zpk2sos(z, p, k) The coefficients of the numerators of the sections: >>> sos[:, :3] array([[ 0.0014154 , 0.00248707, 0.0014154 ], [ 1. , 0.72965193, 1. ], [ 1. , 0.17594966, 1. ]]) The symmetry in the coefficients occurs because all the zeros are on the unit circle. The coefficients of the denominators of the sections: >>> sos[:, 3:] array([[ 1. , -1.32543251, 0.46989499], [ 1. , -1.26117915, 0.6262586 ], [ 1. , -1.25707217, 0.86199667]]) The next example shows the effect of the `pairing` option. We have a system with three poles and three zeros, so the SOS array will have shape (2, 6). The means there is, in effect, an extra pole and an extra zero at the origin in the SOS representation. >>> z1 = np.array([-1, -0.5-0.5j, -0.5+0.5j]) >>> p1 = np.array([0.75, 0.8+0.1j, 0.8-0.1j]) With ``pairing='nearest'`` (the default), we obtain >>> signal.zpk2sos(z1, p1, 1) array([[ 1. , 1. , 0.5 , 1. , -0.75, 0. ], [ 1. , 1. , 0. , 1. , -1.6 , 0.65]]) The first section has the zeros {-0.5-0.05j, -0.5+0.5j} and the poles {0, 0.75}, and the second section has the zeros {-1, 0} and poles {0.8+0.1j, 0.8-0.1j}. Note that the extra pole and zero at the origin have been assigned to different sections. With ``pairing='keep_odd'``, we obtain: >>> signal.zpk2sos(z1, p1, 1, pairing='keep_odd') array([[ 1. , 1. , 0. , 1. , -0.75, 0. ], [ 1. , 1. , 0.5 , 1. , -1.6 , 0.65]]) The extra pole and zero at the origin are in the same section. The first section is, in effect, a first-order section. """ # TODO in the near future: # 1. Add SOS capability to `filtfilt`, `freqz`, etc. somehow (#3259). # 2. Make `decimate` use `sosfilt` instead of `lfilter`. # 3. Make sosfilt automatically simplify sections to first order # when possible. Note this might make `sosfiltfilt` a bit harder (ICs). # 4. Further optimizations of the section ordering / pole-zero pairing. # See the wiki for other potential issues. valid_pairings = ['nearest', 'keep_odd'] if pairing not in valid_pairings: raise ValueError('pairing must be one of %s, not %s' % (valid_pairings, pairing)) if len(z) == len(p) == 0: return array([[k, 0., 0., 1., 0., 0.]]) # ensure we have the same number of poles and zeros, and make copies p = np.concatenate((p, np.zeros(max(len(z) - len(p), 0)))) z = np.concatenate((z, np.zeros(max(len(p) - len(z), 0)))) n_sections = (max(len(p), len(z)) + 1) // 2 sos = zeros((n_sections, 6)) if len(p) % 2 == 1 and pairing == 'nearest': p = np.concatenate((p, [0.])) z = np.concatenate((z, [0.])) assert len(p) == len(z) # Ensure we have complex conjugate pairs # (note that _cplxreal only gives us one element of each complex pair): z = np.concatenate(_cplxreal(z)) p = np.concatenate(_cplxreal(p)) p_sos = np.zeros((n_sections, 2), np.complex128) z_sos = np.zeros_like(p_sos) for si in range(n_sections): # Select the next "worst" pole p1_idx = np.argmin(np.abs(1 - np.abs(p))) p1 = p[p1_idx] p = np.delete(p, p1_idx) # Pair that pole with a zero if np.isreal(p1) and np.isreal(p).sum() == 0: # Special case to set a first-order section z1_idx = _nearest_real_complex_idx(z, p1, 'real') z1 = z[z1_idx] z = np.delete(z, z1_idx) p2 = z2 = 0 else: if not np.isreal(p1) and np.isreal(z).sum() == 1: # Special case to ensure we choose a complex zero to pair # with so later (setting up a first-order section) z1_idx = _nearest_real_complex_idx(z, p1, 'complex') assert not np.isreal(z[z1_idx]) else: # Pair the pole with the closest zero (real or complex) z1_idx = np.argmin(np.abs(p1 - z)) z1 = z[z1_idx] z = np.delete(z, z1_idx) # Now that we have p1 and z1, figure out what p2 and z2 need to be if not np.isreal(p1): if not np.isreal(z1): # complex pole, complex zero p2 = p1.conj() z2 = z1.conj() else: # complex pole, real zero p2 = p1.conj() z2_idx = _nearest_real_complex_idx(z, p1, 'real') z2 = z[z2_idx] assert np.isreal(z2) z = np.delete(z, z2_idx) else: if not np.isreal(z1): # real pole, complex zero z2 = z1.conj() p2_idx = _nearest_real_complex_idx(p, z1, 'real') p2 = p[p2_idx] assert np.isreal(p2) else: # real pole, real zero # pick the next "worst" pole to use idx = np.where(np.isreal(p))[0] assert len(idx) > 0 p2_idx = idx[np.argmin(np.abs(np.abs(p[idx]) - 1))] p2 = p[p2_idx] # find a real zero to match the added pole assert np.isreal(p2) z2_idx = _nearest_real_complex_idx(z, p2, 'real') z2 = z[z2_idx] assert np.isreal(z2) z = np.delete(z, z2_idx) p = np.delete(p, p2_idx) p_sos[si] = [p1, p2] z_sos[si] = [z1, z2] assert len(p) == len(z) == 0 # we've consumed all poles and zeros del p, z # Construct the system, reversing order so the "worst" are last p_sos = np.reshape(p_sos[::-1], (n_sections, 2)) z_sos = np.reshape(z_sos[::-1], (n_sections, 2)) gains = np.ones(n_sections) gains[0] = k for si in range(n_sections): x = zpk2tf(z_sos[si], p_sos[si], gains[si]) sos[si] = np.concatenate(x) return sos def _align_nums(nums): """ Given an array of numerator coefficient arrays [[a_1, a_2,..., a_n],..., [b_1, b_2,..., b_m]], this function pads shorter numerator arrays with zero's so that all numerators have the same length. Such alignment is necessary for functions like 'tf2ss', which needs the alignment when dealing with SIMO transfer functions. """ try: # The statement can throw a ValueError if one # of the numerators is a single digit and another # is array-like e.g. if nums = [5, [1, 2, 3]] nums = asarray(nums) if not np.issubdtype(nums.dtype, np.number): raise ValueError("dtype of numerator is non-numeric") return nums except ValueError: nums = list(nums) maxwidth = len(max(nums, key=lambda num: atleast_1d(num).size)) for index, num in enumerate(nums): num = atleast_1d(num).tolist() nums[index] = [0] * (maxwidth - len(num)) + num return atleast_1d(nums) def normalize(b, a): """Normalize polynomial representation of a transfer function. If values of `b` are too close to 0, they are removed. In that case, a BadCoefficients warning is emitted. """ b = _align_nums(b) b, a = map(atleast_1d, (b, a)) if len(a.shape) != 1: raise ValueError("Denominator polynomial must be rank-1 array.") if len(b.shape) > 2: raise ValueError("Numerator polynomial must be rank-1 or" " rank-2 array.") if len(b.shape) == 1: b = asarray([b], b.dtype.char) while a[0] == 0.0 and len(a) > 1: a = a[1:] outb = b * (1.0) / a[0] outa = a * (1.0) / a[0] if allclose(0, outb[:, 0], atol=1e-14): warnings.warn("Badly conditioned filter coefficients (numerator): the " "results may be meaningless", BadCoefficients) while allclose(0, outb[:, 0], atol=1e-14) and (outb.shape[-1] > 1): outb = outb[:, 1:] if outb.shape[0] == 1: outb = outb[0] return outb, outa def lp2lp(b, a, wo=1.0): """ Transform a lowpass filter prototype to a different frequency. Return an analog low-pass filter with cutoff frequency `wo` from an analog low-pass filter prototype with unity cutoff frequency, in transfer function ('ba') representation. """ a, b = map(atleast_1d, (a, b)) try: wo = float(wo) except TypeError: wo = float(wo[0]) d = len(a) n = len(b) M = max((d, n)) pwo = pow(wo, numpy.arange(M - 1, -1, -1)) start1 = max((n - d, 0)) start2 = max((d - n, 0)) b = b * pwo[start1] / pwo[start2:] a = a * pwo[start1] / pwo[start1:] return normalize(b, a) def lp2hp(b, a, wo=1.0): """ Transform a lowpass filter prototype to a highpass filter. Return an analog high-pass filter with cutoff frequency `wo` from an analog low-pass filter prototype with unity cutoff frequency, in transfer function ('ba') representation. """ a, b = map(atleast_1d, (a, b)) try: wo = float(wo) except TypeError: wo = float(wo[0]) d = len(a) n = len(b) if wo != 1: pwo = pow(wo, numpy.arange(max((d, n)))) else: pwo = numpy.ones(max((d, n)), b.dtype.char) if d >= n: outa = a[::-1] * pwo outb = resize(b, (d,)) outb[n:] = 0.0 outb[:n] = b[::-1] * pwo[:n] else: outb = b[::-1] * pwo outa = resize(a, (n,)) outa[d:] = 0.0 outa[:d] = a[::-1] * pwo[:d] return normalize(outb, outa) def lp2bp(b, a, wo=1.0, bw=1.0): """ Transform a lowpass filter prototype to a bandpass filter. Return an analog band-pass filter with center frequency `wo` and bandwidth `bw` from an analog low-pass filter prototype with unity cutoff frequency, in transfer function ('ba') representation. """ a, b = map(atleast_1d, (a, b)) D = len(a) - 1 N = len(b) - 1 artype = mintypecode((a, b)) ma = max([N, D]) Np = N + ma Dp = D + ma bprime = numpy.zeros(Np + 1, artype) aprime = numpy.zeros(Dp + 1, artype) wosq = wo * wo for j in range(Np + 1): val = 0.0 for i in range(0, N + 1): for k in range(0, i + 1): if ma - i + 2 * k == j: val += comb(i, k) * b[N - i] * (wosq) ** (i - k) / bw ** i bprime[Np - j] = val for j in range(Dp + 1): val = 0.0 for i in range(0, D + 1): for k in range(0, i + 1): if ma - i + 2 * k == j: val += comb(i, k) * a[D - i] * (wosq) ** (i - k) / bw ** i aprime[Dp - j] = val return normalize(bprime, aprime) def lp2bs(b, a, wo=1.0, bw=1.0): """ Transform a lowpass filter prototype to a bandstop filter. Return an analog band-stop filter with center frequency `wo` and bandwidth `bw` from an analog low-pass filter prototype with unity cutoff frequency, in transfer function ('ba') representation. """ a, b = map(atleast_1d, (a, b)) D = len(a) - 1 N = len(b) - 1 artype = mintypecode((a, b)) M = max([N, D]) Np = M + M Dp = M + M bprime = numpy.zeros(Np + 1, artype) aprime = numpy.zeros(Dp + 1, artype) wosq = wo * wo for j in range(Np + 1): val = 0.0 for i in range(0, N + 1): for k in range(0, M - i + 1): if i + 2 * k == j: val += (comb(M - i, k) * b[N - i] * (wosq) ** (M - i - k) * bw ** i) bprime[Np - j] = val for j in range(Dp + 1): val = 0.0 for i in range(0, D + 1): for k in range(0, M - i + 1): if i + 2 * k == j: val += (comb(M - i, k) * a[D - i] * (wosq) ** (M - i - k) * bw ** i) aprime[Dp - j] = val return normalize(bprime, aprime) def bilinear(b, a, fs=1.0): """Return a digital filter from an analog one using a bilinear transform. The bilinear transform substitutes ``(z-1) / (z+1)`` for ``s``. """ fs = float(fs) a, b = map(atleast_1d, (a, b)) D = len(a) - 1 N = len(b) - 1 artype = float M = max([N, D]) Np = M Dp = M bprime = numpy.zeros(Np + 1, artype) aprime = numpy.zeros(Dp + 1, artype) for j in range(Np + 1): val = 0.0 for i in range(N + 1): for k in range(i + 1): for l in range(M - i + 1): if k + l == j: val += (comb(i, k) * comb(M - i, l) * b[N - i] * pow(2 * fs, i) * (-1) ** k) bprime[j] = real(val) for j in range(Dp + 1): val = 0.0 for i in range(D + 1): for k in range(i + 1): for l in range(M - i + 1): if k + l == j: val += (comb(i, k) * comb(M - i, l) * a[D - i] * pow(2 * fs, i) * (-1) ** k) aprime[j] = real(val) return normalize(bprime, aprime) def iirdesign(wp, ws, gpass, gstop, analog=False, ftype='ellip', output='ba'): """Complete IIR digital and analog filter design. Given passband and stopband frequencies and gains, construct an analog or digital IIR filter of minimum order for a given basic type. Return the output in numerator, denominator ('ba'), pole-zero ('zpk') or second order sections ('sos') form. Parameters ---------- wp, ws : float Passband and stopband edge frequencies. For digital filters, these are normalized from 0 to 1, where 1 is the Nyquist frequency, pi radians/sample. (`wp` and `ws` are thus in half-cycles / sample.) For example: - Lowpass: wp = 0.2, ws = 0.3 - Highpass: wp = 0.3, ws = 0.2 - Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6] - Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5] For analog filters, `wp` and `ws` are angular frequencies (e.g. rad/s). gpass : float The maximum loss in the passband (dB). gstop : float The minimum attenuation in the stopband (dB). analog : bool, optional When True, return an analog filter, otherwise a digital filter is returned. ftype : str, optional The type of IIR filter to design: - Butterworth : 'butter' - Chebyshev I : 'cheby1' - Chebyshev II : 'cheby2' - Cauer/elliptic: 'ellip' - Bessel/Thomson: 'bessel' output : {'ba', 'zpk', 'sos'}, optional Type of output: numerator/denominator ('ba'), pole-zero ('zpk'), or second-order sections ('sos'). Default is 'ba'. Returns ------- b, a : ndarray, ndarray Numerator (`b`) and denominator (`a`) polynomials of the IIR filter. Only returned if ``output='ba'``. z, p, k : ndarray, ndarray, float Zeros, poles, and system gain of the IIR filter transfer function. Only returned if ``output='zpk'``. sos : ndarray Second-order sections representation of the IIR filter. Only returned if ``output=='sos'``. See Also -------- butter : Filter design using order and critical points cheby1, cheby2, ellip, bessel buttord : Find order and critical points from passband and stopband spec cheb1ord, cheb2ord, ellipord iirfilter : General filter design using order and critical frequencies Notes ----- The ``'sos'`` output parameter was added in 0.16.0. """ try: ordfunc = filter_dict[ftype][1] except KeyError: raise ValueError("Invalid IIR filter type: %s" % ftype) except IndexError: raise ValueError(("%s does not have order selection. Use " "iirfilter function.") % ftype) wp = atleast_1d(wp) ws = atleast_1d(ws) band_type = 2 * (len(wp) - 1) band_type += 1 if wp[0] >= ws[0]: band_type += 1 btype = {1: 'lowpass', 2: 'highpass', 3: 'bandstop', 4: 'bandpass'}[band_type] N, Wn = ordfunc(wp, ws, gpass, gstop, analog=analog) return iirfilter(N, Wn, rp=gpass, rs=gstop, analog=analog, btype=btype, ftype=ftype, output=output) def iirfilter(N, Wn, rp=None, rs=None, btype='band', analog=False, ftype='butter', output='ba'): """ IIR digital and analog filter design given order and critical points. Design an Nth-order digital or analog filter and return the filter coefficients. Parameters ---------- N : int The order of the filter. Wn : array_like A scalar or length-2 sequence giving the critical frequencies. For digital filters, `Wn` is normalized from 0 to 1, where 1 is the Nyquist frequency, pi radians/sample. (`Wn` is thus in half-cycles / sample.) For analog filters, `Wn` is an angular frequency (e.g. rad/s). rp : float, optional For Chebyshev and elliptic filters, provides the maximum ripple in the passband. (dB) rs : float, optional For Chebyshev and elliptic filters, provides the minimum attenuation in the stop band. (dB) btype : {'bandpass', 'lowpass', 'highpass', 'bandstop'}, optional The type of filter. Default is 'bandpass'. analog : bool, optional When True, return an analog filter, otherwise a digital filter is returned. ftype : str, optional The type of IIR filter to design: - Butterworth : 'butter' - Chebyshev I : 'cheby1' - Chebyshev II : 'cheby2' - Cauer/elliptic: 'ellip' - Bessel/Thomson: 'bessel' output : {'ba', 'zpk', 'sos'}, optional Type of output: numerator/denominator ('ba'), pole-zero ('zpk'), or second-order sections ('sos'). Default is 'ba'. Returns ------- b, a : ndarray, ndarray Numerator (`b`) and denominator (`a`) polynomials of the IIR filter. Only returned if ``output='ba'``. z, p, k : ndarray, ndarray, float Zeros, poles, and system gain of the IIR filter transfer function. Only returned if ``output='zpk'``. sos : ndarray Second-order sections representation of the IIR filter. Only returned if ``output=='sos'``. See Also -------- butter : Filter design using order and critical points cheby1, cheby2, ellip, bessel buttord : Find order and critical points from passband and stopband spec cheb1ord, cheb2ord, ellipord iirdesign : General filter design using passband and stopband spec Notes ----- The ``'sos'`` output parameter was added in 0.16.0. Examples -------- Generate a 17th-order Chebyshev II bandpass filter and plot the frequency response: >>> from scipy import signal >>> import matplotlib.pyplot as plt >>> b, a = signal.iirfilter(17, [50, 200], rs=60, btype='band', ... analog=True, ftype='cheby2') >>> w, h = signal.freqs(b, a, 1000) >>> fig = plt.figure() >>> ax = fig.add_subplot(111) >>> ax.semilogx(w, 20 * np.log10(abs(h))) >>> ax.set_title('Chebyshev Type II bandpass frequency response') >>> ax.set_xlabel('Frequency [radians / second]') >>> ax.set_ylabel('Amplitude [dB]') >>> ax.axis((10, 1000, -100, 10)) >>> ax.grid(which='both', axis='both') >>> plt.show() """ ftype, btype, output = [x.lower() for x in (ftype, btype, output)] Wn = asarray(Wn) try: btype = band_dict[btype] except KeyError: raise ValueError("'%s' is an invalid bandtype for filter." % btype) try: typefunc = filter_dict[ftype][0] except KeyError: raise ValueError("'%s' is not a valid basic IIR filter." % ftype) if output not in ['ba', 'zpk', 'sos']: raise ValueError("'%s' is not a valid output form." % output) if rp is not None and rp < 0: raise ValueError("passband ripple (rp) must be positive") if rs is not None and rs < 0: raise ValueError("stopband attenuation (rs) must be positive") # Get analog lowpass prototype if typefunc == buttap: z, p, k = typefunc(N) elif typefunc == besselap: z, p, k = typefunc(N, norm=bessel_norms[ftype]) elif typefunc == cheb1ap: if rp is None: raise ValueError("passband ripple (rp) must be provided to " "design a Chebyshev I filter.") z, p, k = typefunc(N, rp) elif typefunc == cheb2ap: if rs is None: raise ValueError("stopband attenuation (rs) must be provided to " "design an Chebyshev II filter.") z, p, k = typefunc(N, rs) elif typefunc == ellipap: if rs is None or rp is None: raise ValueError("Both rp and rs must be provided to design an " "elliptic filter.") z, p, k = typefunc(N, rp, rs) else: raise NotImplementedError("'%s' not implemented in iirfilter." % ftype) # Pre-warp frequencies for digital filter design if not analog: if numpy.any(Wn < 0) or numpy.any(Wn > 1): raise ValueError("Digital filter critical frequencies " "must be 0 <= Wn <= 1") fs = 2.0 warped = 2 * fs * tan(pi * Wn / fs) else: warped = Wn # transform to lowpass, bandpass, highpass, or bandstop if btype in ('lowpass', 'highpass'): if numpy.size(Wn) != 1: raise ValueError('Must specify a single critical frequency Wn') if btype == 'lowpass': z, p, k = _zpklp2lp(z, p, k, wo=warped) elif btype == 'highpass': z, p, k = _zpklp2hp(z, p, k, wo=warped) elif btype in ('bandpass', 'bandstop'): try: bw = warped[1] - warped[0] wo = sqrt(warped[0] * warped[1]) except IndexError: raise ValueError('Wn must specify start and stop frequencies') if btype == 'bandpass': z, p, k = _zpklp2bp(z, p, k, wo=wo, bw=bw) elif btype == 'bandstop': z, p, k = _zpklp2bs(z, p, k, wo=wo, bw=bw) else: raise NotImplementedError("'%s' not implemented in iirfilter." % btype) # Find discrete equivalent if necessary if not analog: z, p, k = _zpkbilinear(z, p, k, fs=fs) # Transform to proper out type (pole-zero, state-space, numer-denom) if output == 'zpk': return z, p, k elif output == 'ba': return zpk2tf(z, p, k) elif output == 'sos': return zpk2sos(z, p, k) def _relative_degree(z, p): """ Return relative degree of transfer function from zeros and poles """ degree = len(p) - len(z) if degree < 0: raise ValueError("Improper transfer function. " "Must have at least as many poles as zeros.") else: return degree # TODO: merge these into existing functions or make public versions def _zpkbilinear(z, p, k, fs): """ Return a digital filter from an analog one using a bilinear transform. Transform a set of poles and zeros from the analog s-plane to the digital z-plane using Tustin's method, which substitutes ``(z-1) / (z+1)`` for ``s``, maintaining the shape of the frequency response. Parameters ---------- z : array_like Zeros of the analog IIR filter transfer function. p : array_like Poles of the analog IIR filter transfer function. k : float System gain of the analog IIR filter transfer function. fs : float Sample rate, as ordinary frequency (e.g. hertz). No prewarping is done in this function. Returns ------- z : ndarray Zeros of the transformed digital filter transfer function. p : ndarray Poles of the transformed digital filter transfer function. k : float System gain of the transformed digital filter. """ z = atleast_1d(z) p = atleast_1d(p) degree = _relative_degree(z, p) fs2 = 2*fs # Bilinear transform the poles and zeros z_z = (fs2 + z) / (fs2 - z) p_z = (fs2 + p) / (fs2 - p) # Any zeros that were at infinity get moved to the Nyquist frequency z_z = append(z_z, -ones(degree)) # Compensate for gain change k_z = k * real(prod(fs2 - z) / prod(fs2 - p)) return z_z, p_z, k_z def _zpklp2lp(z, p, k, wo=1.0): r""" Transform a lowpass filter prototype to a different frequency. Return an analog low-pass filter with cutoff frequency `wo` from an analog low-pass filter prototype with unity cutoff frequency, using zeros, poles, and gain ('zpk') representation. Parameters ---------- z : array_like Zeros of the analog IIR filter transfer function. p : array_like Poles of the analog IIR filter transfer function. k : float System gain of the analog IIR filter transfer function. wo : float Desired cutoff, as angular frequency (e.g. rad/s). Defaults to no change. Returns ------- z : ndarray Zeros of the transformed low-pass filter transfer function. p : ndarray Poles of the transformed low-pass filter transfer function. k : float System gain of the transformed low-pass filter. Notes ----- This is derived from the s-plane substitution .. math:: s \rightarrow \frac{s}{\omega_0} """ z = atleast_1d(z) p = atleast_1d(p) wo = float(wo) # Avoid int wraparound degree = _relative_degree(z, p) # Scale all points radially from origin to shift cutoff frequency z_lp = wo * z p_lp = wo * p # Each shifted pole decreases gain by wo, each shifted zero increases it. # Cancel out the net change to keep overall gain the same k_lp = k * wo**degree return z_lp, p_lp, k_lp def _zpklp2hp(z, p, k, wo=1.0): r""" Transform a lowpass filter prototype to a highpass filter. Return an analog high-pass filter with cutoff frequency `wo` from an analog low-pass filter prototype with unity cutoff frequency, using zeros, poles, and gain ('zpk') representation. Parameters ---------- z : array_like Zeros of the analog IIR filter transfer function. p : array_like Poles of the analog IIR filter transfer function. k : float System gain of the analog IIR filter transfer function. wo : float Desired cutoff, as angular frequency (e.g. rad/s). Defaults to no change. Returns ------- z : ndarray Zeros of the transformed high-pass filter transfer function. p : ndarray Poles of the transformed high-pass filter transfer function. k : float System gain of the transformed high-pass filter. Notes ----- This is derived from the s-plane substitution .. math:: s \rightarrow \frac{\omega_0}{s} This maintains symmetry of the lowpass and highpass responses on a logarithmic scale. """ z = atleast_1d(z) p = atleast_1d(p) wo = float(wo) degree = _relative_degree(z, p) # Invert positions radially about unit circle to convert LPF to HPF # Scale all points radially from origin to shift cutoff frequency z_hp = wo / z p_hp = wo / p # If lowpass had zeros at infinity, inverting moves them to origin. z_hp = append(z_hp, zeros(degree)) # Cancel out gain change caused by inversion k_hp = k * real(prod(-z) / prod(-p)) return z_hp, p_hp, k_hp def _zpklp2bp(z, p, k, wo=1.0, bw=1.0): r""" Transform a lowpass filter prototype to a bandpass filter. Return an analog band-pass filter with center frequency `wo` and bandwidth `bw` from an analog low-pass filter prototype with unity cutoff frequency, using zeros, poles, and gain ('zpk') representation. Parameters ---------- z : array_like Zeros of the analog IIR filter transfer function. p : array_like Poles of the analog IIR filter transfer function. k : float System gain of the analog IIR filter transfer function. wo : float Desired passband center, as angular frequency (e.g. rad/s). Defaults to no change. bw : float Desired passband width, as angular frequency (e.g. rad/s). Defaults to 1. Returns ------- z : ndarray Zeros of the transformed band-pass filter transfer function. p : ndarray Poles of the transformed band-pass filter transfer function. k : float System gain of the transformed band-pass filter. Notes ----- This is derived from the s-plane substitution .. math:: s \rightarrow \frac{s^2 + {\omega_0}^2}{s \cdot \mathrm{BW}} This is the "wideband" transformation, producing a passband with geometric (log frequency) symmetry about `wo`. """ z = atleast_1d(z) p = atleast_1d(p) wo = float(wo) bw = float(bw) degree = _relative_degree(z, p) # Scale poles and zeros to desired bandwidth z_lp = z * bw/2 p_lp = p * bw/2 # Square root needs to produce complex result, not NaN z_lp = z_lp.astype(complex) p_lp = p_lp.astype(complex) # Duplicate poles and zeros and shift from baseband to +wo and -wo z_bp = concatenate((z_lp + sqrt(z_lp**2 - wo**2), z_lp - sqrt(z_lp**2 - wo**2))) p_bp = concatenate((p_lp + sqrt(p_lp**2 - wo**2), p_lp - sqrt(p_lp**2 - wo**2))) # Move degree zeros to origin, leaving degree zeros at infinity for BPF z_bp = append(z_bp, zeros(degree)) # Cancel out gain change from frequency scaling k_bp = k * bw**degree return z_bp, p_bp, k_bp def _zpklp2bs(z, p, k, wo=1.0, bw=1.0): r""" Transform a lowpass filter prototype to a bandstop filter. Return an analog band-stop filter with center frequency `wo` and stopband width `bw` from an analog low-pass filter prototype with unity cutoff frequency, using zeros, poles, and gain ('zpk') representation. Parameters ---------- z : array_like Zeros of the analog IIR filter transfer function. p : array_like Poles of the analog IIR filter transfer function. k : float System gain of the analog IIR filter transfer function. wo : float Desired stopband center, as angular frequency (e.g. rad/s). Defaults to no change. bw : float Desired stopband width, as angular frequency (e.g. rad/s). Defaults to 1. Returns ------- z : ndarray Zeros of the transformed band-stop filter transfer function. p : ndarray Poles of the transformed band-stop filter transfer function. k : float System gain of the transformed band-stop filter. Notes ----- This is derived from the s-plane substitution .. math:: s \rightarrow \frac{s \cdot \mathrm{BW}}{s^2 + {\omega_0}^2} This is the "wideband" transformation, producing a stopband with geometric (log frequency) symmetry about `wo`. """ z = atleast_1d(z) p = atleast_1d(p) wo = float(wo) bw = float(bw) degree = _relative_degree(z, p) # Invert to a highpass filter with desired bandwidth z_hp = (bw/2) / z p_hp = (bw/2) / p # Square root needs to produce complex result, not NaN z_hp = z_hp.astype(complex) p_hp = p_hp.astype(complex) # Duplicate poles and zeros and shift from baseband to +wo and -wo z_bs = concatenate((z_hp + sqrt(z_hp**2 - wo**2), z_hp - sqrt(z_hp**2 - wo**2))) p_bs = concatenate((p_hp + sqrt(p_hp**2 - wo**2), p_hp - sqrt(p_hp**2 - wo**2))) # Move any zeros that were at infinity to the center of the stopband z_bs = append(z_bs, +1j*wo * ones(degree)) z_bs = append(z_bs, -1j*wo * ones(degree)) # Cancel out gain change caused by inversion k_bs = k * real(prod(-z) / prod(-p)) return z_bs, p_bs, k_bs def butter(N, Wn, btype='low', analog=False, output='ba'): """ Butterworth digital and analog filter design. Design an Nth-order digital or analog Butterworth filter and return the filter coefficients. Parameters ---------- N : int The order of the filter. Wn : array_like A scalar or length-2 sequence giving the critical frequencies. For a Butterworth filter, this is the point at which the gain drops to 1/sqrt(2) that of the passband (the "-3 dB point"). For digital filters, `Wn` is normalized from 0 to 1, where 1 is the Nyquist frequency, pi radians/sample. (`Wn` is thus in half-cycles / sample.) For analog filters, `Wn` is an angular frequency (e.g. rad/s). btype : {'lowpass', 'highpass', 'bandpass', 'bandstop'}, optional The type of filter. Default is 'lowpass'. analog : bool, optional When True, return an analog filter, otherwise a digital filter is returned. output : {'ba', 'zpk', 'sos'}, optional Type of output: numerator/denominator ('ba'), pole-zero ('zpk'), or second-order sections ('sos'). Default is 'ba'. Returns ------- b, a : ndarray, ndarray Numerator (`b`) and denominator (`a`) polynomials of the IIR filter. Only returned if ``output='ba'``. z, p, k : ndarray, ndarray, float Zeros, poles, and system gain of the IIR filter transfer function. Only returned if ``output='zpk'``. sos : ndarray Second-order sections representation of the IIR filter. Only returned if ``output=='sos'``. See Also -------- buttord, buttap Notes ----- The Butterworth filter has maximally flat frequency response in the passband. The ``'sos'`` output parameter was added in 0.16.0. Examples -------- Plot the filter's frequency response, showing the critical points: >>> from scipy import signal >>> import matplotlib.pyplot as plt >>> b, a = signal.butter(4, 100, 'low', analog=True) >>> w, h = signal.freqs(b, a) >>> plt.semilogx(w, 20 * np.log10(abs(h))) >>> plt.title('Butterworth filter frequency response') >>> plt.xlabel('Frequency [radians / second]') >>> plt.ylabel('Amplitude [dB]') >>> plt.margins(0, 0.1) >>> plt.grid(which='both', axis='both') >>> plt.axvline(100, color='green') # cutoff frequency >>> plt.show() """ return iirfilter(N, Wn, btype=btype, analog=analog, output=output, ftype='butter') def cheby1(N, rp, Wn, btype='low', analog=False, output='ba'): """ Chebyshev type I digital and analog filter design. Design an Nth-order digital or analog Chebyshev type I filter and return the filter coefficients. Parameters ---------- N : int The order of the filter. rp : float The maximum ripple allowed below unity gain in the passband. Specified in decibels, as a positive number. Wn : array_like A scalar or length-2 sequence giving the critical frequencies. For Type I filters, this is the point in the transition band at which the gain first drops below -`rp`. For digital filters, `Wn` is normalized from 0 to 1, where 1 is the Nyquist frequency, pi radians/sample. (`Wn` is thus in half-cycles / sample.) For analog filters, `Wn` is an angular frequency (e.g. rad/s). btype : {'lowpass', 'highpass', 'bandpass', 'bandstop'}, optional The type of filter. Default is 'lowpass'. analog : bool, optional When True, return an analog filter, otherwise a digital filter is returned. output : {'ba', 'zpk', 'sos'}, optional Type of output: numerator/denominator ('ba'), pole-zero ('zpk'), or second-order sections ('sos'). Default is 'ba'. Returns ------- b, a : ndarray, ndarray Numerator (`b`) and denominator (`a`) polynomials of the IIR filter. Only returned if ``output='ba'``. z, p, k : ndarray, ndarray, float Zeros, poles, and system gain of the IIR filter transfer function. Only returned if ``output='zpk'``. sos : ndarray Second-order sections representation of the IIR filter. Only returned if ``output=='sos'``. See Also -------- cheb1ord, cheb1ap Notes ----- The Chebyshev type I filter maximizes the rate of cutoff between the frequency response's passband and stopband, at the expense of ripple in the passband and increased ringing in the step response. Type I filters roll off faster than Type II (`cheby2`), but Type II filters do not have any ripple in the passband. The equiripple passband has N maxima or minima (for example, a 5th-order filter has 3 maxima and 2 minima). Consequently, the DC gain is unity for odd-order filters, or -rp dB for even-order filters. The ``'sos'`` output parameter was added in 0.16.0. Examples -------- Plot the filter's frequency response, showing the critical points: >>> from scipy import signal >>> import matplotlib.pyplot as plt >>> b, a = signal.cheby1(4, 5, 100, 'low', analog=True) >>> w, h = signal.freqs(b, a) >>> plt.semilogx(w, 20 * np.log10(abs(h))) >>> plt.title('Chebyshev Type I frequency response (rp=5)') >>> plt.xlabel('Frequency [radians / second]') >>> plt.ylabel('Amplitude [dB]') >>> plt.margins(0, 0.1) >>> plt.grid(which='both', axis='both') >>> plt.axvline(100, color='green') # cutoff frequency >>> plt.axhline(-5, color='green') # rp >>> plt.show() """ return iirfilter(N, Wn, rp=rp, btype=btype, analog=analog, output=output, ftype='cheby1') def cheby2(N, rs, Wn, btype='low', analog=False, output='ba'): """ Chebyshev type II digital and analog filter design. Design an Nth-order digital or analog Chebyshev type II filter and return the filter coefficients. Parameters ---------- N : int The order of the filter. rs : float The minimum attenuation required in the stop band. Specified in decibels, as a positive number. Wn : array_like A scalar or length-2 sequence giving the critical frequencies. For Type II filters, this is the point in the transition band at which the gain first reaches -`rs`. For digital filters, `Wn` is normalized from 0 to 1, where 1 is the Nyquist frequency, pi radians/sample. (`Wn` is thus in half-cycles / sample.) For analog filters, `Wn` is an angular frequency (e.g. rad/s). btype : {'lowpass', 'highpass', 'bandpass', 'bandstop'}, optional The type of filter. Default is 'lowpass'. analog : bool, optional When True, return an analog filter, otherwise a digital filter is returned. output : {'ba', 'zpk', 'sos'}, optional Type of output: numerator/denominator ('ba'), pole-zero ('zpk'), or second-order sections ('sos'). Default is 'ba'. Returns ------- b, a : ndarray, ndarray Numerator (`b`) and denominator (`a`) polynomials of the IIR filter. Only returned if ``output='ba'``. z, p, k : ndarray, ndarray, float Zeros, poles, and system gain of the IIR filter transfer function. Only returned if ``output='zpk'``. sos : ndarray Second-order sections representation of the IIR filter. Only returned if ``output=='sos'``. See Also -------- cheb2ord, cheb2ap Notes ----- The Chebyshev type II filter maximizes the rate of cutoff between the frequency response's passband and stopband, at the expense of ripple in the stopband and increased ringing in the step response. Type II filters do not roll off as fast as Type I (`cheby1`). The ``'sos'`` output parameter was added in 0.16.0. Examples -------- Plot the filter's frequency response, showing the critical points: >>> from scipy import signal >>> import matplotlib.pyplot as plt >>> b, a = signal.cheby2(4, 40, 100, 'low', analog=True) >>> w, h = signal.freqs(b, a) >>> plt.semilogx(w, 20 * np.log10(abs(h))) >>> plt.title('Chebyshev Type II frequency response (rs=40)') >>> plt.xlabel('Frequency [radians / second]') >>> plt.ylabel('Amplitude [dB]') >>> plt.margins(0, 0.1) >>> plt.grid(which='both', axis='both') >>> plt.axvline(100, color='green') # cutoff frequency >>> plt.axhline(-40, color='green') # rs >>> plt.show() """ return iirfilter(N, Wn, rs=rs, btype=btype, analog=analog, output=output, ftype='cheby2') def ellip(N, rp, rs, Wn, btype='low', analog=False, output='ba'): """ Elliptic (Cauer) digital and analog filter design. Design an Nth-order digital or analog elliptic filter and return the filter coefficients. Parameters ---------- N : int The order of the filter. rp : float The maximum ripple allowed below unity gain in the passband. Specified in decibels, as a positive number. rs : float The minimum attenuation required in the stop band. Specified in decibels, as a positive number. Wn : array_like A scalar or length-2 sequence giving the critical frequencies. For elliptic filters, this is the point in the transition band at which the gain first drops below -`rp`. For digital filters, `Wn` is normalized from 0 to 1, where 1 is the Nyquist frequency, pi radians/sample. (`Wn` is thus in half-cycles / sample.) For analog filters, `Wn` is an angular frequency (e.g. rad/s). btype : {'lowpass', 'highpass', 'bandpass', 'bandstop'}, optional The type of filter. Default is 'lowpass'. analog : bool, optional When True, return an analog filter, otherwise a digital filter is returned. output : {'ba', 'zpk', 'sos'}, optional Type of output: numerator/denominator ('ba'), pole-zero ('zpk'), or second-order sections ('sos'). Default is 'ba'. Returns ------- b, a : ndarray, ndarray Numerator (`b`) and denominator (`a`) polynomials of the IIR filter. Only returned if ``output='ba'``. z, p, k : ndarray, ndarray, float Zeros, poles, and system gain of the IIR filter transfer function. Only returned if ``output='zpk'``. sos : ndarray Second-order sections representation of the IIR filter. Only returned if ``output=='sos'``. See Also -------- ellipord, ellipap Notes ----- Also known as Cauer or Zolotarev filters, the elliptical filter maximizes the rate of transition between the frequency response's passband and stopband, at the expense of ripple in both, and increased ringing in the step response. As `rp` approaches 0, the elliptical filter becomes a Chebyshev type II filter (`cheby2`). As `rs` approaches 0, it becomes a Chebyshev type I filter (`cheby1`). As both approach 0, it becomes a Butterworth filter (`butter`). The equiripple passband has N maxima or minima (for example, a 5th-order filter has 3 maxima and 2 minima). Consequently, the DC gain is unity for odd-order filters, or -rp dB for even-order filters. The ``'sos'`` output parameter was added in 0.16.0. Examples -------- Plot the filter's frequency response, showing the critical points: >>> from scipy import signal >>> import matplotlib.pyplot as plt >>> b, a = signal.ellip(4, 5, 40, 100, 'low', analog=True) >>> w, h = signal.freqs(b, a) >>> plt.semilogx(w, 20 * np.log10(abs(h))) >>> plt.title('Elliptic filter frequency response (rp=5, rs=40)') >>> plt.xlabel('Frequency [radians / second]') >>> plt.ylabel('Amplitude [dB]') >>> plt.margins(0, 0.1) >>> plt.grid(which='both', axis='both') >>> plt.axvline(100, color='green') # cutoff frequency >>> plt.axhline(-40, color='green') # rs >>> plt.axhline(-5, color='green') # rp >>> plt.show() """ return iirfilter(N, Wn, rs=rs, rp=rp, btype=btype, analog=analog, output=output, ftype='elliptic') def bessel(N, Wn, btype='low', analog=False, output='ba', norm='phase'): """Bessel/Thomson digital and analog filter design. Design an Nth-order digital or analog Bessel filter and return the filter coefficients. Parameters ---------- N : int The order of the filter. Wn : array_like A scalar or length-2 sequence giving the critical frequencies (defined by the `norm` parameter). For analog filters, `Wn` is an angular frequency (e.g. rad/s). For digital filters, `Wn` is normalized from 0 to 1, where 1 is the Nyquist frequency, pi radians/sample. (`Wn` is thus in half-cycles / sample.) btype : {'lowpass', 'highpass', 'bandpass', 'bandstop'}, optional The type of filter. Default is 'lowpass'. analog : bool, optional When True, return an analog filter, otherwise a digital filter is returned. (See Notes.) output : {'ba', 'zpk', 'sos'}, optional Type of output: numerator/denominator ('ba'), pole-zero ('zpk'), or second-order sections ('sos'). Default is 'ba'. norm : {'phase', 'delay', 'mag'}, optional Critical frequency normalization: ``phase`` The filter is normalized such that the phase response reaches its midpoint at angular (e.g. rad/s) frequency `Wn`. This happens for both low-pass and high-pass filters, so this is the "phase-matched" case. The magnitude response asymptotes are the same as a Butterworth filter of the same order with a cutoff of `Wn`. This is the default, and matches MATLAB's implementation. ``delay`` The filter is normalized such that the group delay in the passband is 1/`Wn` (e.g. seconds). This is the "natural" type obtained by solving Bessel polynomials. ``mag`` The filter is normalized such that the gain magnitude is -3 dB at angular frequency `Wn`. .. versionadded:: 0.18.0 Returns ------- b, a : ndarray, ndarray Numerator (`b`) and denominator (`a`) polynomials of the IIR filter. Only returned if ``output='ba'``. z, p, k : ndarray, ndarray, float Zeros, poles, and system gain of the IIR filter transfer function. Only returned if ``output='zpk'``. sos : ndarray Second-order sections representation of the IIR filter. Only returned if ``output=='sos'``. Notes ----- Also known as a Thomson filter, the analog Bessel filter has maximally flat group delay and maximally linear phase response, with very little ringing in the step response. [1]_ The Bessel is inherently an analog filter. This function generates digital Bessel filters using the bilinear transform, which does not preserve the phase response of the analog filter. As such, it is only approximately correct at frequencies below about fs/4. To get maximally-flat group delay at higher frequencies, the analog Bessel filter must be transformed using phase-preserving techniques. See `besselap` for implementation details and references. The ``'sos'`` output parameter was added in 0.16.0. Examples -------- Plot the phase-normalized frequency response, showing the relationship to the Butterworth's cutoff frequency (green): >>> from scipy import signal >>> import matplotlib.pyplot as plt >>> b, a = signal.butter(4, 100, 'low', analog=True) >>> w, h = signal.freqs(b, a) >>> plt.semilogx(w, 20 * np.log10(np.abs(h)), color='silver', ls='dashed') >>> b, a = signal.bessel(4, 100, 'low', analog=True, norm='phase') >>> w, h = signal.freqs(b, a) >>> plt.semilogx(w, 20 * np.log10(np.abs(h))) >>> plt.title('Bessel filter magnitude response (with Butterworth)') >>> plt.xlabel('Frequency [radians / second]') >>> plt.ylabel('Amplitude [dB]') >>> plt.margins(0, 0.1) >>> plt.grid(which='both', axis='both') >>> plt.axvline(100, color='green') # cutoff frequency >>> plt.show() and the phase midpoint: >>> plt.figure() >>> plt.semilogx(w, np.unwrap(np.angle(h))) >>> plt.axvline(100, color='green') # cutoff frequency >>> plt.axhline(-np.pi, color='red') # phase midpoint >>> plt.title('Bessel filter phase response') >>> plt.xlabel('Frequency [radians / second]') >>> plt.ylabel('Phase [radians]') >>> plt.margins(0, 0.1) >>> plt.grid(which='both', axis='both') >>> plt.show() Plot the magnitude-normalized frequency response, showing the -3 dB cutoff: >>> b, a = signal.bessel(3, 10, 'low', analog=True, norm='mag') >>> w, h = signal.freqs(b, a) >>> plt.semilogx(w, 20 * np.log10(np.abs(h))) >>> plt.axhline(-3, color='red') # -3 dB magnitude >>> plt.axvline(10, color='green') # cutoff frequency >>> plt.title('Magnitude-normalized Bessel filter frequency response') >>> plt.xlabel('Frequency [radians / second]') >>> plt.ylabel('Amplitude [dB]') >>> plt.margins(0, 0.1) >>> plt.grid(which='both', axis='both') >>> plt.show() Plot the delay-normalized filter, showing the maximally-flat group delay at 0.1 seconds: >>> b, a = signal.bessel(5, 1/0.1, 'low', analog=True, norm='delay') >>> w, h = signal.freqs(b, a) >>> plt.figure() >>> plt.semilogx(w[1:], -np.diff(np.unwrap(np.angle(h)))/np.diff(w)) >>> plt.axhline(0.1, color='red') # 0.1 seconds group delay >>> plt.title('Bessel filter group delay') >>> plt.xlabel('Frequency [radians / second]') >>> plt.ylabel('Group delay [seconds]') >>> plt.margins(0, 0.1) >>> plt.grid(which='both', axis='both') >>> plt.show() References ---------- .. [1] <NAME>., "Delay Networks having Maximally Flat Frequency Characteristics", Proceedings of the Institution of Electrical Engineers, Part III, November 1949, Vol. 96, No. 44, pp. 487-490. """ return iirfilter(N, Wn, btype=btype, analog=analog, output=output, ftype='bessel_'+norm) def maxflat(): pass def yulewalk(): pass def band_stop_obj(wp, ind, passb, stopb, gpass, gstop, type): """ Band Stop Objective Function for order minimization. Returns the non-integer order for an analog band stop filter. Parameters ---------- wp : scalar Edge of passband `passb`. ind : int, {0, 1} Index specifying which `passb` edge to vary (0 or 1). passb : ndarray Two element sequence of fixed passband edges. stopb : ndarray Two element sequence of fixed stopband edges. gstop : float Amount of attenuation in stopband in dB. gpass : float Amount of ripple in the passband in dB. type : {'butter', 'cheby', 'ellip'} Type of filter. Returns ------- n : scalar Filter order (possibly non-integer). """ passbC = passb.copy() passbC[ind] = wp nat = (stopb * (passbC[0] - passbC[1]) / (stopb ** 2 - passbC[0] * passbC[1])) nat = min(abs(nat)) if type == 'butter': GSTOP = 10 ** (0.1 * abs(gstop)) GPASS = 10 ** (0.1 * abs(gpass)) n = (log10((GSTOP - 1.0) / (GPASS - 1.0)) / (2 * log10(nat))) elif type == 'cheby': GSTOP = 10 ** (0.1 * abs(gstop)) GPASS = 10 ** (0.1 * abs(gpass)) n = arccosh(sqrt((GSTOP - 1.0) / (GPASS - 1.0))) / arccosh(nat) elif type == 'ellip': GSTOP = 10 ** (0.1 * gstop) GPASS = 10 ** (0.1 * gpass) arg1 = sqrt((GPASS - 1.0) / (GSTOP - 1.0)) arg0 = 1.0 / nat d0 = special.ellipk([arg0 ** 2, 1 - arg0 ** 2]) d1 = special.ellipk([arg1 ** 2, 1 - arg1 ** 2]) n = (d0[0] * d1[1] / (d0[1] * d1[0])) else: raise ValueError("Incorrect type: %s" % type) return n def buttord(wp, ws, gpass, gstop, analog=False): """Butterworth filter order selection. Return the order of the lowest order digital or analog Butterworth filter that loses no more than `gpass` dB in the passband and has at least `gstop` dB attenuation in the stopband. Parameters ---------- wp, ws : float Passband and stopband edge frequencies. For digital filters, these are normalized from 0 to 1, where 1 is the Nyquist frequency, pi radians/sample. (`wp` and `ws` are thus in half-cycles / sample.) For example: - Lowpass: wp = 0.2, ws = 0.3 - Highpass: wp = 0.3, ws = 0.2 - Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6] - Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5] For analog filters, `wp` and `ws` are angular frequencies (e.g. rad/s). gpass : float The maximum loss in the passband (dB). gstop : float The minimum attenuation in the stopband (dB). analog : bool, optional When True, return an analog filter, otherwise a digital filter is returned. Returns ------- ord : int The lowest order for a Butterworth filter which meets specs. wn : ndarray or float The Butterworth natural frequency (i.e. the "3dB frequency"). Should be used with `butter` to give filter results. See Also -------- butter : Filter design using order and critical points cheb1ord : Find order and critical points from passband and stopband spec cheb2ord, ellipord iirfilter : General filter design using order and critical frequencies iirdesign : General filter design using passband and stopband spec Examples -------- Design an analog bandpass filter with passband within 3 dB from 20 to 50 rad/s, while rejecting at least -40 dB below 14 and above 60 rad/s. Plot its frequency response, showing the passband and stopband constraints in gray. >>> from scipy import signal >>> import matplotlib.pyplot as plt >>> N, Wn = signal.buttord([20, 50], [14, 60], 3, 40, True) >>> b, a = signal.butter(N, Wn, 'band', True) >>> w, h = signal.freqs(b, a, np.logspace(1, 2, 500)) >>> plt.semilogx(w, 20 * np.log10(abs(h))) >>> plt.title('Butterworth bandpass filter fit to constraints') >>> plt.xlabel('Frequency [radians / second]') >>> plt.ylabel('Amplitude [dB]') >>> plt.grid(which='both', axis='both') >>> plt.fill([1, 14, 14, 1], [-40, -40, 99, 99], '0.9', lw=0) # stop >>> plt.fill([20, 20, 50, 50], [-99, -3, -3, -99], '0.9', lw=0) # pass >>> plt.fill([60, 60, 1e9, 1e9], [99, -40, -40, 99], '0.9', lw=0) # stop >>> plt.axis([10, 100, -60, 3]) >>> plt.show() """ wp = atleast_1d(wp) ws = atleast_1d(ws) filter_type = 2 * (len(wp) - 1) filter_type += 1 if wp[0] >= ws[0]: filter_type += 1 # Pre-warp frequencies for digital filter design if not analog: passb = tan(pi * wp / 2.0) stopb = tan(pi * ws / 2.0) else: passb = wp * 1.0 stopb = ws * 1.0 if filter_type == 1: # low nat = stopb / passb elif filter_type == 2: # high nat = passb / stopb elif filter_type == 3: # stop wp0 = optimize.fminbound(band_stop_obj, passb[0], stopb[0] - 1e-12, args=(0, passb, stopb, gpass, gstop, 'butter'), disp=0) passb[0] = wp0 wp1 = optimize.fminbound(band_stop_obj, stopb[1] + 1e-12, passb[1], args=(1, passb, stopb, gpass, gstop, 'butter'), disp=0) passb[1] = wp1 nat = ((stopb * (passb[0] - passb[1])) / (stopb ** 2 - passb[0] * passb[1])) elif filter_type == 4: # pass nat = ((stopb ** 2 - passb[0] * passb[1]) / (stopb * (passb[0] - passb[1]))) nat = min(abs(nat)) GSTOP = 10 ** (0.1 * abs(gstop)) GPASS = 10 ** (0.1 * abs(gpass)) ord = int(ceil(log10((GSTOP - 1.0) / (GPASS - 1.0)) / (2 * log10(nat)))) # Find the Butterworth natural frequency WN (or the "3dB" frequency") # to give exactly gpass at passb. try: W0 = (GPASS - 1.0) ** (-1.0 / (2.0 * ord)) except ZeroDivisionError: W0 = 1.0 print("Warning, order is zero...check input parameters.") # now convert this frequency back from lowpass prototype # to the original analog filter if filter_type == 1: # low WN = W0 * passb elif filter_type == 2: # high WN = passb / W0 elif filter_type == 3: # stop WN = numpy.zeros(2, float) discr = sqrt((passb[1] - passb[0]) ** 2 + 4 * W0 ** 2 * passb[0] * passb[1]) WN[0] = ((passb[1] - passb[0]) + discr) / (2 * W0) WN[1] = ((passb[1] - passb[0]) - discr) / (2 * W0) WN = numpy.sort(abs(WN)) elif filter_type == 4: # pass W0 = numpy.array([-W0, W0], float) WN = (-W0 * (passb[1] - passb[0]) / 2.0 + sqrt(W0 ** 2 / 4.0 * (passb[1] - passb[0]) ** 2 + passb[0] * passb[1])) WN = numpy.sort(abs(WN)) else: raise ValueError("Bad type: %s" % filter_type) if not analog: wn = (2.0 / pi) * arctan(WN) else: wn = WN if len(wn) == 1: wn = wn[0] return ord, wn def cheb1ord(wp, ws, gpass, gstop, analog=False): """Chebyshev type I filter order selection. Return the order of the lowest order digital or analog Chebyshev Type I filter that loses no more than `gpass` dB in the passband and has at least `gstop` dB attenuation in the stopband. Parameters ---------- wp, ws : float Passband and stopband edge frequencies. For digital filters, these are normalized from 0 to 1, where 1 is the Nyquist frequency, pi radians/sample. (`wp` and `ws` are thus in half-cycles / sample.) For example: - Lowpass: wp = 0.2, ws = 0.3 - Highpass: wp = 0.3, ws = 0.2 - Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6] - Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5] For analog filters, `wp` and `ws` are angular frequencies (e.g. rad/s). gpass : float The maximum loss in the passband (dB). gstop : float The minimum attenuation in the stopband (dB). analog : bool, optional When True, return an analog filter, otherwise a digital filter is returned. Returns ------- ord : int The lowest order for a Chebyshev type I filter that meets specs. wn : ndarray or float The Chebyshev natural frequency (the "3dB frequency") for use with `cheby1` to give filter results. See Also -------- cheby1 : Filter design using order and critical points buttord : Find order and critical points from passband and stopband spec cheb2ord, ellipord iirfilter : General filter design using order and critical frequencies iirdesign : General filter design using passband and stopband spec Examples -------- Design a digital lowpass filter such that the passband is within 3 dB up to 0.2*(fs/2), while rejecting at least -40 dB above 0.3*(fs/2). Plot its frequency response, showing the passband and stopband constraints in gray. >>> from scipy import signal >>> import matplotlib.pyplot as plt >>> N, Wn = signal.cheb1ord(0.2, 0.3, 3, 40) >>> b, a = signal.cheby1(N, 3, Wn, 'low') >>> w, h = signal.freqz(b, a) >>> plt.semilogx(w / np.pi, 20 * np.log10(abs(h))) >>> plt.title('Chebyshev I lowpass filter fit to constraints') >>> plt.xlabel('Normalized frequency') >>> plt.ylabel('Amplitude [dB]') >>> plt.grid(which='both', axis='both') >>> plt.fill([.01, 0.2, 0.2, .01], [-3, -3, -99, -99], '0.9', lw=0) # stop >>> plt.fill([0.3, 0.3, 2, 2], [ 9, -40, -40, 9], '0.9', lw=0) # pass >>> plt.axis([0.08, 1, -60, 3]) >>> plt.show() """ wp = atleast_1d(wp) ws = atleast_1d(ws) filter_type = 2 * (len(wp) - 1) if wp[0] < ws[0]: filter_type += 1 else: filter_type += 2 # Pre-warp frequencies for digital filter design if not analog: passb = tan(pi * wp / 2.0) stopb = tan(pi * ws / 2.0) else: passb = wp * 1.0 stopb = ws * 1.0 if filter_type == 1: # low nat = stopb / passb elif filter_type == 2: # high nat = passb / stopb elif filter_type == 3: # stop wp0 = optimize.fminbound(band_stop_obj, passb[0], stopb[0] - 1e-12, args=(0, passb, stopb, gpass, gstop, 'cheby'), disp=0) passb[0] = wp0 wp1 = optimize.fminbound(band_stop_obj, stopb[1] + 1e-12, passb[1], args=(1, passb, stopb, gpass, gstop, 'cheby'), disp=0) passb[1] = wp1 nat = ((stopb * (passb[0] - passb[1])) / (stopb ** 2 - passb[0] * passb[1])) elif filter_type == 4: # pass nat = ((stopb ** 2 - passb[0] * passb[1]) / (stopb * (passb[0] - passb[1]))) nat = min(abs(nat)) GSTOP = 10 ** (0.1 * abs(gstop)) GPASS = 10 ** (0.1 * abs(gpass)) ord = int(ceil(arccosh(sqrt((GSTOP - 1.0) / (GPASS - 1.0))) / arccosh(nat))) # Natural frequencies are just the passband edges if not analog: wn = (2.0 / pi) * arctan(passb) else: wn = passb if len(wn) == 1: wn = wn[0] return ord, wn def cheb2ord(wp, ws, gpass, gstop, analog=False): """Chebyshev type II filter order selection. Return the order of the lowest order digital or analog Chebyshev Type II filter that loses no more than `gpass` dB in the passband and has at least `gstop` dB attenuation in the stopband. Parameters ---------- wp, ws : float Passband and stopband edge frequencies. For digital filters, these are normalized from 0 to 1, where 1 is the Nyquist frequency, pi radians/sample. (`wp` and `ws` are thus in half-cycles / sample.) For example: - Lowpass: wp = 0.2, ws = 0.3 - Highpass: wp = 0.3, ws = 0.2 - Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6] - Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5] For analog filters, `wp` and `ws` are angular frequencies (e.g. rad/s). gpass : float The maximum loss in the passband (dB). gstop : float The minimum attenuation in the stopband (dB). analog : bool, optional When True, return an analog filter, otherwise a digital filter is returned. Returns ------- ord : int The lowest order for a Chebyshev type II filter that meets specs. wn : ndarray or float The Chebyshev natural frequency (the "3dB frequency") for use with `cheby2` to give filter results. See Also -------- cheby2 : Filter design using order and critical points buttord : Find order and critical points from passband and stopband spec cheb1ord, ellipord iirfilter : General filter design using order and critical frequencies iirdesign : General filter design using passband and stopband spec Examples -------- Design a digital bandstop filter which rejects -60 dB from 0.2*(fs/2) to 0.5*(fs/2), while staying within 3 dB below 0.1*(fs/2) or above 0.6*(fs/2). Plot its frequency response, showing the passband and stopband constraints in gray. >>> from scipy import signal >>> import matplotlib.pyplot as plt >>> N, Wn = signal.cheb2ord([0.1, 0.6], [0.2, 0.5], 3, 60) >>> b, a = signal.cheby2(N, 60, Wn, 'stop') >>> w, h = signal.freqz(b, a) >>> plt.semilogx(w / np.pi, 20 * np.log10(abs(h))) >>> plt.title('Chebyshev II bandstop filter fit to constraints') >>> plt.xlabel('Normalized frequency') >>> plt.ylabel('Amplitude [dB]') >>> plt.grid(which='both', axis='both') >>> plt.fill([.01, .1, .1, .01], [-3, -3, -99, -99], '0.9', lw=0) # stop >>> plt.fill([.2, .2, .5, .5], [ 9, -60, -60, 9], '0.9', lw=0) # pass >>> plt.fill([.6, .6, 2, 2], [-99, -3, -3, -99], '0.9', lw=0) # stop >>> plt.axis([0.06, 1, -80, 3]) >>> plt.show() """ wp = atleast_1d(wp) ws = atleast_1d(ws) filter_type = 2 * (len(wp) - 1) if wp[0] < ws[0]: filter_type += 1 else: filter_type += 2 # Pre-warp frequencies for digital filter design if not analog: passb = tan(pi * wp / 2.0) stopb = tan(pi * ws / 2.0) else: passb = wp * 1.0 stopb = ws * 1.0 if filter_type == 1: # low nat = stopb / passb elif filter_type == 2: # high nat = passb / stopb elif filter_type == 3: # stop wp0 = optimize.fminbound(band_stop_obj, passb[0], stopb[0] - 1e-12, args=(0, passb, stopb, gpass, gstop, 'cheby'), disp=0) passb[0] = wp0 wp1 = optimize.fminbound(band_stop_obj, stopb[1] + 1e-12, passb[1], args=(1, passb, stopb, gpass, gstop, 'cheby'), disp=0) passb[1] = wp1 nat = ((stopb * (passb[0] - passb[1])) / (stopb ** 2 - passb[0] * passb[1])) elif filter_type == 4: # pass nat = ((stopb ** 2 - passb[0] * passb[1]) / (stopb * (passb[0] - passb[1]))) nat = min(abs(nat)) GSTOP = 10 ** (0.1 * abs(gstop)) GPASS = 10 ** (0.1 * abs(gpass)) ord = int(ceil(arccosh(sqrt((GSTOP - 1.0) / (GPASS - 1.0))) / arccosh(nat))) # Find frequency where analog response is -gpass dB. # Then convert back from low-pass prototype to the original filter. new_freq = cosh(1.0 / ord * arccosh(sqrt((GSTOP - 1.0) / (GPASS - 1.0)))) new_freq = 1.0 / new_freq if filter_type == 1: nat = passb / new_freq elif filter_type == 2: nat = passb * new_freq elif filter_type == 3: nat = numpy.zeros(2, float) nat[0] = (new_freq / 2.0 * (passb[0] - passb[1]) + sqrt(new_freq ** 2 * (passb[1] - passb[0]) ** 2 / 4.0 + passb[1] * passb[0])) nat[1] = passb[1] * passb[0] / nat[0] elif filter_type == 4: nat = numpy.zeros(2, float) nat[0] = (1.0 / (2.0 * new_freq) * (passb[0] - passb[1]) + sqrt((passb[1] - passb[0]) ** 2 / (4.0 * new_freq ** 2) + passb[1] * passb[0])) nat[1] = passb[0] * passb[1] / nat[0] if not analog: wn = (2.0 / pi) * arctan(nat) else: wn = nat if len(wn) == 1: wn = wn[0] return ord, wn def ellipord(wp, ws, gpass, gstop, analog=False): """Elliptic (Cauer) filter order selection. Return the order of the lowest order digital or analog elliptic filter that loses no more than `gpass` dB in the passband and has at least `gstop` dB attenuation in the stopband. Parameters ---------- wp, ws : float Passband and stopband edge frequencies. For digital filters, these are normalized from 0 to 1, where 1 is the Nyquist frequency, pi radians/sample. (`wp` and `ws` are thus in half-cycles / sample.) For example: - Lowpass: wp = 0.2, ws = 0.3 - Highpass: wp = 0.3, ws = 0.2 - Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6] - Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5] For analog filters, `wp` and `ws` are angular frequencies (e.g. rad/s). gpass : float The maximum loss in the passband (dB). gstop : float The minimum attenuation in the stopband (dB). analog : bool, optional When True, return an analog filter, otherwise a digital filter is returned. Returns ------- ord : int The lowest order for an Elliptic (Cauer) filter that meets specs. wn : ndarray or float The Chebyshev natural frequency (the "3dB frequency") for use with `ellip` to give filter results. See Also -------- ellip : Filter design using order and critical points buttord : Find order and critical points from passband and stopband spec cheb1ord, cheb2ord iirfilter : General filter design using order and critical frequencies iirdesign : General filter design using passband and stopband spec Examples -------- Design an analog highpass filter such that the passband is within 3 dB above 30 rad/s, while rejecting -60 dB at 10 rad/s. Plot its frequency response, showing the passband and stopband constraints in gray. >>> from scipy import signal >>> import matplotlib.pyplot as plt >>> N, Wn = signal.ellipord(30, 10, 3, 60, True) >>> b, a = signal.ellip(N, 3, 60, Wn, 'high', True) >>> w, h = signal.freqs(b, a, np.logspace(0, 3, 500)) >>> plt.semilogx(w, 20 * np.log10(abs(h))) >>> plt.title('Elliptical highpass filter fit to constraints') >>> plt.xlabel('Frequency [radians / second]') >>> plt.ylabel('Amplitude [dB]') >>> plt.grid(which='both', axis='both') >>> plt.fill([.1, 10, 10, .1], [1e4, 1e4, -60, -60], '0.9', lw=0) # stop >>> plt.fill([30, 30, 1e9, 1e9], [-99, -3, -3, -99], '0.9', lw=0) # pass >>> plt.axis([1, 300, -80, 3]) >>> plt.show() """ wp = atleast_1d(wp) ws = atleast_1d(ws) filter_type = 2 * (len(wp) - 1) filter_type += 1 if wp[0] >= ws[0]: filter_type += 1 # Pre-warp frequencies for digital filter design if not analog: passb = tan(pi * wp / 2.0) stopb = tan(pi * ws / 2.0) else: passb = wp * 1.0 stopb = ws * 1.0 if filter_type == 1: # low nat = stopb / passb elif filter_type == 2: # high nat = passb / stopb elif filter_type == 3: # stop wp0 = optimize.fminbound(band_stop_obj, passb[0], stopb[0] - 1e-12, args=(0, passb, stopb, gpass, gstop, 'ellip'), disp=0) passb[0] = wp0 wp1 = optimize.fminbound(band_stop_obj, stopb[1] + 1e-12, passb[1], args=(1, passb, stopb, gpass, gstop, 'ellip'), disp=0) passb[1] = wp1 nat = ((stopb * (passb[0] - passb[1])) / (stopb ** 2 - passb[0] * passb[1])) elif filter_type == 4: # pass nat = ((stopb ** 2 - passb[0] * passb[1]) / (stopb * (passb[0] - passb[1]))) nat = min(abs(nat)) GSTOP = 10 ** (0.1 * gstop) GPASS = 10 ** (0.1 * gpass) arg1 = sqrt((GPASS - 1.0) / (GSTOP - 1.0)) arg0 = 1.0 / nat d0 = special.ellipk([arg0 ** 2, 1 - arg0 ** 2]) d1 = special.ellipk([arg1 ** 2, 1 - arg1 ** 2]) ord = int(
ceil(d0[0] * d1[1] / (d0[1] * d1[0]))
numpy.ceil
import numpy as np import scipy.optimize as sciopt def UniformBeamBendingModes(Type,EI,rho,A,L,w=None,x=None,Mtop=0,norm='tip_norm',nModes=4): """ returns Mode shapes and frequencies for a uniform beam in bending References: Inman : Engineering variation Author: <NAME>""" if x is None or len(x)==0: x = np.linspace(0,L,101) if np.amax(x) != L: raise Exception('Max of x should be equal to L') # Dimensionless spanwise position x0 = x / L s = Type.split('-') if s[0].lower()=='unloaded': # --- "Theory" (clamped-free, vertical, no weight) # See Inman, p.335 or Nielsen1 p129 if 'unloaded-clamped-free' == (Type.lower()): # NOTE: cosh(beta_n)cos(beta_n) =-1 # sigma_n = [ np.sinh(beta_n) - sin(beta_n) ]/[cosh(beta_n) + cos(beta_n)] # for j>5, a good approx is B(j) = (2*j-1)np.pi/2 and S(j)=1; #B = [1.87510407, 4.69409113, 7.85475744,10.99554073,14.13716839, (2*6-1)*np.pi/2]; #S = [0.734095514 1.018467319 0.999224497 1.000033553 0.999998550 1]; B = np.zeros(nModes) for i in np.arange(nModes): B[i] = sciopt.fsolve(lambda x: 1 + np.cosh(x) * np.cos(x), (2*(i+1)-1)*np.pi/2) elif 'unloaded-topmass-clamped-free' == (Type.lower()): # The geometrical stiffning is not accounted for here if Mtop is None: raise Exception('Please specify value for Mtop for %s',Type) M = rho * A * L B = np.zeros(nModes) for i in np.arange(nModes): B[i] = sciopt.fsolve(lambda x: 1+np.cosh(x)*np.cos(x)-x*Mtop/M*(np.sin(x)*np.cosh(x)-np.cos(x)*np.sinh(x)),(2*(i+1)-1)*np.pi/2) else: raise Exception('unknown type %s',Type) #S = ( sinh(B)-sin(B) ) ./ ( cosh(B) + cos(B)); # Sigma #C = ( cosh(B)+cos(B) ) ./ ( sinh(B) + sin(B)); # Sigma SS = np.sinh(B) + np.sin(B) CC = np.cosh(B) + np.cos(B) # Frequency freq = (B / L) ** 2 / (2 * np.pi) * np.sqrt(EI / (rho * A)) # --- Mode shapes ModesU = np.zeros((len(B),len(x0))) ModesV = np.zeros((len(B),len(x0))) ModesK = np.zeros((len(B),len(x0))) for i in np.arange(nModes): ModesU[i,:] = SS[i] * (np.cosh(B[i]*x0) - np.cos(B[i] * x0)) - CC[i] * (np.sinh(B[i] * x0) - np.sin(B[i] * x0)) ModesV[i,:] = B[i] * (SS[i] * (np.sinh(B[i]*x0) + np.sin(B[i] * x0)) - CC[i] * (np.cosh(B[i] * x0) - np.cos(B[i] * x0))) ModesK[i,:] = B[i]**2 * (SS[i] * (np.cosh(B[i]*x0) + np.cos(B[i] * x0)) - CC[i] * (np.sinh(B[i] * x0) + np.sin(B[i] * x0))) # ModesU(i,:) = cosh(B[i]*x0)-cos(B[i]*x0) - S[i]*(sinh(B[i]*x0)-sin(B[i]*x0)) ; # ModesV(i,:) = B[i] *(sinh(B[i]*x0)+sin(B[i]*x0) - S[i]*(cosh(B[i]*x0)-cos(B[i]*x0))); # ModesK(i,:) = B[i]^2*(cosh(B[i]*x0)+cos(B[i]*x0) - S[i]*(sinh(B[i]*x0)+sin(B[i]*x0))); # ModesU(i,:) = cosh(B[i]*x0)-cos(B[i]*x0) - C[i]*(sinh(B[i]*x0)-sin(B[i]*x0)) ; # ModesV(i,:) = B[i] *(sinh(B[i]*x0)+sin(B[i]*x0) - C[i]*(cosh(B[i]*x0)-cos(B[i]*x0))); # ModesK(i,:) = B[i]^2*(cosh(B[i]*x0)+cos(B[i]*x0) - C[i]*(sinh(B[i]*x0)+sin(B[i]*x0))); elif s[0].lower()=='loaded': if 'loaded-clamped-free' == (Type.lower()): if w is None: w = A * rho if L==0: raise Exception('Please specify value for L for %s',Type) B = np.array([1.875,4.694]) freq = (B / L) ** 2 / (2 * np.pi) * np.sqrt(EI / w) else: raise Exception('unknown type %s',Type) else: raise Exception('Unknown %s'^Type) ## Going back to physical dimension x = x0 * L ModesV = ModesV/L ModesK = ModesK/L**2 ## Normalization of modes if norm=='tip_norm': for i in np.arange(nModes): fact = 1 / ModesU[i,-1] ModesU[i,:] = ModesU[i,:] * fact ModesV[i,:] = ModesV[i,:] * fact ModesK[i,:] = ModesK[i,:] * fact else: raise Exception('Norm not implemented or incorrect: `%s`'%norm) return freq,x,ModesU,ModesV,ModesK # --------------------------------------------------------------------------------} # --- Longitudinal modes # --------------------------------------------------------------------------------{ def UniformBeamLongiModes(Type,E,rho,A,L,x=None,nModes=4,norm='tip_norm'): """ Returns longitudinals modes for a uniform beam """ if x is None: x = np.linspace(0,L,101) if np.amax(x) != L: raise Exception('Max of x should be equal to L') # Dimensionless spanwise position x0 = x / L if Type.lower()=='unloaded-clamped-free': c = np.sqrt(E / rho) freq = np.zeros(nModes) ModesU = np.full([nModes,len(x0)],np.nan) for j in
np.arange(nModes)
numpy.arange
''' @Description: code @Author: MiCi @Date: 2020-03-12 21:11:37 @LastEditTime: 2020-03-13 17:16:41 @LastEditors: MiCi ''' import pandas as pd import numpy as np class Basic3(object): def __init__(self): return def basic_use(self): df = pd.DataFrame(np.random.rand(10, 5), columns=list('ABCDE')) # 选取A列数值大于0.5的列 print(df[df['A'] > 0.5]) # 选取A大于0.5、C大于0.7的列 print(df[(df['A'] > 0.5) & (df['C'] > 0.7)]) # 按照E列升序排序 print(df.sort_values('E')) # 使用ascending为降序 print(df.sort_values('E', ascending=False)) # 根据多列不同条件排序 print(df.sort_values(['A', 'E'], ascending=[True, False])) # 使用appley对每一行取最大值 print(df.apply(np.max, axis=1)) # 对某列做分组 df = pd.DataFrame({'A': np.array( ['foo', 'foo', 'foo', 'foo', 'bar', 'bar']), 'B': np.array( ['one', 'one', 'two', 'two', 'three', 'three']), 'C': np.array(['small', 'medium', 'large', 'large', 'small', 'small']), 'D':
np.array([1, 2, 2, 3, 3, 5])
numpy.array
""" Cross-match cluster catalogs made from individual maps in order to check calibration. """ import os import sys import glob import numpy as np import astropy.table as atpy from nemo import catalogs from nemo import plotSettings from collections import OrderedDict as odict import pylab as plt import IPython #------------------------------------------------------------------------------------------------------------ # Main # Pick one #relativeTo='median' #relativeTo='absolute' #relativeTo='S16' relativeTo='S18' # This only makes sense if relativeTo = 'median', 'S16, or 'S18' #mode='residualDiff' mode='ratio' # Applied to reference catalog only (since now doing forced photometry) refSNRCut=10.0 print("relativeTo = %s; refSNRCut = %.1f" % (relativeTo, refSNRCut)) plotsDir="plots_%s_%s_%.1f" % (mode, relativeTo, refSNRCut) os.makedirs(plotsDir, exist_ok = True) # For testing: multiply ycRef by this calFactor=1.00 if calFactor != 1.0: print("WARNING: calFactor set to %.2f - multiplying ycRef by this factor." % (calFactor)) # Reference catalog - used for cross-match positions across other catalogs refTab=atpy.Table().read("../MFMF_S18_auto/MFMF_S18_auto_M500.fits") if relativeTo == 'S16': refTab=atpy.Table().read("../MFMF_S16_auto/MFMF_S16_auto_M500.fits") keepCols=['name', 'RADeg', 'decDeg', 'fixed_SNR', 'fixed_y_c', 'fixed_err_y_c'] removeCols=[] for k in refTab.keys(): if k not in keepCols: removeCols.append(k) refTab.remove_columns(removeCols) refTab=refTab[refTab['fixed_SNR'] > refSNRCut] # Dictionaries in which to store all cross-matched y_c values # Each entry will be a list ycRef={} ycErrRef={} yc={} ycErr={} labels={} # Cross match against nemo output print("Collecting fixed_y_c measurements for each cluster across all maps") xMatchFiles=glob.glob("outputCatalogs/*.fits") xMatchFiles.sort() for f in xMatchFiles: label=os.path.split(f)[-1].split("_optimal")[0] print(" %s" % (label)) tab=atpy.Table().read(f) #tab=tab[tab['fixed_SNR'] > SNRCut] try: refMatched, tabMatched, sep=catalogs.crossMatch(refTab, tab, radiusArcmin = 1.4) except: raise Exception("Matching probably failed because SNRCut is too low so there were no matches") for ref, match in zip(refMatched, tabMatched): name=ref['name'] if name not in yc.keys(): yc[name]=[] ycErr[name]=[] labels[name]=[] ycRef[name]=ref['fixed_y_c']*calFactor ycErrRef[name]=ref['fixed_err_y_c'] yc[name].append(match['fixed_y_c']) ycErr[name].append(match['fixed_err_y_c']) labels[name].append(label) nameList=list(yc.keys()); nameList.sort() for name in nameList: yc[name]=np.array(yc[name]) ycErr[name]=np.array(ycErr[name]) # Check scaled residuals relative to median # Make a plot for each cluster with a fair number of data points # Gather a set so we know the typical offset for each map # We can also make a map of typical offset for each cluster minPoints=10 resByMap={} nameList=list(yc.keys()); nameList.sort() print("Making plots of fixed_y_c for each cluster") for name in nameList: # Plot if len(yc[name]) < minPoints: continue if relativeTo == 'absolute': res=yc[name] resSigma=ycErr[name] ylim=None ylabel="$\\tilde{y_0}\, (10^{-4})$" else: if mode == 'relativeDiff': if relativeTo == 'median': res=(yc[name]-np.median(yc[name]))/ycErr[name] else: # Relative to S16 or S18 act+planck co-add res=(np.array(yc[name])-ycRef[name])/np.sqrt(np.array(ycErr[name])**2+ycErrRef[name]**2) resSigma=[1]*len(res) ylabel="$\Delta \\tilde{y_0} (\sigma)$" ylim=(-4, 4) elif mode == 'ratio': if relativeTo == 'median': res=yc[name]/np.median(yc[name]) resSigma=(ycErr[name]/yc[name])*res else: res=np.array(yc[name])/np.array(ycRef[name]) resSigma=np.sqrt(np.power(ycErr[name]/yc[name], 2)+np.power(ycErrRef[name]/ycRef[name], 2))*res ylim=(0, 2) ylabel="$\\tilde{y_0} / \\tilde{y_0}$ [%s]" % (relativeTo) #medAbsRes=np.median(abs(res)) plotSettings.update_rcParams() plt.figure(figsize=(18, 10)) ax=plt.axes([0.1, 0.4, 0.87, 0.5]) x=np.arange(1, len(labels[name])+1) titleStr=name if relativeTo != 'absolute': if mode == 'relativeDiff': plt.plot(np.linspace(0, len(x)+1, 3), [0]*3, 'k--') elif mode == 'ratio': plt.plot(np.linspace(0, len(x)+1, 3), [1]*3, 'k--') else: # plot median absolute value ycMedian=
np.median(yc[name])
numpy.median
import pandas as pd import numpy as np from keras.callbacks import EarlyStopping from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split from scipy.special import digamma from numpy import linalg as LA from feature_based.multiclass_opencrowd.nn_em import nn_em from sklearn.metrics import roc_auc_score from sklearn.metrics import classification_report from matplotlib import pyplot as plt import random from feature_based.multiclass_opencrowd import arguments NUMBER_OF_LABELS = 0 LABEL_INDEX = [] def init_probabilities(n_infls): # initialize probability z_i (item's quality) randomly qz = (1.0/NUMBER_OF_LABELS) * np.ones((n_infls, NUMBER_OF_LABELS)) # initialize probability alpha beta (worker's reliability) A = 2 B = 2 return qz, A, B def init_alpha_beta(A, B, n_workers): alpha = np.zeros((n_workers, 1),dtype='float32') beta = np.zeros((n_workers, 1),dtype='float32') for w in range(0, n_workers): alpha[w] = A beta[w] = B return alpha, beta def e_step(y_train, n_workers, q_z_i, annotation_matrix, alpha, beta, theta_i,true_labels,new_order,y_val,start_val,end_val,new_alpha_value,max_it=20): old_q_z_i = theta_i.copy() old_alpha = alpha.copy() old_beta = beta.copy() diff = [] train_acc = [] y_val_label = np.argmax(y_val,axis=1) for it in range(max_it): # update q(z) for infl in new_order.tolist(): index_infl = np.where(new_order == infl)[0][0] assert infl == index_infl updated_q_z_i = theta_i[index_infl].copy() infl_aij = annotation_matrix[annotation_matrix[:, 1] == infl].copy() worker_answers = infl_aij[~np.all(infl_aij[:,2:] == 0, axis=1)] worker_n_answers = infl_aij[np.all(infl_aij[:,2:] == 0, axis=1)] T_i = worker_answers[:, 0] for worker in T_i.astype(int): w_answer = worker_answers[worker_answers[:, 0] == worker][:, 2:] w_answer_i = np.where(w_answer[0] == 1)[0][0] alpha_val = alpha[worker] beta_val = beta[worker] updated_q_z_i[w_answer_i] = updated_q_z_i[w_answer_i] * np.exp(digamma(alpha_val) - digamma(alpha_val + beta_val)) for no_answer_i in np.delete(LABEL_INDEX,w_answer_i): updated_q_z_i[no_answer_i] = updated_q_z_i[no_answer_i] * np.exp(digamma(beta_val) - digamma(alpha_val + beta_val)) T_i_n = worker_n_answers[:, 0] for worker in T_i_n.astype(int): alpha_val = alpha[worker] beta_val = beta[worker] for no_answer_i in LABEL_INDEX: updated_q_z_i[no_answer_i] = updated_q_z_i[no_answer_i] * np.exp(digamma(beta_val) - digamma(alpha_val + beta_val)) # normalize new_q_z_i = updated_q_z_i * 1.0 / (updated_q_z_i.sum()) q_z_i[index_infl] = new_q_z_i.copy() q_z_i = np.concatenate((y_train, q_z_i[y_train.shape[0]:])) # update q(r) new_alpha = np.zeros((n_workers, 1)) new_beta = np.zeros((n_workers, 1)) for worker in range(0, n_workers): new_alpha[worker] = alpha[worker] new_beta[worker] = beta[worker] for worker in range(0, n_workers): worker_aij = annotation_matrix[annotation_matrix[:, 0] == worker].copy() T_j = worker_aij[~np.all(worker_aij[:,2:] == 0, axis=1)] T_j_n = worker_aij[np.all(worker_aij[:,2:] == 0, axis=1)] for infl in T_j[:, 1].astype(int): index_infl = np.where(new_order == infl)[0][0] assert infl == index_infl worker_answer = T_j[T_j[:, 1] == infl][:, 2:] worker_answer_i = np.where(worker_answer[0] == 1)[0][0] new_alpha[worker] += q_z_i[index_infl][worker_answer_i] new_beta[worker] += 1 - q_z_i[index_infl][worker_answer_i] for infl in T_j_n[:, 1].astype(int): new_alpha[worker] += new_alpha_value new_beta[worker] += 1 - new_alpha_value for worker in range(0, n_workers): alpha[worker] = new_alpha[worker] beta[worker] = new_beta[worker] q_z_i_change = LA.norm(old_q_z_i - q_z_i) # da = LA.norm(old_alpha - alpha) # db = LA.norm(old_beta - beta) old_q_z_i = q_z_i.copy() old_alpha = alpha.copy() old_beta = beta.copy() q_z_i_val_label = np.argmax(q_z_i[start_val:end_val],axis=1) q_z_i_acc = accuracy_score(y_val_label,q_z_i_val_label) diff.append(q_z_i_change) train_acc.append(q_z_i_acc) print(it, q_z_i_change) if q_z_i_change < 0.1: break return q_z_i,alpha,beta def m_step(nn_em,q_z_i, classifier, social_features, total_epochs, steps, y_test, y_val,X_val,start_val,alpha, beta): theta_i, classifier, weights = nn_em.train_m_step_early_stopp(classifier, social_features, q_z_i, steps, total_epochs, y_test, y_val,X_val,start_val) return theta_i,classifier def var_em(nn_em_in, n_infls_label,aij_s,new_order, n_workers, social_features_labeled, true_labels, supervision_rate, \ column_names, n_neurons, m_feats, weights_before_em,weights_after_em,iterr,total_epochs,evaluation_file,theta_file,steps,new_alpha_value,multiple_input,tweet2vec_dim): n_infls = n_infls_label q_z_i, A, B = init_probabilities(n_infls) alpha, beta = init_alpha_beta(A, B, n_workers) X_train, X_test, y_train, y_test = train_test_split(social_features_labeled, true_labels, test_size=(1 - supervision_rate), shuffle=False) X_val, X_test, y_val, y_test = train_test_split(X_test, y_test, test_size=0.5, shuffle=False) social_features = social_features_labeled start_val = X_train.shape[0] end_val = X_train.shape[0] + X_val.shape[0] n_stat_feats = m_feats - tweet2vec_dim if multiple_input: n_neurons = int((NUMBER_OF_LABELS + n_stat_feats)/2) classifier = nn_em_in.create_multiple_input_model_mlp(n_neurons,(n_stat_feats,),(tweet2vec_dim,),NUMBER_OF_LABELS) # classifier = nn_em_in.create_multiple_input_model(n_neurons,(n_stat_feats,),(tweet2vec_dim,1),NUMBER_OF_LABELS) X_train = [X_train[:,:n_stat_feats],X_train[:,n_stat_feats:]] X_val = [X_val[:,:n_stat_feats],X_val[:,n_stat_feats:]] X_test = [X_test[:,:n_stat_feats],X_test[:,n_stat_feats:]] social_features = [social_features[:,:n_stat_feats],social_features[:,n_stat_feats:]] # X_train = [X_train[:,:n_stat_feats],X_train[:,n_stat_feats:].reshape(X_train[:,n_stat_feats:].shape[0], X_train[:,n_stat_feats:].shape[1], 1)] # X_val = [X_val[:,:n_stat_feats],X_val[:,n_stat_feats:].reshape(X_val[:,n_stat_feats:].shape[0], X_val[:,n_stat_feats:].shape[1], 1)] # X_test = [X_test[:,:n_stat_feats],X_test[:,n_stat_feats:].reshape(X_test[:,n_stat_feats:].shape[0], X_test[:,n_stat_feats:].shape[1], 1)] # social_features = [social_features[:,:n_stat_feats],social_features[:,n_stat_feats:].reshape(social_features[:,n_stat_feats:].shape[0], social_features[:,n_stat_feats:].shape[1], 1)] else: n_neurons = int((NUMBER_OF_LABELS + m_feats)/2) classifier = nn_em_in.define_multiclass_nn(n_neurons,m_feats,NUMBER_OF_LABELS) print(classifier.summary()) steps_it0 = 0 epsilon = 1e-4 theta_i = q_z_i.copy() old_theta_i = np.zeros((n_infls, NUMBER_OF_LABELS)) y_val_label = np.argmax(y_val,axis=1) y_test_label = np.argmax(y_test,axis=1) y_train_label = np.argmax(y_train,axis=1) monitor = EarlyStopping(monitor='val_loss', min_delta=1e-3, patience=10, verbose=0, mode='auto', restore_best_weights=True) classifier.fit(X_train, y_train, validation_data=(X_val,y_val), callbacks=[monitor], verbose=2, epochs=100, batch_size=4) theta_i_val = classifier.predict(X_val) theta_i_test = classifier.predict(X_test) theta_i_val_label = np.argmax(theta_i_val,axis=1) theta_i_test_label =
np.argmax(theta_i_test,axis=1)
numpy.argmax
from distutils.command.clean import clean import numpy as np import torch import torch.nn as nn from exptools.logging.console import colorize import pybullet as p from collections import deque import time import glob import time import os from utils.arguments import get_args from env.envs import UniTreeEnv from myRL.policy import Policy from myRL.trajectory import Trajectory from myRL.algo.ppo import * from myRL.utils import * from env.model.network import localTransformer from torch.utils.data.distributed import DistributedSampler from utils.log import * from env.terrain.thin_obstacle import * from env.terrain.wide_obstacle import * from env.terrain.moving_obstacle import * from env.terrain.office import * from env.terrain.unflatten import * from env.model.mlp import * from env.model.conv2d import * from env.model.transformer import * def main(): args=get_args() print(args) torch.manual_seed(args.seed) torch.cuda.manual_seed_all(args.seed) if torch.cuda.is_available(): torch.backends.cudnn.benchmark=True #torch.cuda.set_device(args.local_rank) device = torch.device("cuda:0" if torch.cuda.is_available() else 'cpu') #torch.distributed.init_process_group(backend='nccl') log_dir=os.path.expanduser(args.log_dir) evaluate_dir=log_dir+'_eval' cleanup_log_dir(log_dir) cleanup_log_dir(evaluate_dir) #simulation settings mode=p.GUI if args.connection_mode=='visual' else p.DIRECT timestep=1./50 envs=UniTreeEnv( obs_type= ["vision",'joints','inertial'], robot_kwargs= dict( robot_type= "a1", pb_control_mode= "POSITION_CONTROL", pb_control_kwargs= dict(force=5), simulate_timestep= timestep, default_base_transform=
np.array([0,0,0.35,0,0,1,1])
numpy.array
from __future__ import division import numpy import theano.tensor as T import theano from theano.tensor.signal import pool from theano.tensor.nnet import conv2d import six.moves.cPickle as pickle import timeit import scipy.io import matplotlib.pyplot as plt from Adam import adam class LogisticRegression(object): def __init__(self, input, n_in, n_out): self.W = theano.shared( value=numpy.zeros( (n_in, n_out), dtype=theano.config.floatX ), name='W', borrow=True ) self.b = theano.shared( value=numpy.zeros( (n_out,), dtype=theano.config.floatX ), name='b', borrow=True ) self.p_y_given_x = T.nnet.softmax(T.dot(input, self.W) + self.b) # symbolic description of how to compute prediction as class whose # probability is maximal self.y_pred = T.argmax(self.p_y_given_x, axis=1) # end-snippet-1 # parameters of the model self.params = [self.W, self.b] # keep track of model input self.input = input def negative_log_likelihood(self, y): return -T.mean(T.log(self.p_y_given_x)[T.arange(y.shape[0]), y]) # end-snippet-2 # Negative log likelihood should be replaced by sigmoid for training, need to be checked again. For the correlation lenght cases. # For the New Gaussian Data, the cost should be investigated again. def sigmoid_cost_function(self, y): # This is only for fvector return T.mean(T.switch(T.eq(y, 1), -T.log(self.p_y_given_x), -T.log(1-self.p_y_given_x))) def errors(self, y): if y.ndim != self.y_pred.ndim: raise TypeError( 'y should have the same shape as self.y_pred', ('y', y.type, 'y_pred', self.y_pred.type) ) if y.dtype.startswith('int'): return T.mean(T.neq(self.y_pred, y)) else: raise NotImplementedError() class LogisticRegression_2(object): def __init__(self, input, n_in, n_out, rng): # start-snippet-1 # initialize with 0 the weights W as a matrix of shape (n_in, n_out) self.W = theano.shared( value=numpy.asarray( rng.uniform( low=-numpy.sqrt(6. / (n_in + n_out)), high=numpy.sqrt(6. / (n_in + n_out)), size=(n_in, n_out)), dtype=theano.config.floatX), name='W', borrow=True ) # self.W = theano.shared( # value=numpy.zeros( # (n_in, n_out), # dtype=theano.config.floatX # ), # name='W', # borrow=True # ) # initialize the biases b as a vector of n_out 0s self.b = theano.shared( value=numpy.zeros( (n_out,), dtype=theano.config.floatX ), name='b', borrow=True ) # symbolic expression for computing the matrix of class-membership # probabilities # Where: # W is a matrix where column-k represent the separation hyperplane for # class-k # x is a matrix where row-j represents input training sample-j # b is a vector where element-k represent the free parameter of # hyperplane-k self.output = T.nnet.sigmoid(T.dot(input, self.W) + self.b) # self.p_y_given_x = T.nnet.softmax(T.dot(input, self.W) + self.b) # self.y_pred = T.round(self.output) # T.dot(input, self.W) + self.b self.prep_y = T.argmax(self.output, axis=1) # end-snippet-1 # parameters of the model self.params = [self.W, self.b] # keep track of model input self.input = input def negative_log_likelihood(self, y): # This is not really good as the relu may resulting output 0, and returning nan return -T.mean(y*T.log(self.output) + (1-y)*T.log(1-self.output)) def sigmoid_cost_function(self, y): return T.mean(T.switch(T.eq(y, 1), -T.log(self.output), -T.log(1-self.output))) def mse_cost_function(self, y): return T.mean(T.square(y - self.output)) def errors(self, y): if y.ndim != self.output.ndim: raise TypeError( 'y should have the same shape as self.y_pred', ('y', y.type, 'y_pred', self.output.type) ) # check if y is of the correct datatype if y.dtype.startswith('float'): return T.mean(T.square(y - self.output)) #T.mean(T.neq(self.y_pred, y)) #T.mean(T.switch(T.eq(y, 1), -T.log(self.output), -T.log(1-self.output))) #T.mean(T.square(y - self.output)) #1 - T.mean(T.all(T.isclose(y, self.output, rtol=0, atol=0.02), axis=1)) #T.mean(T.sqr(y - self.output)) #1 - T.mean(T.all(T.isclose(y, self.output, rtol=0, atol=0.5), axis=1)) #1 - T.mean(T.all(T.isclose(y, self.output, rtol=0, atol=0.2), axis=1)) # T.abs_(T.mean(T.invert(T.all(T.isclose(self.output, y, rtol=0.005, atol=0.3), axis=1)))) else: raise NotImplementedError() class HiddenLayer(object): def __init__(self, rng, input, n_in, n_out, W=None, b=None, activation=T.nnet.relu): self.input = input # end-snippet-1 # `W` is initialized with `W_values` which is uniformely sampled # from sqrt(-6./(n_in+n_hidden)) and sqrt(6./(n_in+n_hidden)) # for tanh activation function # the output of uniform if converted using asarray to dtype # theano.config.floatX so that the code is runable on GPU # Note : optimal initialization of weights is dependent on the # activation function used (among other things). # For example, results presented in [Xavier10] suggest that you # should use 4 times larger initial weights for sigmoid # compared to tanh # We have no info for other function, so we use the same as # tanh. if W is None: W_values = numpy.asarray( rng.uniform( low=-numpy.sqrt(6 / (n_in + n_out)), high=numpy.sqrt(6. / (n_in + n_out)), size=(n_in, n_out) ), dtype=theano.config.floatX ) if activation == theano.tensor.nnet.sigmoid: W_values *= 4 W = theano.shared(value=W_values, name='W', borrow=True) if b is None: b_values = numpy.zeros((n_out,), dtype=theano.config.floatX) b = theano.shared(value=b_values, name='b', borrow=True) self.W = W self.b = b lin_output = T.dot(input, self.W) + self.b self.output = ( lin_output if activation is None else activation(lin_output) ) # parameters of the model self.params = [self.W, self.b] class LeNetConvPoolLayer(object): """Pool Layer of a convolutional network """ def __init__(self, rng, input, filter_shape, image_shape, poolsize=(2, 2)): """ Allocate a LeNetConvPoolLayer with shared variable internal parameters. :type rng: numpy.random.RandomState :param rng: a random number generator used to initialize weights :type input: theano.tensor.dtensor4 :param input: symbolic image tensor, of shape image_shape :type filter_shape: tuple or list of length 4 :param filter_shape: (number of filters, num input feature maps, filter height, filter width) :type image_shape: tuple or list of length 4 :param image_shape: (batch size, num input feature maps, image height, image width) :type poolsize: tuple or list of length 2 :param poolsize: the downsampling (pooling) factor (#rows, #cols) """ assert image_shape[1] == filter_shape[1] self.input = input # there are "num input feature maps * filter height * filter width" # inputs to each hidden unit fan_in = numpy.prod(filter_shape[1:]) # each unit in the lower layer receives a gradient from: # "num output feature maps * filter height * filter width" / # pooling size fan_out = (filter_shape[0] * numpy.prod(filter_shape[2:]) // numpy.prod(poolsize)) # initialize weights with random weights W_bound = numpy.sqrt(6. / (fan_in + fan_out)) self.W = theano.shared( numpy.asarray( rng.uniform(low=-W_bound, high=W_bound, size=filter_shape), dtype=theano.config.floatX ), borrow=True ) # the bias is a 1D tensor -- one bias per output feature map b_values = numpy.zeros((filter_shape[0],), dtype=theano.config.floatX) self.b = theano.shared(value=b_values, borrow=True) # convolve input feature maps with filters conv_out = conv2d( input=input, filters=self.W, filter_shape=filter_shape, input_shape=image_shape ) # pool each feature map individually, using maxpooling pooled_out = pool.pool_2d( input=conv_out, ws=poolsize, ignore_border=True ) # add the bias term. Since the bias is a vector (1D array), we first # reshape it to a tensor of shape (1, n_filters, 1, 1). Each bias will # thus be broadcasted across mini-batches and feature map # width & height self.output = T.nnet.relu(pooled_out + self.b.dimshuffle('x', 0, 'x', 'x')) # store parameters of this layer self.params = [self.W, self.b] # keep track of model input self.input = input class ConvPoolLayer_NoMaxPool(object): """Pool Layer of a convolutional network """ def __init__(self, rng, input, filter_shape, image_shape): """ Allocate a LeNetConvPoolLayer with shared variable internal parameters. :type rng: numpy.random.RandomState :param rng: a random number generator used to initialize weights :type input: theano.tensor.dtensor4 :param input: symbolic image tensor, of shape image_shape :type filter_shape: tuple or list of length 4 :param filter_shape: (number of filters, num input feature maps, filter height, filter width) :type image_shape: tuple or list of length 4 :param image_shape: (batch size, num input feature maps, image height, image width) :type poolsize: tuple or list of length 2 :param poolsize: the downsampling (pooling) factor (#rows, #cols) """ assert image_shape[1] == filter_shape[1] self.input = input # there are "num input feature maps * filter height * filter width" # inputs to each hidden unit fan_in = numpy.prod(filter_shape[1:]) # Filter_shape[1] is the input kernel number # Filter_shape[0] is the output kernel number # each unit in the lower layer receives a gradient from: # "num output feature maps * filter height * filter width" / # pooling size fan_out = filter_shape[0] * numpy.prod(filter_shape[2:]) # initialize weights with random weights W_bound = numpy.sqrt(6. / (fan_in + fan_out)) self.W = theano.shared( numpy.asarray( rng.uniform(low=-W_bound, high=W_bound, size=filter_shape), dtype=theano.config.floatX ), borrow=True ) # the bias is a 1D tensor -- one bias per output feature map b_values = numpy.zeros((filter_shape[0],), dtype=theano.config.floatX) self.b = theano.shared(value=b_values, borrow=True) # convolve input feature maps with filters conv_out = conv2d( input=input, filters=self.W, filter_shape=filter_shape, input_shape=image_shape ) # add the bias term. Since the bias is a vector (1D array), we first # reshape it to a tensor of shape (1, n_filters, 1, 1). Each bias will # thus be broadcasted across mini-batches and feature map # width & height self.output = T.nnet.relu(conv_out + self.b.dimshuffle('x', 0, 'x', 'x')) # store parameters of this layer self.params = [self.W, self.b] # keep track of model input self.input = input def printimage(test_set_x): # Print Image from tensor to numpy and plot it #mm = numpy.squeeze(test_set_x.eval(), axis=(0,)) # print(mm) mm = test_set_x fig = plt.figure() plotwindow = fig.add_subplot(111) plt.imshow(mm) # , cmap='gray') plt.axis('off') fig.savefig('figure1.png', bbox_inches='tight', pad_inches=0) plt.show() return def shared_dataset(data_x, data_y, borrow=True): # 0-9 Label Representation shared_x = theano.shared(numpy.asarray(data_x, dtype=theano.config.floatX), borrow=borrow) shared_y = theano.shared(numpy.asarray(data_y, dtype=theano.config.floatX), borrow=borrow) return shared_x, T.cast(shared_y, 'int32') def shared_dataset_2(data_x, data_y, borrow=True): # One Hot Representation of Label def one_hot(imput_class, number_of_class): imput_class = numpy.array(imput_class) assert imput_class.ndim == 1 return numpy.eye(number_of_class)[imput_class] data_y = one_hot(data_y.astype(int), 10) shared_x = theano.shared(numpy.asarray(data_x, dtype=theano.config.floatX), borrow=borrow) shared_y = theano.shared(numpy.asarray(data_y, dtype=theano.config.floatX), borrow=borrow) return shared_x, shared_y def main_ver1_8080_softmax(learning_rate=0.05, weight_decay=0.001, n_epochs=300, nkerns=[20, 30], batch_size=500): # Need to reproduce softmax as Wrong Regression Cost name = 'Gaussian_Model_'+str(learning_rate)+'_'+str(weight_decay) + '_' + str(nkerns) rng = numpy.random.RandomState(23455) # seed 1 #rng = numpy.random.RandomState(10000) # seed 2 #rng = numpy.random.RandomState(100) # seed 3 train_set_x = numpy.load('Gaussian_Data_Set.npy') train_set_y = numpy.load('Gaussian_Label_Set.npy') valid_set_x = numpy.load('Gaussian_Valid_Data_Set.npy') valid_set_y = numpy.load('Gaussian_Valid_Label_Set.npy') train_set_x, train_set_y = shared_dataset(train_set_x, train_set_y) valid_set_x, valid_set_y = shared_dataset(valid_set_x, valid_set_y) test_set_x, test_set_y = valid_set_x, valid_set_y n_train = train_set_x.get_value(borrow=True).shape[0] n_valid = valid_set_x.get_value(borrow=True).shape[0] n_test = test_set_x.get_value(borrow=True).shape[0] test_set_x = test_set_x.reshape((n_test, 1, 80, 80)) valid_set_x = valid_set_x.reshape((n_valid, 1, 80, 80)) train_set_x = train_set_x.reshape((n_train, 1, 80, 80)) n_train_batches = n_train//batch_size n_valid_batches = n_valid//batch_size n_test_batches = n_test//batch_size x = T.matrix('x') y = T.ivector('y') index = T.lscalar() print('... loading the model') layer0_input = x.reshape((batch_size, 1, 80, 80)) layer0 = LeNetConvPoolLayer( rng, input=layer0_input, image_shape=(batch_size, 1, 80, 80), filter_shape=(nkerns[0], 1, 21, 21), poolsize=(2, 2) ) layer1 = LeNetConvPoolLayer( rng, input=layer0.output, image_shape=(batch_size, nkerns[0], 30, 30), filter_shape=(nkerns[1], nkerns[0], 11, 11), poolsize=(2, 2) ) layer2_input = layer1.output.flatten(2) layer2 = HiddenLayer( rng, input=layer2_input, n_in=nkerns[1] * 10 * 10, n_out=numpy.round(nkerns[1] * 10 * 10/2).astype(int), activation=T.nnet.relu ) layer3 = LogisticRegression(input=layer2.output, n_in=numpy.round(nkerns[1] * 10 * 10/2).astype(int), n_out=10) with open(name + '_Initial.pkl', 'wb') as f: pickle.dump([layer0, layer1, layer2_input, layer2, layer3], f) cost = layer3.negative_log_likelihood(y) params = layer3.params + layer2.params + layer1.params + layer0.params grads = T.grad(cost, params) updates = [ (param_i, param_i - learning_rate * (grad_i + weight_decay * param_i)) for param_i, grad_i in zip(params, grads)] patience_increase = 10 improvement_threshold = 0.001 start_time = timeit.default_timer() print('... training') temp_time_1 = timeit.default_timer() best_validation_loss = numpy.inf best_iter = 0 test_score = 0. patience = 200000 validation_frequency = min(n_train_batches, patience // 2) epoch = 0 done_looping = False error_line = numpy.zeros(n_epochs) test_model = theano.function( [index], layer3.errors(y), givens={ layer0.input: test_set_x[index * batch_size: (index + 1) * batch_size], y: test_set_y[index * batch_size: (index + 1) * batch_size]}) validate_model = theano.function( [index], layer3.errors(y), givens={ layer0.input: valid_set_x[index * batch_size: (index + 1) * batch_size], y: valid_set_y[index * batch_size: (index + 1) * batch_size]}) train_model = theano.function( [index], cost, updates=updates, givens={ layer0.input: train_set_x[index * batch_size: (index + 1) * batch_size], y: train_set_y[index * batch_size: (index + 1) * batch_size]}) while (epoch < n_epochs) and (not done_looping): epoch = epoch + 1 for minibatch_index in range(n_train_batches): iter = (epoch - 1) * n_train_batches + minibatch_index if iter % 100 == 0: print('training @ iter = ', iter) cost_ij = train_model(minibatch_index) if (iter + 1) % validation_frequency == 0: validation_losses = [validate_model(i) for i in range(n_valid_batches)] this_validation_loss = numpy.mean(validation_losses) print('epoch %i, minibatch %i/%i, validation error %f' % (epoch, minibatch_index + 1, n_train_batches, this_validation_loss)) error_line[epoch-1] = this_validation_loss if this_validation_loss < best_validation_loss: if this_validation_loss < best_validation_loss * \ improvement_threshold: patience = max(patience, iter * patience_increase) best_validation_loss = this_validation_loss best_iter = iter test_losses = [ test_model(i) for i in range(n_test_batches) ] test_score = numpy.mean(test_losses) print((' epoch %i, minibatch %i/%i, test error of ' 'best model %f') % (epoch, minibatch_index + 1, n_train_batches, test_score)) [t_layer0, t_layer1, t_layer2_input, t_layer2, t_layer3] = \ [layer0, layer1, layer2_input, layer2, layer3] if patience <= iter: done_looping = True break error_line = error_line[0:epoch-1] #if data_set == 'Gaussian_White_Noise.npy': # name += '_WN' scipy.io.savemat(name+'.mat', mdict={'Error_Spectrum': error_line}) with open(name + '.pkl', 'wb') as f: pickle.dump([t_layer0, t_layer1, t_layer2_input, t_layer2, t_layer3], f) temp_time_2 = timeit.default_timer() print('%.2fm' % ((temp_time_2 - temp_time_1) / 60.)) end_time = timeit.default_timer() print('Optimization complete.') print('Best validation score of %f obtained at iteration %i, ' 'with test performance %f ' % (best_validation_loss, best_iter + 1, test_score)) print('The code for file ran for %.2fm' % ((end_time - start_time) / 60.)) def main_ver1_8080(learning_rate=0.05, weight_decay=0.001, n_epochs=300, nkerns=[20, 30], batch_size=500): name = 'Gaussian_Model_'+str(learning_rate)+'_'+str(weight_decay) + '_' + str(nkerns) rng = numpy.random.RandomState(23455) # seed 1 #rng = numpy.random.RandomState(10000) # seed 2 #rng = numpy.random.RandomState(100) # seed 3 train_set_x = numpy.load('Gaussian_Data_Set.npy') train_set_y = numpy.load('Gaussian_Label_Set.npy') valid_set_x = numpy.load('Gaussian_Valid_Data_Set.npy') valid_set_y = numpy.load('Gaussian_Valid_Label_Set.npy') train_set_x, train_set_y = shared_dataset_2(train_set_x, train_set_y) valid_set_x, valid_set_y = shared_dataset_2(valid_set_x, valid_set_y) test_set_x, test_set_y = valid_set_x, valid_set_y n_train = train_set_x.get_value(borrow=True).shape[0] n_valid = valid_set_x.get_value(borrow=True).shape[0] n_test = test_set_x.get_value(borrow=True).shape[0] test_set_x = test_set_x.reshape((n_test, 1, 80, 80)) valid_set_x = valid_set_x.reshape((n_valid, 1, 80, 80)) train_set_x = train_set_x.reshape((n_train, 1, 80, 80)) n_train_batches = n_train//batch_size n_valid_batches = n_valid//batch_size n_test_batches = n_test//batch_size x = T.matrix('x') y = T.fmatrix('y') index = T.lscalar() print('... loading the model') layer0_input = x.reshape((batch_size, 1, 80, 80)) layer0 = LeNetConvPoolLayer( rng, input=layer0_input, image_shape=(batch_size, 1, 80, 80), filter_shape=(nkerns[0], 1, 11, 11), poolsize=(2, 2) ) layer1 = LeNetConvPoolLayer( rng, input=layer0.output, image_shape=(batch_size, nkerns[0], 35, 35), filter_shape=(nkerns[1], nkerns[0], 11, 11), poolsize=(2, 2) ) layer2_input = layer1.output.flatten(2) layer2 = HiddenLayer( rng, input=layer2_input, n_in=nkerns[1] * 12 * 12, n_out=numpy.round(nkerns[1] * 12 * 12/2).astype(int), activation=T.nnet.relu ) layer3 = LogisticRegression_2(input=layer2.output, n_in=numpy.round(nkerns[1] * 12 * 12/2).astype(int), n_out=10) with open(name + '_Initial.pkl', 'wb') as f: pickle.dump([layer0, layer1, layer2_input, layer2, layer3], f) cost = layer3.negative_log_likelihood(y) params = layer3.params + layer2.params + layer1.params + layer0.params grads = T.grad(cost, params) updates = [ (param_i, param_i - learning_rate * (grad_i + weight_decay * param_i)) for param_i, grad_i in zip(params, grads)] patience_increase = 10 improvement_threshold = 0.001 start_time = timeit.default_timer() print('... training') temp_time_1 = timeit.default_timer() best_validation_loss = numpy.inf best_iter = 0 test_score = 0. patience = 10000 validation_frequency = min(n_train_batches, patience // 2) epoch = 0 done_looping = False error_line = numpy.zeros(n_epochs) test_model = theano.function( [index], layer3.errors(y), givens={ layer0.input: test_set_x[index * batch_size: (index + 1) * batch_size], y: test_set_y[index * batch_size: (index + 1) * batch_size]}) validate_model = theano.function( [index], layer3.errors(y), givens={ layer0.input: valid_set_x[index * batch_size: (index + 1) * batch_size], y: valid_set_y[index * batch_size: (index + 1) * batch_size]}) train_model = theano.function( [index], cost, updates=updates, givens={ layer0.input: train_set_x[index * batch_size: (index + 1) * batch_size], y: train_set_y[index * batch_size: (index + 1) * batch_size]}) while (epoch < n_epochs) and (not done_looping): epoch = epoch + 1 for minibatch_index in range(n_train_batches): iter = (epoch - 1) * n_train_batches + minibatch_index if iter % 100 == 0: print('training @ iter = ', iter) cost_ij = train_model(minibatch_index) if (iter + 1) % validation_frequency == 0: validation_losses = [validate_model(i) for i in range(n_valid_batches)] this_validation_loss = numpy.mean(validation_losses) print('epoch %i, minibatch %i/%i, validation error %f' % (epoch, minibatch_index + 1, n_train_batches, this_validation_loss)) error_line[epoch-1] = this_validation_loss if this_validation_loss < best_validation_loss: if this_validation_loss < best_validation_loss * \ improvement_threshold: patience = max(patience, iter * patience_increase) best_validation_loss = this_validation_loss best_iter = iter test_losses = [ test_model(i) for i in range(n_test_batches) ] test_score = numpy.mean(test_losses) print((' epoch %i, minibatch %i/%i, test error of ' 'best model %f') % (epoch, minibatch_index + 1, n_train_batches, test_score)) [t_layer0, t_layer1, t_layer2_input, t_layer2, t_layer3] = \ [layer0, layer1, layer2_input, layer2, layer3] if patience <= iter: done_looping = True break error_line = error_line[0:epoch-1] #if data_set == 'Gaussian_White_Noise.npy': # name += '_WN' scipy.io.savemat(name+'.mat', mdict={'Error_Spectrum': error_line}) with open(name + '.pkl', 'wb') as f: pickle.dump([t_layer0, t_layer1, t_layer2_input, t_layer2, t_layer3], f) temp_time_2 = timeit.default_timer() print('%.2fm' % ((temp_time_2 - temp_time_1) / 60.)) end_time = timeit.default_timer() print('Optimization complete.') print('Best validation score of %f obtained at iteration %i, ' 'with test performance %f ' % (best_validation_loss, best_iter + 1, test_score)) print('The code for file ran for %.2fm' % ((end_time - start_time) / 60.)) def main_ver_4040_softmax(learning_rate=0.05, weight_decay=0.001, n_epochs=1000, nkerns=[20, 30], batch_size=500): # Need to reproduce softmax as Wrong Regression Cost ? name = 'Gaussian_Model_'+str(learning_rate)+'_'+str(weight_decay) + '_' + str(nkerns) +'_Softmax' #if data_set == 'Gaussian_White_Noise.npy': # name += '_WN' rng = numpy.random.RandomState(23455) # seed 1 #rng = numpy.random.RandomState(10000) # seed 2 #rng = numpy.random.RandomState(100) # seed 3 train_set_x = numpy.load('Gaussian_Data_Set.npy') train_set_y = numpy.load('Gaussian_Label_Set.npy') valid_set_x = numpy.load('Gaussian_Valid_Data_Set.npy') valid_set_y = numpy.load('Gaussian_Valid_Label_Set.npy') train_set_x, train_set_y = shared_dataset(train_set_x, train_set_y) valid_set_x, valid_set_y = shared_dataset(valid_set_x, valid_set_y) test_set_x, test_set_y = valid_set_x, valid_set_y n_train = train_set_x.get_value(borrow=True).shape[0] n_valid = valid_set_x.get_value(borrow=True).shape[0] n_test = test_set_x.get_value(borrow=True).shape[0] test_set_x = test_set_x.reshape((n_test, 1, 40, 40)) valid_set_x = valid_set_x.reshape((n_valid, 1, 40, 40)) train_set_x = train_set_x.reshape((n_train, 1, 40, 40)) n_train_batches = n_train//batch_size n_valid_batches = n_valid//batch_size n_test_batches = n_test//batch_size x = T.matrix('x') y = T.ivector('y') index = T.lscalar() print('... loading the model') layer0_input = x.reshape((batch_size, 1, 40, 40)) layer0 = LeNetConvPoolLayer( rng, input=layer0_input, image_shape=(batch_size, 1, 40, 40), filter_shape=(nkerns[0], 1, 5, 5), poolsize=(2, 2) ) layer1 = LeNetConvPoolLayer( rng, input=layer0.output, image_shape=(batch_size, nkerns[0], 18, 18), filter_shape=(nkerns[1], nkerns[0], 5, 5), poolsize=(2, 2) ) layer2_input = layer1.output.flatten(2) layer2 = HiddenLayer( rng, input=layer2_input, n_in=nkerns[1] * 7 * 7, n_out=numpy.round(nkerns[1] * 7 * 7/2).astype(int), activation=T.nnet.relu ) layer3 = LogisticRegression(input=layer2.output, n_in=numpy.round(nkerns[1] * 7 * 7/2).astype(int), n_out=10) with open(name + '_Initial.pkl', 'wb') as f: pickle.dump([layer0, layer1, layer2_input, layer2, layer3], f) #cost = layer3.negative_log_likelihood(y) cost = layer3.sigmoid_cost_function(y) params = layer3.params + layer2.params + layer1.params + layer0.params grads = T.grad(cost, params) updates = [ (param_i, param_i - learning_rate * (grad_i + weight_decay * param_i)) for param_i, grad_i in zip(params, grads)] patience_increase = 10 improvement_threshold = 0.001 start_time = timeit.default_timer() print('... training') temp_time_1 = timeit.default_timer() best_validation_loss = numpy.inf best_iter = 0 test_score = 0. patience = 200000 validation_frequency = min(n_train_batches, patience // 2) epoch = 0 done_looping = False error_line = numpy.zeros(n_epochs) test_model = theano.function( [index], layer3.errors(y), givens={ layer0.input: test_set_x[index * batch_size: (index + 1) * batch_size], y: test_set_y[index * batch_size: (index + 1) * batch_size]}) validate_model = theano.function( [index], layer3.errors(y), givens={ layer0.input: valid_set_x[index * batch_size: (index + 1) * batch_size], y: valid_set_y[index * batch_size: (index + 1) * batch_size]}) train_model = theano.function( [index], cost, updates=updates, givens={ layer0.input: train_set_x[index * batch_size: (index + 1) * batch_size], y: train_set_y[index * batch_size: (index + 1) * batch_size]}) while (epoch < n_epochs) and (not done_looping): epoch = epoch + 1 for minibatch_index in range(n_train_batches): iter = (epoch - 1) * n_train_batches + minibatch_index if iter % 100 == 0: print('training @ iter = ', iter) cost_ij = train_model(minibatch_index) if (iter + 1) % validation_frequency == 0: validation_losses = [validate_model(i) for i in range(n_valid_batches)] this_validation_loss = numpy.mean(validation_losses) print('epoch %i, minibatch %i/%i, validation error %f' % (epoch, minibatch_index + 1, n_train_batches, this_validation_loss)) error_line[epoch-1] = this_validation_loss if this_validation_loss < best_validation_loss: if this_validation_loss < best_validation_loss * \ improvement_threshold: patience = max(patience, iter * patience_increase) best_validation_loss = this_validation_loss best_iter = iter test_losses = [ test_model(i) for i in range(n_test_batches) ] test_score = numpy.mean(test_losses) print((' epoch %i, minibatch %i/%i, test error of ' 'best model %f') % (epoch, minibatch_index + 1, n_train_batches, test_score)) [t_layer0, t_layer1, t_layer2_input, t_layer2, t_layer3] = \ [layer0, layer1, layer2_input, layer2, layer3] if patience <= iter: done_looping = True break #error_line = error_line[0:epoch-1] #scipy.io.savemat(name+'.mat', mdict={'Error_Spectrum': error_line}) #with open(name + '.pkl', 'wb') as f: # pickle.dump([t_layer0, t_layer1, t_layer2_input, t_layer2, t_layer3], f) temp_time_2 = timeit.default_timer() print('%.2fm' % ((temp_time_2 - temp_time_1) / 60.)) end_time = timeit.default_timer() print('Optimization complete.') print('Best validation score of %f obtained at iteration %i, ' 'with test performance %f ' % (best_validation_loss, best_iter + 1, test_score)) print('The code for file ran for %.2fm' % ((end_time - start_time) / 60.)) def main_ver_4040(learning_rate=0.05, weight_decay=0.001, n_epochs=1000, nkerns=[20, 30], batch_size=500): #if data_set == 'Gaussian_White_Noise.npy': # name += '_WN' name = 'Gaussian_Model_'+str(learning_rate)+'_'+str(weight_decay) + '_' + str(nkerns) +'_2_20' rng = numpy.random.RandomState(23455) # seed 1 #rng = numpy.random.RandomState(10000) # seed 2 #rng = numpy.random.RandomState(100) # seed 3 train_set_x = numpy.load('Gaussian_Data_Set_2_20.npy') train_set_y = numpy.load('Gaussian_Label_Set_2_20.npy') valid_set_x = numpy.load('Gaussian_Valid_Data_Set_2_20.npy') valid_set_y = numpy.load('Gaussian_Valid_Label_Set_2_20.npy') train_set_x, train_set_y = shared_dataset_2(train_set_x, train_set_y) valid_set_x, valid_set_y = shared_dataset_2(valid_set_x, valid_set_y) test_set_x, test_set_y = valid_set_x, valid_set_y n_train = train_set_x.get_value(borrow=True).shape[0] n_valid = valid_set_x.get_value(borrow=True).shape[0] n_test = test_set_x.get_value(borrow=True).shape[0] test_set_x = test_set_x.reshape((n_test, 1, 40, 40)) valid_set_x = valid_set_x.reshape((n_valid, 1, 40, 40)) train_set_x = train_set_x.reshape((n_train, 1, 40, 40)) n_train_batches = n_train//batch_size n_valid_batches = n_valid//batch_size n_test_batches = n_test//batch_size x = T.matrix('x') y = T.fmatrix('y') index = T.lscalar() print('... loading the model') layer0_input = x.reshape((batch_size, 1, 40, 40)) layer0 = LeNetConvPoolLayer( rng, input=layer0_input, image_shape=(batch_size, 1, 40, 40), filter_shape=(nkerns[0], 1, 5, 5), poolsize=(2, 2) ) layer1 = LeNetConvPoolLayer( rng, input=layer0.output, image_shape=(batch_size, nkerns[0], 18, 18), filter_shape=(nkerns[1], nkerns[0], 5, 5), poolsize=(2, 2) ) layer2_input = layer1.output.flatten(2) layer2 = HiddenLayer( rng, input=layer2_input, n_in=nkerns[1] * 7 * 7, n_out=numpy.round(nkerns[1] * 7 * 7/2).astype(int), activation=T.nnet.relu ) layer3 = LogisticRegression_2(input=layer2.output, n_in=numpy.round(nkerns[1] * 7 * 7/2).astype(int), n_out=10, rng=rng) with open(name + '_Initial.pkl', 'wb') as f: pickle.dump([layer0, layer1, layer2_input, layer2, layer3], f) cost = layer3.sigmoid_cost_function(y) params = layer3.params + layer2.params + layer1.params + layer0.params grads = T.grad(cost, params) updates = [ (param_i, param_i - learning_rate * (grad_i + weight_decay * param_i)) for param_i, grad_i in zip(params, grads)] #updates = adam(cost, params) patience_increase = 4 improvement_threshold = 0.00001 start_time = timeit.default_timer() print('... training') temp_time_1 = timeit.default_timer() best_validation_loss = numpy.inf best_iter = 0 test_score = 0. patience = 5000000 validation_frequency = min(n_train_batches, patience // 2) epoch = 0 done_looping = False error_line = numpy.zeros(n_epochs+1) test_model = theano.function( [index], layer3.errors(y), givens={ layer0.input: test_set_x[index * batch_size: (index + 1) * batch_size], y: test_set_y[index * batch_size: (index + 1) * batch_size]}) validate_model = theano.function( [index], layer3.errors(y), givens={ layer0.input: valid_set_x[index * batch_size: (index + 1) * batch_size], y: valid_set_y[index * batch_size: (index + 1) * batch_size]}) train_model = theano.function( [index], cost, updates=updates, givens={ layer0.input: train_set_x[index * batch_size: (index + 1) * batch_size], y: train_set_y[index * batch_size: (index + 1) * batch_size]}) validation_losses = [validate_model(i) for i in range(n_valid_batches)] this_validation_loss = numpy.mean(validation_losses) print('Initial validation error %f' % this_validation_loss) error_line[0] = this_validation_loss while (epoch < n_epochs) and (not done_looping): epoch = epoch + 1 for minibatch_index in range(n_train_batches): iter = (epoch - 1) * n_train_batches + minibatch_index if iter % 100 == 0: print('training @ iter = ', iter) cost_ij = train_model(minibatch_index) if (iter + 1) % validation_frequency == 0: validation_losses = [validate_model(i) for i in range(n_valid_batches)] this_validation_loss = numpy.mean(validation_losses) print('epoch %i, minibatch %i/%i, validation error %f' % (epoch, minibatch_index + 1, n_train_batches, this_validation_loss)) error_line[epoch] = this_validation_loss if this_validation_loss < best_validation_loss: if this_validation_loss < best_validation_loss * \ improvement_threshold: patience = max(patience, iter * patience_increase) best_validation_loss = this_validation_loss best_iter = iter test_losses = [ test_model(i) for i in range(n_test_batches) ] test_score = numpy.mean(test_losses) print((' epoch %i, minibatch %i/%i, test error of ' 'best model %f') % (epoch, minibatch_index + 1, n_train_batches, test_score)) [t_layer0, t_layer1, t_layer2_input, t_layer2, t_layer3] = \ [layer0, layer1, layer2_input, layer2, layer3] if patience <= iter: done_looping = True break error_line = error_line[0:epoch] scipy.io.savemat(name+'.mat', mdict={'Error_Spectrum': error_line}) with open(name + '.pkl', 'wb') as f: pickle.dump([t_layer0, t_layer1, t_layer2_input, t_layer2, t_layer3], f) temp_time_2 = timeit.default_timer() print('%.2fm' % ((temp_time_2 - temp_time_1) / 60.)) end_time = timeit.default_timer() print('Optimization complete.') print('Best validation score of %f obtained at iteration %i, ' 'with test performance %f ' % (best_validation_loss, best_iter + 1, test_score)) print('The code for file ran for %.2fm' % ((end_time - start_time) / 60.)) def main_ver_4040_converge_check_pending(learning_rate=0.05, weight_decay=0.001, n_epochs=1000, nkerns=[20, 30], batch_size=500): #if data_set == 'Gaussian_White_Noise.npy': # name += '_WN' name = 'Gaussian_Model_'+str(learning_rate)+'_'+str(weight_decay) + '_' + str(nkerns) +'_Softmax' rng = numpy.random.RandomState(23455) # seed 1 #rng = numpy.random.RandomState(10000) # seed 2 #rng = numpy.random.RandomState(100) # seed 3 train_set_x =
numpy.load('Gaussian_Data_Set.npy')
numpy.load
import sys from numpy.testing import * import numpy.core.umath as ncu import numpy as np class _FilterInvalids(object): def setUp(self): self.olderr = np.seterr(invalid='ignore') def tearDown(self): np.seterr(**self.olderr) class TestDivision(TestCase): def test_division_int(self): # int division should follow Python x = np.array([5, 10, 90, 100, -5, -10, -90, -100, -120]) if 5 / 10 == 0.5: assert_equal(x / 100, [0.05, 0.1, 0.9, 1, -0.05, -0.1, -0.9, -1, -1.2]) else: assert_equal(x / 100, [0, 0, 0, 1, -1, -1, -1, -1, -2]) assert_equal(x // 100, [0, 0, 0, 1, -1, -1, -1, -1, -2]) assert_equal(x % 100, [5, 10, 90, 0, 95, 90, 10, 0, 80]) def test_division_complex(self): # check that implementation is correct msg = "Complex division implementation check" x = np.array([1. + 1.*1j, 1. + .5*1j, 1. + 2.*1j], dtype=np.complex128) assert_almost_equal(x**2/x, x, err_msg=msg) # check overflow, underflow msg = "Complex division overflow/underflow check" x = np.array([1.e+110, 1.e-110], dtype=np.complex128) y = x**2/x assert_almost_equal(y/x, [1, 1], err_msg=msg) def test_zero_division_complex(self): err = np.seterr(invalid="ignore", divide="ignore") try: x = np.array([0.0], dtype=np.complex128) y = 1.0/x assert_(np.isinf(y)[0]) y = complex(np.inf, np.nan)/x assert_(np.isinf(y)[0]) y = complex(np.nan, np.inf)/x assert_(np.isinf(y)[0]) y = complex(np.inf, np.inf)/x assert_(np.isinf(y)[0]) y = 0.0/x assert_(np.isnan(y)[0]) finally: np.seterr(**err) def test_floor_division_complex(self): # check that implementation is correct msg = "Complex floor division implementation check" x = np.array([.9 + 1j, -.1 + 1j, .9 + .5*1j, .9 + 2.*1j], dtype=np.complex128) y = np.array([0., -1., 0., 0.], dtype=np.complex128) assert_equal(np.floor_divide(x**2,x), y, err_msg=msg) # check overflow, underflow msg = "Complex floor division overflow/underflow check" x = np.array([1.e+110, 1.e-110], dtype=np.complex128) y = np.floor_divide(x**2, x) assert_equal(y, [1.e+110, 0], err_msg=msg) class TestPower(TestCase): def test_power_float(self): x = np.array([1., 2., 3.]) assert_equal(x**0, [1., 1., 1.]) assert_equal(x**1, x) assert_equal(x**2, [1., 4., 9.]) y = x.copy() y **= 2 assert_equal(y, [1., 4., 9.]) assert_almost_equal(x**(-1), [1., 0.5, 1./3]) assert_almost_equal(x**(0.5), [1., ncu.sqrt(2), ncu.sqrt(3)]) def test_power_complex(self): x = np.array([1+2j, 2+3j, 3+4j]) assert_equal(x**0, [1., 1., 1.]) assert_equal(x**1, x) assert_almost_equal(x**2, [-3+4j, -5+12j, -7+24j]) assert_almost_equal(x**3, [(1+2j)**3, (2+3j)**3, (3+4j)**3]) assert_almost_equal(x**4, [(1+2j)**4, (2+3j)**4, (3+4j)**4]) assert_almost_equal(x**(-1), [1/(1+2j), 1/(2+3j), 1/(3+4j)]) assert_almost_equal(x**(-2), [1/(1+2j)**2, 1/(2+3j)**2, 1/(3+4j)**2]) assert_almost_equal(x**(-3), [(-11+2j)/125, (-46-9j)/2197, (-117-44j)/15625]) assert_almost_equal(x**(0.5), [ncu.sqrt(1+2j), ncu.sqrt(2+3j), ncu.sqrt(3+4j)]) norm = 1./((x**14)[0]) assert_almost_equal(x**14 * norm, [i * norm for i in [-76443+16124j, 23161315+58317492j, 5583548873 + 2465133864j]]) # Ticket #836 def assert_complex_equal(x, y): assert_array_equal(x.real, y.real) assert_array_equal(x.imag, y.imag) for z in [complex(0, np.inf), complex(1, np.inf)]: err = np.seterr(invalid="ignore") z = np.array([z], dtype=np.complex_) try: assert_complex_equal(z**1, z) assert_complex_equal(z**2, z*z) assert_complex_equal(z**3, z*z*z) finally: np.seterr(**err) def test_power_zero(self): # ticket #1271 zero = np.array([0j]) one = np.array([1+0j]) cinf = np.array([complex(np.inf, 0)]) cnan = np.array([complex(np.nan, np.nan)]) def assert_complex_equal(x, y): x, y = np.asarray(x), np.asarray(y) assert_array_equal(x.real, y.real) assert_array_equal(x.imag, y.imag) # positive powers for p in [0.33, 0.5, 1, 1.5, 2, 3, 4, 5, 6.6]: assert_complex_equal(np.power(zero, p), zero) # zero power assert_complex_equal(np.power(zero, 0), one) assert_complex_equal(np.power(zero, 0+1j), cnan) # negative power for p in [0.33, 0.5, 1, 1.5, 2, 3, 4, 5, 6.6]: assert_complex_equal(np.power(zero, -p), cnan) assert_complex_equal(np.power(zero, -1+0.2j), cnan) def test_fast_power(self): x=np.array([1,2,3], np.int16) assert (x**2.00001).dtype is (x**2.0).dtype class TestLog2(TestCase): def test_log2_values(self) : x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024] y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for dt in ['f','d','g'] : xf = np.array(x, dtype=dt) yf = np.array(y, dtype=dt) assert_almost_equal(np.log2(xf), yf) class TestExp2(TestCase): def test_exp2_values(self) : x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024] y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for dt in ['f','d','g'] : xf = np.array(x, dtype=dt) yf = np.array(y, dtype=dt) assert_almost_equal(np.exp2(yf), xf) class TestLogAddExp2(_FilterInvalids): # Need test for intermediate precisions def test_logaddexp2_values(self) : x = [1, 2, 3, 4, 5] y = [5, 4, 3, 2, 1] z = [6, 6, 6, 6, 6] for dt, dec in zip(['f','d','g'],[6, 15, 15]) : xf = np.log2(np.array(x, dtype=dt)) yf = np.log2(np.array(y, dtype=dt)) zf = np.log2(np.array(z, dtype=dt)) assert_almost_equal(np.logaddexp2(xf, yf), zf, decimal=dec) def test_logaddexp2_range(self) : x = [1000000, -1000000, 1000200, -1000200] y = [1000200, -1000200, 1000000, -1000000] z = [1000200, -1000000, 1000200, -1000000] for dt in ['f','d','g'] : logxf = np.array(x, dtype=dt) logyf = np.array(y, dtype=dt) logzf = np.array(z, dtype=dt) assert_almost_equal(np.logaddexp2(logxf, logyf), logzf) def test_inf(self) : err = np.seterr(invalid='ignore') inf = np.inf x = [inf, -inf, inf, -inf, inf, 1, -inf, 1] y = [inf, inf, -inf, -inf, 1, inf, 1, -inf] z = [inf, inf, inf, -inf, inf, inf, 1, 1] try: for dt in ['f','d','g'] : logxf = np.array(x, dtype=dt) logyf = np.array(y, dtype=dt) logzf = np.array(z, dtype=dt) assert_equal(np.logaddexp2(logxf, logyf), logzf) finally: np.seterr(**err) def test_nan(self): assert_(np.isnan(np.logaddexp2(np.nan, np.inf))) assert_(np.isnan(np.logaddexp2(np.inf, np.nan))) assert_(np.isnan(np.logaddexp2(np.nan, 0))) assert_(np.isnan(np.logaddexp2(0, np.nan))) assert_(np.isnan(np.logaddexp2(np.nan, np.nan))) class TestLog(TestCase): def test_log_values(self) : x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024] y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for dt in ['f','d','g'] : log2_ = 0.69314718055994530943 xf = np.array(x, dtype=dt) yf = np.array(y, dtype=dt)*log2_ assert_almost_equal(np.log(xf), yf) class TestExp(TestCase): def test_exp_values(self) : x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024] y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for dt in ['f','d','g'] : log2_ = 0.69314718055994530943 xf = np.array(x, dtype=dt) yf = np.array(y, dtype=dt)*log2_ assert_almost_equal(np.exp(yf), xf) class TestLogAddExp(_FilterInvalids): def test_logaddexp_values(self) : x = [1, 2, 3, 4, 5] y = [5, 4, 3, 2, 1] z = [6, 6, 6, 6, 6] for dt, dec in zip(['f','d','g'],[6, 15, 15]) : xf = np.log(np.array(x, dtype=dt)) yf = np.log(np.array(y, dtype=dt)) zf = np.log(np.array(z, dtype=dt)) assert_almost_equal(np.logaddexp(xf, yf), zf, decimal=dec) def test_logaddexp_range(self) : x = [1000000, -1000000, 1000200, -1000200] y = [1000200, -1000200, 1000000, -1000000] z = [1000200, -1000000, 1000200, -1000000] for dt in ['f','d','g'] : logxf = np.array(x, dtype=dt) logyf = np.array(y, dtype=dt) logzf = np.array(z, dtype=dt) assert_almost_equal(np.logaddexp(logxf, logyf), logzf) def test_inf(self) : err = np.seterr(invalid='ignore') inf = np.inf x = [inf, -inf, inf, -inf, inf, 1, -inf, 1] y = [inf, inf, -inf, -inf, 1, inf, 1, -inf] z = [inf, inf, inf, -inf, inf, inf, 1, 1] try: for dt in ['f','d','g'] : logxf = np.array(x, dtype=dt) logyf = np.array(y, dtype=dt) logzf = np.array(z, dtype=dt) assert_equal(np.logaddexp(logxf, logyf), logzf) finally: np.seterr(**err) def test_nan(self): assert_(np.isnan(np.logaddexp(np.nan, np.inf))) assert_(np.isnan(np.logaddexp(np.inf, np.nan))) assert_(np.isnan(np.logaddexp(np.nan, 0))) assert_(np.isnan(np.logaddexp(0, np.nan))) assert_(np.isnan(np.logaddexp(np.nan, np.nan))) class TestLog1p(TestCase): def test_log1p(self): assert_almost_equal(ncu.log1p(0.2), ncu.log(1.2)) assert_almost_equal(ncu.log1p(1e-6), ncu.log(1+1e-6)) class TestExpm1(TestCase): def test_expm1(self): assert_almost_equal(ncu.expm1(0.2), ncu.exp(0.2)-1) assert_almost_equal(ncu.expm1(1e-6), ncu.exp(1e-6)-1) class TestHypot(TestCase, object): def test_simple(self): assert_almost_equal(ncu.hypot(1, 1), ncu.sqrt(2)) assert_almost_equal(ncu.hypot(0, 0), 0) def assert_hypot_isnan(x, y): err = np.seterr(invalid='ignore') try: assert_(np.isnan(ncu.hypot(x, y)), "hypot(%s, %s) is %s, not nan" % (x, y, ncu.hypot(x, y))) finally: np.seterr(**err) def assert_hypot_isinf(x, y): err = np.seterr(invalid='ignore') try: assert_(np.isinf(ncu.hypot(x, y)), "hypot(%s, %s) is %s, not inf" % (x, y, ncu.hypot(x, y))) finally: np.seterr(**err) class TestHypotSpecialValues(TestCase): def test_nan_outputs(self): assert_hypot_isnan(np.nan, np.nan) assert_hypot_isnan(np.nan, 1) def test_nan_outputs(self): assert_hypot_isinf(np.nan, np.inf) assert_hypot_isinf(np.inf, np.nan) assert_hypot_isinf(np.inf, 0) assert_hypot_isinf(0, np.inf) def assert_arctan2_isnan(x, y): assert_(np.isnan(ncu.arctan2(x, y)), "arctan(%s, %s) is %s, not nan" % (x, y, ncu.arctan2(x, y))) def assert_arctan2_ispinf(x, y): assert_((np.isinf(ncu.arctan2(x, y)) and ncu.arctan2(x, y) > 0), "arctan(%s, %s) is %s, not +inf" % (x, y, ncu.arctan2(x, y))) def assert_arctan2_isninf(x, y): assert_((np.isinf(ncu.arctan2(x, y)) and ncu.arctan2(x, y) < 0), "arctan(%s, %s) is %s, not -inf" % (x, y, ncu.arctan2(x, y))) def assert_arctan2_ispzero(x, y): assert_((ncu.arctan2(x, y) == 0 and not np.signbit(ncu.arctan2(x, y))), "arctan(%s, %s) is %s, not +0" % (x, y, ncu.arctan2(x, y))) def assert_arctan2_isnzero(x, y): assert_((ncu.arctan2(x, y) == 0 and np.signbit(ncu.arctan2(x, y))), "arctan(%s, %s) is %s, not -0" % (x, y, ncu.arctan2(x, y))) class TestArctan2SpecialValues(TestCase): def test_one_one(self): # atan2(1, 1) returns pi/4. assert_almost_equal(ncu.arctan2(1, 1), 0.25 * np.pi) assert_almost_equal(ncu.arctan2(-1, 1), -0.25 * np.pi) assert_almost_equal(ncu.arctan2(1, -1), 0.75 * np.pi) def test_zero_nzero(self): # atan2(+-0, -0) returns +-pi. assert_almost_equal(ncu.arctan2(np.PZERO, np.NZERO), np.pi) assert_almost_equal(ncu.arctan2(np.NZERO, np.NZERO), -np.pi) def test_zero_pzero(self): # atan2(+-0, +0) returns +-0. assert_arctan2_ispzero(np.PZERO, np.PZERO) assert_arctan2_isnzero(np.NZERO, np.PZERO) def test_zero_negative(self): # atan2(+-0, x) returns +-pi for x < 0. assert_almost_equal(ncu.arctan2(np.PZERO, -1), np.pi) assert_almost_equal(ncu.arctan2(np.NZERO, -1), -np.pi) def test_zero_positive(self): # atan2(+-0, x) returns +-0 for x > 0. assert_arctan2_ispzero(np.PZERO, 1) assert_arctan2_isnzero(np.NZERO, 1) def test_positive_zero(self): # atan2(y, +-0) returns +pi/2 for y > 0. assert_almost_equal(ncu.arctan2(1, np.PZERO), 0.5 * np.pi) assert_almost_equal(ncu.arctan2(1, np.NZERO), 0.5 * np.pi) def test_negative_zero(self): # atan2(y, +-0) returns -pi/2 for y < 0. assert_almost_equal(ncu.arctan2(-1, np.PZERO), -0.5 * np.pi) assert_almost_equal(ncu.arctan2(-1, np.NZERO), -0.5 * np.pi) def test_any_ninf(self): # atan2(+-y, -infinity) returns +-pi for finite y > 0. assert_almost_equal(ncu.arctan2(1, np.NINF), np.pi) assert_almost_equal(ncu.arctan2(-1, np.NINF), -np.pi) def test_any_pinf(self): # atan2(+-y, +infinity) returns +-0 for finite y > 0. assert_arctan2_ispzero(1, np.inf) assert_arctan2_isnzero(-1, np.inf) def test_inf_any(self): # atan2(+-infinity, x) returns +-pi/2 for finite x. assert_almost_equal(ncu.arctan2( np.inf, 1), 0.5 * np.pi) assert_almost_equal(ncu.arctan2(-np.inf, 1), -0.5 * np.pi) def test_inf_ninf(self): # atan2(+-infinity, -infinity) returns +-3*pi/4. assert_almost_equal(ncu.arctan2( np.inf, -np.inf), 0.75 * np.pi) assert_almost_equal(ncu.arctan2(-np.inf, -np.inf), -0.75 * np.pi) def test_inf_pinf(self): # atan2(+-infinity, +infinity) returns +-pi/4. assert_almost_equal(ncu.arctan2( np.inf, np.inf), 0.25 * np.pi) assert_almost_equal(ncu.arctan2(-np.inf, np.inf), -0.25 * np.pi) def test_nan_any(self): # atan2(nan, x) returns nan for any x, including inf assert_arctan2_isnan(np.nan, np.inf) assert_arctan2_isnan(np.inf, np.nan) assert_arctan2_isnan(np.nan, np.nan) class TestLdexp(TestCase): def _check_ldexp(self, tp): assert_almost_equal(ncu.ldexp(np.array(2., np.float32), np.array(3, tp)), 16.) assert_almost_equal(ncu.ldexp(np.array(2., np.float64), np.array(3, tp)), 16.) assert_almost_equal(ncu.ldexp(np.array(2., np.longdouble), np.array(3, tp)), 16.) def test_ldexp(self): # The default Python int type should work assert_almost_equal(ncu.ldexp(2., 3), 16.) # The following int types should all be accepted self._check_ldexp(np.int8) self._check_ldexp(np.int16) self._check_ldexp(np.int32) self._check_ldexp('i') self._check_ldexp('l') @dec.knownfailureif(sys.platform == 'win32' and sys.version_info < (2, 6), "python.org < 2.6 binaries have broken ldexp in the " "C runtime") def test_ldexp_overflow(self): # silence warning emitted on overflow err = np.seterr(over="ignore") try: imax = np.iinfo(np.dtype('l')).max imin = np.iinfo(np.dtype('l')).min assert_equal(ncu.ldexp(2., imax), np.inf) assert_equal(ncu.ldexp(2., imin), 0) finally: np.seterr(**err) class TestMaximum(_FilterInvalids): def test_reduce(self): dflt = np.typecodes['AllFloat'] dint = np.typecodes['AllInteger'] seq1 = np.arange(11) seq2 = seq1[::-1] func = np.maximum.reduce for dt in dint: tmp1 = seq1.astype(dt) tmp2 = seq2.astype(dt) assert_equal(func(tmp1), 10) assert_equal(func(tmp2), 10) for dt in dflt: tmp1 = seq1.astype(dt) tmp2 = seq2.astype(dt) assert_equal(func(tmp1), 10) assert_equal(func(tmp2), 10) tmp1[::2] = np.nan tmp2[::2] = np.nan assert_equal(func(tmp1), np.nan) assert_equal(func(tmp2), np.nan) def test_reduce_complex(self): assert_equal(np.maximum.reduce([1,2j]),1) assert_equal(np.maximum.reduce([1+3j,2j]),1+3j) def test_float_nans(self): nan = np.nan arg1 = np.array([0, nan, nan]) arg2 = np.array([nan, 0, nan]) out = np.array([nan, nan, nan]) assert_equal(np.maximum(arg1, arg2), out) def test_complex_nans(self): nan = np.nan for cnan in [complex(nan, 0), complex(0, nan), complex(nan, nan)] : arg1 = np.array([0, cnan, cnan], dtype=np.complex) arg2 = np.array([cnan, 0, cnan], dtype=np.complex) out = np.array([nan, nan, nan], dtype=np.complex) assert_equal(np.maximum(arg1, arg2), out) def test_object_array(self): arg1 = np.arange(5, dtype=np.object) arg2 = arg1 + 1 assert_equal(np.maximum(arg1, arg2), arg2) class TestMinimum(_FilterInvalids): def test_reduce(self): dflt = np.typecodes['AllFloat'] dint = np.typecodes['AllInteger'] seq1 = np.arange(11) seq2 = seq1[::-1] func = np.minimum.reduce for dt in dint: tmp1 = seq1.astype(dt) tmp2 = seq2.astype(dt) assert_equal(func(tmp1), 0) assert_equal(func(tmp2), 0) for dt in dflt: tmp1 = seq1.astype(dt) tmp2 = seq2.astype(dt) assert_equal(func(tmp1), 0) assert_equal(func(tmp2), 0) tmp1[::2] = np.nan tmp2[::2] = np.nan assert_equal(func(tmp1), np.nan) assert_equal(func(tmp2), np.nan) def test_reduce_complex(self): assert_equal(np.minimum.reduce([1,2j]),2j) assert_equal(np.minimum.reduce([1+3j,2j]),2j) def test_float_nans(self): nan = np.nan arg1 = np.array([0, nan, nan]) arg2 = np.array([nan, 0, nan]) out = np.array([nan, nan, nan]) assert_equal(np.minimum(arg1, arg2), out) def test_complex_nans(self): nan = np.nan for cnan in [complex(nan, 0), complex(0, nan), complex(nan, nan)] : arg1 = np.array([0, cnan, cnan], dtype=np.complex) arg2 = np.array([cnan, 0, cnan], dtype=np.complex) out = np.array([nan, nan, nan], dtype=np.complex) assert_equal(np.minimum(arg1, arg2), out) def test_object_array(self): arg1 = np.arange(5, dtype=np.object) arg2 = arg1 + 1 assert_equal(np.minimum(arg1, arg2), arg1) class TestFmax(_FilterInvalids): def test_reduce(self): dflt = np.typecodes['AllFloat'] dint = np.typecodes['AllInteger'] seq1 = np.arange(11) seq2 = seq1[::-1] func = np.fmax.reduce for dt in dint: tmp1 = seq1.astype(dt) tmp2 = seq2.astype(dt) assert_equal(func(tmp1), 10) assert_equal(func(tmp2), 10) for dt in dflt: tmp1 = seq1.astype(dt) tmp2 = seq2.astype(dt) assert_equal(func(tmp1), 10) assert_equal(func(tmp2), 10) tmp1[::2] = np.nan tmp2[::2] = np.nan assert_equal(func(tmp1), 9) assert_equal(func(tmp2), 9) def test_reduce_complex(self): assert_equal(np.fmax.reduce([1,2j]),1) assert_equal(np.fmax.reduce([1+3j,2j]),1+3j) def test_float_nans(self): nan = np.nan arg1 = np.array([0, nan, nan]) arg2 = np.array([nan, 0, nan]) out = np.array([0, 0, nan]) assert_equal(np.fmax(arg1, arg2), out) def test_complex_nans(self): nan = np.nan for cnan in [complex(nan, 0), complex(0, nan), complex(nan, nan)] : arg1 = np.array([0, cnan, cnan], dtype=np.complex) arg2 = np.array([cnan, 0, cnan], dtype=np.complex) out = np.array([0, 0, nan], dtype=np.complex) assert_equal(np.fmax(arg1, arg2), out) class TestFmin(_FilterInvalids): def test_reduce(self): dflt = np.typecodes['AllFloat'] dint = np.typecodes['AllInteger'] seq1 = np.arange(11) seq2 = seq1[::-1] func = np.fmin.reduce for dt in dint: tmp1 = seq1.astype(dt) tmp2 = seq2.astype(dt) assert_equal(func(tmp1), 0) assert_equal(func(tmp2), 0) for dt in dflt: tmp1 = seq1.astype(dt) tmp2 = seq2.astype(dt) assert_equal(func(tmp1), 0) assert_equal(func(tmp2), 0) tmp1[::2] = np.nan tmp2[::2] = np.nan assert_equal(func(tmp1), 1) assert_equal(func(tmp2), 1) def test_reduce_complex(self): assert_equal(np.fmin.reduce([1,2j]),2j) assert_equal(np.fmin.reduce([1+3j,2j]),2j) def test_float_nans(self): nan = np.nan arg1 = np.array([0, nan, nan]) arg2 = np.array([nan, 0, nan]) out = np.array([0, 0, nan]) assert_equal(np.fmin(arg1, arg2), out) def test_complex_nans(self): nan = np.nan for cnan in [complex(nan, 0), complex(0, nan), complex(nan, nan)] : arg1 = np.array([0, cnan, cnan], dtype=np.complex) arg2 = np.array([cnan, 0, cnan], dtype=np.complex) out = np.array([0, 0, nan], dtype=np.complex) assert_equal(np.fmin(arg1, arg2), out) class TestFloatingPoint(TestCase): def test_floating_point(self): assert_equal(ncu.FLOATING_POINT_SUPPORT, 1) class TestDegrees(TestCase): def test_degrees(self): assert_almost_equal(ncu.degrees(np.pi), 180.0) assert_almost_equal(ncu.degrees(-0.5*np.pi), -90.0) class TestRadians(TestCase): def test_radians(self): assert_almost_equal(ncu.radians(180.0), np.pi) assert_almost_equal(ncu.radians(-90.0), -0.5*np.pi) class TestSign(TestCase): def test_sign(self): a = np.array([np.inf, -np.inf, np.nan, 0.0, 3.0, -3.0]) out = np.zeros(a.shape) tgt = np.array([1., -1., np.nan, 0.0, 1.0, -1.0]) olderr = np.seterr(invalid='ignore') try: res = ncu.sign(a) assert_equal(res, tgt) res = ncu.sign(a, out) assert_equal(res, tgt) assert_equal(out, tgt) finally: np.seterr(**olderr) class TestSpecialMethods(TestCase): def test_wrap(self): class with_wrap(object): def __array__(self): return np.zeros(1) def __array_wrap__(self, arr, context): r = with_wrap() r.arr = arr r.context = context return r a = with_wrap() x = ncu.minimum(a, a) assert_equal(x.arr, np.zeros(1)) func, args, i = x.context self.assertTrue(func is ncu.minimum) self.assertEqual(len(args), 2) assert_equal(args[0], a) assert_equal(args[1], a) self.assertEqual(i, 0) def test_wrap_with_iterable(self): # test fix for bug #1026: class with_wrap(np.ndarray): __array_priority__ = 10 def __new__(cls): return np.asarray(1).view(cls).copy() def __array_wrap__(self, arr, context): return arr.view(type(self)) a = with_wrap() x = ncu.multiply(a, (1, 2, 3)) self.assertTrue(isinstance(x, with_wrap)) assert_array_equal(x, np.array((1, 2, 3))) def test_priority_with_scalar(self): # test fix for bug #826: class A(np.ndarray): __array_priority__ = 10 def __new__(cls): return np.asarray(1.0, 'float64').view(cls).copy() a = A() x = np.float64(1)*a self.assertTrue(isinstance(x, A)) assert_array_equal(x, np.array(1)) def test_old_wrap(self): class with_wrap(object): def __array__(self): return np.zeros(1) def __array_wrap__(self, arr): r = with_wrap() r.arr = arr return r a = with_wrap() x = ncu.minimum(a, a) assert_equal(x.arr, np.zeros(1)) def test_priority(self): class A(object): def __array__(self): return np.zeros(1) def __array_wrap__(self, arr, context): r = type(self)() r.arr = arr r.context = context return r class B(A): __array_priority__ = 20. class C(A): __array_priority__ = 40. x = np.zeros(1) a = A() b = B() c = C() f = ncu.minimum self.assertTrue(type(f(x,x)) is np.ndarray) self.assertTrue(type(f(x,a)) is A) self.assertTrue(type(f(x,b)) is B) self.assertTrue(type(f(x,c)) is C) self.assertTrue(type(f(a,x)) is A) self.assertTrue(type(f(b,x)) is B) self.assertTrue(type(f(c,x)) is C) self.assertTrue(type(f(a,a)) is A) self.assertTrue(type(f(a,b)) is B) self.assertTrue(type(f(b,a)) is B) self.assertTrue(type(f(b,b)) is B) self.assertTrue(type(f(b,c)) is C) self.assertTrue(type(f(c,b)) is C) self.assertTrue(type(f(c,c)) is C) self.assertTrue(type(ncu.exp(a) is A)) self.assertTrue(type(ncu.exp(b) is B)) self.assertTrue(type(ncu.exp(c) is C)) def test_failing_wrap(self): class A(object): def __array__(self): return np.zeros(1) def __array_wrap__(self, arr, context): raise RuntimeError a = A() self.assertRaises(RuntimeError, ncu.maximum, a, a) def test_default_prepare(self): class with_wrap(object): __array_priority__ = 10 def __array__(self): return np.zeros(1) def __array_wrap__(self, arr, context): return arr a = with_wrap() x = ncu.minimum(a, a) assert_equal(x, np.zeros(1)) assert_equal(type(x), np.ndarray) def test_prepare(self): class with_prepare(np.ndarray): __array_priority__ = 10 def __array_prepare__(self, arr, context): # make sure we can return a new return np.array(arr).view(type=with_prepare) a = np.array(1).view(type=with_prepare) x = np.add(a, a) assert_equal(x, np.array(2)) assert_equal(type(x), with_prepare) def test_failing_prepare(self): class A(object): def __array__(self): return np.zeros(1) def __array_prepare__(self, arr, context=None): raise RuntimeError a = A() self.assertRaises(RuntimeError, ncu.maximum, a, a) def test_array_with_context(self): class A(object): def __array__(self, dtype=None, context=None): func, args, i = context self.func = func self.args = args self.i = i return np.zeros(1) class B(object): def __array__(self, dtype=None): return np.zeros(1, dtype) class C(object): def __array__(self): return np.zeros(1) a = A() ncu.maximum(np.zeros(1), a) self.assertTrue(a.func is ncu.maximum) assert_equal(a.args[0], 0) self.assertTrue(a.args[1] is a) self.assertTrue(a.i == 1) assert_equal(ncu.maximum(a, B()), 0) assert_equal(ncu.maximum(a, C()), 0) class TestChoose(TestCase): def test_mixed(self): c = np.array([True,True]) a = np.array([True,True]) assert_equal(np.choose(c, (a, 1)), np.array([1,1])) def is_longdouble_finfo_bogus(): info = np.finfo(np.longcomplex) return not np.isfinite(np.log10(info.tiny/info.eps)) class TestComplexFunctions(object): funcs = [np.arcsin, np.arccos, np.arctan, np.arcsinh, np.arccosh, np.arctanh, np.sin, np.cos, np.tan, np.exp, np.exp2, np.log, np.sqrt, np.log10, np.log2, np.log1p] def test_it(self): for f in self.funcs: if f is np.arccosh : x = 1.5 else : x = .5 fr = f(x) fz = f(np.complex(x)) assert_almost_equal(fz.real, fr, err_msg='real part %s'%f) assert_almost_equal(fz.imag, 0., err_msg='imag part %s'%f) def test_precisions_consistent(self) : z = 1 + 1j for f in self.funcs : fcf = f(np.csingle(z)) fcd = f(np.cdouble(z)) fcl = f(np.clongdouble(z)) assert_almost_equal(fcf, fcd, decimal=6, err_msg='fch-fcd %s'%f) assert_almost_equal(fcl, fcd, decimal=15, err_msg='fch-fcl %s'%f) def test_branch_cuts(self): # check branch cuts and continuity on them yield _check_branch_cut, np.log, -0.5, 1j, 1, -1 yield _check_branch_cut, np.log2, -0.5, 1j, 1, -1 yield _check_branch_cut, np.log10, -0.5, 1j, 1, -1 yield _check_branch_cut, np.log1p, -1.5, 1j, 1, -1 yield _check_branch_cut, np.sqrt, -0.5, 1j, 1, -1 yield _check_branch_cut, np.arcsin, [ -2, 2], [1j, -1j], 1, -1 yield _check_branch_cut, np.arccos, [ -2, 2], [1j, -1j], 1, -1 yield _check_branch_cut, np.arctan, [-2j, 2j], [1, -1 ], -1, 1 yield _check_branch_cut, np.arcsinh, [-2j, 2j], [-1, 1], -1, 1 yield _check_branch_cut, np.arccosh, [ -1, 0.5], [1j, 1j], 1, -1 yield _check_branch_cut, np.arctanh, [ -2, 2], [1j, -1j], 1, -1 # check against bogus branch cuts: assert continuity between quadrants yield _check_branch_cut, np.arcsin, [-2j, 2j], [ 1, 1], 1, 1 yield _check_branch_cut, np.arccos, [-2j, 2j], [ 1, 1], 1, 1 yield _check_branch_cut, np.arctan, [ -2, 2], [1j, 1j], 1, 1 yield _check_branch_cut, np.arcsinh, [ -2, 2, 0], [1j, 1j, 1 ], 1, 1 yield _check_branch_cut, np.arccosh, [-2j, 2j, 2], [1, 1, 1j], 1, 1 yield _check_branch_cut, np.arctanh, [-2j, 2j, 0], [1, 1, 1j], 1, 1 @dec.knownfailureif(True, "These branch cuts are known to fail") def test_branch_cuts_failing(self): # XXX: signed zero not OK with ICC on 64-bit platform for log, see # http://permalink.gmane.org/gmane.comp.python.numeric.general/25335 yield _check_branch_cut, np.log, -0.5, 1j, 1, -1, True yield _check_branch_cut, np.log2, -0.5, 1j, 1, -1, True yield _check_branch_cut, np.log10, -0.5, 1j, 1, -1, True yield _check_branch_cut, np.log1p, -1.5, 1j, 1, -1, True # XXX: signed zeros are not OK for sqrt or for the arc* functions yield _check_branch_cut, np.sqrt, -0.5, 1j, 1, -1, True yield _check_branch_cut, np.arcsin, [ -2, 2], [1j, -1j], 1, -1, True yield _check_branch_cut, np.arccos, [ -2, 2], [1j, -1j], 1, -1, True yield _check_branch_cut, np.arctan, [-2j, 2j], [1, -1 ], -1, 1, True yield _check_branch_cut, np.arcsinh, [-2j, 2j], [-1, 1], -1, 1, True yield _check_branch_cut, np.arccosh, [ -1, 0.5], [1j, 1j], 1, -1, True yield _check_branch_cut, np.arctanh, [ -2, 2], [1j, -1j], 1, -1, True def test_against_cmath(self): import cmath, sys # cmath.asinh is broken in some versions of Python, see # http://bugs.python.org/issue1381 broken_cmath_asinh = False if sys.version_info < (2,6): broken_cmath_asinh = True points = [-1-1j, -1+1j, +1-1j, +1+1j] name_map = {'arcsin': 'asin', 'arccos': 'acos', 'arctan': 'atan', 'arcsinh': 'asinh', 'arccosh': 'acosh', 'arctanh': 'atanh'} atol = 4*np.finfo(np.complex).eps for func in self.funcs: fname = func.__name__.split('.')[-1] cname = name_map.get(fname, fname) try: cfunc = getattr(cmath, cname) except AttributeError: continue for p in points: a = complex(func(np.complex_(p))) b = cfunc(p) if cname == 'asinh' and broken_cmath_asinh: continue assert_(abs(a - b) < atol, "%s %s: %s; cmath: %s"%(fname,p,a,b)) def check_loss_of_precision(self, dtype): """Check loss of precision in complex arc* functions""" # Check against known-good functions info = np.finfo(dtype) real_dtype = dtype(0.).real.dtype eps = info.eps def check(x, rtol): x = x.astype(real_dtype) z = x.astype(dtype) d = np.absolute(np.arcsinh(x)/np.arcsinh(z).real - 1) assert_(np.all(d < rtol), (np.argmax(d), x[np.argmax(d)], d.max(), 'arcsinh')) z = (1j*x).astype(dtype) d = np.absolute(np.arcsinh(x)/np.arcsin(z).imag - 1) assert_(np.all(d < rtol), (np.argmax(d), x[np.argmax(d)], d.max(), 'arcsin')) z = x.astype(dtype) d = np.absolute(np.arctanh(x)/np.arctanh(z).real - 1) assert_(np.all(d < rtol), (np.argmax(d), x[np.argmax(d)], d.max(), 'arctanh')) z = (1j*x).astype(dtype) d = np.absolute(np.arctanh(x)/np.arctan(z).imag - 1) assert_(np.all(d < rtol), (np.argmax(d), x[np.argmax(d)], d.max(), 'arctan')) # The switchover was chosen as 1e-3; hence there can be up to # ~eps/1e-3 of relative cancellation error before it x_series = np.logspace(-20, -3.001, 200) x_basic = np.logspace(-2.999, 0, 10, endpoint=False) if dtype is np.longcomplex: # It's not guaranteed that the system-provided arc functions # are accurate down to a few epsilons. (Eg. on Linux 64-bit) # So, give more leeway for long complex tests here: check(x_series, 50*eps) else: check(x_series, 2*eps) check(x_basic, 2*eps/1e-3) # Check a few points z = np.array([1e-5*(1+1j)], dtype=dtype) p = 9.999999999333333333e-6 + 1.000000000066666666e-5j d = np.absolute(1-np.arctanh(z)/p) assert_(np.all(d < 1e-15)) p = 1.0000000000333333333e-5 + 9.999999999666666667e-6j d = np.absolute(1-np.arcsinh(z)/p) assert_(np.all(d < 1e-15)) p = 9.999999999333333333e-6j + 1.000000000066666666e-5 d = np.absolute(1-np.arctan(z)/p) assert_(np.all(d < 1e-15)) p = 1.0000000000333333333e-5j + 9.999999999666666667e-6 d = np.absolute(1-np.arcsin(z)/p) assert_(np.all(d < 1e-15)) # Check continuity across switchover points def check(func, z0, d=1): z0 = np.asarray(z0, dtype=dtype) zp = z0 + abs(z0) * d * eps * 2 zm = z0 - abs(z0) * d * eps * 2 assert_(np.all(zp != zm), (zp, zm)) # NB: the cancellation error at the switchover is at least eps good = (abs(func(zp) - func(zm)) < 2*eps) assert_(np.all(good), (func, z0[~good])) for func in (np.arcsinh,np.arcsinh,np.arcsin,np.arctanh,np.arctan): pts = [rp+1j*ip for rp in (-1e-3,0,1e-3) for ip in(-1e-3,0,1e-3) if rp != 0 or ip != 0] check(func, pts, 1) check(func, pts, 1j) check(func, pts, 1+1j) def test_loss_of_precision(self): for dtype in [np.complex64, np.complex_]: yield self.check_loss_of_precision, dtype @dec.knownfailureif(is_longdouble_finfo_bogus(), "Bogus long double finfo") def test_loss_of_precision_longcomplex(self): self.check_loss_of_precision(np.longcomplex) class TestAttributes(TestCase): def test_attributes(self): add = ncu.add assert_equal(add.__name__, 'add') assert_(add.__doc__.startswith('add(x1, x2[, out])\n\n')) self.assertTrue(add.ntypes >= 18) # don't fail if types added self.assertTrue('ii->i' in add.types) assert_equal(add.nin, 2) assert_equal(add.nout, 1) assert_equal(add.identity, 0) class TestSubclass(TestCase): def test_subclass_op(self): class simple(np.ndarray): def __new__(subtype, shape): self = np.ndarray.__new__(subtype, shape, dtype=object) self.fill(0) return self a = simple((3,4)) assert_equal(a+a, a) def _check_branch_cut(f, x0, dx, re_sign=1, im_sign=-1, sig_zero_ok=False, dtype=np.complex): """ Check for a branch cut in a function. Assert that `x0` lies on a branch cut of function `f` and `f` is continuous from the direction `dx`. Parameters ---------- f : func Function to check x0 : array-like Point on branch cut dx : array-like Direction to check continuity in re_sign, im_sign : {1, -1} Change of sign of the real or imaginary part expected sig_zero_ok : bool Whether to check if the branch cut respects signed zero (if applicable) dtype : dtype Dtype to check (should be complex) """ x0 = np.atleast_1d(x0).astype(dtype) dx = np.atleast_1d(dx).astype(dtype) scale = np.finfo(dtype).eps * 1e3 atol = 1e-4 y0 = f(x0) yp = f(x0 + dx*scale*np.absolute(x0)/np.absolute(dx)) ym = f(x0 - dx*scale*np.absolute(x0)/np.absolute(dx)) assert_(np.all(np.absolute(y0.real - yp.real) < atol), (y0, yp)) assert_(np.all(np.absolute(y0.imag - yp.imag) < atol), (y0, yp)) assert_(np.all(np.absolute(y0.real - ym.real*re_sign) < atol), (y0, ym)) assert_(np.all(np.absolute(y0.imag - ym.imag*im_sign) < atol), (y0, ym)) if sig_zero_ok: # check that signed zeros also work as a displacement jr = (x0.real == 0) & (dx.real != 0) ji = (x0.imag == 0) & (dx.imag != 0) x = -x0 x.real[jr] = 0.*dx.real x.imag[ji] = 0.*dx.imag x = -x ym = f(x) ym = ym[jr | ji] y0 = y0[jr | ji] assert_(np.all(np.absolute(y0.real - ym.real*re_sign) < atol), (y0, ym)) assert_(np.all(np.absolute(y0.imag - ym.imag*im_sign) < atol), (y0, ym)) def test_copysign(): assert_(np.copysign(1, -1) == -1) old_err = np.seterr(divide="ignore") try: assert_(1 / np.copysign(0, -1) < 0) assert_(1 / np.copysign(0, 1) > 0) finally: np.seterr(**old_err) assert_(np.signbit(np.copysign(np.nan, -1))) assert_(not np.signbit(np.copysign(np.nan, 1))) def _test_nextafter(t): one = t(1) two = t(2) zero = t(0) eps = np.finfo(t).eps assert_(np.nextafter(one, two) - one == eps) assert_(np.nextafter(one, zero) - one < 0) assert_(np.isnan(np.nextafter(np.nan, one))) assert_(np.isnan(np.nextafter(one, np.nan))) assert_(np.nextafter(one, one) == one) def test_nextafter(): return _test_nextafter(np.float64) def test_nextafterf(): return _test_nextafter(np.float32) @dec.knownfailureif(sys.platform == 'win32', "Long double support buggy on win32") def test_nextafterl(): return _test_nextafter(np.longdouble) def _test_spacing(t): err = np.seterr(invalid='ignore') one = t(1) eps = np.finfo(t).eps nan = t(np.nan) inf = t(np.inf) try: assert_(np.spacing(one) == eps) assert_(np.isnan(np.spacing(nan))) assert_(np.isnan(np.spacing(inf))) assert_(np.isnan(np.spacing(-inf))) assert_(np.spacing(t(1e30)) != 0) finally: np.seterr(**err) def test_spacing(): return _test_spacing(np.float64) def test_spacingf(): return _test_spacing(np.float32) @dec.knownfailureif(sys.platform == 'win32', "Long double support buggy on win32") def test_spacingl(): return _test_spacing(np.longdouble) def test_spacing_gfortran(): # Reference from this fortran file, built with gfortran 4.3.3 on linux # 32bits: # PROGRAM test_spacing # INTEGER, PARAMETER :: SGL = SELECTED_REAL_KIND(p=6, r=37) # INTEGER, PARAMETER :: DBL = SELECTED_REAL_KIND(p=13, r=200) # # WRITE(*,*) spacing(0.00001_DBL) # WRITE(*,*) spacing(1.0_DBL) # WRITE(*,*) spacing(1000._DBL) # WRITE(*,*) spacing(10500._DBL) # # WRITE(*,*) spacing(0.00001_SGL) # WRITE(*,*) spacing(1.0_SGL) # WRITE(*,*) spacing(1000._SGL) # WRITE(*,*) spacing(10500._SGL) # END PROGRAM ref = {} ref[np.float64] = [1.69406589450860068E-021, 2.22044604925031308E-016, 1.13686837721616030E-013, 1.81898940354585648E-012] ref[np.float32] = [ 9.09494702E-13, 1.19209290E-07, 6.10351563E-05, 9.76562500E-04] for dt, dec in zip([np.float32, np.float64], (10, 20)): x = np.array([1e-5, 1, 1000, 10500], dtype=dt) assert_array_almost_equal(np.spacing(x), ref[dt], decimal=dec) def test_nextafter_vs_spacing(): # XXX: spacing does not handle long double yet for t in [np.float32, np.float64]: for _f in [1, 1e-5, 1000]: f = t(_f) f1 = t(_f + 1) assert_(np.nextafter(f, f1) - f ==
np.spacing(f)
numpy.spacing
'''Train CIFAR10 with PyTorch.''' import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import torch.backends.cudnn as cudnn import torchvision import torchvision.transforms as transforms import os import argparse import numpy as np from models import * parser = argparse.ArgumentParser(description='PyTorch CIFAR10 Training') parser.add_argument('--k', default=64, type=int, help='depth of model') parser.add_argument('--noise_rate', default=0.2, type=float, help='label noise') parser.add_argument('--asym', action='store_true') parser.add_argument('--model_path', type=str, default='./checkpoint') parser.add_argument('--mixup', action='store_true') parser.add_argument('--plot_method', default='train', type=str) # parser.add_argument('--plot_train_class', default=4, type=int) # parser.add_argument('--plot_train_imgs', action='store_true') # parser.add_argument('--plot_path', type=str, default='./imgs') # parser.add_argument('--extra_path', type=str, default=None) # parser.add_argument('--imgs', default=None, # type=lambda s: [int(item) for item in s.split(',')], help='which images ids to plot') parser.add_argument('--active_log', action='store_true') parser.add_argument('--num_samples', default=1 , type=int) parser.add_argument('--num_iters', default=10 , type=int) parser.add_argument('--delta', default=0.5, type=float, help='how far from image') parser.add_argument('--set_seed', default=1 , type=int) parser.add_argument('--set_data_seed', default=1 , type=int) # parser.add_argument('--run_name', type=str, default='temp') args = parser.parse_args() device = 'cuda' if torch.cuda.is_available() else 'cpu' print(device) args.eval = True if args.mixup: args.model_path = './checkpoint/mixup' if args.active_log: import wandb if not args.mixup: wandb.init(project="dd_quantif_margin", name = f'ddmargin_{args.plot_method}_{args.noise_rate}noise_{args.k}k') else: wandb.init(project="dd_quantif_margin", name = f'ddmargin_{args.plot_method}_{args.noise_rate}noise_{args.k}k_wmixup') wandb.config.update(args) # best_acc = 0 # best test accuracy # best_epoch = 0 # start_epoch = 0 # start from epoch 0 or last checkpoint epoch # if not os.path.isdir('./checkpoint'): # os.mkdir('./checkpoint') # Data print('==> Preparing data..') transform_train = transforms.Compose([ # transforms.RandomCrop(32, padding=4), # transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)), ]) transform_test = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)), ]) torch.manual_seed(args.set_data_seed) if args.noise_rate > 0: from data_noisy import cifar10Nosiy trainset = cifar10Nosiy(root='./data', train=True,transform=transform_train, download=True, asym=args.asym, nosiy_rate=args.noise_rate) else: trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform_train) trainloader = torch.utils.data.DataLoader( trainset, batch_size=128, shuffle=True, num_workers=2) testset = torchvision.datasets.CIFAR10( root='./data', train=False, download=True, transform=transform_test) testloader = torch.utils.data.DataLoader( testset, batch_size=100, shuffle=False, num_workers=2) classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck') print('RAN FINE TILL HERE!') if args.plot_method == 'train': if args.noise_rate > 0: l_mis = np.where(np.array(trainset.targets) != np.array(trainset.true_targets))[0] #mislabeled images l_corr = np.where(np.array(trainset.targets) == np.array(trainset.true_targets))[0] #correctly labeled images l_all = np.arange(len(trainset.targets)) else: l_all = np.arange(len(testset.targets)) def image_atdelta(img1,img2,delta): a = img2 - img1 a_norm = torch.dot(a.flatten(), a.flatten()).sqrt() a = a / a_norm b = img1 + delta*a return b def old_avg_margin(dlist1,dlist2,loader,num_iters, num_samples,net,device): print(f'In the case of list lengths: {len(dlist1)},{len(dlist2)}') baselist = np.random.choice(dlist1, num_samples) mean_margins = [] for i in baselist: # print(f'The image: {i}') dirlist = np.random.choice(dlist2, num_iters+10) margins = [] img = loader.dataset[i][0].unsqueeze(0) img = img.to(device) img_op = torch.argmax(net(img)).item() iter_count = 0 counts = [] while len(margins) < num_iters and iter_count < num_iters+10: j = dirlist[iter_count] iter_count+=1 img1 = loader.dataset[i][0].unsqueeze(0) img2 = loader.dataset[j][0].unsqueeze(0) delta = 0.01 imdelta = image_atdelta(img1,img2,delta) imdelta = imdelta.to(device) output = torch.argmax(net(imdelta)).item() count = 0 step = 0.01 while (img_op ==output) and count <=100: delta+= step imdelta = image_atdelta(img1,img2,delta) imdelta = imdelta.to(device) output = torch.argmax(net(imdelta)).item() if 10 < count < 20: step = 0.1 elif 20 <= count or count <= 30: step = 0.5 elif 30 < count or count <= 50: step = 1 elif 50 < count or count <= 75: step = 10 elif 75 < count or count <= 100: step = 100 count+=1 # import ipdb; ipdb.set_trace() counts.append(count) if count <= 100: margins.append(delta) # import ipdb; ipdb.set_trace() # print(counts) if len(margins) >= num_iters//3: mean_margins.append(np.mean(margins)) pdone = len(mean_margins) if pdone%1000 ==0: print(f'At {pdone}th point') return mean_margins def delta_counter(max_steps): delta_list = [0] delta = 0 step = 0.01 for count in range(max_steps-1): # print(count,step) if count > 10 and count < 20: step = 0.1 elif count >= 20 and count <= 50: step = 0.5 elif count > 50 and count <= 75: step = 1 elif count > 75 and count <= 100: step = 10 elif count > 100: step = 20 delta+=step delta_list.append(delta) # print(delta_list) return np.array(delta_list) def avg_margin(dlist1,dlist2,loader,num_iters, num_samples,net,device,max_steps=200): print(f'In the case of list lengths: {len(dlist1)},{len(dlist2)}') baselist = np.random.choice(dlist1, num_samples) deltas = torch.from_numpy(delta_counter(max_steps).reshape(max_steps,1,1,1)) deltas = deltas.to(device) deltas_temp = torch.squeeze(deltas) mean_margins = [] for i in baselist: # print(f'The image: {i}') dirlist = np.random.choice(dlist2, num_iters+10) margins = [] iter_count = 0 while len(margins) < num_iters and iter_count < num_iters+10: j = dirlist[iter_count] iter_count+=1 img1 = loader.dataset[i][0].unsqueeze(0) img2 = loader.dataset[j][0].unsqueeze(0) a = img2 - img1 a_norm = torch.dot(a.flatten(), a.flatten()).sqrt() a = a / a_norm img1 = loader.dataset[i][0].unsqueeze(0).expand(max_steps,-1,-1,-1) a = a.expand(max_steps,-1,-1,-1) img1 = img1.to(device) a = a.to(device) # import ipdb; ipdb.set_trace() img_batch = img1 + deltas*a img_batch = img_batch.to(device=device, dtype=torch.float) preds = torch.argmax(net(img_batch),dim=1).cpu().numpy() where_db = np.where(np.diff(preds) != 0)[0] if where_db.size !=0: delta = deltas_temp[where_db[0]].item() margins.append(delta) if len(margins) >= num_iters//2: mean_margins.append(np.mean(margins)) pdone = len(mean_margins) if pdone%1000 ==0: print(f'At {pdone}th point') return mean_margins mp = args.model_path modelpath = f'{mp}/dd_Adam_{args.noise_rate}noise_{args.k}k/ckpt.pth' net = make_resnet18k(args.k) net = net.to(device) if device == 'cuda': net = torch.nn.DataParallel(net) cudnn.benchmark = True print(modelpath) checkpoint = torch.load(modelpath) net.load_state_dict(checkpoint['net']) net.eval() # import time # start = time.time() # cc = avg_margin(l_corr,l_all,trainloader,args.num_iters, args.num_samples,net,device) # print(cc) # end = time.time() # print(f'Time taken: {end-start}') if args.noise_rate > 0 and args.plot_method == 'train': unique_classes = { # 'cc' : avg_margin(l_corr,l_corr,trainloader,args.num_iters, args.num_samples,net,device), # 'mm' : avg_margin(l_mis,l_mis,trainloader,args.num_iters, args.num_samples,net,device), # 'mc' : avg_margin(l_mis,l_corr,trainloader,args.num_iters, args.num_samples,net,device), 'ca' : avg_margin(l_corr,l_all,trainloader,args.num_iters, args.num_samples,net,device), 'ma' : avg_margin(l_mis,l_all,trainloader,args.num_iters, args.num_samples,net,device), 'aa' : avg_margin(l_all,l_all,trainloader,args.num_iters, args.num_samples,net,device) } if args.active_log: wandb.log({ 'aa': np.mean(unique_classes['aa']), 'ca' : np.mean(unique_classes['ca']), 'ma' : np.mean(unique_classes['ma']), 'aa_median': np.median(unique_classes['aa']), 'ca_median' : np.median(unique_classes['ca']), 'ma_median' : np.median(unique_classes['ma']), 'len_aa' : len(unique_classes['aa']), 'len_ca' : len(unique_classes['ca']), 'len_ma' : len(unique_classes['ma'] )}) else: print({ 'aa': np.mean(unique_classes['aa']), 'ca' : np.mean(unique_classes['ca']), 'ma' : np.mean(unique_classes['ma']), 'aa_median': np.median(unique_classes['aa']), 'ca_median' : np.median(unique_classes['ca']), 'ma_median' : np.median(unique_classes['ma']), 'len_aa' : len(unique_classes['aa']), 'len_ca' : len(unique_classes['ca']), 'len_ma' : len(unique_classes['ma'] )}) else: if args.plot_method == 'train': unique_classes = { 'aa' : avg_margin(l_all,l_all,trainloader,args.num_iters, args.num_samples,net,device) } if args.active_log: wandb.log({ 'aa':
np.mean(unique_classes['aa'])
numpy.mean
import matplotlib matplotlib.use('Agg') import numpy as np # import os import matplotlib.pyplot as plt from pylab import rcParams axis_font = {'fontname': 'Arial', 'size': '8', 'family': 'serif'} fs = 8 ms = 8 lw = 2 def create_plots(cwd=''): """ Function to plot the results of the fault-tolerant Boussinesq system Args: cwd: current workign directory """ ref = 'PFASST_BOUSSINESQ_stats_hf_NOFAULT_P16.npz' # noinspection PyShadowingBuiltins list = [('PFASST_BOUSSINESQ_stats_hf_SPREAD_P16.npz', 'SPREAD', '1-sided', 'red', 's'), ('PFASST_BOUSSINESQ_stats_hf_INTERP_P16.npz', 'INTERP', '2-sided', 'orange', 'o'), ('PFASST_BOUSSINESQ_stats_hf_SPREAD_PREDICT_P16.npz', 'SPREAD_PREDICT', '1-sided+corr', 'blue', '^'), ('PFASST_BOUSSINESQ_stats_hf_INTERP_PREDICT_P16.npz', 'INTERP_PREDICT', '2-sided+corr', 'green', 'd'), ('PFASST_BOUSSINESQ_stats_hf_NOFAULT_P16.npz', 'NOFAULT', 'no fault', 'black', 'v')] nprocs = 16 xtick_dist = 8 minstep = 128 maxstep = 176 # minstep = 0 # maxstep = 320 nblocks = int(320 / nprocs) # maxiter = 14 nsteps = 0 maxiter = 0 vmax = -99 vmin = -8 for file, strategy, label, color, marker in list: data = np.load(cwd + 'data/' + file) iter_count = data['iter_count'][minstep:maxstep] residual = data['residual'][:, minstep:maxstep] residual[residual <= 0] = 1E-99 residual = np.log10(residual) vmax = max(vmax, int(np.amax(residual))) maxiter = max(maxiter, int(max(iter_count))) nsteps = max(nsteps, len(iter_count)) print(vmin, vmax) data = np.load(cwd + 'data/' + ref) ref_iter_count = data['iter_count'][nprocs - 1::nprocs] rcParams['figure.figsize'] = 6.0, 2.5 fig, ax = plt.subplots() plt.plot(range(nblocks), [0] * nblocks, 'k-', linewidth=2) ymin = 99 ymax = 0 for file, strategy, label, color, marker in list: if file is not ref: data = np.load(cwd + 'data/' + file) iter_count = data['iter_count'][nprocs - 1::nprocs] ymin = min(ymin, min(iter_count - ref_iter_count)) ymax = max(ymax, max(iter_count - ref_iter_count)) plt.plot(range(nblocks), iter_count - ref_iter_count, color=color, label=label, marker=marker, linestyle='', linewidth=lw, markersize=ms) plt.xlabel('block', **axis_font) plt.ylabel('$K_\\mathrm{add}$', **axis_font) plt.title('ALL', **axis_font) plt.xlim(-1, nblocks) plt.ylim(-1 + ymin, ymax + 1) plt.legend(loc=2, numpoints=1, fontsize=fs) plt.tick_params(axis='both', which='major', labelsize=fs) ax.xaxis.labelpad = -0.5 ax.yaxis.labelpad = -1 # plt.tight_layout() fname = 'data/BOUSSINESQ_Kadd_vs_NOFAULT_hf.png' plt.savefig(fname, rasterized=True, bbox_inches='tight') # os.system('pdfcrop ' + fname + ' ' + fname) for file, strategy, label, color, marker in list: data = np.load(cwd + 'data/' + file) residual = data['residual'][:, minstep:maxstep] stats = data['hard_stats'] residual[residual <= 0] = 1E-99 residual = np.log10(residual) rcParams['figure.figsize'] = 6.0, 2.5 fig, ax = plt.subplots() cmap = plt.get_cmap('Reds', vmax - vmin + 1) pcol = plt.pcolor(residual, cmap=cmap, vmin=vmin, vmax=vmax) pcol.set_edgecolor('face') if file is not ref: for item in stats: if item[0] in range(minstep, maxstep): plt.text(item[0] + 0.5 - (maxstep - nsteps), item[1] - 1 + 0.5, 'x', horizontalalignment='center', verticalalignment='center') plt.axis([0, nsteps, 0, maxiter]) ticks = np.arange(vmin, vmax + 1) tickpos = np.linspace(ticks[0] + 0.5, ticks[-1] - 0.5, len(ticks)) cax = plt.colorbar(pcol, ticks=tickpos, pad=0.02) cax.set_ticklabels(ticks) cax.ax.tick_params(labelsize=fs) cax.set_label('log10(residual)', **axis_font) plt.tick_params(axis='both', which='major', labelsize=fs) ax.xaxis.labelpad = -0.5 ax.yaxis.labelpad = -0.5 ax.set_xlabel('step', **axis_font) ax.set_ylabel('iteration', **axis_font) ax.set_yticks(np.arange(1, maxiter, 2) + 0.5, minor=False) ax.set_xticks(
np.arange(0, nsteps, xtick_dist)
numpy.arange
import itertools import numpy as np import pandas as pd import nltk nltk.download('stopwords') from collections import Counter from bs4 import BeautifulSoup from nltk.stem import WordNetLemmatizer from nltk.stem.snowball import SnowballStemmer from nltk.corpus import stopwords import string import re from functools import partial """ Class BasicPreprocessText Basic preprocessing tool for text data: 1. Remove punctuation 2. Remove noisy symbols """ class BasicPreprocessText: def __init__(self, lang='english'): self.LANG = lang self.stemmer = SnowballStemmer(self.LANG) self.stopWords = set(stopwords.words(self.LANG)) def parse_words(self, column_data): str_data = column_data.astype('str') str_data = str_data[str_data != 'nan'] split_words = str_data.apply(lambda word: word.split(' ')) strings_data = list(itertools.chain.from_iterable(split_words)) return strings_data def vectorize_process_text(self, text_arr, leave_stop_words=None): if leave_stop_words is None: leave_stop_words = [] assert isinstance(leave_stop_words, list) modified_process_text = partial(self.process_text, leave_stop_words=leave_stop_words) vectorize_process_text =
np.vectorize(modified_process_text)
numpy.vectorize
#!/usr/bin/env python2.7 ''' CONFIDENTIAL Copyright (c) 2021 <NAME>, Department of Remote Sensing and Photogrammetry, Finnish Geospatial Research Institute (FGI), National Land Survey of Finland (NLS) PERMISSION IS HEREBY LIMITED TO FGI'S INTERNAL USE ONLY. THE CODE MAY BE RE-LICENSED, SHARED, OR TAKEN INTO OTHER USE ONLY WITH A WRITTEN CONSENT FROM THE HEAD OF THE DEPARTMENT. The software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the software or the use or other dealings in the software. ''' try: import rospy from sensor_msgs.msg import Image, CameraInfo, PointCloud2, PointField from cv_bridge import CvBridge, CvBridgeError import message_filters import cv2 import numpy as np import ros_numpy import cv2.aruco as aruco import math import pickle import open3d import std_msgs.msg import sensor_msgs.point_cloud2 as pcl2 import pcl import matplotlib.pyplot as plt from collections import deque from sensor_msgs import point_cloud2 from sklearn import preprocessing from scipy.spatial.distance import euclidean from fastdtw import fastdtw from testNode.msg import extras from pyquaternion import Quaternion import matplotlib import pandas as pd except: print('Change python version') from termcolor import colored from scipy.spatial import distance_matrix import struct import rosbag def getRGBfromI(RGBint): blue = RGBint & 255 green = (RGBint >> 8) & 255 red = (RGBint >> 16) & 255 #return red, green, blue return blue, green, red #return BGR def getIfromRGB(rgb): red = rgb[0] green = rgb[1] blue = rgb[2] #print red, green, blue RGBint = (red<<16) + (green<<8) + blue return RGBint def load_obj(name): with open('/home/eugeniu/Desktop/my_data/CameraCalibration/data/saved_files/' + name + '.pkl', 'rb') as f: return pickle.load(f) def get_z(T_cam_world, T_world_pc, K): R = T_cam_world[:3, :3] t = T_cam_world[:3, 3] proj_mat = np.dot(K, np.hstack((R, t[:, np.newaxis]))) xyz_hom = np.hstack((T_world_pc, np.ones((T_world_pc.shape[0], 1)))) xy_hom = np.dot(proj_mat, xyz_hom.T).T z = xy_hom[:, -1] z = np.asarray(z).squeeze() return z def readCalibration(): name = 'inside' # name = 'outside' camera_model = load_obj('{}_combined_camera_model'.format(name)) camera_model_rectify = load_obj('{}_combined_camera_model_rectify'.format(name)) K_left = camera_model['K_left'] K_right = camera_model['K_right'] D_left = camera_model['D_left'] D_right = camera_model['D_right'] K = K_right D = D_right calib_file = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/combined_extrinsics{}.npz' calib_file = '/home/eugeniu/catkin_ws/src/testNode/CAMERA_CALIBRATION/solvePnP_extrinsicscharuco.npz' with open(calib_file, 'r') as f: data = f.read().split() # print('data:{}'.format(data)) qx = float(data[0]) qy = float(data[1]) qz = float(data[2]) qw = float(data[3]) tx = float(data[4]) ty = float(data[5]) tz = float(data[6]) q = Quaternion(qw, qx, qy, qz).transformation_matrix q[0, 3], q[1, 3], q[2, 3] = tx, ty, tz tvec = q[:3, 3] rot_mat = q[:3, :3] rvec, _ = cv2.Rodrigues(rot_mat) return rvec, tvec,q, K,D rvec, tvec,q, K, D = readCalibration() rospy.init_node('testNode', anonymous=True) global myI myI = 10 bridge = CvBridge() display = True display = False plotTimeLine = False useColor = True #useColor = False useMeanTime = True #used the mean time for each laser scan #useMeanTime = False velodyne_points = '/lidar_VLS128_Center_13202202695611/velodyne_points' left_cam = '/camera_IDS_Left_4103423533/image_raw' left_cam_topic_extras = '/camera_IDS_Left_4103423533/extras' left_cam = '/camera_IDS_Right_4103423537/image_raw' left_cam_topic_extras = '/camera_IDS_Right_4103423537/extras' right_cam = '/camera_IDS_Left_4103423533/image_raw' Syncronized_Lidar_pub = rospy.Publisher(velodyne_points, PointCloud2, queue_size=200) Syncronized_Cam_pub = rospy.Publisher(left_cam, Image, queue_size=200) r,g,b, a = int(0 * 255.0),int(1 * 255.0),int(0 * 255.0), 255 rgb = struct.unpack('I', struct.pack('BBBB', b, g, r, a))[0] r,g,b, a = int(1 * 255.0),int(0 * 255.0),int(0 * 255.0), 255 rgb_red = struct.unpack('I', struct.pack('BBBB', b, g, r, a))[0] cmap = matplotlib.cm.get_cmap('hsv') def hsv_to_rgb(h, s, v): if s == 0.0: return v, v, v i = int(h * 6.0) f = (h * 6.0) - i p = v * (1.0 - s) q = v * (1.0 - s * f) t = v * (1.0 - s * (1.0 - f)) i = i % 6 if i == 0: return v, t, p if i == 1: return q, v, p if i == 2: return p, v, t if i == 3: return p, q, v if i == 4: return t, p, v if i == 5: return v, p, q removeShadow = True #removeShadow = False global STOP, cloud_points_save, left_image_Save, right_image_Save def publishSyncronized_msg(cloud_synchronized,image_synchronized, image_synchronized2=None, pixel_opacity = 1): try: # publish lidar header = std_msgs.msg.Header() header.stamp = rospy.Time.now() header.frame_id = 'VLS128_Center' # columns=["X", "Y", "Z",'rgb',"intens","ring","time"] if useColor: objPoints_left = cloud_synchronized[:,:3] Z = get_z(q, objPoints_left, K) cloud_synchronized = cloud_synchronized[Z > 0] objPoints_left = objPoints_left[Z > 0] points2D, _ = cv2.projectPoints(objPoints_left, rvec, tvec, K, D) points2D = np.squeeze(points2D) image = bridge.imgmsg_to_cv2(image_synchronized, "bgr8") inrange = np.where( (points2D[:, 0] >= 0) & (points2D[:, 1] >= 0) & (points2D[:, 0] < image.shape[1] - 1) & (points2D[:, 1] < image.shape[0] - 1) ) points2D = points2D[inrange[0]].round().astype('int') cloud_synchronized = cloud_synchronized[inrange[0]] #filter again here -> save the closest to the camera distance = np.linalg.norm(cloud_synchronized[:, :3], axis=1) if removeShadow: '''sort points by distance''' idx_sorted = np.argsort(distance) #ascending idx_sorted = idx_sorted[::-1] #descending cloud_synchronized = cloud_synchronized[idx_sorted] points2D = points2D[idx_sorted] distance = distance[idx_sorted] #cv2.imshow('image ',image) #cv2.waitKey(1) MIN_DISTANCE, MAX_DISTANCE = np.min(distance), np.max(distance) colours = (distance - MIN_DISTANCE) / (MAX_DISTANCE - MIN_DISTANCE) colours = np.asarray([np.asarray(hsv_to_rgb(0.75 * c, np.sqrt(pixel_opacity), 1.0)) for c in colours]) cols = pixel_opacity * 255 * colours # print('colours:{}, cols:{}'.format(np.shape(colours), np.shape(cols))) colors_left = image[points2D[:, 1], points2D[:, 0], :] colors_left = np.array([getIfromRGB(col) for col in colors_left]).squeeze() #greenColors = np.ones(len(cloud_synchronized))*rgb cloud_synchronized[:, 3]=colors_left image = cv2.Canny(image, 100, 200) #for i in range(len(points2D)): #cv2.circle(image, tuple(points2D[i]), 2, (0, 255, 0), 1) #cv2.circle(image, tuple(points2D[i]), 2, cols[i], -1) _pcl = pcl2.create_cloud(header=header, fields=fields, points=cloud_synchronized) Syncronized_Lidar_pub.publish(_pcl) # publish camera Syncronized_Cam_pub.publish(bridge.cv2_to_imgmsg(image)) else: _pcl = pcl2.create_cloud(header=header, fields=fields, points=cloud_synchronized) Syncronized_Lidar_pub.publish(_pcl) #publish camera Syncronized_Cam_pub.publish(image_synchronized) cloud_points_save = cloud_synchronized left_image_Save = image_synchronized right_image_Save = image_synchronized2 except Exception as e: rospy.logerr(e) def do_job(path, lidar_msgs, cam, cam_right): global myI print('cam_right -> {}'.format(np.shape(cam_right))) print('got path:{}, lidar_msgs:{}, cam:{}'.format(np.shape(path), np.shape(lidar_msgs), np.shape(cam))) if useMeanTime: for (x1, x2) in path: cloud_synchronized = lidar_msgs[x1] image_synchronized = cam[x2] try: image_synchronized2 = cam_right[x2] except: image_synchronized2 = cam_right[x2-1] # print('cloud_synchronized:{}, image_synchronized:{}'.format(np.shape(cloud_synchronized), np.shape(image_synchronized))) publishSyncronized_msg(cloud_synchronized,image_synchronized, image_synchronized2) l=bridge.imgmsg_to_cv2(image_synchronized, "bgr8") r=bridge.imgmsg_to_cv2(image_synchronized2, "bgr8") cv2.imshow('left', cv2.resize(l,None,fx=.4,fy=.4)) cv2.imshow('right', cv2.resize(r,None,fx=.4,fy=.4)) k = cv2.waitKey(1) if k==ord('s'): print('Sve cv2') print('Saved {}, {}'.format(np.shape(l), np.shape(r))) cv2.imwrite('/home/eugeniu/left_{}.png'.format(myI), l) cv2.imwrite('/home/eugeniu/right_{}.png'.format(myI), r) with open('/home/eugeniu/cloud_{}.npy'.format(myI), 'wb') as f: np.save(f, cloud_synchronized) myI+=1 else: _lidar_synchro = [] lidar_msgs = np.vstack(lidar_msgs) print('lidar_msgs -> {}'.format(np.shape(lidar_msgs))) ''' vstack the lidar msg list for all unique idx in camera in path -take all lidar points that belongs to it -publish them toghether ''' unique_cam, indices = np.unique(path[:,1], return_index=True) for i,u in enumerate(unique_cam): inrange = np.where(path[:,1]==u) #take all lidar points that belongs to this cam msg cloud_synchronized = lidar_msgs[inrange[0]] image_synchronized = cam[i] #print('cloud_synchronized:{}, image_synchronized:{}'.format(np.shape(cloud_synchronized), np.shape(image_synchronized))) publishSyncronized_msg(cloud_synchronized,image_synchronized) print(colored('Data published','green')) cv2.destroyAllWindows() k = 0 plot_data_left = deque(maxlen=200) LiDAR_msg, LeftCam_msg, LeftCam_TimeSeries = [],[],[] RightCam_msg = [] chessBag = '/home/eugeniu/chessboard_Lidar_Camera.bag' charucoBag = '/home/eugeniu/charuco_LiDAR_Camera.bag' bag = rosbag.Bag(charucoBag) if display: if plotTimeLine: fig, (ax, ax2, ax3) = plt.subplots(3, 1) else: fig, (ax,ax2) = plt.subplots(2, 1) ax.grid() ax2.grid() ax3.grid() ppsLine, = ax.plot([0], 'b', label='PPS pulse') ax.legend() import time import threading skip = 1 history = [] from pynput.keyboard import Key, Listener global STOP, cloud_points_save, left_image_Save, right_image_Save STOP = False def on_press(key): try: print('alphanumeric key {0} pressed'.format(key.char)) if key.char == 's': print('Save data----------------------------------------') else: global STOP STOP = True except AttributeError: print('special key {0} pressed'.format(key)) listener = Listener(on_press=on_press) listener.start() for topic, msg, t in bag.read_messages(topics=[left_cam, left_cam_topic_extras, velodyne_points, right_cam]): #print('topic -> {}, msg->{} t->{}'.format(topic, np.shape(msg),t)) if topic == left_cam_topic_extras:# check pps and apply synchronization pps = int(msg.pps) m = 'pps->{}, LiDAR->{}, Cam->{}'.format(pps, np.shape(LiDAR_msg), np.shape(LeftCam_msg)) if pps == 1: print(colored(m, 'red')) lidar,cam =
np.copy(LiDAR_msg)
numpy.copy
import sys import os import numpy as np import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as plt from argparse import ArgumentParser from clair.utils import setup_environment def plot_tensor(ofn, XArray): plot = plt.figure(figsize=(15, 8)) plot_min = -30 plot_max = 30 plot_arr = ["A+", "C+", "G+", "T+", "A-", "C-", "G-", "T-"] plt.subplot(4, 1, 1) plt.xticks(np.arange(0, 33, 1)) plt.yticks(np.arange(0, 8, 1), plot_arr) plt.imshow(XArray[0, :, :, 0].transpose(), vmin=0, vmax=plot_max, interpolation="nearest", cmap=plt.cm.hot) plt.colorbar() plt.subplot(4, 1, 2) plt.xticks(
np.arange(0, 33, 1)
numpy.arange
import numpy as np import tensorflow as tf import gym import os import sys import time from spinup.utils.logx import EpochLogger from spinup.utils.mpi_tf import MpiAdamOptimizer, sync_all_params from spinup.utils.mpi_tools import mpi_fork, mpi_avg, proc_id, mpi_statistics_scalar, num_procs from spinup.utils.logx import restore_tf_graph import os.path as osp from HPCSimSkip_wait_backfil import * def load_policy(model_path, itr='last'): # handle which epoch to load from if itr == 'last': saves = [int(x[11:]) for x in os.listdir(model_path) if 'simple_save' in x and len(x) > 11] itr = '%d' % max(saves) if len(saves) > 0 else '' else: itr = '%d' % itr # load the things! sess = tf.Session() model = restore_tf_graph(sess, osp.join(model_path, 'simple_save' + itr)) # get the correct op for executing actions pi = model['pi'] v = model['v'] # make function for producing an action given a single state get_probs = lambda x, y: sess.run(pi, feed_dict={model['x']: x.reshape(-1, MAX_QUEUE_SIZE * JOB_FEATURES), model['mask']: y.reshape(-1, MAX_QUEUE_SIZE)}) get_v = lambda x: sess.run(v, feed_dict={model['x']: x.reshape(-1, MAX_QUEUE_SIZE * JOB_FEATURES)}) return get_probs, get_v def mlp_v1(x, act_dim): x = tf.reshape(x, shape=[-1, JOB_SEQUENCE_SIZE * JOB_FEATURES]) x = tf.layers.dense(x, units=128, activation=tf.nn.relu) x = tf.layers.dense(x, units=128, activation=tf.nn.relu) x = tf.layers.dense(x, units=128, activation=tf.nn.relu) return tf.layers.dense(x, units=act_dim) def mlp_v2(x, act_dim): x = tf.reshape(x, shape=[-1, JOB_SEQUENCE_SIZE * JOB_FEATURES]) x = tf.layers.dense(x, units=32, activation=tf.nn.relu) x = tf.layers.dense(x, units=16, activation=tf.nn.relu) x = tf.layers.dense(x, units=8, activation=tf.nn.relu) return tf.layers.dense(x, units=act_dim) def mlp_v3(x, act_dim): x = tf.reshape(x, shape=[-1, JOB_SEQUENCE_SIZE * JOB_FEATURES]) x = tf.layers.dense(x, units=32, activation=tf.nn.relu) x = tf.layers.dense(x, units=32, activation=tf.nn.relu) x = tf.layers.dense(x, units=32, activation=tf.nn.relu) x = tf.layers.dense(x, units=32, activation=tf.nn.relu) x = tf.layers.dense(x, units=32, activation=tf.nn.relu) return tf.layers.dense(x, units=act_dim) def rl_kernel(x, act_dim): x = tf.reshape(x, shape=[-1, MAX_QUEUE_SIZE, JOB_FEATURES]) x = tf.layers.dense(x, units=32, activation=tf.nn.relu) x = tf.layers.dense(x, units=16, activation=tf.nn.relu) x = tf.layers.dense(x, units=8, activation=tf.nn.relu) x = tf.squeeze(tf.layers.dense(x, units=1), axis=-1) return x def attention(x, act_dim): x = tf.reshape(x, shape=[-1, MAX_QUEUE_SIZE, JOB_FEATURES]) # x = tf.layers.dense(x, units=32, activation=tf.nn.relu) q = tf.layers.dense(x, units=32, activation=tf.nn.relu) k = tf.layers.dense(x, units=32, activation=tf.nn.relu) v = tf.layers.dense(x, units=32, activation=tf.nn.relu) score = tf.matmul(q, tf.transpose(k, [0, 2, 1])) score = tf.nn.softmax(score, -1) attn = tf.reshape(score, (-1, MAX_QUEUE_SIZE, MAX_QUEUE_SIZE)) x = tf.matmul(attn, v) x = tf.layers.dense(x, units=16, activation=tf.nn.relu) x = tf.layers.dense(x, units=8, activation=tf.nn.relu) x = tf.squeeze(tf.layers.dense(x, units=1), axis=-1) # x = tf.layers.dense(x, units=128, activation=tf.nn.relu) # x = tf.layers.dense(x, units=64, activation=tf.nn.relu) # x = tf.layers.dense(x, units=64, activation=tf.nn.relu) return x def lenet(x_ph, act_dim): m = int(np.sqrt(MAX_QUEUE_SIZE)) x = tf.reshape(x_ph, shape=[-1, m, m, JOB_FEATURES]) x = tf.layers.conv2d(inputs=x, filters=32, kernel_size=[1, 1], strides=1) x = tf.layers.max_pooling2d(x, [2, 2], 2) x = tf.layers.conv2d(inputs=x, filters=64, kernel_size=[1, 1], strides=1) x = tf.layers.max_pooling2d(x, [2, 2], 2) x = tf.layers.flatten(x) x = tf.layers.dense(x, units=64) return tf.layers.dense( inputs=x, units=act_dim, activation=None ) # Actor def mlp_skip(x, act_dim): x = tf.reshape(x, shape=[-1, JOB_SEQUENCE_SIZE * JOB_FEATURES]) x = tf.layers.dense(x, units=32, activation=tf.nn.relu) x = tf.layers.dense(x, units=16, activation=tf.nn.relu) x = tf.layers.dense(x, units=8, activation=tf.nn.relu) return tf.layers.dense(x, units=1) def kernel_skip(x, act_dim): x = tf.reshape(x, shape=[-1, MAX_QUEUE_SIZE*JOB_FEATURES]) x = tf.layers.dense(x, units=32, activation=tf.nn.relu) x = tf.layers.dense(x, units=16, activation=tf.nn.relu) x = tf.layers.dense(x, units=8, activation=tf.nn.relu) return tf.layers.dense(x, units=2) # Critic def critic_mlp(x, act_dim): x = tf.reshape(x, shape=[-1, JOB_SEQUENCE_SIZE*JOB_FEATURES]) x = tf.layers.dense(x, units=32, activation=tf.nn.relu) x = tf.layers.dense(x, units=16, activation=tf.nn.relu) x = tf.layers.dense(x, units=8, activation=tf.nn.relu) return tf.layers.dense(x, units=act_dim) def critic_kernel(x, act_dim): x = tf.reshape(x, shape=[-1, MAX_QUEUE_SIZE*JOB_FEATURES]) x = tf.layers.dense(x, units=32, activation=tf.nn.relu) x = tf.layers.dense(x, units=16, activation=tf.nn.relu) x = tf.layers.dense(x, units=8, activation=tf.nn.relu) return tf.layers.dense(x, units=act_dim) """ Policies """ def categorical_policy(x, a, mask, action_space, attn): act_dim = action_space.n if attn: output_layer = attention(x, act_dim) else: output_layer = kernel_skip(x, act_dim) # output_layer_sigmoid = tf.nn.sigmoid(output_layer) # output_layer_sigmoid_concat = tf.concat([output_layer_sigmoid, 1-output_layer_sigmoid], 1) # logp_all = tf.log(tf.clip_by_value(output_layer_sigmoid_concat, 1e-15, 1.0)) # pi = tf.squeeze(tf.multinomial(output_layer_sigmoid_concat, 1), axis=1) output_layer = output_layer + (mask - 1) * 1000000 logp_all = tf.nn.log_softmax(output_layer) pi = tf.squeeze(tf.multinomial(output_layer, 1), axis=1) logp = tf.reduce_sum(tf.one_hot(a, depth=act_dim) * logp_all, axis=1) logp_pi = tf.reduce_sum(tf.one_hot(pi, depth=act_dim) * logp_all, axis=1) return pi, logp, logp_pi, output_layer """ Actor-Critics """ def actor_critic(x, a, mask, action_space=None, attn=False): with tf.variable_scope('pi'): pi, logp, logp_pi, out = categorical_policy(x, a, mask, action_space, attn) with tf.variable_scope('v'): v = tf.squeeze(critic_kernel(x, 1), axis=1) return pi, logp, logp_pi, v, out class PPOBuffer: """ A buffer for storing trajectories experienced by a PPO agent interacting with the environment, and using Generalized Advantage Estimation (GAE-Lambda) for calculating the advantages of state-action pairs. """ def __init__(self, obs_dim, act_dim, size, gamma=0.99, lam=0.95): size = size * 100 # assume the traj can be really long self.obs_buf = np.zeros(combined_shape(size, obs_dim), dtype=np.float32) # self.cobs_buf = np.zeros(combined_shape(size, JOB_SEQUENCE_SIZE*3), dtype=np.float32) self.cobs_buf = None self.act_buf = np.zeros(combined_shape(size, act_dim), dtype=np.float32) self.mask_buf = np.zeros(combined_shape(size, 2), dtype=np.float32) self.adv_buf =
np.zeros(size, dtype=np.float32)
numpy.zeros
import logging import numpy as np import scipy as sp import collections import torch import functools from numpy.lib.stride_tricks import as_strided from sklearn.utils.extmath import randomized_svd from sklearn.utils import check_random_state logging.basicConfig() def form_lag_matrix(X, T, stride=1, stride_tricks=True, rng=None, writeable=False): """Form the data matrix with `T` lags. Parameters ---------- X : ndarray (n_time, N) Timeseries with no lags. T : int Number of lags. stride : int or float If stride is an `int`, it defines the stride between lagged samples used to estimate the cross covariance matrix. Setting stride > 1 can speed up the calculation, but may lead to a loss in accuracy. Setting stride to a `float` greater than 0 and less than 1 will random subselect samples. rng : NumPy random state Only used if `stride` is a float. stride_tricks : bool Whether to use numpy stride tricks to form the lagged matrix or create a new array. Using numpy stride tricks can can lower memory usage, especially for large `T`. If `False`, a new array is created. writeable : bool For testing. You should not need to set this to True. This function uses stride tricks to form the lag matrix which means writing to the array will have confusing behavior. If `stride_tricks` is `False`, this flag does nothing. Returns ------- X_with_lags : ndarray (n_lagged_time, N * T) Timeseries with lags. """ if not isinstance(stride, int) or stride < 1: if not isinstance(stride, float) or stride <= 0. or stride >= 1.: raise ValueError('stride should be an int and greater than or equal to 1 or a float ' + 'between 0 and 1.') N = X.shape[1] frac = None if isinstance(stride, float): frac = stride stride = 1 n_lagged_samples = (len(X) - T) // stride + 1 if n_lagged_samples < 1: raise ValueError('T is too long for a timeseries of length {}.'.format(len(X))) if stride_tricks: X = np.asarray(X, dtype=float, order='C') shape = (n_lagged_samples, N * T) strides = (X.strides[0] * stride,) + (X.strides[-1],) X_with_lags = as_strided(X, shape=shape, strides=strides, writeable=writeable) else: X_with_lags = np.zeros((n_lagged_samples, T * N)) for i in range(n_lagged_samples): X_with_lags[i, :] = X[i * stride:i * stride + T, :].flatten() if frac is not None: rng = check_random_state(rng) idxs = np.sort(rng.choice(n_lagged_samples, size=int(np.ceil(n_lagged_samples * frac)), replace=False)) X_with_lags = X_with_lags[idxs] return X_with_lags def rectify_spectrum(cov, epsilon=1e-6, logger=None): """Rectify the spectrum of a covariance matrix. Parameters ---------- cov : ndarray Covariance matrix epsilon : float Minimum eigenvalue for the rectified spectrum. verbose : bool Whethere to print when the spectrum needs to be rectified. """ eigvals = sp.linalg.eigvalsh(cov) n_neg = np.sum(eigvals <= 0.) if n_neg > 0: cov += (-np.min(eigvals) + epsilon) * np.eye(cov.shape[0]) if logger is not None: string = 'Non-PSD matrix, {} of {} eigenvalues were not positive.' logger.info(string.format(n_neg, eigvals.size)) def toeplitzify(cov, T, N, symmetrize=True): """Make a matrix block-Toeplitz by averaging along the block diagonal. Parameters ---------- cov : ndarray (T*N, T*N) Covariance matrix to make block toeplitz. T : int Number of blocks. N : int Number of features per block. symmetrize : bool Whether to ensure that the whole matrix is symmetric. Optional (default=True). Returns ------- cov_toep : ndarray (T*N, T*N) Toeplitzified matrix. """ cov_toep = np.zeros((T * N, T * N)) for delta_t in range(T): to_avg_lower = np.zeros((T - delta_t, N, N)) to_avg_upper = np.zeros((T - delta_t, N, N)) for i in range(T - delta_t): to_avg_lower[i] = cov[(delta_t + i) * N:(delta_t + i + 1) * N, i * N:(i + 1) * N] to_avg_upper[i] = cov[i * N:(i + 1) * N, (delta_t + i) * N:(delta_t + i + 1) * N] avg_lower = np.mean(to_avg_lower, axis=0) avg_upper = np.mean(to_avg_upper, axis=0) if symmetrize: avg_lower = 0.5 * (avg_lower + avg_upper.T) avg_upper = avg_lower.T for i in range(T - delta_t): cov_toep[(delta_t + i) * N:(delta_t + i + 1) * N, i * N:(i + 1) * N] = avg_lower cov_toep[i * N:(i + 1) * N, (delta_t + i) * N:(delta_t + i + 1) * N] = avg_upper return cov_toep def calc_chunked_cov(X, T, stride, chunks, cov_est=None, rng=None, stride_tricks=True): """Calculate an unormalized (by sample count) lagged covariance matrix in chunks to save memory. Parameters ---------- X : np.ndarray, shape (# time-steps, N) The N-dimensional time series data from which the cross-covariance matrices are computed. T : int The number of time lags. stride : int The number of time-points to skip between samples. chunks : int Number of chunks to break the data into when calculating the lagged cross covariance. More chunks will mean less memory used cov_est : ndarray Current estimate of unnormalized cov_est to be added to. Return ------ cov_est : ndarray Current covariance estimate. n_samples How many samples were used. """ if cov_est is None: cov_est = 0. n_samples = 0 if X.shape[0] < T * chunks: raise ValueError('Time series is too short to chunk for cov estimation.') ends = np.linspace(0, X.shape[0], chunks + 1, dtype=int)[1:] start = 0 for chunk in range(chunks): X_with_lags = form_lag_matrix(X[start:ends[chunk]], T, stride=stride, rng=rng, stride_tricks=stride_tricks) start = ends[chunk] - T + 1 ni_samples = X_with_lags.shape[0] cov_est += np.dot(X_with_lags.T, X_with_lags) n_samples += ni_samples return cov_est, n_samples def calc_cross_cov_mats_from_data(X, T, mean=None, chunks=None, stride=1, rng=None, regularization=None, reg_ops=None, stride_tricks=True, logger=None): """Compute the N-by-N cross-covariance matrix, where N is the data dimensionality, for each time lag up to T-1. Parameters ---------- X : np.ndarray, shape (# time-steps, N) The N-dimensional time series data from which the cross-covariance matrices are computed. T : int The number of time lags. chunks : int Number of chunks to break the data into when calculating the lagged cross covariance. More chunks will mean less memory used stride : int or float If stride is an `int`, it defines the stride between lagged samples used to estimate the cross covariance matrix. Setting stride > 1 can speed up the calculation, but may lead to a loss in accuracy. Setting stride to a `float` greater than 0 and less than 1 will random subselect samples. rng : NumPy random state Only used if `stride` is a float. regularization : string Regularization method for computing the spatiotemporal covariance matrix. reg_ops : dict Paramters for regularization. stride_tricks : bool Whether to use numpy stride tricks in form_lag_matrix. True will use less memory for large T. Returns ------- cross_cov_mats : np.ndarray, shape (T, N, N), float Cross-covariance matrices. cross_cov_mats[dt] is the cross-covariance between X(t) and X(t+dt), where X(t) is an N-dimensional vector. """ if reg_ops is None: reg_ops = dict() if chunks is not None and regularization is not None: raise NotImplementedError if isinstance(X, list) or X.ndim == 3: for Xi in X: if len(Xi) <= T: raise ValueError('T must be shorter than the length of the shortest ' + 'timeseries. If you are using the DCA model, 2 * DCA.T must be ' + 'shorter than the shortest timeseries.') if mean is None: mean = np.concatenate(X).mean(axis=0, keepdims=True) X = [Xi - mean for Xi in X] N = X[0].shape[-1] if chunks is None: cov_est = np.zeros((N * T, N * T)) n_samples = 0 for Xi in X: X_with_lags = form_lag_matrix(Xi, T, stride=stride, stride_tricks=stride_tricks, rng=rng) cov_est += np.dot(X_with_lags.T, X_with_lags) n_samples += len(X_with_lags) cov_est /= (n_samples - 1.) else: n_samples = 0 cov_est = np.zeros((N * T, N * T)) for Xi in X: cov_est, ni_samples = calc_chunked_cov(Xi, T, stride, chunks, cov_est=cov_est, stride_tricks=stride_tricks, rng=rng) n_samples += ni_samples cov_est /= (n_samples - 1.) else: if len(X) <= T: raise ValueError('T must be shorter than the length of the shortest ' + 'timeseries. If you are using the DCA model, 2 * DCA.T must be ' + 'shorter than the shortest timeseries.') if mean is None: mean = X.mean(axis=0, keepdims=True) X = X - mean N = X.shape[-1] if chunks is None: X_with_lags = form_lag_matrix(X, T, stride=stride, stride_tricks=stride_tricks, rng=rng) cov_est = np.cov(X_with_lags, rowvar=False) else: cov_est, n_samples = calc_chunked_cov(X, T, stride, chunks, stride_tricks=stride_tricks, rng=rng) cov_est /= (n_samples - 1.) if regularization is None: cov_est = toeplitzify(cov_est, T, N) elif regularization == 'kron': num_folds = reg_ops.get('num_folds', 5) r_vals = np.arange(1, min(2 * T, N**2 + 1)) sigma_vals = np.concatenate([np.linspace(1, 4 * T + 1, 10), [100. * T]]) alpha_vals = np.concatenate([[0.], np.logspace(-2, -1, 10)]) ll_vals, opt_idx = cv_toeplitz(X_with_lags, T, N, r_vals, sigma_vals, alpha_vals, num_folds=num_folds) ri, si, ai = opt_idx cov = np.cov(X_with_lags, rowvar=False) cov_est = toeplitz_reg_taper_shrink(cov, T, N, r_vals[ri], sigma_vals[si], alpha_vals[ai]) else: raise ValueError rectify_spectrum(cov_est, logger=logger) cross_cov_mats = calc_cross_cov_mats_from_cov(cov_est, T, N) return cross_cov_mats def calc_cross_cov_mats_from_cov(cov, T, N): """Calculates T N-by-N cross-covariance matrices given a N*T-by-N*T spatiotemporal covariance matrix by averaging over off-diagonal cross-covariance blocks with constant `|t1-t2|`. Parameters ---------- N : int Numbner of spatial dimensions. T: int Number of time-lags. cov : np.ndarray, shape (N*T, N*T) Spatiotemporal covariance matrix. Returns ------- cross_cov_mats : np.ndarray, shape (T, N, N) Cross-covariance matrices. """ use_torch = isinstance(cov, torch.Tensor) if use_torch: cross_cov_mats = torch.zeros((T, N, N)) else: cross_cov_mats = np.zeros((T, N, N)) for delta_t in range(T): if use_torch: to_avg_lower = torch.zeros((T - delta_t, N, N)) to_avg_upper = torch.zeros((T - delta_t, N, N)) else: to_avg_lower = np.zeros((T - delta_t, N, N)) to_avg_upper = np.zeros((T - delta_t, N, N)) for i in range(T - delta_t): to_avg_lower[i, :, :] = cov[(delta_t + i) * N:(delta_t + i + 1) * N, i * N:(i + 1) * N] to_avg_upper[i, :, :] = cov[i * N:(i + 1) * N, (delta_t + i) * N:(delta_t + i + 1) * N] avg_lower = to_avg_lower.mean(axis=0) avg_upper = to_avg_upper.mean(axis=0) if use_torch: cross_cov_mats[delta_t, :, :] = 0.5 * (avg_lower + avg_upper.t()) else: cross_cov_mats[delta_t, :, :] = 0.5 * (avg_lower + avg_upper.T) return cross_cov_mats def calc_cov_from_cross_cov_mats(cross_cov_mats): """Calculates the N*T-by-N*T spatiotemporal covariance matrix based on T N-by-N cross-covariance matrices. Parameters ---------- cross_cov_mats : np.ndarray, shape (T, N, N) Cross-covariance matrices: cross_cov_mats[dt] is the cross-covariance between X(t) and X(t+dt), where each of X(t) and X(t+dt) is a N-dimensional vector. Returns ------- cov : np.ndarray, shape (N*T, N*T) Big covariance matrix, stationary in time by construction. """ N = cross_cov_mats.shape[1] T = len(cross_cov_mats) use_torch = isinstance(cross_cov_mats, torch.Tensor) cross_cov_mats_repeated = [] for i in range(T): for j in range(T): if i > j: cross_cov_mats_repeated.append(cross_cov_mats[abs(i - j)]) else: if use_torch: cross_cov_mats_repeated.append(cross_cov_mats[abs(i - j)].t()) else: cross_cov_mats_repeated.append(cross_cov_mats[abs(i - j)].T) if use_torch: cov_tensor = torch.reshape(torch.stack(cross_cov_mats_repeated), (T, T, N, N)) cov = torch.cat([torch.cat([cov_ii_jj for cov_ii_jj in cov_ii], dim=1) for cov_ii in cov_tensor]) else: cov_tensor = np.reshape(np.stack(cross_cov_mats_repeated), (T, T, N, N)) cov = np.concatenate([np.concatenate([cov_ii_jj for cov_ii_jj in cov_ii], axis=1) for cov_ii in cov_tensor]) return cov def calc_pi_from_data(X, T, proj=None, stride=1, rng=None): """Calculates the Gaussian Predictive Information between variables {1,...,T_pi} and {T_pi+1,...,2*T_pi}.. Parameters ---------- X : ndarray or torch tensor (time, features) or (batches, time, features) Data used to calculate the PI. T : int This T should be 2 * T_pi. This T sets the joint window length not the past or future window length. proj : ndarray or torch tensor Projection matrix for data (optional). If `proj` is not given, the PI of the dataset is given. stride : int or float If stride is an `int`, it defines the stride between lagged samples used to estimate the cross covariance matrix. Setting stride > 1 can speed up the calculation, but may lead to a loss in accuracy. Setting stride to a `float` greater than 0 and less than 1 will random subselect samples. rng : NumPy random state Only used if `stride` is a float. Returns ------- PI : float Mutual information in nats. """ ccms = calc_cross_cov_mats_from_data(X, T, stride=stride, rng=rng) return calc_pi_from_cross_cov_mats(ccms, proj=proj) def calc_pi_from_cov(cov_2_T_pi): """Calculates the Gaussian Predictive Information between variables {1,...,T_pi} and {T_pi+1,...,2*T_pi} with covariance matrix cov_2_T_pi. Parameters ---------- cov_2_T_pi : np.ndarray, shape (2*T_pi, 2*T_pi) Covariance matrix. Returns ------- PI : float Mutual information in nats. """ T_pi = cov_2_T_pi.shape[0] // 2 use_torch = isinstance(cov_2_T_pi, torch.Tensor) cov_T_pi = cov_2_T_pi[:T_pi, :T_pi] if use_torch: logdet_T_pi = torch.slogdet(cov_T_pi)[1] logdet_2T_pi = torch.slogdet(cov_2_T_pi)[1] else: logdet_T_pi = np.linalg.slogdet(cov_T_pi)[1] logdet_2T_pi = np.linalg.slogdet(cov_2_T_pi)[1] PI = logdet_T_pi - .5 * logdet_2T_pi return PI def project_cross_cov_mats(cross_cov_mats, proj): """Projects the cross covariance matrices. Parameters ---------- cross_cov_mats : np.ndarray, shape (T, N, N) Cross-covariance matrices: cross_cov_mats[dt] is the cross-covariance between X(t) and X(t+dt), where each of X(t) and X(t+dt) is a N-dimensional vector. proj: np.ndarray, shape (N, d), optional If provided, the N-dimensional data are projected onto a d-dimensional basis given by the columns of proj. Then, the mutual information is computed for this d-dimensional timeseries. Returns ------- cross_cov_mats_proj : ndarray, shape (T, d, d) Projected cross covariances matrices. """ if isinstance(cross_cov_mats, torch.Tensor): use_torch = True elif isinstance(cross_cov_mats[0], torch.Tensor): cross_cov_mats = torch.stack(cross_cov_mats) use_torch = True else: use_torch = False if use_torch and isinstance(proj, np.ndarray): proj = torch.tensor(proj, device=cross_cov_mats.device, dtype=cross_cov_mats.dtype) T = cross_cov_mats.shape[0] // 2 if use_torch: cross_cov_mats_proj = torch.matmul(proj.t().unsqueeze(0), torch.matmul(cross_cov_mats, proj.unsqueeze(0))) else: cross_cov_mats_proj = [] for i in range(2 * T): cross_cov = cross_cov_mats[i] cross_cov_proj = np.dot(proj.T,
np.dot(cross_cov, proj)
numpy.dot
from builtins import object import astropy.io.fits as fits import astropy.units as u import numpy as np import os import warnings from threeML.io.fits_file import FITSExtension, FITSFile from threeML.utils.OGIP.response import EBOUNDS, SPECRESP_MATRIX class PHAWrite(object): def __init__(self, *ogiplike): """ This class handles writing of PHA files from OGIPLike style plugins. It takes an arbitrary number of plugins as input. While OGIPLike provides a write_pha method, it is only for writing the given instance to disk. The class in general can be used to save an entire series of OGIPLikes to PHAs which can be used for time-resolved style plugins. An example implentation is given in FermiGBMTTELike. :param ogiplike: OGIPLike plugin(s) to be written to disk """ self._ogiplike = ogiplike self._n_spectra = len(ogiplike) # The following lists corresponds to the different columns in the PHA/CSPEC # formats, and they will be filled up by addSpectrum() self._tstart = {'pha': [], 'bak': []} self._tstop = {'pha': [], 'bak': []} self._channel = {'pha': [], 'bak': []} self._rate = {'pha': [], 'bak': []} self._stat_err = {'pha': [], 'bak': []} self._sys_err = {'pha': [], 'bak': []} self._backscal = {'pha': [], 'bak': []} self._quality = {'pha': [], 'bak': []} self._grouping = {'pha': [], 'bak': []} self._exposure = {'pha': [], 'bak': []} self._backfile = {'pha': [], 'bak': []} self._respfile = {'pha': [], 'bak': []} self._ancrfile = {'pha': [], 'bak': []} self._mission = {'pha': [], 'bak': []} self._instrument = {'pha': [], 'bak': []} # If the PHAs have existing background files # then it is assumed that we will not need to write them # out. THe most likely case is that the background file does not # exist i.e. these are simulations are from EventList object # Just one instance of no background file existing cause the write self._write_bak_file = False # Assuming all entries will have one answer self._is_poisson = {'pha': True, 'bak': True} self._pseudo_time = 0. self._spec_iterator = 1 def write(self, outfile_name, overwrite=True, force_rsp_write=False): """ Write a PHA Type II and BAK file for the given OGIP plugin. Automatically determines if BAK files should be generated. :param outfile_name: string (excluding .pha) of the PHA to write :param overwrite: (optional) bool to overwrite existing file :param force_rsp_write: force the writing of an RSP :return: """ # Remove the .pha extension if any if os.path.splitext(outfile_name)[-1].lower() == '.pha': outfile_name = os.path.splitext(outfile_name)[0] self._outfile_basename = outfile_name self._outfile_name = {'pha': '%s.pha' % outfile_name, 'bak': '%s_bak.pha' % outfile_name} self._out_rsp = [] for ogip in self._ogiplike: self._append_ogip(ogip, force_rsp_write) self._write_phaII(overwrite) def _append_ogip(self, ogip, force_rsp_write): """ Add an ogip instance's data into the data list :param ogip: and OGIPLike instance :param force_rsp_write: force the writing of an rsp :return: None """ # grab the ogip pha info pha_info = ogip.get_pha_files() first_channel = pha_info['rsp'].first_channel for key in ['pha', 'bak']: if key not in pha_info: continue if key == 'pha' and 'bak' in pha_info: if pha_info[key].background_file is not None: self._backfile[key].append(pha_info[key].background_file) else: self._backfile[key].append('%s_bak.pha{%d}' % (self._outfile_basename, self._spec_iterator)) # We want to write the bak file self._write_bak_file = True else: self._backfile[key] = None if pha_info[key].ancillary_file is not None: self._ancrfile[key].append(pha_info[key].ancillary_file) else: # There is no ancillary file, so we need to flag it. self._ancrfile[key].append('NONE') if pha_info['rsp'].rsp_filename is not None and not force_rsp_write: self._respfile[key].append(pha_info['rsp'].rsp_filename) else: # This will be reached in the case that a response was generated from a plugin # e.g. if we want to use weighted DRMs from GBM. rsp_file_name = "%s.rsp{%d}"%(self._outfile_basename,self._spec_iterator) self._respfile[key].append(rsp_file_name) if key == 'pha': self._out_rsp.append(pha_info['rsp']) self._rate[key].append(pha_info[key].rates.tolist()) self._backscal[key].append(pha_info[key].scale_factor) if not pha_info[key].is_poisson: self._is_poisson[key] = pha_info[key].is_poisson self._stat_err[key].append(pha_info[key].rate_errors.tolist()) else: self._stat_err[key] = None # If there is systematic error, we add it # otherwise create an array of zeros as XSPEC # simply adds systematic in quadrature to statistical # error. if pha_info[key].sys_errors.tolist() is not None: # It returns an array which does not work! self._sys_err[key].append(pha_info[key].sys_errors.tolist()) else: self._sys_err[key].append(np.zeros_like(pha_info[key].rates, dtype=np.float32).tolist()) self._exposure[key].append(pha_info[key].exposure) self._quality[key].append(ogip.quality.to_ogip().tolist()) self._grouping[key].append(ogip.grouping.tolist()) self._channel[key].append(np.arange(pha_info[key].n_channels, dtype=np.int32) + first_channel) self._instrument[key] = pha_info[key].instrument self._mission[key] = pha_info[key].mission if ogip.tstart is not None: self._tstart[key].append(ogip.tstart) if ogip.tstop is not None: self._tstop[key].append(ogip.tstop) else: RuntimeError('OGIP TSTART is a number but TSTOP is None. This is a bug.') # We will assume that the exposure is the true DT # and assign starts and stops accordingly. This means # we are most likely are dealing with a simulation. else: self._tstart[key].append(self._pseudo_time) self._pseudo_time += pha_info[key].exposure self._tstop[key].append(self._pseudo_time) self._spec_iterator += 1 def _write_phaII(self, overwrite): # Fix this later... if needed. trigger_time = None if self._backfile['pha'] is not None: # Assuming background and pha files have the same # number of channels assert len(self._rate['pha'][0]) == len( self._rate['bak'][0]), "PHA and BAK files do not have the same number of channels. Something is wrong." assert self._instrument['pha'] == self._instrument[ 'bak'], "Instrument for PHA and BAK (%s,%s) are not the same. Something is wrong with the files. " % ( self._instrument['pha'], self._instrument['bak']) assert self._mission['pha'] == self._mission[ 'bak'], "Mission for PHA and BAK (%s,%s) are not the same. Something is wrong with the files. " % ( self._mission['pha'], self._mission['bak']) if self._write_bak_file: keys = ['pha', 'bak'] else: keys = ['pha'] for key in keys: if trigger_time is not None: tstart = self._tstart[key] - trigger_time else: tstart = self._tstart[key] # build a PHAII instance fits_file = PHAII(self._instrument[key], self._mission[key], tstart, np.array(self._tstop[key]) - np.array(self._tstart[key]), self._channel[key], self._rate[key], self._quality[key], self._grouping[key], self._exposure[key], self._backscal[key], self._respfile[key], self._ancrfile[key], back_file=self._backfile[key], sys_err=self._sys_err[key], stat_err=self._stat_err[key], is_poisson=self._is_poisson[key]) # write the file fits_file.writeto(self._outfile_name[key], overwrite=overwrite) if self._out_rsp: # add the various responses needed extensions = [EBOUNDS(self._out_rsp[0].ebounds)] extensions.extend([SPECRESP_MATRIX(this_rsp.monte_carlo_energies, this_rsp.ebounds, this_rsp.matrix) for this_rsp in self._out_rsp]) for i, ext in enumerate(extensions[1:]): # Set telescope and instrument name ext.hdu.header.set("TELESCOP", self._mission['pha']) ext.hdu.header.set("INSTRUME", self._instrument['pha']) ext.hdu.header.set("EXTVER", i+1) rsp2 = FITSFile(fits_extensions=extensions) rsp2.writeto("%s.rsp" % self._outfile_basename, overwrite=True) def _atleast_2d_with_dtype(value,dtype=None): if dtype is not None: value = np.array(value,dtype=dtype) arr = np.atleast_2d(value) return arr def _atleast_1d_with_dtype(value,dtype=None): if dtype is not None: value =
np.array(value,dtype=dtype)
numpy.array