Repository navigation
Expand file tree
/
Copy pathNdArray.ReShape.cs
More file actions
105 lines (94 loc) · 3.45 KB
/
Copy pathNdArray.ReShape.cs
File metadata and controls
105 lines (94 loc) · 3.45 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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Linq;
namespace NumSharp.Extensions
{
public static partial class NDArrayExtensions
{
public static NDArray<int> reshape(this NDArray<int> np, params int[] shape)
{
np.Shape = new Shape(shape);
return np;
}
/// <summary>
/// Gives a new shape to an array without changing its data.
/// </summary>
/// <typeparam name="TData"></typeparam>
/// <returns></returns>
public static NDArray<T> ReShape<T>(this NDArray<T> np, params int[] shape)
{
var count = shape.Length;
var idx = FindNegativeIndex(shape);
if (idx == -1)
np.Shape = new Shape(shape);
else
np.Shape = new Shape(CalculateNegativeShape(idx, np.Shape.Shapes.ToList(), shape));
//np.Shape = newShape;
return np;
}
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<int> currentShape, params int[] shapeParams)
{
var currentShapeCount = currentShape.Count;
var shapeParamCount = shapeParams.Length;
var newShape = new List<int>();
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");
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();
}
}
}