forked from SciSharp/NumSharp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNdArray.cs
More file actions
336 lines (290 loc) · 10.7 KB
/
NdArray.cs
File metadata and controls
336 lines (290 loc) · 10.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
/*
* 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 <http://www.apache.org/licenses/LICENSE-2.0/>.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Globalization;
namespace NumSharp
{
/// <summary>
/// A powerful N-dimensional array object
/// Inspired from https://www.numpy.org/devdocs/user/quickstart.html
/// </summary>
public partial class NDArray<T>
{
/// <summary>
/// 1 dim array data storage
/// </summary>
public T[] Data { get; set; }
/// <summary>
/// Data length of every dimension
/// </summary>
public Shape Shape { get; set; }
/// <summary>
/// Dimension count
/// </summary>
public int NDim => Shape.Length;
/// <summary>
/// Total of elements
/// </summary>
public int Size => Data.Length;
public NDArray()
{
// set default shape as 1 dim and 0 elements.
Shape = new Shape(new int[] { 0 });
Data = new T[] { };
}
/// <summary>
/// Index accessor
/// </summary>
/// <param name="select"></param>
/// <returns></returns>
public T this[params int[] select]
{
get
{
return Data[GetIndexInShape(select)];
}
set
{
Data[GetIndexInShape(select)] = value;
}
}
public NDArray<T> Vector(params int[] select)
{
if (select.Length == NDim)
{
throw new Exception("Please use NDArray[m, n] to access element.");
}
else
{
int start = GetIndexInShape(select);
int length = Shape.DimOffset[select.Length - 1];
var n = new NDArray<T>();
//n.Shape = shape.Skip(select.Length).ToList();
Span<T> data = Data;
n.Data = data.Slice(start, length).ToArray();
// Since n.Shape is a IList it cannot be converted to Span<T>
// This is a lot of hoops to jump throught to get it into a span
// shape.Skip(select.Length).ToList() may be more efficient - not sure
n.Shape = new Shape(Shape.Shapes.ToArray().AsSpan().Slice(select.Length).ToArray());
return n;
}
}
public void Vector(Shape shape, T value)
{
if (shape.Length == NDim)
{
throw new Exception("Please use NDArray[m, n] to access element.");
}
else
{
int start = GetIndexInShape(shape.Shapes.ToArray());
int length = Shape.DimOffset[shape.Length - 1];
Span<T> data = Data;
var elements = data.Slice(start, length);
for (int i = 0; i < elements.Length; i++)
{
elements[i] = value;
}
}
}
/// <summary>
/// Filter specific elements through select.
/// </summary>
/// <param name="select"></param>
/// <returns>Return a new NDArray with filterd elements.</returns>
public NDArray<T> this[IList<int> select]
{
get
{
var n = new NDArray<T>();
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;
}
}
/// <summary>
/// Overload
/// </summary>
/// <param name="select"></param>
/// <returns></returns>
public NDArray<T> this[NDArray<int> 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;
}
public override string ToString()
{
string output = "";
if (this.NDim == 2)
{
output = this._ToMatrixString();
}
else
{
output = "array([";
// loop
for (int r = 0; r < Data.Length; r++)
{
output += (r == 0) ? Data[r] + "" : ", " + Data[r];
}
output += "])";
}
return output;
}
public override bool Equals(object obj)
{
return Data[0].Equals(obj);
}
public static bool operator ==(NDArray<T> np, object obj)
{
return np.Data[0].Equals(obj);
}
public static bool operator !=(NDArray<T> 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<TCast>()
{
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 _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<char>(' ',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<char>(' ',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;
}
}
}