From 3d1aafc0628c8962dd5e7563827b53bab4ab2995 Mon Sep 17 00:00:00 2001 From: dotchris90 Date: Thu, 20 Dec 2018 14:11:52 +0100 Subject: [PATCH 1/4] Removed : Because not used, old array or not relevant --- src/NumSharp.Core/Extensions/Matrix .sum.cs | 44 ----------- .../Extensions/NDArrayWithDType.AMin.cs | 76 ------------------- .../Extensions/NdArray.AsMatrix.cs | 20 ----- src/NumSharp.Core/Extensions/NdArray.Max.cs | 44 ----------- src/NumSharp.Core/Extensions/NdArray.Sum.cs | 24 ------ .../Extensions/NdArray.VStack.cs | 41 ---------- src/NumSharp.Core/Extensions/NdArray.Zeros.cs | 47 ------------ .../Selection/NDArray.Enumerator.cs | 42 ---------- .../Selection/NDArray.Slicing.cs | 47 ------------ .../Docs/NDArray.Creation.cs | 29 ------- .../Docs/NDArray.LinAlgebra.cs | 37 --------- .../NdArrayRandom.Permutation.Test.cs | 26 ------- test/NumSharp.UnitTest/Shared/ArrayHelper.cs | 41 ---------- test/NumSharp.UnitTest/TestBase.cs | 14 ---- 14 files changed, 532 deletions(-) delete mode 100644 src/NumSharp.Core/Extensions/Matrix .sum.cs delete mode 100644 src/NumSharp.Core/Extensions/NDArrayWithDType.AMin.cs delete mode 100644 src/NumSharp.Core/Extensions/NdArray.AsMatrix.cs delete mode 100644 src/NumSharp.Core/Extensions/NdArray.Max.cs delete mode 100644 src/NumSharp.Core/Extensions/NdArray.Sum.cs delete mode 100644 src/NumSharp.Core/Extensions/NdArray.VStack.cs delete mode 100644 src/NumSharp.Core/Extensions/NdArray.Zeros.cs delete mode 100644 src/NumSharp.Core/Selection/NDArray.Enumerator.cs delete mode 100644 src/NumSharp.Core/Selection/NDArray.Slicing.cs delete mode 100644 test/NumSharp.UnitTest/Docs/NDArray.Creation.cs delete mode 100644 test/NumSharp.UnitTest/Docs/NDArray.LinAlgebra.cs delete mode 100644 test/NumSharp.UnitTest/Extensions/NdArrayRandom.Permutation.Test.cs delete mode 100644 test/NumSharp.UnitTest/Shared/ArrayHelper.cs delete mode 100644 test/NumSharp.UnitTest/TestBase.cs diff --git a/src/NumSharp.Core/Extensions/Matrix .sum.cs b/src/NumSharp.Core/Extensions/Matrix .sum.cs deleted file mode 100644 index 3d69a3ef..00000000 --- a/src/NumSharp.Core/Extensions/Matrix .sum.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace NumSharp.Core -{ - public partial class matrix - { - public new matrix transpose() - { - Storage.Shape = new Shape(this.Storage.Shape.Shapes.Reverse().ToArray()); - - var nd = new NDArray(this.dtype, this.shape); - switch (this.dtype.Name) - { - case "Double": - nd.Set(this.float64); - break; - case "Int32": - nd.Set(this.int32); - break; - } - - if (ndim == 1) - { - Storage = NDStorage.CreateByShapeAndType(dtype, new Shape(1, shape.Shapes[0])); - Storage.SetData(nd.float64); - } - else if (ndim == 2) - { - for (int idx = 0; idx < shape.Shapes[0]; idx++) - for (int jdx = 0; jdx < shape.Shapes[1]; jdx++) - this[idx, jdx] = nd[jdx, idx]; - } - else - { - throw new NotImplementedException(); - } - - return this; - } - } -} diff --git a/src/NumSharp.Core/Extensions/NDArrayWithDType.AMin.cs b/src/NumSharp.Core/Extensions/NDArrayWithDType.AMin.cs deleted file mode 100644 index 49e09804..00000000 --- a/src/NumSharp.Core/Extensions/NDArrayWithDType.AMin.cs +++ /dev/null @@ -1,76 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace NumSharp.Core -{ - public partial class NDArray - { - public NDArray AMin(int? axis = null) - { - NDArray res = new NDArray(dtype); - if (axis == null) - { - switch (dtype.Name) - { - case "Double": - //res.Storage.Set(new double[1] { Storage.Double8.Min() }); - break; - } - - res.Storage.Shape = new Shape(new int[] { 1 }); - } - else - { - if (axis < 0 || axis >= shape.NDim) - throw new Exception("Invalid input: axis"); - int[] resShapes = new int[shape.Shapes.Count - 1]; - int index = 0; //index for result shape set - //axis departs the shape into three parts: prev, cur and post. They are all product of shapes - int prev = 1; - int cur = 1; - int post = 1; - int size = 1; //total number of the elements for result - //Calculate new Shape - for (int i = 0; i < shape.Shapes.Count; i++) - { - if (i == axis) - cur = shape.Shapes[i]; - else - { - resShapes[index++] = shape.Shapes[i]; - size *= shape.Shapes[i]; - if (i < axis) - prev *= shape.Shapes[i]; - else - post *= shape.Shapes[i]; - } - } - res.Storage.Shape = new Shape(resShapes); - //Fill in data - index = 0; //index for result data set - int sameSetOffset = shape.DimOffset[axis.Value]; - int increments = cur * post; - int start = 0; - double min; - for (int i = 0; i < this.size; i += increments) - { - for (int j = i; j < i + post; j++) - { - start = j; - /* - min = Storage.Double8[start]; - for (int k = 0; k < cur; k++) - { - min = Math.Min(min, Storage.Double8[start]); - start += sameSetOffset; - } - res.Storage.Double8[index++] = min;*/ - } - } - } - return res; - } - } -} diff --git a/src/NumSharp.Core/Extensions/NdArray.AsMatrix.cs b/src/NumSharp.Core/Extensions/NdArray.AsMatrix.cs deleted file mode 100644 index 11182210..00000000 --- a/src/NumSharp.Core/Extensions/NdArray.AsMatrix.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; -using System.Text; - -namespace NumSharp.Core.Extensions -{ - public static partial class NDArrayExtensions - { - public static matrix AsMatrix(this NDArray nd) - { - var npAsMatrix = new matrix(nd); - - npAsMatrix.reshape(nd.shape); - - return npAsMatrix; - } - } -} diff --git a/src/NumSharp.Core/Extensions/NdArray.Max.cs b/src/NumSharp.Core/Extensions/NdArray.Max.cs deleted file mode 100644 index 7e4447bf..00000000 --- a/src/NumSharp.Core/Extensions/NdArray.Max.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace NumSharp.Core.Extensions -{ - public static partial class NDArrayExtensions - { - public static NDArrayGeneric Max(this NDArrayGeneric np) - { - if (np.NDim == 1) - { - var max = new NDArrayGeneric().Zeros(np.Size); - max.Shape = new Shape(1); - max.Data = new double[] { np.Data.Max() }; - - return max; - } - else if (np.NDim == 2) - { - var max = new NDArrayGeneric().Zeros(np.Shape.Shapes[1]); - - for (int col = 0; col < np.Shape.Shapes[1]; col++) - { - max[col] = np[0, col]; - for (int row = 0; row < np.Shape.Shapes[0]; row++) - { - if (np[row, col] > max[col]) - { - max[col] = np[row, col]; - } - } - } - - return max; - } - else - { - throw new NotImplementedException(); - } - } - } -} diff --git a/src/NumSharp.Core/Extensions/NdArray.Sum.cs b/src/NumSharp.Core/Extensions/NdArray.Sum.cs deleted file mode 100644 index 7b6f2422..00000000 --- a/src/NumSharp.Core/Extensions/NdArray.Sum.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace NumSharp.Core.Extensions -{ - public static partial class NDArrayExtensions - { - public static int Sum(this NDArrayGeneric np, NDArrayGeneric np2) - { - int result = 0; - for(int i = 0; i < np.Size; i++) - { - if(np[i].Equals(np2[i])) - { - result++; - } - } - - return result; - } - } -} diff --git a/src/NumSharp.Core/Extensions/NdArray.VStack.cs b/src/NumSharp.Core/Extensions/NdArray.VStack.cs deleted file mode 100644 index 79ed89d9..00000000 --- a/src/NumSharp.Core/Extensions/NdArray.VStack.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace NumSharp.Core.Extensions -{ - public static partial class NDArrayExtensions - { - /// - /// Stack arrays in sequence vertically (row wise). - /// - /// - /// - public static NDArrayGeneric VStack(this NDArrayGeneric np1, params NDArrayGeneric[] nps) - { - if (nps == null || nps.Length == 0) - throw new Exception("Input arrays can not be empty"); - List list = new List(); - NDArrayGeneric np = new NDArrayGeneric(); - foreach (NDArrayGeneric ele in nps) - { - if (nps[0].Shape != ele.Shape) - throw new Exception("Arrays mush have same shapes"); - list.AddRange(ele.Data); - } - np.Data = list.ToArray(); - if (nps[0].NDim == 1) - { - np.Shape = new Shape(new int[] { nps.Length, nps[0].Shape.Shapes[0] }); - } - else - { - int[] shapes = nps[0].Shape.Shapes.ToArray(); - shapes[0] *= nps.Length; - np.Shape = new Shape(shapes); - } - return np; - } - } -} diff --git a/src/NumSharp.Core/Extensions/NdArray.Zeros.cs b/src/NumSharp.Core/Extensions/NdArray.Zeros.cs deleted file mode 100644 index 86c9ecbd..00000000 --- a/src/NumSharp.Core/Extensions/NdArray.Zeros.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Linq; -using System.Text; - -namespace NumSharp.Core.Extensions -{ - public partial class NDArrayExtensions - { - /// - /// Return a new array of given shape and type, filled with zeros. - /// - /// - /// - /// - public static NDArrayGeneric Zeros(this NDArrayGeneric np, params int[] shape) - { - int length = 1; - - for(int i = 0; i< shape.Length; i++) - { - length *= shape[i]; - } - - np.Data = Enumerable.Range(0, length).Select(x => 0).ToArray(); - np.reshape(shape); - - return np; - } - - public static NDArrayGeneric Zeros(this NDArrayGeneric np, params int[] shape) - { - int length = 1; - - for (int i = 0; i < shape.Length; i++) - { - length *= shape[i]; - } - - np.Data = Enumerable.Range(0, length).Select(x => 0.0).ToArray(); - np.reshape(shape); - - return np; - } - } -} diff --git a/src/NumSharp.Core/Selection/NDArray.Enumerator.cs b/src/NumSharp.Core/Selection/NDArray.Enumerator.cs deleted file mode 100644 index 969f89f3..00000000 --- a/src/NumSharp.Core/Selection/NDArray.Enumerator.cs +++ /dev/null @@ -1,42 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Text; - -namespace NumSharp.Core -{ - public partial class NDArrayGeneric : IEnumerable, IEnumerator - { - private int pos = -1; - public object Current - { - get - { - if (shape.NDim == 1) - { - return Data[pos]; - } - else - { - return this[new Shape(pos)]; - } - } - } - - public IEnumerator GetEnumerator() - { - return this; - } - - public bool MoveNext() - { - pos++; - return pos < Shape[0]; - } - - public void Reset() - { - pos = -1; - } - } -} diff --git a/src/NumSharp.Core/Selection/NDArray.Slicing.cs b/src/NumSharp.Core/Selection/NDArray.Slicing.cs deleted file mode 100644 index 8af97b27..00000000 --- a/src/NumSharp.Core/Selection/NDArray.Slicing.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace NumSharp.Core -{ - public partial class NDArrayGeneric - { - public NDArrayGeneric> this[Slice select] - { - get - { - var result = new NDArrayGeneric>(); - result.Data = new NDArrayGeneric[select.Length]; - result.shape = new Shape(select.Length); - - int[] shape = new int[Shape.NDim]; - for (int i = 0; i < Shape.NDim; i++) - { - if (i == 0) - { - shape[i] = select.Step; - } - else - { - shape[i] = Shape[i]; - } - } - - int index = 0; - var list = new NDArrayGeneric(); - for (int s = select.Start; s< select.Stop; s+= select.Step) - { - var n = new NDArrayGeneric(); - Span data = Data; - n.Data = data.Slice(s, select.Step).ToArray(); - n.Shape = new Shape(shape); - - result.Data[index] = n; - index++; - } - - return result; - } - } - } -} diff --git a/test/NumSharp.UnitTest/Docs/NDArray.Creation.cs b/test/NumSharp.UnitTest/Docs/NDArray.Creation.cs deleted file mode 100644 index 7b68f5cb..00000000 --- a/test/NumSharp.UnitTest/Docs/NDArray.Creation.cs +++ /dev/null @@ -1,29 +0,0 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; -using System.Collections.Generic; -using System.Text; -using NumSharp.Core.Extensions; -using NumSharp.Core; - -namespace NumSharp.UnitTest.Docs -{ - [TestClass] - public class NDArrayCreationTester - { - [TestMethod] - public void Dump() - { - var np = new NDArray(typeof(double)); - np.Storage.SetData(new double[] {1,2,3,4,5,6,7,8,9}); - np.Storage.Shape = new Shape(3,3); - - Assert.IsTrue(np.ndim == 2); - - var npGen = np.MakeGeneric(); - - Assert.IsTrue(npGen[0,0] == 1); - Assert.IsTrue(npGen[1,1] == 5); - Assert.IsTrue(npGen[2,2] == 9); - } - } -} diff --git a/test/NumSharp.UnitTest/Docs/NDArray.LinAlgebra.cs b/test/NumSharp.UnitTest/Docs/NDArray.LinAlgebra.cs deleted file mode 100644 index 55912f4d..00000000 --- a/test/NumSharp.UnitTest/Docs/NDArray.LinAlgebra.cs +++ /dev/null @@ -1,37 +0,0 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; -using System.Collections.Generic; -using System.Text; -using NumSharp.Core.Extensions; -using NumSharp.Core; - -namespace NumSharp.UnitTest.Docs -{ - /* - [TestClass] - public class LinearAlgebraTester - { - NumPy np = new NumPy(); - - [TestMethod] - public void LinearRegression() - { - // the time array - var time = np.linspace(0, 10, 1000); - - // the values over t - linear dependence with noice - var values = time * 3 + 5 + np.random.randn(time.Size); - var A = np.vstack(np.ones(1000), time); - var A_T = A.transpose(); - var A_T_A = A_T.dot(A); - - //var A_PseudoInv = A.transpose().dot(A).inv(); - - //var param = A_PseudoInv.dot(A.transpose()); - - //param = param.dot(param); - - } - } - */ -} diff --git a/test/NumSharp.UnitTest/Extensions/NdArrayRandom.Permutation.Test.cs b/test/NumSharp.UnitTest/Extensions/NdArrayRandom.Permutation.Test.cs deleted file mode 100644 index c12f338b..00000000 --- a/test/NumSharp.UnitTest/Extensions/NdArrayRandom.Permutation.Test.cs +++ /dev/null @@ -1,26 +0,0 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using NumSharp.Core.Extensions; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace NumSharp.UnitTest.Extensions -{ - [TestClass] - public class NdArrayRandomPermutationTest - { - [TestMethod] - public void Prmutation() - { - // var np = new NDArray_Legacy(); - // var rands = np.Random().Permutation(10); - // var results = rands.Data.Distinct(); - - // var str = String.Join(", ", results); - - // Assert.IsTrue(results.Count() == 10); - // Assert.IsTrue(str != "0, 1, 2, 3, 4, 5, 6, 7, 8, 9"); - } - } -} diff --git a/test/NumSharp.UnitTest/Shared/ArrayHelper.cs b/test/NumSharp.UnitTest/Shared/ArrayHelper.cs deleted file mode 100644 index d42c7425..00000000 --- a/test/NumSharp.UnitTest/Shared/ArrayHelper.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System; -using System.Linq; - -namespace NumSharp.UnitTest.Shared -{ - internal static class ArrayHelper - { - internal static bool CompareTwoJaggedArrays(T[][] np1, T[][] np2 ) - { - bool arraysSame = true; - - for(int idx = 0; idx < np1.Length;idx++) - { - for (int jdx = 0; jdx < np2[0].Length;jdx++) - { - if (!np1[idx][jdx].Equals(np2[idx][jdx])) - { - arraysSame = false; - } - else - { - // pass - } - } - } - return arraysSame; - } - internal static T[][] CreateJaggedArrayByMatrix(T[,] np) - { - int dim0 = np.GetLength(0); - int dim1 = np.GetLength(1); - - var returnResult = new T[dim0][]; - returnResult = returnResult.Select(x => new T[dim1]).ToArray(); - - returnResult = returnResult.Select((x,idx) => x.Select((y,jdx) => np[idx,jdx]).ToArray()).ToArray(); - - return returnResult; - } - } -} \ No newline at end of file diff --git a/test/NumSharp.UnitTest/TestBase.cs b/test/NumSharp.UnitTest/TestBase.cs deleted file mode 100644 index 96b5f57a..00000000 --- a/test/NumSharp.UnitTest/TestBase.cs +++ /dev/null @@ -1,14 +0,0 @@ -using NumSharp.Core; -using System; -using System.Collections.Generic; -using System.Text; - -namespace NumSharp.UnitTest -{ - public class TestBase - { - public TestBase() - { - } - } -} From ce20ee73a0aed5909afe53bc471570203ec66628 Mon Sep 17 00:00:00 2001 From: dotchris90 Date: Thu, 20 Dec 2018 14:13:10 +0100 Subject: [PATCH 2/4] Add : Renamed Order to Layout and Shapes to Dimensions --- src/NumSharp.Core/Interfaces/IShape.cs | 9 ++++----- src/NumSharp.Core/Interfaces/IStorage.cs | 24 ++++++------------------ 2 files changed, 10 insertions(+), 23 deletions(-) diff --git a/src/NumSharp.Core/Interfaces/IShape.cs b/src/NumSharp.Core/Interfaces/IShape.cs index 2ff7ce10..d6bf06fc 100644 --- a/src/NumSharp.Core/Interfaces/IShape.cs +++ b/src/NumSharp.Core/Interfaces/IShape.cs @@ -8,15 +8,14 @@ public interface IShape { int Size {get;} int NDim {get;} - int TensorOrder {get;} - IReadOnlyList DimOffset {get;} - IReadOnlyList Shapes {get;} - int ReShape(params int[] dimensions); + int TensorLayout {get;} + int[] DimOffset {get;} + int[] Dimensions {get;} int GetIndexInShape(params int[] select); int[] GetDimIndexOutShape(int select); int UniShape {get;} (int, int) BiShape {get;} (int, int, int) TriShape {get;} - bool ChangeTensorOrder(int order); + void ChangeTensorLayout(int order); } } \ No newline at end of file diff --git a/src/NumSharp.Core/Interfaces/IStorage.cs b/src/NumSharp.Core/Interfaces/IStorage.cs index b3b20331..919781d7 100644 --- a/src/NumSharp.Core/Interfaces/IStorage.cs +++ b/src/NumSharp.Core/Interfaces/IStorage.cs @@ -18,7 +18,7 @@ namespace NumSharp.Core.Interfaces /// - CloneData clone storage and cast this clone /// /// - public interface IStorage + public interface IStorage : ICloneable { /// /// Data Type of stored elements @@ -34,14 +34,14 @@ public interface IStorage /// column wise or row wise order /// /// 0 row wise, 1 column wise - int TensorOrder {get;} + int TensorLayout {get;} /// /// Allocate memory by dtype, shape, tensororder (default column wise) /// /// storage data type /// storage data shape /// row or column wise - void Allocate(Type dtype, Shape shape, int tensorOrder = 1); + void Allocate(Type dtype, IShape shape, int tensorOrder = 1); /// /// Allocate memory by Array and tensororder and deduce shape and dtype (default column wise) /// @@ -119,19 +119,6 @@ public interface IStorage /// void SetData(object value, params int[] indexes); /// - /// Set a 1D Array of type T to internal storage and cast dtype - /// - /// - /// - void SetData(T[] values); - /// - /// Set a single value of type dtype to internal storage and cast storage - /// - /// - /// - /// - void SetData(T value, params int[] indexes); - /// /// Set an Array to internal storage, cast it to new dtype and change dtype /// /// @@ -142,12 +129,13 @@ public interface IStorage /// /// new storage data type /// sucess or not - bool ChangeDataType(Type dtype); + void ChangeDataType(Type dtype); /// /// Cange layout to 0 row wise or 1 colum wise /// /// 0 or 1 /// success or not - bool SwitchTensorOrder(int order); + void ChangeTensorLayout(int order); + void Reshape(params int[] dimensions); } } \ No newline at end of file From 60783e3ba1c9888210ce6a878f317a1f45377730 Mon Sep 17 00:00:00 2001 From: dotchris90 Date: Thu, 20 Dec 2018 14:14:08 +0100 Subject: [PATCH 3/4] Add : Implement the interfaces IStorage and IShape --- src/NumSharp.Core/NDStorage.cs | 687 ++++++++++++++++++--------------- src/NumSharp.Core/NdArray.cs | 173 ++------- src/NumSharp.Core/Shape.cs | 121 +++--- 3 files changed, 473 insertions(+), 508 deletions(-) diff --git a/src/NumSharp.Core/NDStorage.cs b/src/NumSharp.Core/NDStorage.cs index 4f574276..8082301a 100644 --- a/src/NumSharp.Core/NDStorage.cs +++ b/src/NumSharp.Core/NDStorage.cs @@ -1,200 +1,297 @@ -/* - * NumSharp - * Copyright (C) 2018 Haiping Chen - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the Apache License 2.0 as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the Apache License 2.0 - * along with this program. If not, see . - */ - +using NumSharp; +using NumSharp.Core.Interfaces; +using NumSharp.Core; using System; -using System.Collections; -using System.Collections.Generic; using System.Linq; -using System.Text; -using System.Numerics; namespace NumSharp.Core { /// - /// Numerical dynamic storage + /// Storage + /// + /// Responsible for : + /// + /// - store data type, elements, Shape + /// - offers methods for accessing elements depending on shape + /// - offers methods for casting elements + /// - offers methods for change tensor order + /// - GetData always return reference object to the true storage + /// - GetData and SetData change dtype and cast storage + /// - CloneData always create a clone of storage and return this as reference object + /// - CloneData clone storage and cast this clone + /// /// - public class NDStorage : IEnumerable, IEnumerator//IComparable, IComparable, IConvertible, IEquatable, IFormattable + public class NDStorage : IStorage { - /// - /// memory allocation - /// - private Array values { get; set; } - public Type dtype {get;set;} - public Shape Shape { get; set; } - public int Length => values.Length; - public NDStorage() - { - dtype = typeof(ValueType); - Shape = new Shape(1); - values = new int[] {0}; - } - public NDStorage(Type dtype) - { - this.dtype = dtype; - Shape = new Shape(1); - values = Array.CreateInstance(dtype,1); - } - /// - /// Create a NDStorage by data type and array shape - /// - /// The type of arrays elements - /// The shape of array/param> - /// The constructed NDStorage - public static NDStorage CreateByShapeAndType(Type dtype,Shape shape) - { - var storage = new NDStorage(dtype); - storage.Shape = shape; - storage.Allocate(shape.Size); - return storage; - } - public static NDStorage CreateByArray(Array values) + protected Array _values; + protected Type _DType; + protected IShape _Shape; + protected int _TensorLayout; + protected void _ChangeRowToColumnLayout() { - Type dtype = null; - - if ( !values.GetType().GetElementType().IsArray ) - dtype = values.GetType().GetElementType(); - else - throw new IncorrectShapeException(); + if ( _Shape.NDim == 1 ) + { - int[] dims = new int[values.Rank]; + } + else if (_Shape.NDim == 2) + { + var puffer = Array.CreateInstance(_values.GetType().GetElementType(),_values.Length); - for (int idx = 0; idx < dims.Length;idx++) - dims[idx] = values.GetLength(idx); + var pufferShape = new Shape(_Shape.Dimensions); + pufferShape.ChangeTensorLayout(2); - var storage = NDStorage.CreateByShapeAndType(dtype,new Shape(dims)); - storage.values = Array.CreateInstance(dtype,values.Length); + for(int idx = 0; idx < _values.Length;idx++) + puffer.SetValue(_values.GetValue(idx),pufferShape.GetIndexInShape(Shape.GetDimIndexOutShape(idx))); + + _values = puffer; + } + else + { + var puffer = Array.CreateInstance(_values.GetType().GetElementType(),_values.Length); - storage.SetData(values); + var pufferShape = new Shape(_Shape.Dimensions); + pufferShape.ChangeTensorLayout(2); - return storage; + for(int idx = 0; idx < _values.Length;idx++) + puffer.SetValue(_values.GetValue(idx),pufferShape.GetIndexInShape(Shape.GetDimIndexOutShape(idx))); + + _values = puffer; + } + Shape.ChangeTensorLayout(2); + _TensorLayout = 2; } - /// - /// Retrieve element - /// low performance, use generic Data method for performance sensitive invoke - /// - /// - /// - public object this[params int[] select] + protected void _ChangeColumnToRowLayout() { - get + if ( _Shape.NDim == 1 ) { - if (select.Length == Shape.NDim) - { - switch (values) - { - case double[] values: - return values[Shape.GetIndexInShape(select)]; - case int[] values: - return values[Shape.GetIndexInShape(select)]; - } - return null; - } - else - { - int start = Shape.GetIndexInShape(select); - int length = Shape.DimOffset[select.Length - 1]; + } + else if (_Shape.NDim == 2) + { + var puffer = Array.CreateInstance(_values.GetType().GetElementType(),_values.Length); - var nd = new NDArray(dtype); + var pufferShape = new Shape(_Shape.Dimensions); + pufferShape.ChangeTensorLayout(1); - switch (values) - { - case double[] values: - Span double8 = GetData(); - nd.Storage.Set(double8.Slice(start, length).ToArray()); - break; - case int[] values: - Span int32 = GetData(); - nd.Storage.Set(int32.Slice(start, length).ToArray()); - break; - } + for(int idx = 0; idx < _values.Length;idx++) + puffer.SetValue(_values.GetValue(idx),pufferShape.GetIndexInShape(Shape.GetDimIndexOutShape(idx))); + + _values = puffer; + } + else + { + var puffer = Array.CreateInstance(_values.GetType().GetElementType(),_values.Length); - int[] shape = new int[Shape.NDim - select.Length]; - for (int i = select.Length; i < Shape.NDim; i++) - { - shape[i - select.Length] = Shape[i]; - } - nd.Storage.Shape = new Shape(shape); + var pufferShape = new Shape(_Shape.Dimensions); + pufferShape.ChangeTensorLayout(1); - return nd; - } + for(int idx = 0; idx < _values.Length;idx++) + puffer.SetValue(_values.GetValue(idx),pufferShape.GetIndexInShape(Shape.GetDimIndexOutShape(idx))); + + _values = puffer; } + _TensorLayout = 1; + Shape.ChangeTensorLayout(1); + } + protected Array _ChangeTypeOfArray(Array arrayVar, Type dtype) + { + Array newValues = null; - set + switch (Type.GetTypeCode(dtype)) { - if (select.Length == Shape.NDim) + case TypeCode.Double : { - switch (values) - { - case double[] values: - values[Shape.GetIndexInShape(select)] = (double)value; - break; - case int[] values: - values[Shape.GetIndexInShape(select)] = (int)value; - break; - } + newValues = new double[arrayVar.Length]; + for(int idx = 0;idx < arrayVar.Length;idx++) + newValues.SetValue(Convert.ToDouble(arrayVar.GetValue(idx)),idx); + break; } - else + case TypeCode.Single : { - int start = Shape.GetIndexInShape(select); - int length = Shape.DimOffset[Shape.NDim - 1]; - - switch (value) + newValues = new float[arrayVar.Length]; + for(int idx = 0;idx < arrayVar.Length;idx++) + newValues.SetValue(Convert.ToSingle(arrayVar.GetValue(idx)),idx); + break; + } + case TypeCode.Decimal : + { + newValues = new Decimal[arrayVar.Length]; + for(int idx = 0;idx < arrayVar.Length;idx++) + newValues.SetValue(Convert.ToDecimal(arrayVar.GetValue(idx)),idx); + break; + } + case TypeCode.Int32 : + { + newValues = new int[arrayVar.Length]; + for(int idx = 0;idx < arrayVar.Length;idx++) + newValues.SetValue(Convert.ToInt32(arrayVar.GetValue(idx)),idx); + break; + } + case TypeCode.Int64 : + { + newValues = new Int64[arrayVar.Length]; + for(int idx = 0;idx < arrayVar.Length;idx++) + newValues.SetValue(Convert.ToInt64(arrayVar.GetValue(idx)),idx); + break; + } + case TypeCode.Object : + { + if( dtype == typeof(System.Numerics.Complex) ) { - case double v: - Span data1 = GetData(); - var elements1 = data1.Slice(start, length); - - for (int i = 0; i < elements1.Length; i++) - { - elements1[i] = v; - } - - break; - case int v: - Span data2 = GetData(); - var elements2 = data2.Slice(start, length); - - for (int i = 0; i < elements2.Length; i++) - { - elements2[i] = v; - } - - break; + newValues = new System.Numerics.Complex[arrayVar.Length]; + for(int idx = 0;idx < arrayVar.Length;idx++) + newValues.SetValue(new System.Numerics.Complex((double)arrayVar.GetValue(idx),0),idx); + break; } - - + else if ( dtype == typeof(System.Numerics.Quaternion) ) + { + newValues = new System.Numerics.Quaternion[arrayVar.Length]; + for(int idx = 0;idx < arrayVar.Length;idx++) + newValues.SetValue(new System.Numerics.Quaternion(new System.Numerics.Vector3(0,0,0) , (float)arrayVar.GetValue(idx)),idx); + break; + } + else + { + newValues = new object[arrayVar.Length]; + for(int idx = 0;idx < arrayVar.Length;idx++) + newValues.SetValue(arrayVar.GetValue(idx),idx); + break; + } + + } + default : + { + break; } } + + return newValues; } /// - /// Get all elements as one System.Array object without shape + /// Data Type of stored elements + /// + /// numpys equal dtype + public Type DType {get {return _DType;}} + /// + /// storage shape for outside representation /// - /// + /// numpys equal shape + public IShape Shape {get {return _Shape;}} + /// + /// column wise or row wise order + /// + /// 0 row wise, 1 column wise + public int TensorLayout {get {return _TensorLayout;}} + public NDStorage() + { + _DType = np.float64; + _values = new double[1]; + _Shape = new Shape(1); + _TensorLayout = 1; + } + public NDStorage(Type dtype) + { + _DType = dtype; + _values = Array.CreateInstance(dtype,1); + _Shape = new Shape(1); + _TensorLayout = 1; + } + public NDStorage(double[] values) + { + _DType = typeof(double); + _Shape = new Shape(values.Length); + _values = values; + _TensorLayout = 1; + } + public NDStorage(object[] values) + { + _DType = values.GetType().GetElementType(); + _Shape = new Shape(values.Length); + _values = values; + _TensorLayout = 1; + } + /// + /// Allocate memory by dtype, shape, tensororder (default column wise) + /// + /// storage data type + /// storage data shape + /// row or column wise + public void Allocate(Type dtype, IShape shape, int tensorOrder = 1) + { + _DType = dtype; + _Shape = shape; + _Shape.ChangeTensorLayout(tensorOrder); + int elementNumber = 1; + for(int idx = 0; idx < shape.Dimensions.Length;idx++) + elementNumber *= shape.Dimensions[idx]; + + _values = Array.CreateInstance(dtype,elementNumber); + _TensorLayout = tensorOrder; + } + /// + /// Allocate memory by Array and tensororder and deduce shape and dtype (default column wise) + /// + /// elements to store + /// row or column wise + public void Allocate(Array values, int tensorOrder = 1) + { + _TensorLayout = tensorOrder; + int[] dim = new int[values.Rank]; + for (int idx = 0; idx < dim.Length;idx++) + dim[idx] = values.GetLength(idx); + + _Shape = new Shape(dim); + Type elementType = values.GetType(); + while (elementType.IsArray) + elementType = elementType.GetElementType(); + + _DType = elementType; + } + /// + /// Get Back Storage with Columnwise tensor Layout + /// By this method the layout is changed if layout is not columnwise + /// + /// reference to storage (transformed or not) + public IStorage GetColumWiseStorage() + { + if ( _TensorLayout != 2 ) + this._ChangeRowToColumnLayout(); + + return this; + } + /// + /// Get Back Storage with row wise tensor Layout + /// By this method the layout is changed if layout is not row wise + /// + /// reference to storage (transformed or not) + public IStorage GetRowWiseStorage() + { + if ( _TensorLayout != 1 ) + this._ChangeColumnToRowLayout(); + + return this; + } + /// + /// Get reference to internal data storage + /// + /// reference to internal storage as System.Array public Array GetData() { - return values; + return _values; } /// - /// Get all elements with correct type by parameter instead of generic + /// Clone internal storage and get reference to it /// - /// - /// + /// reference to cloned storage as System.Array + public Array CloneData() + { + return (Array) _values.Clone(); + } + /// + /// Get reference to internal data storage and cast elements to new dtype + /// + /// new storage data type + /// reference to internal (casted) storage as System.Array public Array GetData(Type dtype) { var methods = this.GetType().GetMethods().Where(x => x.Name.Equals("GetData") && x.IsGenericMethod && x.ReturnType.Name.Equals("T[]")); @@ -202,201 +299,161 @@ public Array GetData(Type dtype) return (Array) genMethods.Invoke(this,null); } - public void SetData(Array values) + /// + /// Clone internal storage and cast elements to new dtype + /// + /// cloned storage data type + /// reference to cloned storage as System.Array + public Array CloneData(Type dtype) { - this.values = values; + var puffer = (Array) this.GetData().Clone(); + + if (puffer.GetType().GetElementType() != dtype) + puffer = _ChangeTypeOfArray(puffer,dtype); + + return puffer; } - public void SetData(object value, params int[] indexes) + /// + /// Get reference to internal data storage and cast elements to new dtype + /// + /// new storage data type + /// reference to internal (casted) storage as T[] + public T[] GetData() { - this.values.SetValue(value,Shape.GetIndexInShape(indexes)); + if (typeof(T) != this._DType) + this.ChangeDataType(typeof(T)); + + return (_values as T[]); } /// - /// Get specific element depending on Shape of array + /// Get all elements from cloned storage as T[] and cast dtype /// - /// The indexes of dimensions - /// + /// cloned storgae dtype + /// reference to cloned storage as T[] + public T[] CloneData() + { + var puffer = (Array) this.GetData().Clone(); + + if (puffer.GetType().GetElementType() != typeof(T)) + puffer = _ChangeTypeOfArray(puffer,typeof(T)); + + return (puffer as T[]); + } + /// + /// Get single value from internal storage and do not cast dtype + /// + /// indexes + /// element from internal storage public object GetData(params int[] indexes) { object element = null; if (indexes.Length == Shape.NDim) - element = values.GetValue(Shape.GetIndexInShape(indexes)); - else if (Shape.Shapes.Last() == 1) - element = values.GetValue(Shape.GetIndexInShape(indexes)); + element = _values.GetValue(Shape.GetIndexInShape(indexes)); + else if (Shape.Dimensions.Last() == 1) + element = _values.GetValue(Shape.GetIndexInShape(indexes)); else throw new Exception("indexes must be equal to number of dimension."); return element; } /// - /// Return all elements as one 1D .NET array but cast to specific type. + /// Get single value from internal storage as type T and cast dtype to T /// - /// Data type of elements - /// casted array - public T[] GetData() + /// indexes + /// new storage data type + /// element from internal storage + public T GetData(params int[] indexes) { - T[] returnArray = null; + this.ChangeDataType(this.DType); + T[] values = this.GetData() as T[]; - if (values.GetType().GetElementType() == typeof(T)) - returnArray = values as T[]; - else - { - returnArray = new T[values.Length]; - switch (Type.GetTypeCode(typeof(T))) - { - case TypeCode.Double : - { - var returnArray_ = returnArray as double[]; - for(int idx = 0;idx < returnArray.Length;idx++) - returnArray_[idx] = Convert.ToDouble(values.GetValue(idx)); - break; - } - case TypeCode.Single : - { - var returnArray_ = returnArray as float[]; - for(int idx = 0;idx < returnArray.Length;idx++) - returnArray_[idx] = Convert.ToSingle(values.GetValue(idx)); - break; - } - case TypeCode.Decimal : - { - var returnArray_ = returnArray as decimal[]; - for(int idx = 0;idx < returnArray.Length;idx++) - returnArray_[idx] = Convert.ToDecimal(values.GetValue(idx)); - break; - } - case TypeCode.Int32 : - { - var returnArray_ = returnArray as int[]; - for(int idx = 0;idx < returnArray.Length;idx++) - returnArray_[idx] = Convert.ToInt32(values.GetValue(idx)); - break; - } - case TypeCode.Int64 : - { - var returnArray_ = returnArray as Int64[]; - for(int idx = 0;idx < returnArray.Length;idx++) - returnArray_[idx] = Convert.ToInt64(values.GetValue(idx)); - break; - } - case TypeCode.Object : - { - if( typeof(T) == typeof(Complex) ) - { - var returnArray_ = returnArray as Complex[]; - for(int idx = 0;idx < returnArray.Length;idx++) - returnArray_[idx] = new Complex((double)values.GetValue(idx),0); - break; - } - else if ( typeof(T) == typeof(Quaternion) ) - { - var returnArray_ = returnArray as Quaternion[]; - for(int idx = 0;idx < returnArray.Length;idx++) - returnArray_[idx] = new Quaternion(new Vector3(0,0,0),(float)values.GetValue(idx)); - break; - } - else - { - var returnArray_ = returnArray as object[]; - for(int idx = 0;idx < returnArray.Length;idx++) - returnArray_[idx] = values.GetValue(idx); - } - break; - } - default : - { - break; - } - } - } - return returnArray; + return values[Shape.GetIndexInShape(indexes)]; } - public T GetData(params int[] indexes) + /// + /// Set an array to internal storage and keep dtype + /// + /// + public void SetData(Array values) { - T element; - T[] elements = values as T[]; - if (indexes.Length == Shape.NDim) - element = elements[Shape.GetIndexInShape(indexes)]; - else - throw new Exception("indexes must be equal to number of dimension."); - return element; + _values = values; + this.ChangeDataType(this._DType); } - public void Set(T[] value) + /// + /// Set 1 single value to internal storage and keep dtype + /// + /// + /// + public void SetData(object value, params int[] indexes) { - values = value; + _values.SetValue(value,_Shape.GetIndexInShape(indexes)); } - public void Set(Shape shape, T value) + /// + /// Set a 1D Array of type T to internal storage and cast dtype + /// + /// + /// + public void SetData(Array values) { - if (shape.NDim == Shape.NDim) - { - throw new Exception("Please use NDArray[m, n] to access element."); - } - else - { - int start = Shape.GetIndexInShape(shape.Shapes.ToArray()); - int length = Shape.DimOffset[shape.NDim - 1]; - - Span data = Data(); - var elements = data.Slice(start, length); - - for (int i = 0; i < elements.Length; i++) - { - elements[i] = value; - } - } + _values = values; + this.ChangeDataType(typeof(T)); } - public T[] Data() + /// + /// Set an Array to internal storage, cast it to new dtype and change dtype + /// + /// + /// + public void SetData(Array values, Type dtype) { - return values as T[]; - } - + _values = values; + this.ChangeDataType(dtype); + } /// - /// Allocate memory of size + /// Change dtype of elements /// - /// - internal void Allocate(int size) + /// new storage data type + /// sucess or not + public void ChangeDataType(Type dtype) { - values = Array.CreateInstance(this.dtype,size); + if( _values.GetType().GetElementType() != dtype) + _values = this._ChangeTypeOfArray(_values,dtype); + _DType = dtype; } - - private int pos = -1; - public object Current + public void Reshape(params int[] dimensions) { - get + if (_TensorLayout == 2) { - if (Shape.NDim == 1) - { - switch (values) - { - case int[] a: - return a[pos]; - case float[] a: - return a[pos]; - case double[] a: - return a[pos]; - } - - return null; - } - else - { - return null; - } + _Shape = new Shape(dimensions); } + else + { + ChangeTensorLayout(2); + _Shape = new Shape(dimensions); + _Shape.ChangeTensorLayout(2); + ChangeTensorLayout(1); + + } + + } - - public IEnumerator GetEnumerator() + public object Clone() { - return this; - } + var puffer = new NDStorage(); + puffer.Allocate(_DType, new Shape(_Shape.Dimensions), _TensorLayout); + puffer.SetData((Array)_values.Clone()); - public bool MoveNext() - { - pos++; - return pos < Shape[0]; + return puffer; } - - public void Reset() + /// + /// Cange layout to 0 row wise or 1 colum wise + /// + /// 0 or 1 + /// success or not + public void ChangeTensorLayout(int layout) { - pos = -1; + if (layout != _TensorLayout) + if (_TensorLayout == 1) + _ChangeRowToColumnLayout(); + else + _ChangeColumnToRowLayout(); } } -} +} \ No newline at end of file diff --git a/src/NumSharp.Core/NdArray.cs b/src/NumSharp.Core/NdArray.cs index 3daca163..ca3df400 100644 --- a/src/NumSharp.Core/NdArray.cs +++ b/src/NumSharp.Core/NdArray.cs @@ -23,6 +23,8 @@ using System.Text; using System.Globalization; using System.Collections; +using NumSharp.Core.Interfaces; +using NumSharp.Core; namespace NumSharp.Core { @@ -35,80 +37,58 @@ public partial class NDArray /// /// Data type of NDArray /// - public Type dtype => Storage.dtype; + public Type dtype => Storage.DType; /// /// Data length of every dimension /// - public Shape shape => Storage.Shape; + public IShape shape => Storage.Shape; /// /// Dimension count /// - public int ndim => shape.NDim; + public int ndim => Storage.Shape.NDim; /// /// Total of elements /// - public int size => shape.Size; + public int size => Storage.Shape.Size; /// /// The internal storage for elements of NDArray /// /// - public NDStorage Storage { get; set; } + public NDStorage Storage {get;set;} + public NDArray() { - Storage = NDStorage.CreateByShapeAndType(typeof(double),new Shape(1)); + Storage = new NDStorage(); } public NDArray(Type dtype) { - Storage = NDStorage.CreateByShapeAndType(dtype,new Shape(1)); + Storage = new NDStorage(dtype); } - public NDArray(Type dtype, Shape shape) + public NDArray(Array values ) : this(values.GetType().GetElementType()) { - Storage = NDStorage.CreateByShapeAndType(dtype,shape); - } - public NDArray(Type dtype, params int[] shapes) - { - Storage = NDStorage.CreateByShapeAndType(dtype,new Shape(shapes)); - } - public override string ToString() - { - string output = ""; + int[] strgDim = new int[values.Rank]; - if (this.ndim == 2) - { - if(dtype == typeof(int)) - { - output = this._ToMatrixString(); - } - else if(dtype == typeof(double)) - { - output = this._ToMatrixString(); - } - - } - else + for(int idx = 0; idx < strgDim.Length;idx++) + strgDim[idx] = values.GetLength(idx); + + Storage.Allocate(Storage.DType,new Shape(strgDim),1); + + switch( values.Rank ) { - if (dtype == typeof(int)) + case 1 : { - //output = this._ToVectorString(); + + break; } - else if (dtype == typeof(double)) - { - //output = this._ToVectorString(); - } - } - - return output; + } } - - public override bool Equals(object obj) + public NDArray(Type dtype, IShape shape) + { + Storage = new NDStorage(); + Storage.Allocate(dtype,shape,1); + } + public NDArray(Type dtype, params int[] shapes) : this(dtype, new Shape(shapes) ) { - switch (obj) - { - case int o: - return o == Data()[0]; - } - - return false; } public override int GetHashCode() { @@ -120,99 +100,20 @@ public override int GetHashCode() return result; } } - protected string _ToVectorString() + public override bool Equals(object obj) { - string returnValue = "array(["; - - int digitBefore = 0; - int digitAfter = 0; - - var dataParsed = Data().Select(x => _ParseNumber(x,ref digitBefore,ref digitAfter)).ToArray(); - - string elementFormatStart = "{0:"; - - string elementFormatEnd = ""; - for(int idx = 0; idx < digitAfter;idx++) - elementFormatEnd += "0"; - - elementFormatEnd += "}"; - - int missingDigits; - string elementFormat; - - for (int idx = 0; idx < (Storage.Shape.Size-1);idx++) - { - missingDigits = digitBefore - dataParsed[idx].Replace(" ","").Split('.')[0].Length; - - elementFormat = elementFormatStart + new string(Enumerable.Repeat(' ',missingDigits).ToArray()) + "0." + elementFormatEnd; - - returnValue += (String.Format(new CultureInfo("en-us"),elementFormat, Storage[idx]) + ", "); + bool isSame = false; + try + { + var objCast = (NDArray) obj; + isSame = this == objCast; } - missingDigits = digitBefore - dataParsed.Last().Replace(" ","").Split('.')[0].Length; - - elementFormat = elementFormatStart + new string(Enumerable.Repeat(' ',missingDigits).ToArray()) + "." + elementFormatEnd; - - returnValue += (String.Format(new CultureInfo("en-us"),elementFormat, Storage.Data().Last()) + "])"); - - return returnValue; - } - protected string _ToMatrixString() - { - string returnValue = "array([["; - - int digitBefore = 0; - int digitAfter = 0; - - string[] dataParsed = Data().Select(x => _ParseNumber(x, ref digitBefore, ref digitAfter)).ToArray(); - - string elementFormatStart = "{0:"; - - string elementFormatEnd = ""; - for(int idx = 0; idx < digitAfter;idx++) - elementFormatEnd += "0"; - - elementFormatEnd += "}"; - - int missingDigits; - string elementFormat; - - for (int idx = 0; idx < shape.NDim - 1; idx++) + catch { - missingDigits = digitBefore - dataParsed[idx].Replace(" ", "").Split('.')[0].Length; - elementFormat = elementFormatStart + new string(Enumerable.Repeat(' ', missingDigits).ToArray()) + "0." + elementFormatEnd; - - if (((idx + 1) % shape.Shapes[1]) == 0) - { - returnValue += (String.Format(new CultureInfo("en-us"), elementFormat, Storage[idx]) + "], \n ["); - } - else - { - returnValue += (String.Format(new CultureInfo("en-us"), elementFormat, Storage[idx]) + ", "); - } } - - missingDigits = digitBefore - dataParsed.Last().Replace(" ","").Split('.')[0].Length; - - elementFormat = elementFormatStart + new string(Enumerable.Repeat(' ',missingDigits).ToArray()) + "." + elementFormatEnd; - - returnValue += (String.Format(new CultureInfo("en-us"),elementFormat, Data().Last()) + "]])"); - - return returnValue; - } - protected string _ParseNumber(object number, ref int noBefore,ref int noAfter) - { - string parsed = string.Format(new CultureInfo("en-us"),"{0:0.00000000}",number); - - parsed = (parsed.StartsWith("-")) ? parsed : (" " + parsed); - - int noBefore_local = parsed.Split('.')[0].Length; - int noAfter_local = parsed.Split('.')[1].ToCharArray().Reverse().SkipWhile(x => x == '0').ToArray().Length; - - noBefore = (noBefore_local > noBefore) ? noBefore_local : noBefore; - noAfter = (noAfter_local > noAfter ) ? noAfter_local : noAfter; - - return parsed; + return isSame; } + } } diff --git a/src/NumSharp.Core/Shape.cs b/src/NumSharp.Core/Shape.cs index 26f13422..96710232 100644 --- a/src/NumSharp.Core/Shape.cs +++ b/src/NumSharp.Core/Shape.cs @@ -1,70 +1,63 @@ using System; +using NumSharp.Core.Interfaces; using System.Collections.Generic; using System.Text; +using System.Linq; namespace NumSharp.Core { - public partial class Shape + public partial class Shape : IShape { - private readonly IReadOnlyList shape; - private readonly IReadOnlyList dimOffset; - private readonly int dimOffsetTotal; - - public int Size + protected int _TensorLayout; + public int TensorLayout {get {return _TensorLayout;}} + protected int[] _Dimensions; + protected int[] _DimOffset; + protected int _size; + public int NDim => _Dimensions.Length; + public int[] Dimensions {get{return _Dimensions;}} + public int[] DimOffset {get{return _DimOffset;}} + public int Size {get{return _size;}} + protected void _SetDimOffset() { - get + if (this._TensorLayout == 1) { - int idx = 1; - for (int i = 0; i < shape.Count; i++) - { - idx *= shape[i]; - } - return idx; + _DimOffset[0] = 1; + + for(int idx = 1;idx < _DimOffset.Length;idx++) + _DimOffset[idx] = _DimOffset[idx-1] * this._Dimensions[idx-1]; + } + else if ( _TensorLayout == 2) + { + _DimOffset[_DimOffset.Length-1] = 1; + for(int idx = _DimOffset.Length-1;idx >= 1;idx--) + _DimOffset[idx-1] = _DimOffset[idx] * this._Dimensions[idx]; } } - - public int NDim => shape.Count; - - public int this[int dim] => shape[dim]; - public Shape(params int[] shape) { if (shape.Length == 0) throw new Exception("Shape cannot be empty."); - this.shape = shape; - int[] temp = new int[shape.Length]; - temp[shape.Length - 1] = 1; - for (int i = shape.Length - 1; i >= 1; i--) - { - temp[i - 1] = temp[i] * shape[i]; - } - dimOffset = temp; - } + this._Dimensions = shape; + this._DimOffset = new int[this._Dimensions.Length] ; + this._TensorLayout = 1; - public Shape(IReadOnlyList shape) + this._size = 1; + + for (int idx =0; idx < shape.Length;idx++) + _size *= shape[idx]; + this._SetDimOffset(); + } + public Shape(IEnumerable shape) : this(shape.ToArray()) { - if (shape.Count == 0) - throw new Exception("Shape cannot be empty."); - this.shape = shape; - int[] temp = new int[shape.Count]; - temp[shape.Count - 1] = 1; - for (int i = shape.Count - 1; i >= 1; i--) - { - temp[i - 1] = temp[i] * shape[i]; - } - dimOffset = temp; + } - - public IReadOnlyList DimOffset => dimOffset; - public IReadOnlyList Shapes => shape; - public int GetIndexInShape(params int[] select) { int idx = 0; for (int i = 0; i < select.Length; i++) { - idx += dimOffset[i] * select[i]; + idx += _DimOffset[i] * select[i]; } return idx; @@ -72,32 +65,46 @@ public int GetIndexInShape(params int[] select) public int[] GetDimIndexOutShape(int select) { int[] dimIndexes = null; - if (this.dimOffset.Count == 1) + if (this._DimOffset.Length == 1) dimIndexes = new int[] {select}; - else if (this.dimOffset.Count == 2) + else if (this._TensorLayout == 1) { - dimIndexes = new int[dimOffset.Count]; - - int remaining = select; + int counter = select; + dimIndexes = new int[_DimOffset.Length]; - for (int idx = 0;idx < dimOffset.Count;idx++) + for (int idx = _DimOffset.Length-1; idx > -1;idx--) { - dimIndexes[idx] = remaining / dimOffset[idx]; - remaining -= (dimIndexes[idx] * dimOffset[idx] ); - } + dimIndexes[idx] = counter / _DimOffset[idx]; + counter -= dimIndexes[idx] * _DimOffset[idx]; + } } - else + else { - throw new IncorrectShapeException(); + int counter = select; + dimIndexes = new int[_DimOffset.Length]; + + for (int idx = 0; idx < _DimOffset.Length;idx++) + { + dimIndexes[idx] = counter / _DimOffset[idx]; + counter -= dimIndexes[idx] * _DimOffset[idx]; + } } return dimIndexes; } + public void ChangeTensorLayout(int layout) + { + _DimOffset = new int[this._Dimensions.Length]; - public int UniShape => shape[0]; + layout = (layout == 0) ? 1 : layout; + + _TensorLayout = layout; + _SetDimOffset(); + } + public int UniShape => _Dimensions[0]; - public (int, int) BiShape => shape.Count == 2 ? (shape[0], shape[1]) : (0, 0); + public (int, int) BiShape => _Dimensions.Length == 2 ? (_Dimensions[0], _Dimensions[1]) : (0, 0); - public (int, int, int) TriShape => shape.Count == 3 ? (shape[0], shape[1], shape[2]) : (0, 0, 0); + public (int, int, int) TriShape => _Dimensions.Length == 3 ? (_Dimensions[0], _Dimensions[1], _Dimensions[2]) : (0, 0, 0); } } From cf3dc9e94c610925aed34a6aa89362a139dfa5c7 Mon Sep 17 00:00:00 2001 From: dotchris90 Date: Thu, 20 Dec 2018 14:17:38 +0100 Subject: [PATCH 4/4] Add : Adapted all files to changed made before --- src/NumSharp.Core/Casting/NdArray.ToString.cs | 138 +++++++++ .../Casting/NdArrayToJaggedArray.cs | 24 +- .../Casting/NdArrayToMultiDimArray.cs | 4 +- src/NumSharp.Core/Creation/NdArray.ARange.cs | 2 +- .../Creation/NdArray.AsMatrix.cs | 20 ++ src/NumSharp.Core/Creation/NdArray.Eye.cs | 18 +- src/NumSharp.Core/Creation/NdArray.HStack.cs | 16 +- .../Creation/NdArray.LinSpace.cs | 66 +---- src/NumSharp.Core/Creation/NdArray.Ones.cs | 4 +- src/NumSharp.Core/Creation/NdArray.ReShape.cs | 99 +------ src/NumSharp.Core/Creation/NdArray.VStack.cs | 42 +-- src/NumSharp.Core/Creation/np.arange.cs | 2 +- src/NumSharp.Core/Creation/np.array.cs | 23 +- src/NumSharp.Core/Creation/np.asarray.cs | 14 +- src/NumSharp.Core/Creation/np.linspace.cs | 2 +- src/NumSharp.Core/Creation/np.ones.cs | 6 +- src/NumSharp.Core/Creation/np.ones_like.cs | 2 +- src/NumSharp.Core/Creation/np.zeros.cs | 2 +- .../Extensions/NdArray.ArgMax.cs | 12 +- .../Extensions/NdArray.Normalize.cs | 8 +- .../Extensions/NdArray.Unique.cs | 7 +- src/NumSharp.Core/Generics/NDArrayGeneric.cs | 271 +----------------- .../LinearAlgebra/NdArray.Dot.cs | 78 ++--- .../LinearAlgebra/NdArray.Inv.cs | 12 +- .../LinearAlgebra/NdArray.LstSq.cs | 6 +- src/NumSharp.Core/LinearAlgebra/NdArray.QR.cs | 8 +- .../LinearAlgebra/NdArray.Transpose.cs | 31 +- .../LinearAlgebra/NdArray.multi_dot.cs | 8 +- .../Manipulation/NdArray.delete.cs | 2 +- src/NumSharp.Core/Manipulation/np.ravel.cs | 4 +- .../Manipulation/np.transpose.cs | 8 +- src/NumSharp.Core/Manipulation/np.vstack.cs | 10 +- src/NumSharp.Core/Math/NDArray.argmax.cs | 4 +- src/NumSharp.Core/Math/NdArray.Convolve.cs | 12 +- src/NumSharp.Core/Math/NdArray.Mean.cs | 18 +- src/NumSharp.Core/Math/NdArray.log.cs | 51 ---- src/NumSharp.Core/Math/np.power.cs | 2 +- src/NumSharp.Core/Matrix.cs | 36 +-- .../Operations/NDArray.Equals.cs | 2 +- .../Operations/NdArray.Addition.cs | 110 +------ .../Operations/NdArray.Division.cs | 191 +++++++----- .../Operations/NdArray.Multiplication.cs | 117 +------- .../Operations/NdArray.Substraction.cs | 111 +------ src/NumSharp.Core/Operations/Shape.Equals.cs | 6 +- .../Random/np.random.permutation.cs | 4 +- src/NumSharp.Core/Random/np.random.randint.cs | 6 +- src/NumSharp.Core/Random/np.random.randn.cs | 6 +- .../Selection/NDArray.Indexing.cs | 176 +----------- src/NumSharp.Core/Selection/NdArray.AMax.cs | 30 +- src/NumSharp.Core/Selection/NdArray.AMin.cs | 30 +- src/NumSharp.Core/np.cs | 1 - src/NumSharp.PowerShell/GetGreeting.cs | 6 +- .../Creation/NdArray.Array.Test.cs | 11 +- .../Creation/NdArray.Zeros.Test.cs | 8 +- .../Creation/np.arange.Test.cs | 8 +- .../Extensions/NdArray.AsMatrix.Test.cs | 2 +- .../Extensions/NdArray.ReShape.Test.cs | 26 +- .../Extensions/NdArrayRandom.RandInt.Test.cs | 4 +- test/NumSharp.UnitTest/LAPACK/dgels.cs | 3 +- .../LinearAlgebra/NdArray.Dot.Test.cs | 46 +-- .../LinearAlgebra/NdArray.LstSq.Test.cs | 1 - .../LinearAlgebra/NdArray.QR.Test.cs | 3 +- .../LinearAlgebra/NdArray.Transpose.cs | 2 +- .../Math/NDArray.log.Test.cs | 2 +- .../Math/NDArray.sin.Test.cs | 16 +- .../Math/NdArray.Sqrt.Test.cs | 9 +- test/NumSharp.UnitTest/NdArray.Test.cs | 19 +- test/NumSharp.UnitTest/NdArrayRandom.Test.cs | 4 +- .../Operations/Matrix.Addition.Test.cs | 8 +- .../Operations/Matrix.Substraction.Test.cs | 6 +- .../Selection/NDArray.Indexing.Test.cs | 15 +- test/NumSharp.UnitTest/Shape.Test.cs | 60 +++- test/NumSharp.UnitTest/Storage.Test.cs | 205 +++++++++++-- 73 files changed, 871 insertions(+), 1455 deletions(-) create mode 100644 src/NumSharp.Core/Casting/NdArray.ToString.cs create mode 100644 src/NumSharp.Core/Creation/NdArray.AsMatrix.cs diff --git a/src/NumSharp.Core/Casting/NdArray.ToString.cs b/src/NumSharp.Core/Casting/NdArray.ToString.cs new file mode 100644 index 00000000..141e35ef --- /dev/null +++ b/src/NumSharp.Core/Casting/NdArray.ToString.cs @@ -0,0 +1,138 @@ +using System; +using NumSharp.Core; +using System.Linq; +using System.Globalization; +using System.Collections.Generic; + +namespace NumSharp.Core +{ + public partial class NDArray + { + public override string ToString() + { + string output = ""; + + if (this.ndim == 2) + { + if(dtype == typeof(int)) + { + output = this._ToMatrixString(); + } + else if(dtype == typeof(double)) + { + output = this._ToMatrixString(); + } + + } + else + { + if (dtype == typeof(int)) + { + //output = this._ToVectorString(); + } + else if (dtype == typeof(double)) + { + //output = this._ToVectorString(); + } + } + + return output; + } + protected string _ToVectorString() + { + string returnValue = "array(["; + + int digitBefore = 0; + int digitAfter = 0; + + var dataParsed = Storage.GetData().Select(x => _ParseNumber(x,ref digitBefore,ref digitAfter)).ToArray(); + + string elementFormatStart = "{0:"; + + string elementFormatEnd = ""; + for(int idx = 0; idx < digitAfter;idx++) + elementFormatEnd += "0"; + + elementFormatEnd += "}"; + + int missingDigits; + string elementFormat; + + for (int idx = 0; idx < (Storage.Shape.Size-1);idx++) + { + missingDigits = digitBefore - dataParsed[idx].Replace(" ","").Split('.')[0].Length; + + elementFormat = elementFormatStart + new string(Enumerable.Repeat(' ',missingDigits).ToArray()) + "0." + elementFormatEnd; + + returnValue += (String.Format(new CultureInfo("en-us"),elementFormat, Storage.GetData()[idx]) + ", "); + } + missingDigits = digitBefore - dataParsed.Last().Replace(" ","").Split('.')[0].Length; + + elementFormat = elementFormatStart + new string(Enumerable.Repeat(' ',missingDigits).ToArray()) + "." + elementFormatEnd; + + returnValue += (String.Format(new CultureInfo("en-us"),elementFormat, Storage.GetData().Last()) + "])"); + + return returnValue; + } + protected string _ToMatrixString() + { + string returnValue = "array([["; + + int digitBefore = 0; + int digitAfter = 0; + + string[] dataParsed = Storage.GetData().Select(x => _ParseNumber(x, ref digitBefore, ref digitAfter)).ToArray(); + + string elementFormatStart = "{0:"; + + string elementFormatEnd = ""; + for(int idx = 0; idx < digitAfter;idx++) + elementFormatEnd += "0"; + + elementFormatEnd += "}"; + + int missingDigits; + string elementFormat; + + for (int idx = 0; idx < shape.NDim - 1; idx++) + { + missingDigits = digitBefore - dataParsed[idx].Replace(" ", "").Split('.')[0].Length; + + elementFormat = elementFormatStart + new string(Enumerable.Repeat(' ', missingDigits).ToArray()) + "0." + elementFormatEnd; + + if (((idx + 1) % shape.Dimensions[1]) == 0) + { + returnValue += (String.Format(new CultureInfo("en-us"), elementFormat, Storage.GetData()[idx]) + "], \n ["); + } + else + { + returnValue += (String.Format(new CultureInfo("en-us"), elementFormat, Storage.GetData()[idx]) + ", "); + } + } + + missingDigits = digitBefore - dataParsed.Last().Replace(" ","").Split('.')[0].Length; + + elementFormat = elementFormatStart + new string(Enumerable.Repeat(' ',missingDigits).ToArray()) + "." + elementFormatEnd; + + returnValue += (String.Format(new CultureInfo("en-us"),elementFormat, Storage.GetData().Last()) + "]])"); + + return returnValue; + } + protected string _ParseNumber(object number, ref int noBefore,ref int noAfter) + { + string parsed = string.Format(new CultureInfo("en-us"),"{0:0.00000000}",number); + + parsed = (parsed.StartsWith("-")) ? parsed : (" " + parsed); + + int noBefore_local = parsed.Split('.')[0].Length; + int noAfter_local = parsed.Split('.')[1].ToCharArray().Reverse().SkipWhile(x => x == '0').ToArray().Length; + + noBefore = (noBefore_local > noBefore) ? noBefore_local : noBefore; + noAfter = (noAfter_local > noAfter ) ? noAfter_local : noAfter; + + return parsed; + } + } + +} + diff --git a/src/NumSharp.Core/Casting/NdArrayToJaggedArray.cs b/src/NumSharp.Core/Casting/NdArrayToJaggedArray.cs index f687012d..ed9c4a92 100644 --- a/src/NumSharp.Core/Casting/NdArrayToJaggedArray.cs +++ b/src/NumSharp.Core/Casting/NdArrayToJaggedArray.cs @@ -42,13 +42,13 @@ public Array ToJaggedArray() } case 2 : { - T[] data = Storage.GetData(); - T[][] dotNetArrayPuffer = new T[shape.Shapes[0]][]; + T[][] dotNetArrayPuffer = new T[shape.Dimensions[0]][]; for (int idx = 0; idx < dotNetArrayPuffer.Length;idx++) - dotNetArrayPuffer[idx] = new T[shape.Shapes[1]]; + dotNetArrayPuffer[idx] = new T[shape.Dimensions[1]]; - for (int idx = 0;idx < data.Length;idx++ ) - dotNetArrayPuffer[idx/shape.Shapes[1]][idx%shape.Shapes[1]] = data[idx]; + for (int idx = 0;idx < dotNetArrayPuffer.Length;idx++ ) + for (int jdx = 0; jdx < dotNetArrayPuffer[0].Length;jdx++) + dotNetArrayPuffer[idx][jdx] = (T) this[idx,jdx]; dotNetArray = dotNetArrayPuffer; @@ -57,19 +57,19 @@ public Array ToJaggedArray() case 3 : { T[] data = Storage.GetData(); - T[][][] dotNetArrayPuffer = new T[shape.Shapes[0]][][]; + T[][][] dotNetArrayPuffer = new T[shape.Dimensions[0]][][]; for (int idx = 0; idx < dotNetArrayPuffer.Length;idx++) { - dotNetArrayPuffer[idx] = new T[shape.Shapes[1]][]; + dotNetArrayPuffer[idx] = new T[shape.Dimensions[1]][]; for (int jdx = 0; jdx < dotNetArrayPuffer[idx].Length;jdx++) - dotNetArrayPuffer[idx][jdx] = new T[shape.Shapes[2]]; + dotNetArrayPuffer[idx][jdx] = new T[shape.Dimensions[2]]; } - for (int idx = 0; idx < shape.Shapes[0];idx++) - for (int jdx = 0;jdx < shape.Shapes[1];jdx++) - for(int kdx = 0; kdx < shape.Shapes[2];kdx++) + for (int idx = 0; idx < shape.Dimensions[0];idx++) + for (int jdx = 0;jdx < shape.Dimensions[1];jdx++) + for(int kdx = 0; kdx < shape.Dimensions[2];kdx++) dotNetArrayPuffer[idx][jdx][kdx] = (T) this[idx,jdx,kdx]; - + dotNetArray = dotNetArrayPuffer; break; diff --git a/src/NumSharp.Core/Casting/NdArrayToMultiDimArray.cs b/src/NumSharp.Core/Casting/NdArrayToMultiDimArray.cs index 8326c610..87c2cfbb 100644 --- a/src/NumSharp.Core/Casting/NdArrayToMultiDimArray.cs +++ b/src/NumSharp.Core/Casting/NdArrayToMultiDimArray.cs @@ -43,9 +43,9 @@ public Array ToMuliDimArray() case 2 : { T[] data = Storage.GetData(); - T[,] dotNetArrayPuffer = new T[shape.Shapes[0],shape.Shapes[1]]; + T[,] dotNetArrayPuffer = new T[shape.Dimensions[0],shape.Dimensions[1]]; for (int idx = 0;idx < data.Length;idx++ ) - dotNetArrayPuffer[idx/shape.Shapes[1],idx%shape.Shapes[1]] = data[idx]; + dotNetArrayPuffer[idx/shape.Dimensions[1],idx%shape.Dimensions[1]] = data[idx]; dotNetArray = dotNetArrayPuffer; diff --git a/src/NumSharp.Core/Creation/NdArray.ARange.cs b/src/NumSharp.Core/Creation/NdArray.ARange.cs index 620b9644..61bcdf13 100644 --- a/src/NumSharp.Core/Creation/NdArray.ARange.cs +++ b/src/NumSharp.Core/Creation/NdArray.ARange.cs @@ -65,7 +65,7 @@ public NDArray arange(int stop, int start = 0, int step = 1) } } - this.Storage.Shape = new Shape(list.Length); + this.Storage.Reshape(list.Length); return this; } diff --git a/src/NumSharp.Core/Creation/NdArray.AsMatrix.cs b/src/NumSharp.Core/Creation/NdArray.AsMatrix.cs new file mode 100644 index 00000000..61da5d69 --- /dev/null +++ b/src/NumSharp.Core/Creation/NdArray.AsMatrix.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; + +namespace NumSharp.Core.Extensions +{ + public static partial class NDArrayExtensions + { + public static matrix AsMatrix(this NDArray nd) + { + var npAsMatrix = new matrix(nd); + + npAsMatrix.reshape((Shape)nd.shape); + + return npAsMatrix; + } + } +} diff --git a/src/NumSharp.Core/Creation/NdArray.Eye.cs b/src/NumSharp.Core/Creation/NdArray.Eye.cs index 2229a243..c4818c02 100644 --- a/src/NumSharp.Core/Creation/NdArray.Eye.cs +++ b/src/NumSharp.Core/Creation/NdArray.Eye.cs @@ -20,21 +20,17 @@ public NDArray eye(int dim, int diagonalIndex = 0) } else { - puffer = new NDArray(this.dtype,this.shape.Shapes.ToArray()); + puffer = new NDArray(this.dtype,this.shape.Dimensions.ToArray()); } - - puffer.Storage.SetData(Array.CreateInstance(dtype,puffer.size)); - - Array storageArr = puffer.Storage.GetData(); - if (diagonalIndex > -1) + puffer.Storage.SetData(Array.CreateInstance(dtype,puffer.size)); + + if (diagonalIndex >= 0) for(int idx = 0; idx < noOfDiagElement;idx++ ) - storageArr.SetValue(1,diagonalIndex + idx + idx * puffer.shape.Shapes[1]); + puffer.Storage.SetData(1,idx,idx+diagonalIndex); else - for(int idx = dim - 1; idx > dim - noOfDiagElement - 1;idx-- ) - storageArr.SetValue(1,diagonalIndex + idx + idx * puffer.shape.Shapes[1]); // = 1; - - this.Storage = puffer.Storage; + for(int idx = puffer.Storage.Shape.Dimensions[0]-1; idx > puffer.Storage.Shape.Dimensions[0]-1 - noOfDiagElement;idx-- ) + puffer.Storage.SetData(1,idx,idx+diagonalIndex); return puffer; } diff --git a/src/NumSharp.Core/Creation/NdArray.HStack.cs b/src/NumSharp.Core/Creation/NdArray.HStack.cs index 4501b840..f737266c 100644 --- a/src/NumSharp.Core/Creation/NdArray.HStack.cs +++ b/src/NumSharp.Core/Creation/NdArray.HStack.cs @@ -39,11 +39,14 @@ public NDArray hstack(params NDArray[] nps) } else { + for(int idx = 0; idx < npAll.Length;idx++) + npAll[idx].Storage.ChangeTensorLayout(2); + var list = new List(); - int total = npAll[0].ndim == 1 ? 1 : npAll[0].shape.Shapes[0]; + int total = npAll[0].ndim == 1 ? 1 : npAll[0].shape.Dimensions[0]; - int pageSize = npAll[0].ndim == 1 ? npAll[0].shape.Shapes[0] : npAll[0].shape.DimOffset[0]; + int pageSize = npAll[0].ndim == 1 ? npAll[0].shape.Dimensions[0] : npAll[0].shape.DimOffset[0]; for (int i = 0; i < total; i++) { @@ -54,18 +57,17 @@ public NDArray hstack(params NDArray[] nps) } } - nd.Storage.SetData( list.ToArray()); - - int[] shapes = npAll[0].shape.Shapes.ToArray(); + int[] shapes = npAll[0].shape.Dimensions.ToArray(); if (shapes.Length == 1) shapes[0] *= npAll.Length; else shapes[1] *= npAll.Length; - nd.Storage.Shape = new Shape(shapes); + nd.Storage.Allocate(nd.Storage.DType,new Shape(shapes),2); + nd.Storage.SetData(list.ToArray()); + nd.Storage.ChangeTensorLayout(1); - } return nd; diff --git a/src/NumSharp.Core/Creation/NdArray.LinSpace.cs b/src/NumSharp.Core/Creation/NdArray.LinSpace.cs index fa037ece..4629ce71 100644 --- a/src/NumSharp.Core/Creation/NdArray.LinSpace.cs +++ b/src/NumSharp.Core/Creation/NdArray.LinSpace.cs @@ -66,71 +66,9 @@ public NDArray linspace(double start, double stop,int num, bool entdpoint = true } } - this.Storage.Shape = new Shape(doubleArray.Length); + this.Storage.Reshape(doubleArray.Length); return this; } } - public partial class NDArrayGeneric - { - public NDArrayGeneric linspace(double start, double stop,int num, bool entdpoint = true) - { - double steps = (stop - start)/((entdpoint) ? (double) num - 1.0 : (double) num); - - double[] doubleArray = new double[num]; - - for (int idx = 0; idx < doubleArray.Length;idx++) - doubleArray[idx] = start + idx * steps; - - Data = new T[doubleArray.Length]; - - switch (Data) - { - case int[] dataArray : - { - for(int idx = 0; idx < dataArray.Length;idx++) - dataArray[idx] = (int)doubleArray[idx]; - break; - } - case long[] dataArray : - { - for(int idx = 0; idx < dataArray.Length;idx++) - dataArray[idx] = (long) doubleArray[idx]; - break; - } - case double[] dataArray : - { - for(int idx = 0; idx < dataArray.Length;idx++) - dataArray[idx] = doubleArray[idx]; - break; - } - case float[] dataArray : - { - for(int idx = 0; idx < dataArray.Length;idx++) - dataArray[idx] = (float)doubleArray[idx]; - break; - } - case Complex[] dataArray : - { - for(int idx = 0; idx < dataArray.Length;idx++) - dataArray[idx] = (Complex)doubleArray[idx]; - break; - } - case Quaternion[] dataArray : - { - for(int idx = 0; idx < dataArray.Length;idx++) - dataArray[idx] = new Quaternion(new Vector3(0,0,0),(float)doubleArray[idx]); - break; - } - default : - { - throw new Exception("This method was not yet implemented for this type" + typeof(T).Name); - } - } - - this.Shape = new Shape(doubleArray.Length); - - return this; - } - } -} +} \ No newline at end of file diff --git a/src/NumSharp.Core/Creation/NdArray.Ones.cs b/src/NumSharp.Core/Creation/NdArray.Ones.cs index 55148e23..3b5ed96c 100644 --- a/src/NumSharp.Core/Creation/NdArray.Ones.cs +++ b/src/NumSharp.Core/Creation/NdArray.Ones.cs @@ -17,7 +17,9 @@ public NDArray ones(Type dtype = null, params int[] shapes) for (int idx = 0; idx < dataLength;idx++) dataArray.SetValue(1,idx); - this.Storage = NDStorage.CreateByShapeAndType(dtype,new Shape(shapes)); + this.Storage = new NDStorage(dtype); + this.Storage.Allocate(dtype,new Shape(shapes)); + this.Storage.SetData(dataArray); return this; diff --git a/src/NumSharp.Core/Creation/NdArray.ReShape.cs b/src/NumSharp.Core/Creation/NdArray.ReShape.cs index 90b78503..7f313922 100644 --- a/src/NumSharp.Core/Creation/NdArray.ReShape.cs +++ b/src/NumSharp.Core/Creation/NdArray.ReShape.cs @@ -10,108 +10,24 @@ public partial class NDArray { public NDArray reshape(Shape shape) { - return reshape(shape.Shapes.ToArray()); + return reshape(shape.Dimensions.ToArray()); } public NDArray reshape(params int[] shape) { var count = shape.Length; var idx = NDArray.FindNegativeIndex(shape); - if (idx == -1) - this.Storage.Shape = new Shape(shape); - else - this.Storage.Shape = new Shape(CalculateNegativeShape(idx, this.shape.Shapes.ToList(), shape)); - - return this; - } - private static int FindNegativeIndex(params int[] shape) - { - var count = shape.Length; - var negOne = false; - var indexOfNegOne = -1; - for (int i = 0; i < count; i++) - { - if (shape[i] == -1) - { - if (negOne) - throw new ArgumentException("Only allowed to pass one shape dimension as -1"); - - negOne = true; - indexOfNegOne = i; - } - } - return indexOfNegOne; - } - private static int[] CalculateNegativeShape(int negativeIndex, IList currentShape, params int[] shapeParams) - { - var currentShapeCount = currentShape.Count; - var shapeParamCount = shapeParams.Length; - var newShape = new List(); - var curShapeVolume = currentShape.Aggregate((x, y) => x * y); - if (negativeIndex > -1) - { - int x = shapeParams[0]; - int y = 0; - if (shapeParamCount >= 1) - y = shapeParams[1]; - if (shapeParamCount > 2) - throw new ArgumentException("We cannot currently handle reshapes of more than 2 dimensions"); + var pufferShape = this.Storage.Shape.Dimensions; - if (negativeIndex == 0 && shapeParamCount == 2) - { - var mod = curShapeVolume % y == 0; - if (!mod) - throw new ArgumentException($"Wrong Reshape. {curShapeVolume} is not evenly divisible by {y}"); - else - { - var a = curShapeVolume / y; - var b = y; - newShape.Add(a); - newShape.Add(b); - } - } - else if (negativeIndex == 1 && shapeParamCount == 2) - { - var mod = curShapeVolume % x == 0; - if (!mod) - throw new ArgumentException($"Wrong Reshape. {curShapeVolume} is not evenly divisible by {x}"); - else - { - var a = x; - var b = curShapeVolume / x; - newShape.Add(a); - newShape.Add(b); - } - } - } - else - return currentShape.ToArray(); - - return newShape.ToArray(); - } - - } - public partial class NDArrayGeneric - { - /// - /// Gives a new shape to an array without changing its data. - /// - /// - /// - public NDArrayGeneric reshape(params int[] shape) - { - var count = shape.Length; - var idx = FindNegativeIndex(shape); if (idx == -1) - this.Shape = new Shape(shape); + this.Storage.Reshape(shape); else - this.Shape = new Shape(CalculateNegativeShape(idx, this.Shape.Shapes.ToList(), shape)); + this.Storage.Reshape(CalculateNegativeShape(idx, this.shape.Dimensions.ToList(), shape)); return this; } - - private static int FindNegativeIndex(params int[] shape) + protected static int FindNegativeIndex(params int[] shape) { var count = shape.Length; var negOne = false; @@ -130,8 +46,7 @@ private static int FindNegativeIndex(params int[] shape) return indexOfNegOne; } - - private static int[] CalculateNegativeShape(int negativeIndex, IList currentShape, params int[] shapeParams) + protected static int[] CalculateNegativeShape(int negativeIndex, IList currentShape, params int[] shapeParams) { var currentShapeCount = currentShape.Count; var shapeParamCount = shapeParams.Length; @@ -178,5 +93,7 @@ private static int[] CalculateNegativeShape(int negativeIndex, IList curren return newShape.ToArray(); } + } } + \ No newline at end of file diff --git a/src/NumSharp.Core/Creation/NdArray.VStack.cs b/src/NumSharp.Core/Creation/NdArray.VStack.cs index 34ffafa0..f104871d 100644 --- a/src/NumSharp.Core/Creation/NdArray.VStack.cs +++ b/src/NumSharp.Core/Creation/NdArray.VStack.cs @@ -26,50 +26,18 @@ public NDArray vstack(params NDArray[] nps) np.Storage.SetData(list.ToArray()); - if (nps[0].shape.Shapes.Count == 1) + if (nps[0].shape.Dimensions.Length == 1) { - np.Storage.Shape = new Shape(new int[] { nps.Length +1, nps[0].shape.Shapes[0] }); + np.Storage.Reshape(new int[] { nps.Length +1, nps[0].shape.Dimensions[0] }); } else { - int[] shapes = nps[0].shape.Shapes.ToArray(); + int[] shapes = nps[0].shape.Dimensions.ToArray(); shapes[0] *= nps.Length + 1; - np.Storage.Shape = new Shape(shapes) ; - } - return np; - } - } - public static partial class NDArrayExtensions - { - /// - /// Stack arrays in sequence vertically (row wise). - /// - /// - /// - public static NDArrayGeneric VStack(this NDArrayGeneric np1, params NDArrayGeneric[] nps) - { - if (nps == null || nps.Length == 0) - throw new Exception("Input arrays can not be empty"); - List list = new List(); - NDArrayGeneric np = new NDArrayGeneric(); - foreach (NDArrayGeneric ele in nps) - { - if (nps[0].Shape != ele.Shape) - throw new Exception("Arrays mush have same shapes"); - list.AddRange(ele.Data); - } - np.Data = list.ToArray(); - if (nps[0].NDim == 1) - { - np.Shape = new Shape(new int[] { nps.Length, nps[0].Shape.Shapes[0] }); - } - else - { - int[] shapes = nps[0].Shape.Shapes.ToArray(); - shapes[0] *= nps.Length; - np.Shape = new Shape(shapes); + np.Storage.Reshape(shapes) ; } return np; } } + } diff --git a/src/NumSharp.Core/Creation/np.arange.cs b/src/NumSharp.Core/Creation/np.arange.cs index 44ac6ace..fec00df7 100644 --- a/src/NumSharp.Core/Creation/np.arange.cs +++ b/src/NumSharp.Core/Creation/np.arange.cs @@ -51,7 +51,7 @@ public static NDArray arange(int start, int stop, int step = 1) var nd = new NDArray(np.int32, new Shape(length)); - if(nd.Data() is int[] a) + if(nd.Storage.GetData() is int[] a) { for (int i = start; i < stop; i += step) a[index++] = i; diff --git a/src/NumSharp.Core/Creation/np.array.cs b/src/NumSharp.Core/Creation/np.array.cs index 65c844b1..7342bf47 100644 --- a/src/NumSharp.Core/Creation/np.array.cs +++ b/src/NumSharp.Core/Creation/np.array.cs @@ -17,7 +17,9 @@ public static NDArray array(Array array, Type dtype = null, int ndim = 1) if ((array.Rank == 1) && ( !array.GetType().GetElementType().IsArray )) { - nd.Storage = NDStorage.CreateByShapeAndType (dtype, new Shape(new int[] { array.Length })); + nd.Storage = new NDStorage(dtype); + nd.Storage.Allocate(dtype, new Shape(new int[] { array.Length }),1); + nd.Storage.SetData(array); } else @@ -39,31 +41,24 @@ public static NDArray array(System.Drawing.Bitmap image) System.Runtime.InteropServices.Marshal.Copy(bmpd.Scan0, bytes, 0, dataSize); image.UnlockBits(bmpd); - imageArray.Set(bytes); - imageArray.Storage.Shape = new Shape(new int[] { bmpd.Height, bmpd.Width, System.Drawing.Image.GetPixelFormatSize(image.PixelFormat) / 8 }); - + imageArray.Storage.Allocate(typeof(byte),new Shape(bmpd.Height, bmpd.Width, System.Drawing.Image.GetPixelFormatSize(image.PixelFormat) / 8),1); + imageArray.Storage.SetData(bytes); + return imageArray; } public static NDArray array(T[][] data) { - int size = data.Length * data[0].Length; - var all = new T[size]; - - int idx = 0; + var nd = new NDArray(typeof(T),data.Length,data[0].Length); + for (int row = 0; row < data.Length; row++) { for (int col = 0; col < data[row].Length; col++) { - all[idx] = data[row][col]; - idx++; + nd[row,col] = data[row][col]; } } - var nd = new NDArray(typeof(T)); - nd.Set(all.ToArray()); - nd.Storage.Shape = new Shape(new int[] { data.Length, data[0].Length }); - return nd; } } diff --git a/src/NumSharp.Core/Creation/np.asarray.cs b/src/NumSharp.Core/Creation/np.asarray.cs index 6ab9b423..ba7dfaac 100644 --- a/src/NumSharp.Core/Creation/np.asarray.cs +++ b/src/NumSharp.Core/Creation/np.asarray.cs @@ -12,29 +12,23 @@ public static partial class np public static NDArray asarray(double[] data, int ndim = 1) { var nd = new NDArray(typeof(double), data.Length); - nd.Storage.Set(data); - return nd; - } - - public static NDArray asarray(float data) - { - var nd = new NDArray(typeof(float), 1); - nd.Storage.Set(new float[] { data }); + nd.Storage.SetData(data); return nd; } public static NDArray asarray(float[] data, int ndim = 1) { var nd = new NDArray(typeof(float), data.Length); - nd.Storage.Set(data); + nd.Storage.SetData(data); return nd; } - + /* public static NDArray asarray(matrix mx, int ndim = 1) { var nd = new NDArray(mx.dtype, mx.shape); nd.Storage = mx.Storage; return nd; } + */ } } diff --git a/src/NumSharp.Core/Creation/np.linspace.cs b/src/NumSharp.Core/Creation/np.linspace.cs index 59b865f1..0c6e4f8e 100644 --- a/src/NumSharp.Core/Creation/np.linspace.cs +++ b/src/NumSharp.Core/Creation/np.linspace.cs @@ -23,7 +23,7 @@ public static NDArray linspace(double start, double stop, int num, bool entdp doubleArray[idx] = start + idx * steps; var nd = new NDArray(typeof(T), doubleArray.Length); - nd.Set(doubleArray); + nd.Storage.SetData(doubleArray); return nd; } diff --git a/src/NumSharp.Core/Creation/np.ones.cs b/src/NumSharp.Core/Creation/np.ones.cs index 4a7a691a..4509c07a 100644 --- a/src/NumSharp.Core/Creation/np.ones.cs +++ b/src/NumSharp.Core/Creation/np.ones.cs @@ -42,15 +42,15 @@ public static NDArray ones(Shape shape, Type dtype = null) switch (dtype.Name) { case "Int32": - nd.Set(Enumerable.Range(0, nd.size).Select(x => 1).ToArray()); + nd.Storage.SetData(Enumerable.Range(0, nd.size).Select(x => 1).ToArray()); break; case "Double": - nd.Set(Enumerable.Range(0, nd.size).Select(x => 1.0).ToArray()); + nd.Storage.SetData(Enumerable.Range(0, nd.size).Select(x => 1.0).ToArray()); break; case "Boolean": - nd.Set(Enumerable.Range(0, nd.size).Select(x => true).ToArray()); + nd.Storage.SetData(Enumerable.Range(0, nd.size).Select(x => true).ToArray()); break; } diff --git a/src/NumSharp.Core/Creation/np.ones_like.cs b/src/NumSharp.Core/Creation/np.ones_like.cs index f83a909a..57984baa 100644 --- a/src/NumSharp.Core/Creation/np.ones_like.cs +++ b/src/NumSharp.Core/Creation/np.ones_like.cs @@ -9,7 +9,7 @@ public static partial class np { public static NDArray ones_like(NDArray nd, string order = "C") { - return np.ones(new Shape(nd.shape.Shapes)); + return np.ones(new Shape(nd.shape.Dimensions)); } } } diff --git a/src/NumSharp.Core/Creation/np.zeros.cs b/src/NumSharp.Core/Creation/np.zeros.cs index 3861d187..7ac92c51 100644 --- a/src/NumSharp.Core/Creation/np.zeros.cs +++ b/src/NumSharp.Core/Creation/np.zeros.cs @@ -21,7 +21,7 @@ public static NDArray zeros(params int[] shape) public static NDArray zeros(params int[] shape) { var nd = new NDArray(typeof(T)); - nd.Storage.Shape = new Shape(shape); + nd.Storage.Reshape(shape); return nd; } diff --git a/src/NumSharp.Core/Extensions/NdArray.ArgMax.cs b/src/NumSharp.Core/Extensions/NdArray.ArgMax.cs index bc4e0493..0a3e79a8 100644 --- a/src/NumSharp.Core/Extensions/NdArray.ArgMax.cs +++ b/src/NumSharp.Core/Extensions/NdArray.ArgMax.cs @@ -7,17 +7,11 @@ namespace NumSharp.Core.Extensions { public static partial class NDArrayExtensions { - public static int ArgMax(this NDArrayGeneric np ) + public static int ArgMax(this NDArray np ) { - var max = np.Data.Max(); + var max = np.Storage.GetData().Max(); - return np.Data.ToList().IndexOf(max); - } - public static int ArgMax(this NDArrayGeneric np ) - { - var max = np.Data.Max(); - - return np.Data.ToList().IndexOf(max); + return np.Storage.GetData().ToList().IndexOf(max); } } } diff --git a/src/NumSharp.Core/Extensions/NdArray.Normalize.cs b/src/NumSharp.Core/Extensions/NdArray.Normalize.cs index ba85c8b7..657bb8e1 100644 --- a/src/NumSharp.Core/Extensions/NdArray.Normalize.cs +++ b/src/NumSharp.Core/Extensions/NdArray.Normalize.cs @@ -14,13 +14,13 @@ public void normalize() if (ndim == 2) { - for (int col = 0; col < shape.Shapes[1]; col++) + for (int col = 0; col < shape.Dimensions[1]; col++) { - double der = max.Data(col) - min.Data(col); - for (int row = 0; row < shape.Shapes[0]; row++) + double der = max.Storage.GetData(col) - min.Storage.GetData(col); + for (int row = 0; row < shape.Dimensions[0]; row++) { - this[row, col] = (Data(row, col) - min.Data(col)) / der; + this[row, col] = (Storage.GetData(row, col) - min.Storage.GetData(col)) / der; } } } diff --git a/src/NumSharp.Core/Extensions/NdArray.Unique.cs b/src/NumSharp.Core/Extensions/NdArray.Unique.cs index 41e79610..6365a4bf 100644 --- a/src/NumSharp.Core/Extensions/NdArray.Unique.cs +++ b/src/NumSharp.Core/Extensions/NdArray.Unique.cs @@ -10,9 +10,10 @@ public partial class NDArray public NDArray unique() { var nd = new NDArray(dtype); - var data = Data().Distinct().ToArray(); - nd.Set(data); - nd.Storage.Shape = new Shape(data.Length); + var data = Storage.GetData().Distinct().ToArray(); + nd.Storage.SetData(data); + + nd.Storage.Reshape(data.Length); return nd; } diff --git a/src/NumSharp.Core/Generics/NDArrayGeneric.cs b/src/NumSharp.Core/Generics/NDArrayGeneric.cs index f464dc51..0974c724 100644 --- a/src/NumSharp.Core/Generics/NDArrayGeneric.cs +++ b/src/NumSharp.Core/Generics/NDArrayGeneric.cs @@ -24,6 +24,7 @@ using System.Globalization; using System.Collections; using NumSharp.Core; +using NumSharp.Core.Interfaces; namespace NumSharp.Generic { @@ -31,14 +32,19 @@ public class NDArray : NumSharp.Core.NDArray where T : struct { public NDArray() { - Storage.dtype = typeof(T); - Storage = NDStorage.CreateByShapeAndType(this.dtype,new Shape(1)); + Storage = new NDStorage(typeof(T)); + Storage.Allocate(this.dtype,new Shape(1),1); } - public NDArray(Shape shape) : this() + public NDArray(IShape shape) : this() { - Storage = NDStorage.CreateByShapeAndType(Storage.dtype, shape); + Storage = new NDStorage(typeof(T)); + Storage.Allocate(this.dtype, shape,1); } - public T this[params int[] select] + /// + /// indexing of generic - overridden on purpose + /// + /// + new public T this[params int[] select] { get { @@ -52,257 +58,4 @@ public T this[params int[] select] } } } - - -namespace NumSharp.Core -{ - /// - /// A powerful N-dimensional array object - /// Inspired from https://www.numpy.org/devdocs/user/quickstart.html - /// - /// dtype - [Obsolete("please use NDArray")] - public partial class NDArrayGeneric - { - /// - /// 1 dim array data storage - /// - public T[] Data { get; set; } - - private Shape shape; - /// - /// Data length of every dimension - /// - public Shape Shape - { - get - { - return shape; - } - set - { - shape = value; - } - } - - /// - /// Dimension count - /// - public int NDim => Shape.NDim; - - /// - /// Total of elements - /// - public int Size => Shape.Size; - - public NDArrayGeneric() - { - // set default shape as 1 dim and 0 elements. - Shape = new Shape(new int[] { 0 }); - } - - public void Set(Shape shape, T value) - { - if (shape.NDim == NDim) - { - throw new Exception("Please use NDArray[m, n] to access element."); - } - else - { - int start = GetIndexInShape(shape.Shapes.ToArray()); - int length = Shape.DimOffset[shape.NDim - 1]; - - Span data = Data; - var elements = data.Slice(start, length); - - for (int i = 0; i < elements.Length; i++) - { - elements[i] = value; - } - } - } - - public override string ToString() - { - string output = ""; - - if (this.NDim == 2) - { - output = this._ToMatrixString(); - } - else - { - output = this._ToVectorString(); - } - - return output; - } - - public override bool Equals(object obj) - { - return Data[0].Equals(obj); - } - - public static bool operator ==(NDArrayGeneric np, object obj) - { - return np.Data[0].Equals(obj); - } - - public static bool operator !=(NDArrayGeneric np, object obj) - { - return np.Data[0].Equals(obj); - } - - public override int GetHashCode() - { - unchecked - { - var result = 1337; - result = (result * 397) ^ this.NDim; - result = (result * 397) ^ this.Size; - return result; - } - } - - public TCast ToDotNetArray() - { - dynamic dotNetArray = null; - switch (this.NDim) - { - case 1 : dotNetArray = new T[this.Shape.Shapes[0]].ToArray();break; - case 2 : dotNetArray = new T[this.Shape.Shapes[0]][].Select(x => new T[this.Shape.Shapes[1]].ToArray()).ToArray();break; - case 3 : dotNetArray = new T[this.Shape.Shapes[0]][][].Select(x => new T[this.Shape.Shapes[1]][].Select(y => new T[this.Shape.Shapes[2]].ToArray().ToArray()).ToArray()).ToArray();break; - } - - switch (this.NDim) - { - case 1 : - { - dotNetArray = this.Data.ToArray(); - break; - } - case 2 : - { - for(int idx = 0; idx < this.Shape.Shapes[0];idx++) - { - for(int jdx = 0; jdx < this.Shape.Shapes[1];jdx++) - { - dotNetArray[idx][jdx] = this[idx,jdx]; - } - } - break; - } - case 3 : - { - for(int idx = 0; idx < this.Shape.Shapes[0];idx++) - { - for(int jdx = 0; jdx < this.Shape.Shapes[1];jdx++) - { - for(int kdx = 0; kdx < this.Shape.Shapes[2];kdx++) - { - dotNetArray[idx][jdx][kdx] = this[idx,jdx,kdx]; - } - } - } - break; - } - } - TCast castedDotNetArray = (TCast)dotNetArray; - return castedDotNetArray; - } - protected string _ToVectorString() - { - string returnValue = "array(["; - - int digitBefore = 0; - int digitAfter = 0; - - var dataParsed = Data.Select(x => _ParseNumber(x,ref digitBefore,ref digitAfter)).ToArray(); - - string elementFormatStart = "{0:"; - - string elementFormatEnd = ""; - for(int idx = 0; idx < digitAfter;idx++) - elementFormatEnd += "0"; - - elementFormatEnd += "}"; - - int missingDigits; - string elementFormat; - - for (int idx = 0; idx < (Data.Length-1);idx++) - { - missingDigits = digitBefore - dataParsed[idx].Replace(" ","").Split('.')[0].Length; - - elementFormat = elementFormatStart + new string(Enumerable.Repeat(' ',missingDigits).ToArray()) + "0." + elementFormatEnd; - - returnValue += (String.Format(new CultureInfo("en-us"),elementFormat, Data[idx]) + ", "); - } - missingDigits = digitBefore - dataParsed.Last().Replace(" ","").Split('.')[0].Length; - - elementFormat = elementFormatStart + new string(Enumerable.Repeat(' ',missingDigits).ToArray()) + "." + elementFormatEnd; - - returnValue += (String.Format(new CultureInfo("en-us"),elementFormat, Data.Last()) + "])"); - - return returnValue; - } - protected string _ToMatrixString() - { - string returnValue = "array([["; - - int digitBefore = 0; - int digitAfter = 0; - - var dataParsed = Data.Select(x => _ParseNumber(x,ref digitBefore,ref digitAfter)).ToArray(); - - string elementFormatStart = "{0:"; - - string elementFormatEnd = ""; - for(int idx = 0; idx < digitAfter;idx++) - elementFormatEnd += "0"; - - elementFormatEnd += "}"; - - int missingDigits; - string elementFormat; - - for (int idx = 0; idx < (Data.Length-1);idx++) - { - missingDigits = digitBefore - dataParsed[idx].Replace(" ","").Split('.')[0].Length; - - elementFormat = elementFormatStart + new string(Enumerable.Repeat(' ',missingDigits).ToArray()) + "0." + elementFormatEnd; - - if( ((idx+1) % Shape.Shapes[1] ) == 0 ) - { - returnValue += (String.Format(new CultureInfo("en-us"),elementFormat, Data[idx]) + "], \n ["); - } - else - { - returnValue += (String.Format(new CultureInfo("en-us"),elementFormat, Data[idx]) + ", "); - } - - } - missingDigits = digitBefore - dataParsed.Last().Replace(" ","").Split('.')[0].Length; - - elementFormat = elementFormatStart + new string(Enumerable.Repeat(' ',missingDigits).ToArray()) + "." + elementFormatEnd; - - returnValue += (String.Format(new CultureInfo("en-us"),elementFormat, Data.Last()) + "]])"); - - return returnValue; - } - protected string _ParseNumber(T number, ref int noBefore,ref int noAfter) - { - string parsed = string.Format(new CultureInfo("en-us"),"{0:0.00000000}",number); - - parsed = (parsed.StartsWith("-")) ? parsed : (" " + parsed); - - int noBefore_local = parsed.Split('.')[0].Length; - int noAfter_local = parsed.Split('.')[1].ToCharArray().Reverse().SkipWhile(x => x == '0').ToArray().Length; - - noBefore = (noBefore_local > noBefore) ? noBefore_local : noBefore; - noAfter = (noAfter_local > noAfter ) ? noAfter_local : noAfter; - - return parsed; - } - } -} + \ No newline at end of file diff --git a/src/NumSharp.Core/LinearAlgebra/NdArray.Dot.cs b/src/NumSharp.Core/LinearAlgebra/NdArray.Dot.cs index 8defb6db..abc29b73 100644 --- a/src/NumSharp.Core/LinearAlgebra/NdArray.Dot.cs +++ b/src/NumSharp.Core/LinearAlgebra/NdArray.Dot.cs @@ -20,30 +20,39 @@ public NDArray dot(NDArray nd2) { var pufferShape = nd2.Storage.Shape; + // in case must do a reshape + var oldStorage1 = this.Storage; + var oldStorage2 = nd2.Storage; + if ((this.shape.NDim == 1 ) & (nd2.shape.NDim == 1)) - if (this.shape.Shapes[0] != nd2.shape.Shapes[0]) + if (this.shape.Dimensions[0] != nd2.shape.Dimensions[0]) throw new IncorrectShapeException(); else { - nd2.Storage.Shape = new Shape(nd2.Storage.GetData().Length,1); - this.Storage.Shape = new Shape(1,this.Storage.GetData().Length); + this.Storage = new NDStorage(); + this.Storage.Allocate(oldStorage1.DType,new Shape(1,oldStorage1.GetData().Length),1); + this.Storage.SetData(oldStorage1.GetData()); + + nd2.Storage = new NDStorage(); + nd2.Storage.Allocate(oldStorage2.DType, new Shape(oldStorage2.GetData().Length,1),1); + nd2.Storage.SetData(oldStorage2.GetData()); } else - if (this.shape.Shapes[1] != nd2.shape.Shapes[0]) + if (this.shape.Dimensions[1] != nd2.shape.Dimensions[0]) throw new IncorrectShapeException(); if ((shape.NDim == 2) & (nd2.shape.NDim == 1)) { - var pufferList = pufferShape.Shapes.ToList(); + var pufferList = pufferShape.Dimensions.ToList(); pufferList.Add(1); - nd2.Storage.Shape = new Shape(pufferList.ToArray()); + nd2.Storage.Reshape(pufferList.ToArray()); } - int iterator = this.shape.Shapes[1]; - int dim0 = this.shape.Shapes[0]; - int dim1 = nd2.shape.Shapes[1]; + int iterator = this.shape.Dimensions[1]; + int dim0 = this.shape.Dimensions[0]; + int dim1 = nd2.shape.Dimensions[1]; - var prod = new NDArray(this.Storage.dtype, dim0, dim1); + var prod = new NDArray(this.Storage.DType, dim0, dim1); Array nd1SystemArray = this.Storage.GetData(); @@ -56,11 +65,11 @@ public NDArray dot(NDArray nd2) for (int idx = 0; idx < prod.size; idx++) { - int puffer1 = idx / dim1; - int puffer2 = idx % dim1; - int puffer3 = puffer1 * iterator; + int puffer1 = idx % dim0; + int puffer2 = idx / dim0; + int puffer3 = puffer2 * iterator; for (int kdx = 0; kdx < iterator; kdx++) - result[idx] += nd1Array[puffer3 + kdx] * nd2Array[dim1 * kdx + puffer2]; + result[idx] += nd2Array[puffer3 + kdx] * nd1Array[dim0 * kdx + puffer1]; } break; } @@ -71,11 +80,11 @@ public NDArray dot(NDArray nd2) for (int idx = 0; idx < prod.size; idx++) { - int puffer1 = idx / dim1; - int puffer2 = idx % dim1; - int puffer3 = puffer1 * iterator; + int puffer1 = idx % dim0; + int puffer2 = idx / dim0; + int puffer3 = puffer2 * iterator; for (int kdx = 0; kdx < iterator; kdx++) - result[idx] += nd1Array[puffer3 + kdx] * nd2Array[dim1 * kdx + puffer2]; + result[idx] += nd2Array[puffer3 + kdx] * nd1Array[dim0 * kdx + puffer1]; } break; } @@ -86,11 +95,11 @@ public NDArray dot(NDArray nd2) for (int idx = 0; idx < prod.size; idx++) { - int puffer1 = idx / dim1; - int puffer2 = idx % dim1; - int puffer3 = puffer1 * iterator; + int puffer1 = idx % dim0; + int puffer2 = idx / dim0; + int puffer3 = puffer2 * iterator; for (int kdx = 0; kdx < iterator; kdx++) - result[idx] += nd1Array[puffer3 + kdx] * nd2Array[dim1 * kdx + puffer2]; + result[idx] += nd2Array[puffer3 + kdx] * nd1Array[dim0 * kdx + puffer1]; } break; } @@ -101,11 +110,11 @@ public NDArray dot(NDArray nd2) for (int idx = 0; idx < prod.size; idx++) { - int puffer1 = idx / dim1; - int puffer2 = idx % dim1; - int puffer3 = puffer1 * iterator; + int puffer1 = idx % dim0; + int puffer2 = idx / dim0; + int puffer3 = puffer2 * iterator; for (int kdx = 0; kdx < iterator; kdx++) - result[idx] += nd1Array[puffer3 + kdx] * nd2Array[dim1 * kdx + puffer2]; + result[idx] += nd2Array[puffer3 + kdx] * nd1Array[dim0 * kdx + puffer1]; } break; } @@ -116,11 +125,11 @@ public NDArray dot(NDArray nd2) for (int idx = 0; idx < prod.size; idx++) { - int puffer1 = idx / dim1; - int puffer2 = idx % dim1; - int puffer3 = puffer1 * iterator; + int puffer1 = idx % dim0; + int puffer2 = idx / dim0; + int puffer3 = puffer2 * iterator; for (int kdx = 0; kdx < iterator; kdx++) - result[idx] += nd1Array[puffer3 + kdx] * nd2Array[dim1 * kdx + puffer2]; + result[idx] += nd2Array[puffer3 + kdx] * nd1Array[dim0 * kdx + puffer1]; } break; } @@ -132,12 +141,13 @@ public NDArray dot(NDArray nd2) if ((this.shape.NDim == 1 ) & (nd2.shape.NDim == 1)) { - this.Storage.Shape = new Shape(this.Storage.GetData().Length); - nd2.Storage.Shape = new Shape(nd2.Storage.GetData().Length); - prod.Storage.Shape = new Shape(1); + this.Storage.Reshape(this.Storage.GetData().Length); + nd2.Storage.Reshape(nd2.Storage.GetData().Length); + prod.Storage.Reshape(1); } - nd2.Storage.Shape = pufferShape; + this.Storage = oldStorage1; + nd2.Storage = oldStorage2; return prod; } diff --git a/src/NumSharp.Core/LinearAlgebra/NdArray.Inv.cs b/src/NumSharp.Core/LinearAlgebra/NdArray.Inv.cs index 66b19072..fca6eebe 100644 --- a/src/NumSharp.Core/LinearAlgebra/NdArray.Inv.cs +++ b/src/NumSharp.Core/LinearAlgebra/NdArray.Inv.cs @@ -11,20 +11,20 @@ public partial class NDArray { public NDArray inv() { - var npInv = new NDArray(this.Storage.dtype,this.shape); + var npInv = new NDArray(this.Storage.DType,this.shape); Array matrixStorage = this.Storage.GetData(); - Array invStorage = Array.CreateInstance(npInv.Storage.dtype,matrixStorage.Length); + Array invStorage = Array.CreateInstance(npInv.Storage.DType,matrixStorage.Length); switch (matrixStorage) { case double[] np : { - double[][] matrix = new double[this.Storage.Shape[0]][]; + double[][] matrix = new double[this.Storage.Shape.Dimensions[0]][]; for (int idx = 0; idx < matrix.Length;idx++) { - matrix[idx] = new double[this.Storage.Shape[1]]; + matrix[idx] = new double[this.Storage.Shape.Dimensions[1]]; for (int jdx = 0; jdx < matrix[idx].Length;jdx++) matrix[idx][jdx] = np[this.Storage.Shape.GetIndexInShape(idx,jdx)]; } @@ -32,9 +32,9 @@ public NDArray inv() double[][] matrixInv = MatrixInv.InverseMatrix(matrix); double[] invArray = invStorage as double[]; - for (int idx = 0; idx < npInv.shape.Shapes[0]; idx++) + for (int idx = 0; idx < npInv.shape.Dimensions[0]; idx++) { - for (int jdx = 0; jdx < npInv.shape.Shapes[1]; jdx++) + for (int jdx = 0; jdx < npInv.shape.Dimensions[1]; jdx++) { invArray[this.Storage.Shape.GetIndexInShape(idx,jdx)] = matrixInv[idx][jdx]; } diff --git a/src/NumSharp.Core/LinearAlgebra/NdArray.LstSq.cs b/src/NumSharp.Core/LinearAlgebra/NdArray.LstSq.cs index a8aca4e1..d309031a 100644 --- a/src/NumSharp.Core/LinearAlgebra/NdArray.LstSq.cs +++ b/src/NumSharp.Core/LinearAlgebra/NdArray.LstSq.cs @@ -18,10 +18,10 @@ public NDArray lstqr(NDArray nDArrayB, double rcon = 0.0001) var A = (double[]) AT.Storage.GetData().Clone(); var b = (double[]) bT.Storage.GetData().Clone(); - int m = this.shape.Shapes[0]; - int n = this.shape.Shapes[1]; + int m = this.shape.Dimensions[0]; + int n = this.shape.Dimensions[1]; - int nrhs = nDArrayB.shape.Shapes[1]; + int nrhs = nDArrayB.shape.Dimensions[1]; int lda = m; int ldb = m; diff --git a/src/NumSharp.Core/LinearAlgebra/NdArray.QR.cs b/src/NumSharp.Core/LinearAlgebra/NdArray.QR.cs index 62a8ac5d..d3ea9074 100644 --- a/src/NumSharp.Core/LinearAlgebra/NdArray.QR.cs +++ b/src/NumSharp.Core/LinearAlgebra/NdArray.QR.cs @@ -13,8 +13,8 @@ public partial class NDArray { var a = (double[]) this.Storage.GetData().Clone(); - int m = this.Storage.Shape.Shapes[0]; - int n = this.Storage.Shape.Shapes[1]; + int m = this.Storage.Shape.Dimensions[0]; + int n = this.Storage.Shape.Dimensions[1]; int lda = m; @@ -31,7 +31,7 @@ public partial class NDArray for(int idx = 0; idx < n; idx++) for(int jdx = idx;jdx < n;jdx++) - RDouble[n*idx+jdx] = a[idx+jdx*n]; + RDouble[idx+jdx * n] = a[idx+jdx*n]; var R = new NDArray(typeof(double),n,n); @@ -44,7 +44,9 @@ public partial class NDArray var Q = new NDArray(typeof(double),tau.Length,tau.Length); + Q.Storage.Allocate(Q.Storage.DType,Q.Storage.Shape,2); Q.Storage.SetData(a); + Q.Storage.ChangeTensorLayout(1); return (Q,R); } diff --git a/src/NumSharp.Core/LinearAlgebra/NdArray.Transpose.cs b/src/NumSharp.Core/LinearAlgebra/NdArray.Transpose.cs index 0378f1d6..4954066b 100644 --- a/src/NumSharp.Core/LinearAlgebra/NdArray.Transpose.cs +++ b/src/NumSharp.Core/LinearAlgebra/NdArray.Transpose.cs @@ -11,16 +11,17 @@ public partial class NDArray { public NDArray transpose() { - var nd = new NDArray(dtype, new Shape(this.Storage.Shape.Shapes.Reverse().ToArray())); + var nd = new NDArray(dtype, new Shape(this.Storage.Shape.Dimensions.Reverse().ToArray())); if (ndim == 1) { - nd.Storage = NDStorage.CreateByShapeAndType(dtype, new Shape(1, shape.Shapes[0])); + nd.Storage = new NDStorage(dtype); + nd.Storage.Allocate(dtype, new Shape(1, shape.Dimensions[0]),1); } else if (ndim == 2) { - for (int idx = 0; idx < nd.shape.Shapes[0]; idx++) - for (int jdx = 0; jdx < nd.shape.Shapes[1]; jdx++) + for (int idx = 0; idx < nd.shape.Dimensions[0]; idx++) + for (int jdx = 0; jdx < nd.shape.Dimensions[1]; jdx++) nd[idx, jdx] = this[jdx, idx]; } else @@ -32,26 +33,4 @@ public NDArray transpose() } } - public partial class NDArrayGeneric - { - public NDArrayGeneric transpose() - { - var np = new NDArrayGeneric(); - np.Data = new T[this.Data.Length]; - - if (NDim == 1) - { - np.Shape = new Shape(1,Shape.Shapes[0]); - } - else - { - np.Shape = new Shape(this.Shape.Shapes.Reverse().ToArray()); - for (int idx = 0;idx < np.shape.Shapes[0];idx++) - for (int jdx = 0;jdx < np.shape.Shapes[1];jdx++) - np[idx,jdx] = this[jdx,idx]; - } - - return np; - } - } } diff --git a/src/NumSharp.Core/LinearAlgebra/NdArray.multi_dot.cs b/src/NumSharp.Core/LinearAlgebra/NdArray.multi_dot.cs index 7ed1f474..ee9032ff 100644 --- a/src/NumSharp.Core/LinearAlgebra/NdArray.multi_dot.cs +++ b/src/NumSharp.Core/LinearAlgebra/NdArray.multi_dot.cs @@ -21,15 +21,15 @@ public NDArray multi_dot(params NDArray[] np2Multi) var np2 = np2Multi.Last(); if ((this.shape.NDim == 1 ) & (np2.shape.NDim == 1)) - if (this.shape.Shapes[0] != np2.shape.Shapes[0]) + if (this.shape.Dimensions[0] != np2.shape.Dimensions[0]) throw new IncorrectShapeException(); else { - np2.Storage.Shape = new Shape(np2.Storage.GetData().Length,1); - this.Storage.Shape = new Shape(1,this.Storage.GetData().Length); + np2.Storage.Reshape(np2.Storage.GetData().Length,1); + this.Storage.Reshape(1,this.Storage.GetData().Length); } else - if (this.shape.Shapes[1] != np2.shape.Shapes[0]) + if (this.shape.Dimensions[1] != np2.shape.Dimensions[0]) throw new IncorrectShapeException(); var prod = this.dot(np2Multi[0]); diff --git a/src/NumSharp.Core/Manipulation/NdArray.delete.cs b/src/NumSharp.Core/Manipulation/NdArray.delete.cs index b6aecb08..29b0b585 100644 --- a/src/NumSharp.Core/Manipulation/NdArray.delete.cs +++ b/src/NumSharp.Core/Manipulation/NdArray.delete.cs @@ -9,7 +9,7 @@ public partial class NDArray { public NDArray ravel() { - Storage.Shape = new Shape(shape.Size); + Storage.Reshape(shape.Size); return this; } } diff --git a/src/NumSharp.Core/Manipulation/np.ravel.cs b/src/NumSharp.Core/Manipulation/np.ravel.cs index 668f4425..59cb835a 100644 --- a/src/NumSharp.Core/Manipulation/np.ravel.cs +++ b/src/NumSharp.Core/Manipulation/np.ravel.cs @@ -13,10 +13,10 @@ public NDArray ravel(matrix mx) switch (mx.dtype.Name) { case "Double": - nd.Set(mx.float64); + nd.Storage.SetData(mx.Storage.GetData()); break; case "Int32": - nd.Set(mx.int32); + nd.Storage.SetData(mx.Storage.GetData()); break; } diff --git a/src/NumSharp.Core/Manipulation/np.transpose.cs b/src/NumSharp.Core/Manipulation/np.transpose.cs index 530436a0..449644a8 100644 --- a/src/NumSharp.Core/Manipulation/np.transpose.cs +++ b/src/NumSharp.Core/Manipulation/np.transpose.cs @@ -15,13 +15,13 @@ public static NDArray transpose(NDArray nd) if (nd.ndim == 1) { - np.Storage.Shape = new Shape(1, np.shape.Shapes[0]); + np.Storage.Reshape(1, np.shape.Dimensions[0]); } else { - np.Storage.Shape = new Shape(np.shape.Shapes.Reverse().ToArray()); - for (int idx = 0;idx < np.shape.Shapes[0];idx++) - for (int jdx = 0;jdx < np.shape.Shapes[1];jdx++) + np.Storage.Reshape(np.shape.Dimensions.Reverse().ToArray()); + for (int idx = 0;idx < np.shape.Dimensions[0];idx++) + for (int jdx = 0;jdx < np.shape.Dimensions[1];jdx++) np[idx,jdx] = nd[jdx,idx]; } diff --git a/src/NumSharp.Core/Manipulation/np.vstack.cs b/src/NumSharp.Core/Manipulation/np.vstack.cs index 0441a643..b2a3065d 100644 --- a/src/NumSharp.Core/Manipulation/np.vstack.cs +++ b/src/NumSharp.Core/Manipulation/np.vstack.cs @@ -22,18 +22,18 @@ public static NDArray vstack(params NDArray[] nps) { if (nps[0].shape != ele.shape) throw new Exception("Arrays mush have same shapes"); - list.AddRange(ele.Data()); + list.AddRange(ele.Storage.GetData()); } - np.Set(list.ToArray()); + np.Storage.SetData(list.ToArray()); if (nps[0].ndim == 1) { - np.Storage.Shape = new Shape(new int[] { nps.Length, nps[0].shape.Shapes[0] }); + np.Storage.Reshape(new int[] { nps.Length, nps[0].shape.Dimensions[0] }); } else { - int[] shapes = nps[0].shape.Shapes.ToArray(); + int[] shapes = nps[0].shape.Dimensions.ToArray(); shapes[0] *= nps.Length; - np.Storage.Shape = new Shape(shapes); + np.Storage.Reshape(shapes); } return np; } diff --git a/src/NumSharp.Core/Math/NDArray.argmax.cs b/src/NumSharp.Core/Math/NDArray.argmax.cs index 4d5bec17..1b3f04a6 100644 --- a/src/NumSharp.Core/Math/NDArray.argmax.cs +++ b/src/NumSharp.Core/Math/NDArray.argmax.cs @@ -51,9 +51,9 @@ public int argmax() public int argmax() { - var max = Data().Max(); + var max = Storage.GetData().Max(); - return Data().ToList().IndexOf(max); + return Storage.GetData().ToList().IndexOf(max); } } } diff --git a/src/NumSharp.Core/Math/NdArray.Convolve.cs b/src/NumSharp.Core/Math/NdArray.Convolve.cs index f8ef2ef1..adbc8839 100644 --- a/src/NumSharp.Core/Math/NdArray.Convolve.cs +++ b/src/NumSharp.Core/Math/NdArray.Convolve.cs @@ -17,8 +17,8 @@ public partial class NDArray /// public NDArray Convolve(NDArray numSharpArray2, string mode = "full" ) { - int nf = this.shape.Shapes[0]; - int ng = numSharpArray2.shape.Shapes[0]; + int nf = this.shape.Dimensions[0]; + int ng = numSharpArray2.shape.Dimensions[0]; if (shape.NDim > 1) throw new IncorrectShapeException(); @@ -47,7 +47,8 @@ public NDArray Convolve(NDArray numSharpArray2, string mode = "full" ) } } - numSharpReturn.Storage = NDStorage.CreateByShapeAndType(numSharpReturn.dtype, new Shape(outArray.Length)); + numSharpReturn.Storage = new NDStorage(); + numSharpReturn.Storage.Allocate(numSharpReturn.dtype, new Shape(outArray.Length)); numSharpReturn.Storage.SetData(outArray); break; @@ -72,7 +73,8 @@ public NDArray Convolve(NDArray numSharpArray2, string mode = "full" ) } } - numSharpReturn.Storage = NDStorage.CreateByShapeAndType(numSharpReturn.dtype, new Shape(outArray.Length)); + numSharpReturn.Storage = new NDStorage(); + numSharpReturn.Storage.Allocate(numSharpReturn.dtype, new Shape(outArray.Length),1); numSharpReturn.Storage.SetData(outArray); break; @@ -82,7 +84,7 @@ public NDArray Convolve(NDArray numSharpArray2, string mode = "full" ) // followed the discussion on // https://stackoverflow.com/questions/38194270/matlab-convolution-same-to-numpy-convolve // implemented numpy convolve because we follow numpy - var npad = numSharpArray2.shape.Shapes[0] - 1; + var npad = numSharpArray2.shape.Dimensions[0] - 1; double[] np1New = null; diff --git a/src/NumSharp.Core/Math/NdArray.Mean.cs b/src/NumSharp.Core/Math/NdArray.Mean.cs index b94e9201..fd133ad2 100644 --- a/src/NumSharp.Core/Math/NdArray.Mean.cs +++ b/src/NumSharp.Core/Math/NdArray.Mean.cs @@ -23,43 +23,43 @@ public static NDArray mean(this NDArray np, int axis = -1) // to compute mean by compressing row and row else if (axis == 0) { - double[] sumVec = new double[np.shape.Shapes[0]]; + double[] sumVec = new double[np.shape.Dimensions[0]]; for (int d = 0; d < sumVec.Length; d++) { - for (int p = 0; p < np.shape.Shapes[1]; p++) + for (int p = 0; p < np.shape.Dimensions[1]; p++) { sumVec[p] += Convert.ToDouble(np[d,p]); } } var puffer = mean.Storage.GetData().ToList(); - for (int d = 0; d < np.shape.Shapes[1]; d++) + for (int d = 0; d < np.shape.Dimensions[1]; d++) { - puffer.Add(sumVec[d] / np.shape.Shapes[0]); + puffer.Add(sumVec[d] / np.shape.Dimensions[0]); } mean.Storage.SetData(puffer.ToArray()); - mean.Storage.Shape = new Shape(mean.Storage.GetData().Length); + mean.Storage.Reshape(mean.Storage.GetData().Length); } else if (axis == 1) { var puffer = mean.Storage.GetData().ToList(); - for (int d = 0; d < np.shape.Shapes[0]; d++) + for (int d = 0; d < np.shape.Dimensions[0]; d++) { double rowSum = 0; - for (int p = 0; p < np.shape.Shapes[1]; p++) + for (int p = 0; p < np.shape.Dimensions[1]; p++) { rowSum += Convert.ToDouble(np[d,p]); } - puffer.Add(rowSum / np.shape.Shapes[1]); + puffer.Add(rowSum / np.shape.Dimensions[1]); } mean.Storage.SetData(puffer.ToArray()); - mean.Storage.Shape = new Shape(mean.Storage.GetData().Length); + mean.Storage.Reshape(mean.Storage.GetData().Length); } return mean; diff --git a/src/NumSharp.Core/Math/NdArray.log.cs b/src/NumSharp.Core/Math/NdArray.log.cs index ad300afa..09e6fe46 100644 --- a/src/NumSharp.Core/Math/NdArray.log.cs +++ b/src/NumSharp.Core/Math/NdArray.log.cs @@ -58,55 +58,4 @@ public NDArray log() return logArray; } } - public partial class NDArrayGeneric - { - public NDArrayGeneric log() - { - NDArrayGeneric logArray = new NDArrayGeneric(); - logArray.Data = new T[this.Data.Length]; - logArray.Shape = new Shape(this.Shape.Shapes); - - switch (logArray.Data) - { - case double[] logData : - { - double[] npData = this.Data as double[]; - - for (int idx = 0; idx < npData.Length;idx++) - { - logData[idx] = Math.Log(npData[idx]); - } - break; - } - case float[] logData : - { - double[] npData = this.Data as double[]; - - for (int idx = 0; idx < npData.Length;idx++) - { - // boxing necessary because Math.Sin just for double - logData[idx] = (float) Math.Log(npData[idx]); - } - break; - } - case Complex[] logData : - { - Complex[] npData = this.Data as Complex[]; - - for (int idx = 0; idx < npData.Length;idx++) - { - // boxing necessary because Math.Sin just for double - logData[idx] = Complex.Log( npData[idx]); - } - break; - } - default : - { - throw new Exception("The operation is not implemented for the"); - } - - } - return logArray; - } - } } diff --git a/src/NumSharp.Core/Math/np.power.cs b/src/NumSharp.Core/Math/np.power.cs index 42ba7563..d44559a9 100644 --- a/src/NumSharp.Core/Math/np.power.cs +++ b/src/NumSharp.Core/Math/np.power.cs @@ -16,7 +16,7 @@ public static NDArray power(NDArray nd, ValueType exponent) public static NDArray power(NDArray nd, T exponent) { var sinArray = new NDArray(nd.dtype); - sinArray.Storage.Shape = new Shape(nd.shape.Shapes); + sinArray.Storage.Reshape(nd.shape.Dimensions); switch (sinArray[0]) { diff --git a/src/NumSharp.Core/Matrix.cs b/src/NumSharp.Core/Matrix.cs index 6284494d..9d1bc92a 100644 --- a/src/NumSharp.Core/Matrix.cs +++ b/src/NumSharp.Core/Matrix.cs @@ -7,32 +7,15 @@ public partial class matrix: NDArray { public matrix(NDArray data, Type dtype = null) { - if (dtype == null) - { - dtype = data.dtype; - this.Storage.dtype = data.dtype; - } - - this.Storage.Shape = new Shape(data.shape.Shapes); - - switch (data.dtype.Name) - { - case "Double": - Set(data.float64); - break; - case "Int32": - Set(data.int32); - break; - case "Complex": - Set(data.complex128); - break; - } + this.Storage = data.Storage; } public matrix(string matrixString, Type dtype = null) { string[][] splitted = null; + dtype = (dtype == null) ? np.float64 : dtype; + if (matrixString.Contains(",")) { splitted = matrixString.Split(';') @@ -49,14 +32,9 @@ public matrix(string matrixString, Type dtype = null) int dim0 = splitted.Length; int dim1 = splitted[0].Length; - if (dtype == null) - { - dtype = typeof(double); - this.Storage.dtype = typeof(double); - } + var shape = new Shape( new int[] { dim0, dim1 }); - this.Storage.Shape = new Shape(new int[] { dim0, dim1 }); - this.Storage.Allocate(shape.Size); + this.Storage.Allocate(dtype,shape,1); switch (this.dtype.Name) { @@ -85,8 +63,8 @@ public override string ToString() { string returnValue = "matrix([["; - int dim0 = shape.Shapes[0]; - int dim1 = shape.Shapes[1]; + int dim0 = shape.Dimensions[0]; + int dim1 = shape.Dimensions[1]; for (int idx = 0; idx < (dim0-1);idx++) { diff --git a/src/NumSharp.Core/Operations/NDArray.Equals.cs b/src/NumSharp.Core/Operations/NDArray.Equals.cs index 41469dc6..ff0dc1a4 100644 --- a/src/NumSharp.Core/Operations/NDArray.Equals.cs +++ b/src/NumSharp.Core/Operations/NDArray.Equals.cs @@ -11,7 +11,7 @@ public partial class NDArray switch (obj) { case int o: - return o == np.Data()[0]; + return o == np.Storage.GetData()[0]; } return false; diff --git a/src/NumSharp.Core/Operations/NdArray.Addition.cs b/src/NumSharp.Core/Operations/NdArray.Addition.cs index 1fa69ddb..17e26d16 100644 --- a/src/NumSharp.Core/Operations/NdArray.Addition.cs +++ b/src/NumSharp.Core/Operations/NdArray.Addition.cs @@ -13,7 +13,7 @@ public partial class NDArray { NDArray sum = new NDArray(np1.dtype,np1.Storage.Shape); - if (!Enumerable.SequenceEqual(np1.Storage.Shape.Shapes,np2.Storage.Shape.Shapes)) + if (!Enumerable.SequenceEqual(np1.Storage.Shape.Dimensions,np2.Storage.Shape.Dimensions)) throw new IncorrectShapeException(); Array np1SysArr = np1.Storage.GetData(); @@ -169,112 +169,4 @@ public partial class NDArray } } - public partial class NDArrayGeneric - { - public static NDArrayGeneric operator +(NDArrayGeneric np1, NDArrayGeneric np2) - { - NDArrayGeneric sum = new NDArrayGeneric(); - sum.Shape = np1.Shape; - sum.Data = new T[np1.Data.Length]; - - switch (sum.Data) - { - case double[] sumArray : - { - double[] np1Array = np1.Data as double[]; - double[] np2Array = np2.Data as double[]; - // for is faster than linq - for (int idx = 0; idx < sumArray.Length;idx++) - sumArray[idx] = np1Array[idx] + np2Array[idx]; - break; - } - case float[] sumArray : - { - float[] np1Array = np1.Data as float[]; - float[] np2Array = np2.Data as float[]; - // for is faster than linq - for (int idx = 0; idx < sumArray.Length;idx++) - sumArray[idx] = np1Array[idx] + np2Array[idx]; - break; - } - case Complex[] sumArray : - { - Complex[] np1Array = np1.Data as Complex[]; - Complex[] np2Array = np2.Data as Complex[]; - // for is faster than linq - for (int idx = 0; idx < sumArray.Length;idx++) - sumArray[idx] = np1Array[idx] + np2Array[idx]; - break; - } - case Quaternion[] sumArray : - { - Quaternion[] np1Array = np1.Data as Quaternion[]; - Quaternion[] np2Array = np2.Data as Quaternion[]; - // for is faster than linq - for (int idx = 0; idx < sumArray.Length;idx++) - sumArray[idx] = np1Array[idx] + np2Array[idx]; - break; - } - default : - { - throw new Exception("The operation is not implemented for the " + typeof(T).Name); - } - } - - return (NDArrayGeneric) sum; - } - public static NDArrayGeneric operator +(NDArrayGeneric np1, T scalar) - { - NDArrayGeneric sum = new NDArrayGeneric(); - sum.Shape = np1.Shape; - sum.Data = new T[np1.Data.Length]; - - switch (scalar) - { - case double scalarDouble : - { - double[] np1Array = np1.Data as double[]; - double[] sumArray = sum.Data as double[]; - // for is faster than linq - for (int idx = 0; idx < sumArray.Length;idx++) - sumArray[idx] = np1Array[idx] + scalarDouble; - break; - } - case float scalarFloat : - { - float[] np1Array = np1.Data as float[]; - float[] sumArray = sum.Data as float[]; - // for is faster than linq - for (int idx = 0; idx < sumArray.Length;idx++) - sumArray[idx] = np1Array[idx] + scalarFloat; - break; - } - case Complex scalarComplex : - { - Complex[] np1Array = np1.Data as Complex[]; - Complex[] sumArray = sum.Data as Complex[]; - // for is faster than linq - for (int idx = 0; idx < sumArray.Length;idx++) - sumArray[idx] = np1Array[idx] + scalarComplex; - break; - } - case Quaternion scalarQuaternion : - { - Quaternion[] np1Array = np1.Data as Quaternion[]; - Quaternion[] sumArray = sum.Data as Quaternion[]; - // for is faster than linq - for (int idx = 0; idx < sumArray.Length;idx++) - sumArray[idx] = np1Array[idx] + scalarQuaternion; - break; - } - default : - { - throw new Exception("The operation is not implemented for the " + typeof(T).Name); - } - } - - return (NDArrayGeneric) sum; - } - - } } diff --git a/src/NumSharp.Core/Operations/NdArray.Division.cs b/src/NumSharp.Core/Operations/NdArray.Division.cs index 37a9a43c..ed9e6ee3 100644 --- a/src/NumSharp.Core/Operations/NdArray.Division.cs +++ b/src/NumSharp.Core/Operations/NdArray.Division.cs @@ -4,128 +4,169 @@ using System.Linq; using System.Text; using System.Numerics; -using NumSharp.Core.Shared; namespace NumSharp.Core { public partial class NDArray { - public static NDArray operator /(NDArray np1, NDArray np2) + public static NDArray operator /(NDArray np1, NDArray np2) { - var sum = new NDArray(np1.dtype, np1.shape); + NDArray div = new NDArray(np1.dtype,np1.Storage.Shape); - switch (sum.dtype.Name) + if (!Enumerable.SequenceEqual(np1.Storage.Shape.Dimensions,np2.Storage.Shape.Dimensions)) + throw new IncorrectShapeException(); + + Array np1SysArr = np1.Storage.GetData(); + Array np2SysArr = np2.Storage.GetData(); + Array np3SysArr = div.Storage.GetData(); + + switch (np3SysArr) { - case "Double": + case double[] divArray : { - double[] np1Array = np1.Data(); - double[] np2Array = np2.Data(); + double[] np1Array = np1SysArr as double[]; + double[] np2Array = np2SysArr as double[]; // for is faster than linq - for (int idx = 0; idx < sum.size;idx++) - sum[idx] = np1Array[idx] / np2Array[idx]; + for (int idx = 0; idx < divArray.Length;idx++) + divArray[idx] = np1Array[idx] / np2Array[idx]; break; } - /*case float[] sumArray : + case float[] divArray : { - float[] np1Array = np1.Data(); - float[] np2Array = np2.Data(); + float[] np1Array = np1SysArr as float[]; + float[] np2Array = np2SysArr as float[]; // for is faster than linq - for (int idx = 0; idx < sumArray.Length;idx++) - sumArray[idx] = np1Array[idx] / np2Array[idx]; + for (int idx = 0; idx < divArray.Length;idx++) + divArray[idx] = np1Array[idx] / np2Array[idx]; break; } - case Complex[] sumArray : + case int[] divArray : { - Complex[] np1Array = np1.Data(); - Complex[] np2Array = np2.Data(); + int[] np1Array = np1SysArr as int[]; + int[] np2Array = np2SysArr as int[]; // for is faster than linq - for (int idx = 0; idx < sumArray.Length;idx++) - sumArray[idx] = np1Array[idx] / np2Array[idx]; + for (int idx = 0; idx < divArray.Length;idx++) + divArray[idx] = np1Array[idx] / np2Array[idx]; break; } - case Quaternion[] sumArray : + case Int64[] divArray : { - Quaternion[] np1Array = np1.Data(); - Quaternion[] np2Array = np2.Data(); + Int64[] np1Array = np1SysArr as Int64[]; + Int64[] np2Array = np2SysArr as Int64[]; // for is faster than linq - for (int idx = 0; idx < sumArray.Length;idx++) - sumArray[idx] = np1Array[idx] / np2Array[idx]; + for (int idx = 0; idx < divArray.Length;idx++) + divArray[idx] = np1Array[idx] / np2Array[idx]; break; - }*/ + } + case Complex[] divArray : + { + Complex[] np1Array = np1SysArr as Complex[]; + Complex[] np2Array = np2SysArr as Complex[]; + // for is faster than linq + for (int idx = 0; idx < divArray.Length;idx++) + divArray[idx] = np1Array[idx] / np2Array[idx]; + break; + } + case Quaternion[] divArray : + { + Quaternion[] np1Array = np1SysArr as Quaternion[]; + Quaternion[] np2Array = np2SysArr as Quaternion[]; + // for is faster than linq + for (int idx = 0; idx < divArray.Length;idx++) + divArray[idx] = np1Array[idx] / np2Array[idx]; + break; + } default : { - throw new Exception("The operation is not implemented for the " + np1.dtype.Name); + throw new IncorrectTypeException(); } } - return sum; + return div; } - - public static NDArray operator /(NDArray np1, double scalar) + public static NDArray operator /(NDArray np1, ValueType scalar) { - var sum = new NDArray(np1.dtype, np1.shape); + NDArray div = new NDArray(np1.dtype,np1.shape); - switch (sum.dtype.Name) + Array np1SysArr = np1.Storage.GetData(); + Array divSysArr = div.Storage.GetData(); + + switch (divSysArr) { - case "Double": + case double[] divArr : { - // for is faster than linq - for (int idx = 0; idx < sum.size;idx++) - sum[idx] = sum.float64[idx] / scalar; + double scalar_ = Convert.ToDouble(scalar); + double[] np1Array = np1SysArr as double[]; + + for (int idx = 0;idx < np1Array.Length;idx++) + divArr[idx] = np1Array[idx] / scalar_; + break; } - /*case float[] np1Array: + case float[] divArr : { - // for is faster than linq - for (int idx = 0; idx < sum.Size;idx++) - sum[idx] = np1Array[idx] / scalar; - break; + float scalar_ = Convert.ToSingle(scalar); + float[] np1Array = np1SysArr as float[]; + + for (int idx = 0;idx < np1Array.Length;idx++) + divArr[idx] = np1Array[idx] / scalar_; + + break; } - case Complex[] np1Array: + case int[] divArr : { - // for is faster than linq - for (int idx = 0; idx < sum.Size;idx++) - sum[idx] = np1Array[idx] / scalar; - break; + int scalar_ = Convert.ToInt32(scalar); + int[] np1Array = np1SysArr as int[]; + + for (int idx = 0;idx < np1Array.Length;idx++) + divArr[idx] = np1Array[idx] / scalar_; + + break; } - case Quaternion[] np1Array: + case Int64[] divArr : { - // for is faster than linq - for (int idx = 0; idx < sum.Size;idx++) - sum[idx] = np1Array[idx] / scalar; - break; - }*/ + Int64 scalar_ = Convert.ToInt64(scalar); + Int64[] np1Array = np1SysArr as Int64[]; + + for (int idx = 0;idx < np1Array.Length;idx++) + divArr[idx] = np1Array[idx] / scalar_; + + break; + } + case Complex[] divArr : + { + Complex scalar_ = (Complex) scalar; + Complex[] np1Array = np1SysArr as Complex[]; + + for (int idx = 0;idx < np1Array.Length;idx++) + divArr[idx] = np1Array[idx] / scalar_; + + break; + } + case Quaternion[] divArr : + { + Quaternion scalar_ = (Quaternion) scalar; + Quaternion[] np1Array = np1SysArr as Quaternion[]; + + for (int idx = 0;idx < np1Array.Length;idx++) + divArr[idx] = np1Array[idx] / scalar_; + + break; + } default : { - throw new Exception("The operation is not implemented for the " + np1.dtype.Name); + throw new IncorrectTypeException(); } } - return sum; - } - - public static NDArray operator /(int scalar, NDArray np1) - { - return (double)scalar / np1; + + return div; } - + public static NDArray operator /(double scalar, NDArray np1) { - var nd = new NDArray(typeof(double), np1.shape); - - switch (np1.dtype.Name) - { - case "Double": - nd.Set(np1.float64.Select(x => scalar / x).ToArray()); - break; - case "Int32": - nd.Set(np1.int32.Select(x => scalar / x).ToArray()); - break; - } - - return nd; + return np1 / scalar; } - - } -} + +} \ No newline at end of file diff --git a/src/NumSharp.Core/Operations/NdArray.Multiplication.cs b/src/NumSharp.Core/Operations/NdArray.Multiplication.cs index ef392804..ef958f16 100644 --- a/src/NumSharp.Core/Operations/NdArray.Multiplication.cs +++ b/src/NumSharp.Core/Operations/NdArray.Multiplication.cs @@ -14,7 +14,7 @@ public partial class NDArray { NDArray sum = new NDArray(np1.dtype,np1.Storage.Shape); - if (!Enumerable.SequenceEqual(np1.Storage.Shape.Shapes,np2.Storage.Shape.Shapes)) + if (!Enumerable.SequenceEqual(np1.Storage.Shape.Dimensions,np2.Storage.Shape.Dimensions)) throw new IncorrectShapeException(); Array np1SysArr = np1.Storage.GetData(); @@ -142,7 +142,7 @@ public partial class NDArray { scalar_ = (Complex) scalar; } - catch (InvalidCastException e) + catch (InvalidCastException) { TypeCode tc = Type.GetTypeCode(scalar.GetType()) ; @@ -190,116 +190,5 @@ public partial class NDArray return np1 * scalar; } } - public partial class NDArrayGeneric - { - public static NDArrayGeneric operator *(NDArrayGeneric np1, NDArrayGeneric np2) - { - NDArrayGeneric sum = new NDArrayGeneric(); - sum.Shape = np1.Shape; - sum.Data = new T[np1.Data.Length]; - - switch (sum.Data) - { - case double[] sumArray : - { - double[] np1Array = np1.Data as double[]; - double[] np2Array = np2.Data as double[]; - // for is faster than linq - for (int idx = 0; idx < sumArray.Length;idx++) - sumArray[idx] = np1Array[idx] * np2Array[idx]; - break; - } - case float[] sumArray : - { - float[] np1Array = np1.Data as float[]; - float[] np2Array = np2.Data as float[]; - // for is faster than linq - for (int idx = 0; idx < sumArray.Length;idx++) - sumArray[idx] = np1Array[idx] * np2Array[idx]; - break; - } - case Complex[] sumArray : - { - Complex[] np1Array = np1.Data as Complex[]; - Complex[] np2Array = np2.Data as Complex[]; - // for is faster than linq - for (int idx = 0; idx < sumArray.Length;idx++) - sumArray[idx] = np1Array[idx] * np2Array[idx]; - break; - } - case Quaternion[] sumArray : - { - Quaternion[] np1Array = np1.Data as Quaternion[]; - Quaternion[] np2Array = np2.Data as Quaternion[]; - // for is faster than linq - for (int idx = 0; idx < sumArray.Length;idx++) - sumArray[idx] = np1Array[idx] * np2Array[idx]; - break; - } - default : - { - throw new Exception("The operation is not implemented for the " + typeof(T).Name); - } - } - - return (NDArrayGeneric) sum; - } - public static NDArrayGeneric operator *(NDArrayGeneric np1, T scalar) - { - NDArrayGeneric sum = new NDArrayGeneric(); - sum.Shape = np1.Shape; - sum.Data = new T[np1.Data.Length]; - - switch (scalar) - { - case double scalarDouble : - { - double[] np1Array = np1.Data as double[]; - double[] sumArray = sum.Data as double[]; - // for is faster than linq - for (int idx = 0; idx < sumArray.Length;idx++) - sumArray[idx] = np1Array[idx] * scalarDouble; - break; - } - case float scalarFloat : - { - float[] np1Array = np1.Data as float[]; - float[] sumArray = sum.Data as float[]; - // for is faster than linq - for (int idx = 0; idx < sumArray.Length;idx++) - sumArray[idx] = np1Array[idx] * scalarFloat; - break; - } - case Complex scalarComplex : - { - Complex[] np1Array = np1.Data as Complex[]; - Complex[] sumArray = sum.Data as Complex[]; - // for is faster than linq - for (int idx = 0; idx < sumArray.Length;idx++) - sumArray[idx] = np1Array[idx] * scalarComplex; - break; - } - case Quaternion scalarQuaternion : - { - Quaternion[] np1Array = np1.Data as Quaternion[]; - Quaternion[] sumArray = sum.Data as Quaternion[]; - // for is faster than linq - for (int idx = 0; idx < sumArray.Length;idx++) - sumArray[idx] = np1Array[idx] * scalarQuaternion; - break; - } - default : - { - throw new Exception("The operation is not implemented for the " + typeof(T).Name); - } - } - - return (NDArrayGeneric) sum; - } - - public static NDArrayGeneric operator *(T scalar, NDArrayGeneric np1) - { - return np1 * scalar; - } - } + } \ No newline at end of file diff --git a/src/NumSharp.Core/Operations/NdArray.Substraction.cs b/src/NumSharp.Core/Operations/NdArray.Substraction.cs index ac1c2f4e..4f9105ca 100644 --- a/src/NumSharp.Core/Operations/NdArray.Substraction.cs +++ b/src/NumSharp.Core/Operations/NdArray.Substraction.cs @@ -13,7 +13,7 @@ public partial class NDArray { NDArray sum = new NDArray(np1.dtype, np1.Storage.Shape); - if (!Enumerable.SequenceEqual(np1.Storage.Shape.Shapes, np2.Storage.Shape.Shapes)) + if (!Enumerable.SequenceEqual(np1.Storage.Shape.Dimensions, np2.Storage.Shape.Dimensions)) throw new IncorrectShapeException(); Array np1SysArr = np1.Storage.GetData(); @@ -169,112 +169,5 @@ public partial class NDArray return (np1 - scalar) * (-1); } } - public partial class NDArrayGeneric - { - public static NDArrayGeneric operator -(NDArrayGeneric np1, NDArrayGeneric np2) - { - NDArrayGeneric sum = new NDArrayGeneric(); - sum.Shape = np1.Shape; - sum.Data = new T[np1.Data.Length]; - - switch (sum.Data) - { - case double[] sumArray : - { - double[] np1Array = np1.Data as double[]; - double[] np2Array = np2.Data as double[]; - // for is faster than linq - for (int idx = 0; idx < sumArray.Length;idx++) - sumArray[idx] = np1Array[idx] - np2Array[idx]; - break; - } - case float[] sumArray : - { - float[] np1Array = np1.Data as float[]; - float[] np2Array = np2.Data as float[]; - // for is faster than linq - for (int idx = 0; idx < sumArray.Length;idx++) - sumArray[idx] = np1Array[idx] - np2Array[idx]; - break; - } - case Complex[] sumArray : - { - Complex[] np1Array = np1.Data as Complex[]; - Complex[] np2Array = np2.Data as Complex[]; - // for is faster than linq - for (int idx = 0; idx < sumArray.Length;idx++) - sumArray[idx] = np1Array[idx] - np2Array[idx]; - break; - } - case Quaternion[] sumArray : - { - Quaternion[] np1Array = np1.Data as Quaternion[]; - Quaternion[] np2Array = np2.Data as Quaternion[]; - // for is faster than linq - for (int idx = 0; idx < sumArray.Length;idx++) - sumArray[idx] = np1Array[idx] - np2Array[idx]; - break; - } - default : - { - throw new Exception("The operation is not implemented for the " + typeof(T).Name); - } - } - - return (NDArrayGeneric) sum; - } - public static NDArrayGeneric operator -(NDArrayGeneric np1, T scalar) - { - NDArrayGeneric sum = new NDArrayGeneric(); - sum.Shape = np1.Shape; - sum.Data = new T[np1.Data.Length]; - - switch (scalar) - { - case double scalarDouble : - { - double[] np1Array = np1.Data as double[]; - double[] sumArray = sum.Data as double[]; - // for is faster than linq - for (int idx = 0; idx < sumArray.Length;idx++) - sumArray[idx] = np1Array[idx] - scalarDouble; - break; - } - case float scalarFloat : - { - float[] np1Array = np1.Data as float[]; - float[] sumArray = sum.Data as float[]; - // for is faster than linq - for (int idx = 0; idx < sumArray.Length;idx++) - sumArray[idx] = np1Array[idx] - scalarFloat; - break; - } - case Complex scalarComplex : - { - Complex[] np1Array = np1.Data as Complex[]; - Complex[] sumArray = sum.Data as Complex[]; - // for is faster than linq - for (int idx = 0; idx < sumArray.Length;idx++) - sumArray[idx] = np1Array[idx] - scalarComplex; - break; - } - case Quaternion scalarQuaternion : - { - Quaternion[] np1Array = np1.Data as Quaternion[]; - Quaternion[] sumArray = sum.Data as Quaternion[]; - // for is faster than linq - for (int idx = 0; idx < sumArray.Length;idx++) - sumArray[idx] = np1Array[idx] - scalarQuaternion; - break; - } - default : - { - throw new Exception("The operation is not implemented for the " + typeof(T).Name); - } - } - - return (NDArrayGeneric) sum; - } - - } + } \ No newline at end of file diff --git a/src/NumSharp.Core/Operations/Shape.Equals.cs b/src/NumSharp.Core/Operations/Shape.Equals.cs index 80336b2e..d76d4662 100644 --- a/src/NumSharp.Core/Operations/Shape.Equals.cs +++ b/src/NumSharp.Core/Operations/Shape.Equals.cs @@ -10,7 +10,7 @@ public partial class Shape public static bool operator ==(Shape a, Shape b) { if (b is null) return false; - return Enumerable.SequenceEqual(a.shape, b?.shape); + return Enumerable.SequenceEqual(a.Dimensions, b?.Dimensions); } public static bool operator !=(Shape a, Shape b) @@ -22,7 +22,7 @@ public override bool Equals(object obj) { if (obj.GetType() != typeof(Shape)) return false; - return Enumerable.SequenceEqual(this.shape, ((Shape)obj).shape); + return Enumerable.SequenceEqual(this.Dimensions, ((Shape)obj).Dimensions); } public override int GetHashCode() @@ -32,7 +32,7 @@ public override int GetHashCode() public override string ToString() { - return "(" + String.Join(", ", shape) + ")"; + return "(" + String.Join(", ", _Dimensions) + ")"; } } } diff --git a/src/NumSharp.Core/Random/np.random.permutation.cs b/src/NumSharp.Core/Random/np.random.permutation.cs index 5963efdc..af061ee2 100644 --- a/src/NumSharp.Core/Random/np.random.permutation.cs +++ b/src/NumSharp.Core/Random/np.random.permutation.cs @@ -16,8 +16,8 @@ public NDArray permutation(int max) for (int i = 0; i < max; i++) { var pos = random.Next(0, max); - var zero = nd.Data(0); - nd[0] = nd.Data(pos); + var zero = nd.Storage.GetData(0); + nd[0] = nd.Storage.GetData(pos); nd[pos] = zero; } diff --git a/src/NumSharp.Core/Random/np.random.randint.cs b/src/NumSharp.Core/Random/np.random.randint.cs index 202560fe..1141821c 100644 --- a/src/NumSharp.Core/Random/np.random.randint.cs +++ b/src/NumSharp.Core/Random/np.random.randint.cs @@ -18,7 +18,7 @@ public NDArray randint(int low, int size = 1) } var np = new NDArray(typeof(int), size); - np.Set(data); + np.Storage.SetData(data); return np; } @@ -40,8 +40,8 @@ public NDArray randint(int low, int? high = null, Shape shape = null) data[i] = rng.Next(low, high.Value); } - var np = new NDArray(typeof(int), shape.Shapes.ToArray()); - np.Set(data); + var np = new NDArray(typeof(int), shape.Dimensions.ToArray()); + np.Storage.SetData(data); return np; } diff --git a/src/NumSharp.Core/Random/np.random.randn.cs b/src/NumSharp.Core/Random/np.random.randn.cs index 66a64d04..d6bc6781 100644 --- a/src/NumSharp.Core/Random/np.random.randn.cs +++ b/src/NumSharp.Core/Random/np.random.randn.cs @@ -30,6 +30,8 @@ public NDArray normal(double loc, double scale, params int[] size) var array = new NDArray(typeof(double), new Shape(size).Size); Random rand = new Random(); //reuse this if you are generating many + double[] arr = array.Storage.GetData(); + for (int i = 0; i < array.size; i++) { double u1 = 1.0 - rand.NextDouble(); //uniform(0,1] random doubles @@ -37,10 +39,10 @@ public NDArray normal(double loc, double scale, params int[] size) double randStdNormal = Math.Sqrt(-2.0 * Math.Log(u1)) * Math.Sin(2.0 * Math.PI * u2); //random normal(0,1) double randNormal = loc + scale * randStdNormal; //random normal(mean,stdDev^2) - array[i] = randNormal; + arr[i] = randNormal; } - array.Storage.Shape = new Shape(size); + array.Storage.Allocate(arr,1); return array; } diff --git a/src/NumSharp.Core/Selection/NDArray.Indexing.cs b/src/NumSharp.Core/Selection/NDArray.Indexing.cs index 1cb3f6e0..69a02c59 100644 --- a/src/NumSharp.Core/Selection/NDArray.Indexing.cs +++ b/src/NumSharp.Core/Selection/NDArray.Indexing.cs @@ -26,180 +26,8 @@ public object this[params int[] select] Storage.SetData(value, select); } } - - /// - /// Filter specific elements through select. - /// - /// - /// Return a new NDArray with filterd elements. - public NDArray this[IList select] - { - get - { - var n = new NDArray(dtype); - if (ndim == 1) - { - n.Storage.Shape = new Shape(select.Count); - for (int i = 0; i < select.Count; i++) - { - n[i] = this[select[i]]; - } - } - else if (ndim == 2) - { - n.Storage.Shape = new Shape(select.Count, shape[1]); - for (int i = 0; i < select.Count; i++) - { - for (int j = 0; j < shape[1]; j++) - { - n[i, j] = this[select[i], j]; - } - } - } - else - { - throw new NotImplementedException(); - } - - return n; - } - } - - public NDArray this[NDArray select] => this[select.Data().ToList()]; - - public T[] Data() => Storage.Data(); - - public T Data(params int[] shape) => Storage.Data()[this.shape.GetIndexInShape(shape)]; - - /// - /// shortcut for Double data type, 8 bytes - /// - public double[] float64 => Storage.Data(); - - /// - /// shortcut for Int32 data type - /// - public int[] int32 => Storage.Data(); - - // - /// shortcut for complex data type - /// - public Complex[] complex128 => Storage.Data(); - - // - /// shortcut for string data type - /// - public string[] chars => Storage.Data(); - - public void Set(T[] data) => Storage.Set(data); - - public void Set(Shape shape, T value) => Storage.Set(shape, value); + } - public partial class NDArrayGeneric - { - /// - /// Index accessor - /// - /// - /// - public T this[params int[] select] - { - get - { - return Data[GetIndexInShape(select)]; - } - - set - { - Data[GetIndexInShape(select)] = value; - } - } - - public NDArrayGeneric this[Shape select] - { - get - { - if (select.NDim == NDim) - { - throw new Exception("Please use NDArray[m, n] to access element."); - } - else - { - int start = GetIndexInShape(select.Shapes.ToArray()); - int length = Shape.DimOffset[select.NDim - 1]; - - var n = new NDArrayGeneric(); - Span data = Data; - n.Data = data.Slice(start, length).ToArray(); - int[] shape = new int[Shape.NDim - select.NDim]; - for (int i = select.NDim; i < Shape.NDim; i++) - { - shape[i - select.NDim] = Shape[i]; - } - n.Shape = new Shape(shape); - // n.Shape = new Shape(Shape.Shapes.ToArray().AsSpan().Slice(select.Length).ToArray()); - return n; - } - } - } - - /// - /// Filter specific elements through select. - /// - /// - /// Return a new NDArray with filterd elements. - public NDArrayGeneric this[IList select] - { - get - { - var n = new NDArrayGeneric(); - if (NDim == 1) - { - n.Data = new T[select.Count]; - n.Shape = new Shape(select.Count); - for (int i = 0; i < select.Count; i++) - { - n[i] = this[select[i]]; - } - } - else if (NDim == 2) - { - n.Data = new T[select.Count * Shape[1]]; - n.Shape = new Shape(select.Count, Shape[1]); - for (int i = 0; i < select.Count; i++) - { - for (int j = 0; j < Shape[1]; j++) - { - n[i, j] = this[select[i], j]; - } - } - } - else - { - throw new NotImplementedException(); - } - - return n; - } - } - - /// - /// Overload - /// - /// - /// - public NDArrayGeneric this[NDArrayGeneric select] => this[select.Data.ToList()]; - - private int GetIndexInShape(params int[] select) - { - int idx = 0; - for (int i = 0; i < select.Length; i++) - { - idx += Shape.DimOffset[i] * select[i]; - } - - return idx; - } - } + } diff --git a/src/NumSharp.Core/Selection/NdArray.AMax.cs b/src/NumSharp.Core/Selection/NdArray.AMax.cs index fc45d8a7..3098b3fe 100644 --- a/src/NumSharp.Core/Selection/NdArray.AMax.cs +++ b/src/NumSharp.Core/Selection/NdArray.AMax.cs @@ -17,6 +17,9 @@ public NDArray amax(int? axis = null) { var res = new NDArray(dtype); + int oldLayout = this.Storage.TensorLayout; + + this.Storage.ChangeTensorLayout(2); double[] npArr = this.Storage.GetData(); if (axis == null) @@ -25,13 +28,15 @@ public NDArray amax(int? axis = null) for (int i = 0; i < npArr.Length; i++) min = Math.Max(min, npArr[i]); - res.Storage = NDStorage.CreateByArray(new double[1] {min}); + res.Storage = new NDStorage(); + res.Storage.Allocate(dtype,new Shape(1),1); + res.Storage.SetData( new double[1] {min}); } else { if (axis < 0 || axis >= this.ndim) throw new Exception("Invalid input: axis"); - int[] resShapes = new int[this.shape.Shapes.Count - 1]; + int[] resShapes = new int[this.shape.Dimensions.Length - 1]; int index = 0; //index for result shape set //axis departs the shape into three parts: prev, cur and post. They are all product of shapes int prev = 1; @@ -39,21 +44,21 @@ public NDArray amax(int? axis = null) int post = 1; int size = 1; //total number of the elements for result //Calculate new Shape - for (int i = 0; i < this.shape.Shapes.Count; i++) + for (int i = 0; i < this.shape.Dimensions.Length; i++) { if (i == axis) - cur = this.shape.Shapes[i]; + cur = this.shape.Dimensions[i]; else { - resShapes[index++] = this.shape.Shapes[i]; - size *= this.shape.Shapes[i]; + resShapes[index++] = this.shape.Dimensions[i]; + size *= this.shape.Dimensions[i]; if (i < axis) - prev *= this.shape.Shapes[i]; + prev *= this.shape.Dimensions[i]; else - post *= this.shape.Shapes[i]; + post *= this.shape.Dimensions[i]; } } - res.Storage.Shape = new Shape(resShapes); + //Fill in data index = 0; //index for result data set int sameSetOffset = this.shape.DimOffset[axis.Value]; @@ -75,9 +80,12 @@ public NDArray amax(int? axis = null) resData[index++] = min; } } - res.Storage = NDStorage.CreateByArray(resData); - res.Storage.Shape = new Shape(resShapes); + res.Storage = new NDStorage(); + res.Storage.Allocate(this.dtype, new Shape(resShapes),2); // (resData); + res.Storage.SetData(resData); + res.Storage.ChangeTensorLayout(1); } + this.Storage.ChangeTensorLayout(oldLayout); return res; } } diff --git a/src/NumSharp.Core/Selection/NdArray.AMin.cs b/src/NumSharp.Core/Selection/NdArray.AMin.cs index edc60dac..fd6709d8 100644 --- a/src/NumSharp.Core/Selection/NdArray.AMin.cs +++ b/src/NumSharp.Core/Selection/NdArray.AMin.cs @@ -17,6 +17,9 @@ public NDArray amin(int? axis = null) { var res = new NDArray(dtype); + int oldLayout = this.Storage.TensorLayout; + + this.Storage.ChangeTensorLayout(2); double[] npArr = this.Storage.GetData(); if (axis == null) @@ -25,13 +28,15 @@ public NDArray amin(int? axis = null) for (int i = 0; i < npArr.Length; i++) min = Math.Min(min, npArr[i]); - res.Storage = NDStorage.CreateByArray(new double[1] {min}); + res.Storage = new NDStorage(); + res.Storage.Allocate(dtype,new Shape(1),1); + res.Storage.SetData( new double[1] {min}); } else { if (axis < 0 || axis >= this.ndim) throw new Exception("Invalid input: axis"); - int[] resShapes = new int[this.shape.Shapes.Count - 1]; + int[] resShapes = new int[this.shape.Dimensions.Length - 1]; int index = 0; //index for result shape set //axis departs the shape into three parts: prev, cur and post. They are all product of shapes int prev = 1; @@ -39,21 +44,21 @@ public NDArray amin(int? axis = null) int post = 1; int size = 1; //total number of the elements for result //Calculate new Shape - for (int i = 0; i < this.shape.Shapes.Count; i++) + for (int i = 0; i < this.shape.Dimensions.Length; i++) { if (i == axis) - cur = this.shape.Shapes[i]; + cur = this.shape.Dimensions[i]; else { - resShapes[index++] = this.shape.Shapes[i]; - size *= this.shape.Shapes[i]; + resShapes[index++] = this.shape.Dimensions[i]; + size *= this.shape.Dimensions[i]; if (i < axis) - prev *= this.shape.Shapes[i]; + prev *= this.shape.Dimensions[i]; else - post *= this.shape.Shapes[i]; + post *= this.shape.Dimensions[i]; } } - res.Storage.Shape = new Shape(resShapes); + //Fill in data index = 0; //index for result data set int sameSetOffset = this.shape.DimOffset[axis.Value]; @@ -75,9 +80,12 @@ public NDArray amin(int? axis = null) resData[index++] = min; } } - res.Storage = NDStorage.CreateByArray(resData); - res.Storage.Shape = new Shape(resShapes); + + res.Storage.Allocate(res.dtype,new Shape(resShapes),2); + res.Storage.SetData(resData); + res.Storage.ChangeTensorLayout(1); } + this.Storage.ChangeTensorLayout(oldLayout); return res; } } diff --git a/src/NumSharp.Core/np.cs b/src/NumSharp.Core/np.cs index 113feb55..e574fdc9 100644 --- a/src/NumSharp.Core/np.cs +++ b/src/NumSharp.Core/np.cs @@ -17,6 +17,5 @@ public static partial class np public static Type float64 => typeof(double); public static Type chars => typeof(string); - public static NumPyRandom random => new NumPyRandom(); } } diff --git a/src/NumSharp.PowerShell/GetGreeting.cs b/src/NumSharp.PowerShell/GetGreeting.cs index 81adbe99..d99e2d32 100644 --- a/src/NumSharp.PowerShell/GetGreeting.cs +++ b/src/NumSharp.PowerShell/GetGreeting.cs @@ -6,7 +6,7 @@ namespace NumSharp.PowerShell { [Cmdlet(VerbsCommon.New,"NDArray")] - [OutputType(typeof(NDArrayGeneric<>))] + [OutputType(typeof(NDArray))] public class NewNDArray : Cmdlet { protected dynamic _NDArray; @@ -23,7 +23,7 @@ protected override void ProcessRecord() case "float" : { float[] array = Array.Select(x => (float) x).ToArray(); - _NDArray = new NumSharp.Core.NDArrayGeneric(); + _NDArray = new NumSharp.Core.NDArray(); _NDArray.Data = array; _NDArray.Shape = new Shape(array.Length); break; @@ -31,7 +31,7 @@ protected override void ProcessRecord() case "double" : { double[] array = Array.Select(x => (double) x).ToArray(); - _NDArray = new NumSharp.Core.NDArrayGeneric(); + _NDArray = new NumSharp.Core.NDArray(); _NDArray.Data = array; _NDArray.Shape = new Shape(array.Length); break; diff --git a/test/NumSharp.UnitTest/Creation/NdArray.Array.Test.cs b/test/NumSharp.UnitTest/Creation/NdArray.Array.Test.cs index dbad837a..3b004068 100644 --- a/test/NumSharp.UnitTest/Creation/NdArray.Array.Test.cs +++ b/test/NumSharp.UnitTest/Creation/NdArray.Array.Test.cs @@ -17,7 +17,7 @@ public void Array1Dim() var list = new int[] { 1, 2, 3 }; var n = np.array(list); - Assert.IsTrue(Enumerable.SequenceEqual(n.Data(), new int[] { 1, 2, 3 })); + Assert.IsTrue(Enumerable.SequenceEqual(n.Storage.GetData(), new int[] { 1, 2, 3 })); } [TestMethod] @@ -31,7 +31,7 @@ public void Array2Dim() var n = np.array(list); - Assert.IsTrue(n.Data(1, 0) == 3); + Assert.IsTrue(n.Storage.GetData(1, 0) == 3); } [TestMethod] @@ -52,9 +52,10 @@ public void ArrayImage() var image = new System.Drawing.Bitmap(imagePath); var imageNDArray = np.array(image); - Assert.IsTrue(imageNDArray.Data(0, 0, 0) == 255); - Assert.IsTrue(imageNDArray.Data(0, 0, 1) == 253); - Assert.IsTrue(imageNDArray.Data(0, 0, 2) == 252); + Assert.IsTrue(imageNDArray.Storage.GetData()[0] == 255 ); + Assert.IsTrue(imageNDArray.Storage.GetData()[1] == 253 ); + Assert.IsTrue(imageNDArray.Storage.GetData()[2] == 252 ); + } } } diff --git a/test/NumSharp.UnitTest/Creation/NdArray.Zeros.Test.cs b/test/NumSharp.UnitTest/Creation/NdArray.Zeros.Test.cs index c313ce97..18b5099d 100644 --- a/test/NumSharp.UnitTest/Creation/NdArray.Zeros.Test.cs +++ b/test/NumSharp.UnitTest/Creation/NdArray.Zeros.Test.cs @@ -8,27 +8,27 @@ namespace NumSharp.UnitTest.Extensions { [TestClass] - public class NdArrayZerosTest : TestBase + public class NdArrayZerosTest { [TestMethod] public void Zeros1Dim() { var n = np.zeros(3); - Assert.IsTrue(Enumerable.SequenceEqual(n.float64, new double[] { 0, 0, 0 })); + Assert.IsTrue(Enumerable.SequenceEqual(n.Storage.GetData(), new double[] { 0, 0, 0 })); } [TestMethod] public void Zeros2Dim() { var n = np.zeros(3, 2); - Assert.IsTrue(Enumerable.SequenceEqual(n.float64, new double[] { 0, 0, 0, 0, 0, 0 })); + Assert.IsTrue(Enumerable.SequenceEqual(n.Storage.GetData(), new double[] { 0, 0, 0, 0, 0, 0 })); } [TestMethod] public void Zeros1DimWithDtype() { var n = np.zeros(new Shape(3), np.int32); - Assert.IsTrue(Enumerable.SequenceEqual(n.int32, new int[] { 0, 0, 0 })); + Assert.IsTrue(Enumerable.SequenceEqual(n.Storage.GetData(), new int[] { 0, 0, 0 })); } } } diff --git a/test/NumSharp.UnitTest/Creation/np.arange.Test.cs b/test/NumSharp.UnitTest/Creation/np.arange.Test.cs index 30c87b29..106c3bb4 100644 --- a/test/NumSharp.UnitTest/Creation/np.arange.Test.cs +++ b/test/NumSharp.UnitTest/Creation/np.arange.Test.cs @@ -15,16 +15,16 @@ public class NumPyArangeTest public void arange() { var n = np.arange(3); - Assert.IsTrue(Enumerable.SequenceEqual(n.Data(), new int[] { 0, 1, 2 })); + Assert.IsTrue(Enumerable.SequenceEqual(n.Storage.GetData(), new int[] { 0, 1, 2 })); n = np.arange(3, 7); - Assert.IsTrue(Enumerable.SequenceEqual(n.Data(), new int[] { 3, 4, 5, 6 })); + Assert.IsTrue(Enumerable.SequenceEqual(n.Storage.GetData(), new int[] { 3, 4, 5, 6 })); n = np.arange(3.0, 7.0, 2.0); - Assert.IsTrue(Enumerable.SequenceEqual(n.Data(), new double[] { 3, 5 })); + Assert.IsTrue(Enumerable.SequenceEqual(n.Storage.GetData(), new double[] { 3, 5 })); n = np.arange(0, 11, 3); - Assert.IsTrue(Enumerable.SequenceEqual(n.Data(), new int[] { 0, 3, 6, 9 })); + Assert.IsTrue(Enumerable.SequenceEqual(n.Storage.GetData(), new int[] { 0, 3, 6, 9 })); } } } diff --git a/test/NumSharp.UnitTest/Extensions/NdArray.AsMatrix.Test.cs b/test/NumSharp.UnitTest/Extensions/NdArray.AsMatrix.Test.cs index 279c5c4a..72c6bba8 100644 --- a/test/NumSharp.UnitTest/Extensions/NdArray.AsMatrix.Test.cs +++ b/test/NumSharp.UnitTest/Extensions/NdArray.AsMatrix.Test.cs @@ -9,7 +9,7 @@ namespace NumSharp.UnitTest.Extensions { [TestClass] - public class NdArrayAsMatrixTest : TestBase + public class NdArrayAsMatrixTest { [TestMethod] public void ConvertNDArrayNDArrayDouble() diff --git a/test/NumSharp.UnitTest/Extensions/NdArray.ReShape.Test.cs b/test/NumSharp.UnitTest/Extensions/NdArray.ReShape.Test.cs index ebff1330..62029785 100644 --- a/test/NumSharp.UnitTest/Extensions/NdArray.ReShape.Test.cs +++ b/test/NumSharp.UnitTest/Extensions/NdArray.ReShape.Test.cs @@ -17,7 +17,6 @@ public void ReShape() Assert.IsTrue(n[0, 0] == 0); Assert.IsTrue(n[1, 1] == 3); Assert.IsTrue(n[2, 1] == 5); - // Assert.IsTrue(np2.ToString().Equals("array([[0, 1], [2, 3], [4, 5]])")); n = np.reshape(np.arange(6), 2, 3, 1).MakeGeneric(); Assert.IsTrue(n[1, 1, 0] == 4); @@ -33,6 +32,7 @@ public void ReShape() Assert.IsTrue(n[2, 0] == 8); n = np.reshape(n, 2, 6).MakeGeneric(); + Assert.IsTrue(n[1, 0] == 6); } @@ -55,37 +55,37 @@ public void ReshapeNegative() var np = new NDArray(typeof(int),12).MakeGeneric(); np.arange(12); np.reshape(-1, 2); - Assert.IsTrue(np.shape.Shapes[0] == 6); - Assert.IsTrue(np.shape.Shapes[1] == 2); + Assert.IsTrue(np.shape.Dimensions[0] == 6); + Assert.IsTrue(np.shape.Dimensions[1] == 2); np.arange(12); np.reshape(2, -1); - Assert.IsTrue(np.shape.Shapes[0] == 2); - Assert.IsTrue(np.shape.Shapes[1] == 6); + Assert.IsTrue(np.shape.Dimensions[0] == 2); + Assert.IsTrue(np.shape.Dimensions[1] == 6); np.arange(12); np.reshape(1, 3, 4); np.reshape(-1, 3); - Assert.IsTrue(np.shape.Shapes[0] == 4); - Assert.IsTrue(np.shape.Shapes[1] == 3); + Assert.IsTrue(np.shape.Dimensions[0] == 4); + Assert.IsTrue(np.shape.Dimensions[1] == 3); np.arange(12); np.reshape(1, 3, 4); np.reshape(3, -1); - Assert.IsTrue(np.shape.Shapes[0] == 3); - Assert.IsTrue(np.shape.Shapes[1] == 4); + Assert.IsTrue(np.shape.Dimensions[0] == 3); + Assert.IsTrue(np.shape.Dimensions[1] == 4); np.arange(100 * 100 * 3); np.reshape(100, 100, 3); np.reshape(-1, 3); - Assert.IsTrue(np.shape.Shapes[0] == 10000); - Assert.IsTrue(np.shape.Shapes[1] == 3); + Assert.IsTrue(np.shape.Dimensions[0] == 10000); + Assert.IsTrue(np.shape.Dimensions[1] == 3); np.arange(15801033); np.reshape(2531, 2081, 3); np.reshape(-1, 3); - Assert.IsTrue(np.shape.Shapes[0] == 5267011); - Assert.IsTrue(np.shape.Shapes[1] == 3); + Assert.IsTrue(np.shape.Dimensions[0] == 5267011); + Assert.IsTrue(np.shape.Dimensions[1] == 3); } } } diff --git a/test/NumSharp.UnitTest/Extensions/NdArrayRandom.RandInt.Test.cs b/test/NumSharp.UnitTest/Extensions/NdArrayRandom.RandInt.Test.cs index 83ad66a2..66d18e3f 100644 --- a/test/NumSharp.UnitTest/Extensions/NdArrayRandom.RandInt.Test.cs +++ b/test/NumSharp.UnitTest/Extensions/NdArrayRandom.RandInt.Test.cs @@ -14,8 +14,8 @@ public class NdArrayRandomRandIntTest [TestMethod] public void randint() { - var a = np.random.randint(low: 0, high: 10, shape: new Shape(5, 5)); - Assert.IsTrue(a.Data().Count(x => x < 10) == 25); + var a = new NumSharp.Core.NumPyRandom().randint(low: 0, high: 10, shape: new Shape(5, 5)); + Assert.IsTrue(a.Storage.GetData().Count(x => x < 10) == 25); } } } diff --git a/test/NumSharp.UnitTest/LAPACK/dgels.cs b/test/NumSharp.UnitTest/LAPACK/dgels.cs index b8e50a89..8d93b15e 100644 --- a/test/NumSharp.UnitTest/LAPACK/dgels.cs +++ b/test/NumSharp.UnitTest/LAPACK/dgels.cs @@ -4,7 +4,6 @@ using NumSharp.Core.Extensions; using System.Linq; using System.Numerics; -using NumSharp.UnitTest.Shared; using Microsoft.VisualStudio.TestTools.UnitTesting; using NumSharp.Core; @@ -15,7 +14,7 @@ namespace NumSharp.UnitTest.Extensions /// https://www.numpy.org/devdocs/reference/generated/numpy.convolve.html /// [TestClass] - public class NdArrayDGELSTest : TestBase + public class NdArrayDGELSTest { [TestMethod] public void Standard() diff --git a/test/NumSharp.UnitTest/LinearAlgebra/NdArray.Dot.Test.cs b/test/NumSharp.UnitTest/LinearAlgebra/NdArray.Dot.Test.cs index 3a724944..e11bd8f5 100644 --- a/test/NumSharp.UnitTest/LinearAlgebra/NdArray.Dot.Test.cs +++ b/test/NumSharp.UnitTest/LinearAlgebra/NdArray.Dot.Test.cs @@ -4,7 +4,6 @@ using NumSharp.Core.Extensions; using System.Linq; using System.Numerics; -using NumSharp.UnitTest.Shared; using Microsoft.VisualStudio.TestTools.UnitTesting; using NumSharp.Core; @@ -15,7 +14,7 @@ namespace NumSharp.UnitTest.Extensions /// https://www.numpy.org/devdocs/reference/generated/numpy.convolve.html /// [TestClass] - public class NdArrayDotTest : TestBase + public class NdArrayDotTest { [TestMethod] public void DotTwo1Int() @@ -44,7 +43,7 @@ public void DotTwo1DDouble() var series1 = np.arange(1.0,4.0,1.0) ; - var series2 = new NDArray(typeof(int),new Shape(3)); + var series2 = new NDArray(typeof(double),new Shape(3)); series2.Storage.SetData(new double[]{0, 1, 0.5}); var innerProduct = series1.dot(series2); @@ -59,6 +58,8 @@ public void MatrixMutliplyDifferentDataLength() var C = A.dot(B); + C.Storage.ChangeTensorLayout(2); + Assert.IsTrue(Enumerable.SequenceEqual(new double[]{7,8,9,10,11,12,13,21,26,31,36,41,46,51,35,44,53,62,71,80,89},C.Storage.GetData())); } @@ -67,7 +68,7 @@ public void MatrixMultiplyDouble() { var matrix1 = np.arange(1,7,1).reshape(3,2); - var matrix2 = np.arange(7,13,1).reshape(2,3) ; + var matrix2 = np.arange(7,13,1).reshape(2,3); var matrix3 = matrix1.dot(matrix2); @@ -80,7 +81,7 @@ public void MatrixMultiplyDouble() matrix4[idx,jdx] = 0; for (int kdx = 0; kdx < 2;kdx++) { - matrix4[idx,jdx] += ((int)matrix1[idx,kdx] * (int) matrix2[kdx,jdx]); + matrix4[idx,jdx] += ((int)matrix1[idx,kdx] * (int)matrix2[kdx,jdx]); } } } @@ -100,25 +101,34 @@ public void MatrixMultiplyDouble() public void MatrixMultiplyComplex() { var matrix1 = new NDArray(typeof(Complex),3,2); + matrix1.Storage.ChangeTensorLayout(2); matrix1.Storage.SetData(new Complex[] {new Complex(1,-1),new Complex(2,-2), new Complex(3,0),new Complex(4,0), 5, 6}); - + matrix1.Storage.ChangeTensorLayout(1); + var matrix2 = new NDArray(typeof(Complex),2,3); + matrix2.Storage.ChangeTensorLayout(2); matrix2.Storage.SetData(new Complex[] {7,8,9,new Complex(10,-10),11, new Complex(12,-12)}); + matrix2.Storage.ChangeTensorLayout(1); var matrix3 = matrix1.dot(matrix2); - var matrix4 = new Complex[9]; - matrix4[0] = new Complex(7,-47); - matrix4[1] = new Complex(30,-30); - matrix4[2] = new Complex(9,-57); - matrix4[3] = new Complex(61,-40); - matrix4[4] = new Complex(68,0); - matrix4[5] = new Complex(75,-48); - matrix4[6] = new Complex(95,-60); - matrix4[7] = new Complex(106,0); - matrix4[8] = new Complex(117,-72); - - Assert.IsTrue(Enumerable.SequenceEqual(matrix4,matrix3.Storage.GetData())); + var matrix4 = new NDArray(typeof(Complex),3,3); + matrix4.Storage.ChangeTensorLayout(2); + matrix4.Storage.SetData(new Complex[9]); + var mat4 = matrix4.Storage.GetData(); + mat4[0] = new Complex(7,-47); + mat4[1] = new Complex(30,-30); + mat4[2] = new Complex(9,-57); + mat4[3] = new Complex(61,-40); + mat4[4] = new Complex(68,0); + mat4[5] = new Complex(75,-48); + mat4[6] = new Complex(95,-60); + mat4[7] = new Complex(106,0); + mat4[8] = new Complex(117,-72); + + matrix4.Storage.ChangeTensorLayout(1); + + Assert.IsTrue(Enumerable.SequenceEqual(matrix4.Storage.GetData(),matrix3.Storage.GetData())); } [TestMethod] public void DotTwo1DComplex() diff --git a/test/NumSharp.UnitTest/LinearAlgebra/NdArray.LstSq.Test.cs b/test/NumSharp.UnitTest/LinearAlgebra/NdArray.LstSq.Test.cs index 925bff5e..c97a5252 100644 --- a/test/NumSharp.UnitTest/LinearAlgebra/NdArray.LstSq.Test.cs +++ b/test/NumSharp.UnitTest/LinearAlgebra/NdArray.LstSq.Test.cs @@ -4,7 +4,6 @@ using NumSharp.Core.Extensions; using System.Linq; using System.Numerics; -using NumSharp.UnitTest.Shared; using Microsoft.VisualStudio.TestTools.UnitTesting; using NumSharp.Core; diff --git a/test/NumSharp.UnitTest/LinearAlgebra/NdArray.QR.Test.cs b/test/NumSharp.UnitTest/LinearAlgebra/NdArray.QR.Test.cs index 3824638e..e44c4843 100644 --- a/test/NumSharp.UnitTest/LinearAlgebra/NdArray.QR.Test.cs +++ b/test/NumSharp.UnitTest/LinearAlgebra/NdArray.QR.Test.cs @@ -4,7 +4,6 @@ using NumSharp.Core.Extensions; using System.Linq; using System.Numerics; -using NumSharp.UnitTest.Shared; using Microsoft.VisualStudio.TestTools.UnitTesting; using NumSharp.Core; @@ -15,7 +14,7 @@ namespace NumSharp.UnitTest.Extensions /// https://www.numpy.org/devdocs/reference/generated/numpy.convolve.html /// [TestClass] - public class NdArrayQRTest : TestBase + public class NdArrayQRTest { [TestMethod] public void FullMatrix() diff --git a/test/NumSharp.UnitTest/LinearAlgebra/NdArray.Transpose.cs b/test/NumSharp.UnitTest/LinearAlgebra/NdArray.Transpose.cs index 824b56f3..d514b88c 100644 --- a/test/NumSharp.UnitTest/LinearAlgebra/NdArray.Transpose.cs +++ b/test/NumSharp.UnitTest/LinearAlgebra/NdArray.Transpose.cs @@ -10,7 +10,7 @@ namespace NumSharp.UnitTest.LinearAlgebra { [TestClass] - public class TransposeTest : TestBase + public class TransposeTest { [TestMethod] public void TwoxThree() diff --git a/test/NumSharp.UnitTest/Math/NDArray.log.Test.cs b/test/NumSharp.UnitTest/Math/NDArray.log.Test.cs index feff1d73..a427056f 100644 --- a/test/NumSharp.UnitTest/Math/NDArray.log.Test.cs +++ b/test/NumSharp.UnitTest/Math/NDArray.log.Test.cs @@ -15,7 +15,7 @@ public class LogTest [TestMethod] public void Simple1DArray() { - var np1 = np.array(new double[] {1, Math.E, Math.E*Math.E, 0}).MakeGeneric(); + var np1 = np.array(new double[] {1, Math.E, Math.E*Math.E, 0});// .MakeGeneric(); var np2 = np1.log().MakeGeneric(); diff --git a/test/NumSharp.UnitTest/Math/NDArray.sin.Test.cs b/test/NumSharp.UnitTest/Math/NDArray.sin.Test.cs index ccc5e8b6..7c9f767e 100644 --- a/test/NumSharp.UnitTest/Math/NDArray.sin.Test.cs +++ b/test/NumSharp.UnitTest/Math/NDArray.sin.Test.cs @@ -19,14 +19,14 @@ public void Simple1DArray() var nd2 = np.sin(nd); - Assert.IsTrue(nd2.Data(0) == 0); - Assert.IsTrue(nd2.Data(1) < 0.501); - Assert.IsTrue(nd2.Data(1) > 0.498); - Assert.IsTrue(nd2.Data(2) < 0.708); - Assert.IsTrue(nd2.Data(2) > 0.7069); - Assert.IsTrue(nd2.Data(3) < 0.867); - Assert.IsTrue(nd2.Data(3) > 0.8659); - Assert.IsTrue(nd2.Data(4) == 1); + Assert.IsTrue(nd2.Storage.GetData(0) == 0); + Assert.IsTrue(nd2.Storage.GetData(1) < 0.501); + Assert.IsTrue(nd2.Storage.GetData(1) > 0.498); + Assert.IsTrue(nd2.Storage.GetData(2) < 0.708); + Assert.IsTrue(nd2.Storage.GetData(2) > 0.7069); + Assert.IsTrue(nd2.Storage.GetData(3) < 0.867); + Assert.IsTrue(nd2.Storage.GetData(3) > 0.8659); + Assert.IsTrue(nd2.Storage.GetData(4) == 1); } } diff --git a/test/NumSharp.UnitTest/Math/NdArray.Sqrt.Test.cs b/test/NumSharp.UnitTest/Math/NdArray.Sqrt.Test.cs index 0a62424d..5d2d3f1d 100644 --- a/test/NumSharp.UnitTest/Math/NdArray.Sqrt.Test.cs +++ b/test/NumSharp.UnitTest/Math/NdArray.Sqrt.Test.cs @@ -15,11 +15,10 @@ public class NDArraySqrtTest [TestMethod] public void DoubleSqrtTest() { - var np = new NDArray().arange(3).MakeGeneric(); - np[0] = 1; - np[1] = 4; - np[2] = 9; - Assert.IsTrue(Enumerable.SequenceEqual(np.sqrt().Storage.GetData(), new double[] { 1, 2, 3 })); + var nd = new NDArray(np.float64,3); + nd.Storage.SetData(new double[]{1,4,9}); + + Assert.IsTrue(Enumerable.SequenceEqual(nd.sqrt().Storage.GetData(), new double[] { 1, 2, 3 })); } [TestMethod] public void ComplexSqrtTest() diff --git a/test/NumSharp.UnitTest/NdArray.Test.cs b/test/NumSharp.UnitTest/NdArray.Test.cs index 8e8c0d76..6b2a8cdf 100644 --- a/test/NumSharp.UnitTest/NdArray.Test.cs +++ b/test/NumSharp.UnitTest/NdArray.Test.cs @@ -14,7 +14,8 @@ public class NDArrayTest [TestMethod] public void StringCheck() { - var nd = np.arange(9.0).reshape(3,3); + /* + var nd = np.arange(9.0).reshape(3,3); var random = new Random(); nd.Set(nd.Data().Select(x => x + random.NextDouble()).ToArray()); @@ -33,6 +34,7 @@ public void StringCheck() stringOfNp = nd.ToString(); Assert.IsTrue(stringOfNp.Contains("([[ 0,"));*/ + } [TestMethod] public void CheckVectorString() @@ -48,20 +50,6 @@ public void CheckVectorString() var stringOfNp = np.ToString(); } - [TestMethod] - public void DimOrder() - { - NDArrayGeneric np1 = new NDArrayGeneric().Zeros(2,2); - - np1[0,0] = 0; - np1[1,0] = 10; - np1[0,1] = 1; - np1[1,1] = 11; - - // columns first than rows - Assert.IsTrue(Enumerable.SequenceEqual(new double[] {0,1,10,11}, np1.Data )); - } - [TestMethod] public void ToDotNetArray1D() { @@ -76,7 +64,6 @@ public void ToDotNetArray1D() public void ToDotNetArray2D() { var np1 = new NDArray(typeof(double)).arange(9).reshape(3,3).MakeGeneric(); - double[][] np1_ = (double[][]) np1.ToJaggedArray(); for (int idx = 0; idx < 3; idx ++) diff --git a/test/NumSharp.UnitTest/NdArrayRandom.Test.cs b/test/NumSharp.UnitTest/NdArrayRandom.Test.cs index c9b12baa..3d4e37ff 100644 --- a/test/NumSharp.UnitTest/NdArrayRandom.Test.cs +++ b/test/NumSharp.UnitTest/NdArrayRandom.Test.cs @@ -12,13 +12,13 @@ public class NDArrayRandomTest [TestMethod] public void randn() { - var n = np.random.randn(5, 2); + var n = new NumSharp.Core.NumPyRandom().randn(5, 2); } [TestMethod] public void normal() { - var n = np.random.normal(0, 1, 5); + var n = new NumSharp.Core.NumPyRandom().normal(0, 1, 5); } } } diff --git a/test/NumSharp.UnitTest/Operations/Matrix.Addition.Test.cs b/test/NumSharp.UnitTest/Operations/Matrix.Addition.Test.cs index 88f1a2f5..ac6d469e 100644 --- a/test/NumSharp.UnitTest/Operations/Matrix.Addition.Test.cs +++ b/test/NumSharp.UnitTest/Operations/Matrix.Addition.Test.cs @@ -9,7 +9,7 @@ namespace NumSharp.UnitTest.Operations { [TestClass] - public class MatrixAdditionTest : TestBase + public class MatrixAdditionTest { [TestMethod] public void DoubleTwo2D_MatrixAddition() @@ -19,7 +19,9 @@ public void DoubleTwo2D_MatrixAddition() var np3 = np1 + np2; - Assert.IsTrue(Enumerable.SequenceEqual(new double[] { 2, 4, 6, 8, 10, 12, 14, 16, 18 }, np3.float64)); + np3.Storage.ChangeTensorLayout(2); + + Assert.IsTrue(Enumerable.SequenceEqual(new double[] { 2, 4, 6, 8, 10, 12, 14, 16, 18 }, np3.Storage.GetData())); } [TestMethod] @@ -30,7 +32,7 @@ public void ComplexTwo2D_MatrixAddition() var np3 = np1 + np2; - Assert.IsTrue(Enumerable.SequenceEqual(new Complex[] { new Complex(6, 8), new Complex(10, 12) }, np3.Data())); + Assert.IsTrue(Enumerable.SequenceEqual(new Complex[] { new Complex(6, 8), new Complex(10, 12) }, np3.Storage.GetData())); } } } diff --git a/test/NumSharp.UnitTest/Operations/Matrix.Substraction.Test.cs b/test/NumSharp.UnitTest/Operations/Matrix.Substraction.Test.cs index 4489ccfd..2d65d271 100644 --- a/test/NumSharp.UnitTest/Operations/Matrix.Substraction.Test.cs +++ b/test/NumSharp.UnitTest/Operations/Matrix.Substraction.Test.cs @@ -9,7 +9,7 @@ namespace NumSharp.UnitTest.Operations { [TestClass] - public class MatrixSubstractionTest : TestBase + public class MatrixSubstractionTest { [TestMethod] @@ -20,7 +20,7 @@ public void DoubleTwo2D_MatrixSubstraction() var np3 = np1 - np2; - Assert.IsTrue(Enumerable.SequenceEqual(new double[] { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, np3.float64)); + Assert.IsTrue(Enumerable.SequenceEqual(new double[] { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, np3.Storage.GetData())); } [TestMethod] @@ -33,7 +33,7 @@ public void ComplexTwo2D_MatrixSubstraction() var expArray = new Complex[] { new Complex(-7, -5), new Complex(-3, -1), new Complex(1, 3), new Complex(5, 7) }; - Assert.IsTrue(Enumerable.SequenceEqual(expArray, np3.complex128)); + Assert.IsTrue(Enumerable.SequenceEqual(expArray, np3.Storage.GetData())); } } } diff --git a/test/NumSharp.UnitTest/Selection/NDArray.Indexing.Test.cs b/test/NumSharp.UnitTest/Selection/NDArray.Indexing.Test.cs index f82ef02a..cbd6bb41 100644 --- a/test/NumSharp.UnitTest/Selection/NDArray.Indexing.Test.cs +++ b/test/NumSharp.UnitTest/Selection/NDArray.Indexing.Test.cs @@ -11,8 +11,8 @@ public void IndexAccessorGetter() { var nd = np.arange(12).reshape(3, 4); - Assert.IsTrue(nd.Data(1, 1) == 5); - Assert.IsTrue(nd.Data(2, 0) == 8); + Assert.IsTrue(nd.Storage.GetData(1, 1) == 5); + Assert.IsTrue(nd.Storage.GetData(2, 0) == 8); } @@ -21,14 +21,13 @@ public void IndexAccessorSetter() { var nd = np.arange(12).reshape(3, 4); - Assert.IsTrue(nd.Data(0, 3) == 3); - Assert.IsTrue(nd.Data(1, 3) == 7); + Assert.IsTrue(nd.Storage.GetData(0, 3) == 3); + Assert.IsTrue(nd.Storage.GetData(1, 3) == 7); // set value - nd.Set(new Shape(0), 10); - Assert.IsTrue(nd.Data(0, 0) == 10); - Assert.IsTrue(nd.Data(0, 3) == 10); - Assert.IsTrue(nd.Data(1, 3) == 7); + nd.Storage.SetData(10, 0, 0); + Assert.IsTrue(nd.Storage.GetData(0, 0) == 10); + Assert.IsTrue(nd.Storage.GetData(1, 3) == 7); } } } diff --git a/test/NumSharp.UnitTest/Shape.Test.cs b/test/NumSharp.UnitTest/Shape.Test.cs index 0c1c5e0f..cc763314 100644 --- a/test/NumSharp.UnitTest/Shape.Test.cs +++ b/test/NumSharp.UnitTest/Shape.Test.cs @@ -17,10 +17,64 @@ public void Index() var shape0 = new Shape(4,3); int idx0 = shape0.GetIndexInShape(2,1); - int[] idx00 = shape0.GetDimIndexOutShape(idx0); + + Assert.IsTrue(idx0 == 6); + } + [TestMethod] + public void CheckIndexing() + { + var shape0 = new Shape(4,3,2); + + int[] strgDimSize = shape0.DimOffset; + + int index = shape0.GetIndexInShape(1,2,1); + + Assert.IsTrue(Enumerable.SequenceEqual(shape0.GetDimIndexOutShape(index),new int[]{1,2,1})); + + var rnd = new Random(); + var randomIndex = new int[]{rnd.Next(0,3),rnd.Next(0,2),rnd.Next(0,1)}; + + int index1 = shape0.GetIndexInShape(randomIndex); + Assert.IsTrue(Enumerable.SequenceEqual(shape0.GetDimIndexOutShape(index1),randomIndex)); + + var shape1 = new Shape(2,3,4); + + index = shape1.GetIndexInShape(1,2,1); + Assert.IsTrue(Enumerable.SequenceEqual(shape1.GetDimIndexOutShape(index),new int[]{1,2,1})); + + randomIndex = new int[]{rnd.Next(0,1),rnd.Next(0,2),rnd.Next(0,3)}; + index = shape1.GetIndexInShape(randomIndex); + Assert.IsTrue(Enumerable.SequenceEqual(shape1.GetDimIndexOutShape(index),randomIndex)); + + randomIndex = new int[]{rnd.Next(1,10),rnd.Next(1,10),rnd.Next(1,10)}; + + var shape2 = new Shape(randomIndex); + + randomIndex = new int[]{rnd.Next(0,shape2.Dimensions[0]),rnd.Next(0,shape2.Dimensions[1]),rnd.Next(0,shape2.Dimensions[2])}; + + index = shape2.GetIndexInShape(randomIndex); + Assert.IsTrue(Enumerable.SequenceEqual(shape2.GetDimIndexOutShape(index),randomIndex)); + } + [TestMethod] + public void CheckColRowSwitch() + { + var shape1 = new Shape(5); + Assert.IsTrue(Enumerable.SequenceEqual(shape1.DimOffset,new int[]{1})); + + shape1.ChangeTensorLayout(2); + Assert.IsTrue(Enumerable.SequenceEqual(shape1.DimOffset,new int[]{1})); + + var shape2 = new Shape(4,3); + Assert.IsTrue(Enumerable.SequenceEqual(shape2.DimOffset,new int[]{1,4})); + + shape2.ChangeTensorLayout(2); + Assert.IsTrue(Enumerable.SequenceEqual(shape2.DimOffset,new int[]{3,1})); + + var shape3 = new Shape(2,3,4); + Assert.IsTrue(Enumerable.SequenceEqual(shape3.DimOffset,new int[]{1,2,6})); - Assert.IsTrue(idx00[0] == 2); - Assert.IsTrue(idx00[1] == 1); + shape3.ChangeTensorLayout(2); + Assert.IsTrue(Enumerable.SequenceEqual(shape3.DimOffset,new int[]{12,4,1})); } } diff --git a/test/NumSharp.UnitTest/Storage.Test.cs b/test/NumSharp.UnitTest/Storage.Test.cs index f6cb9830..64c61358 100644 --- a/test/NumSharp.UnitTest/Storage.Test.cs +++ b/test/NumSharp.UnitTest/Storage.Test.cs @@ -11,39 +11,208 @@ namespace NumSharp.UnitTest [TestClass] public class StorageTester { - public NDStorage Storage1DInt {get;set;} - public NDStorage Storage2DInt {get;set;} - public NDStorage Storage1DDouble {get;set;} + public NDStorage strg1D; + public NDStorage strg2D; + public NDStorage strg2DNonFull; + public NDStorage strg3D; + public NDStorage strg3DNonFull; public StorageTester() { - Storage1DInt = NDStorage.CreateByShapeAndType(typeof(int),new Shape(6)); - Storage1DInt.SetData(new int[] {0,1,2,3,4,5}); + strg1D = new NDStorage(np.float64); + strg1D.Allocate(np.float64,new Shape(10),1); + strg1D.SetData(new double[]{0,1,2,3,4,5,6,7,8,9}); - Storage1DDouble = NDStorage.CreateByShapeAndType(typeof(double),new Shape(6)); - Storage1DDouble.SetData(new double[] {0.1,1.5,2.2,3.5,4.9,5.0}); + strg2D = new NDStorage(np.int64); + strg2D.Allocate(np.int64,new Shape(3,3),1); + strg2D.SetData(new Int64[]{0,1,2,3,4,5,6,7,8}); + + strg2DNonFull = new NDStorage(np.float32); + strg2DNonFull.Allocate(np.float32,new Shape(5,2),1); + strg2DNonFull.SetData(new float[]{0,1,2,3,4,5,6,7,8,9}); + + strg3D = new NDStorage(typeof(Complex)); + strg3D.Allocate(typeof(Complex),new Shape(2,2,2)); + strg3D.SetData(new Complex[]{1,2,3,4,5,6,7,8}); + + strg3DNonFull = new NDStorage(typeof(Complex)); + strg3DNonFull.Allocate(typeof(Complex),new Shape(2,3,4)); + var puffer = new Complex[24]; + for(int idx = 1;idx < 25;idx++) + puffer[idx-1] = new Complex(idx,0); + + strg3DNonFull.SetData(puffer); - Storage2DInt = NDStorage.CreateByShapeAndType(typeof(int),new Shape(2,3)); - Storage2DInt.SetData(new int[] {0,1,2,3,4,5}); } [TestMethod] public void Creation() { - Assert.IsNotNull(Storage1DInt); - Assert.IsNotNull(Storage2DInt); + Assert.IsNotNull(strg1D); + Assert.IsNotNull(strg2D); + Assert.IsNotNull(strg2DNonFull); + Assert.IsNotNull(strg3D); + } + [TestMethod] + public void InternalArrayCheck() + { + Assert.IsTrue(strg1D.GetData().Length == 10); + Assert.IsTrue(strg2D.GetData().Length == 9); + Assert.IsTrue(strg2DNonFull.GetData().Length == 10); + } + [TestMethod] + public void IndexingCheck() + { + var element1D = strg1D.GetData(0); + Assert.IsTrue(element1D == 0); + for (int idx = 1; idx < 10;idx++) + { + element1D = strg1D.GetData(idx); + Assert.IsTrue(element1D == idx); + } + + var element2D = strg2D.GetData(0,0); + Assert.IsTrue(element2D == 0); + element2D = strg2D.GetData(1,0); + Assert.IsTrue(element2D == 1); + element2D = strg2D.GetData(2,0); + Assert.IsTrue(element2D == 2); + element2D = strg2D.GetData(0,1); + Assert.IsTrue(element2D == 3); + element2D = strg2D.GetData(1,1); + Assert.IsTrue(element2D == 4); + element2D = strg2D.GetData(2,1); + Assert.IsTrue(element2D == 5); + element2D = strg2D.GetData(0,2); + Assert.IsTrue(element2D == 6); + element2D = strg2D.GetData(1,2); + Assert.IsTrue(element2D == 7); + element2D = strg2D.GetData(2,2); + Assert.IsTrue(element2D == 8); + var element3d = strg3D.GetData(0,0,0); + element3d = strg3D.GetData(1,0,0); + element3d = strg3D.GetData(0,1,0); + element3d = strg3D.GetData(1,1,0); + + element3d = strg3D.GetData(0,0,1); + element3d = strg3D.GetData(1,0,1); + element3d = strg3D.GetData(0,1,1); + element3d = strg3D.GetData(1,1,1); } [TestMethod] - public void Casting() + public void CloneCheck() + { + var strg1DCpy = (NDStorage) strg1D.Clone(); + + Assert.IsTrue(strg1DCpy.DType == strg1DCpy.GetData().GetType().GetElementType()); + Assert.IsFalse(strg1D.GetData() == strg1DCpy.GetData()); + Assert.IsTrue(strg1D.GetData().Length == strg1DCpy.GetData().Length); + + Assert.IsTrue(Enumerable.SequenceEqual(strg1DCpy.GetData(),strg1D.GetData())); + } + [TestMethod] + public void CastingViaGet() { - int[] directCastInt = Storage1DInt.GetData(); + double[] arr1 = strg1D.GetData(); + + } + [TestMethod] + public void CheckChangeTensorLayout2D() + { + var strg2DCpy = (NDStorage) strg2D.Clone(); + + Assert.IsTrue(strg2DCpy.TensorLayout == 1); + + strg2DCpy.ChangeTensorLayout(2); + + Assert.IsTrue(strg2DCpy.TensorLayout == 2); + Assert.IsTrue(strg2DCpy.Shape.TensorLayout == 2); + + Assert.IsTrue(Enumerable.SequenceEqual(strg2DCpy.Shape.Dimensions,new int[]{3,3})); + Assert.IsTrue(Enumerable.SequenceEqual(strg2DCpy.GetData(), new Int64[]{0,3,6,1,4,7,2,5,8} )); + + strg2DCpy.ChangeTensorLayout(1); + + Assert.IsTrue(strg2DCpy.TensorLayout == 1); + Assert.IsTrue(strg2DCpy.Shape.TensorLayout == 1); + + Assert.IsTrue(Enumerable.SequenceEqual(strg2DCpy.Shape.Dimensions,new int[]{3,3})); + Assert.IsTrue(Enumerable.SequenceEqual(strg2DCpy.GetData(), strg2D.GetData() )); + + strg2DCpy = (NDStorage) strg2DNonFull.Clone(); + + Assert.IsTrue(strg2DCpy.TensorLayout == 1); + + strg2DCpy.ChangeTensorLayout(2); + + Assert.IsTrue(strg2DCpy.TensorLayout == 2); + Assert.IsTrue(strg2DCpy.Shape.TensorLayout == 2); + + Assert.IsTrue(Enumerable.SequenceEqual(strg2DCpy.Shape.Dimensions,new int[]{5,2})); + Assert.IsTrue(Enumerable.SequenceEqual(strg2DCpy.GetData(), new Int64[]{0,5,1,6,2,7,3,8,4,9} )); + + strg2DCpy.ChangeTensorLayout(1); + + Assert.IsTrue(strg2DCpy.TensorLayout == 1); + Assert.IsTrue(strg2DCpy.Shape.TensorLayout == 1); + + Assert.IsTrue(Enumerable.SequenceEqual(strg2DCpy.Shape.Dimensions,new int[]{5,2})); + Assert.IsTrue(Enumerable.SequenceEqual(strg2DCpy.GetData(), strg2DNonFull.GetData() )); + + strg2DCpy = new NDStorage(); + strg2DCpy.Allocate(typeof(Int64),new Shape(5,2),2); + + strg2DCpy.SetData(strg2DNonFull.GetData()); + + strg2DCpy.ChangeTensorLayout(1); + + Assert.IsTrue(Enumerable.SequenceEqual(strg2DCpy.GetData(),new Int64[]{0,2,4,6,8,1,3,5,7,9})); + + } + [TestMethod] + public void CheckChangeTensorLayout3D() + { + var strg3DCpy = (NDStorage) strg3D.Clone(); + + Assert.IsTrue(strg3DCpy.TensorLayout == 1); + + strg3DCpy.ChangeTensorLayout(2); + + Assert.IsTrue(strg3DCpy.TensorLayout == 2); + Assert.IsTrue(strg3DCpy.Shape.TensorLayout == 2); + + Assert.IsTrue(Enumerable.SequenceEqual(strg3DCpy.Shape.Dimensions,new int[]{2,2,2})); + Assert.IsTrue(Enumerable.SequenceEqual(strg3DCpy.GetData(), new Complex[]{1,5,3,7,2,6,4,8} )); + + strg3DCpy.ChangeTensorLayout(1); + + Assert.IsTrue(strg3DCpy.TensorLayout == 1); + Assert.IsTrue(strg3DCpy.Shape.TensorLayout == 1); + + Assert.IsTrue(Enumerable.SequenceEqual(strg3DCpy.Shape.Dimensions,new int[]{2,2,2})); + Assert.IsTrue(Enumerable.SequenceEqual(strg3DCpy.GetData(), strg3D.GetData() )); + + strg3DCpy = (NDStorage) strg3DNonFull.Clone(); + + Assert.IsTrue(strg3DCpy.TensorLayout == 1); + + strg3DCpy.ChangeTensorLayout(2); + + Assert.IsTrue(strg3DCpy.TensorLayout == 2); + Assert.IsTrue(strg3DCpy.Shape.TensorLayout == 2); + + var expectedValues = new Complex[]{1,7,13,19, 3,9,15,21, 5,11,17,23, 2,8,14,20, 4,10,16,22, 6,12,18,24 }; + + Assert.IsTrue(Enumerable.SequenceEqual(strg3DCpy.Shape.Dimensions,new int[]{2,3,4})); + Assert.IsTrue(Enumerable.SequenceEqual(strg3DCpy.GetData(), expectedValues )); + + strg3DCpy.ChangeTensorLayout(1); - double[] boxingCast = Storage1DInt.GetData(); + Assert.IsTrue(strg3DCpy.TensorLayout == 1); + Assert.IsTrue(strg3DCpy.Shape.TensorLayout == 1); - double[] directCastDouble = Storage1DDouble.GetData(); + Assert.IsTrue(Enumerable.SequenceEqual(strg3DCpy.Shape.Dimensions,new int[]{2,3,4})); + Assert.IsTrue(Enumerable.SequenceEqual(strg3DCpy.GetData(), strg3DNonFull.GetData() )); - int[] boxingToInt = Storage1DDouble.GetData(); - - } }