|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Diagnostics; |
| 4 | +using System.Text; |
| 5 | + |
| 6 | +namespace Tensorflow.Common.Types |
| 7 | +{ |
| 8 | + public class GeneralizedTensorShape: IEnumerable<long?[]> |
| 9 | + { |
| 10 | + public TensorShapeConfig[] Shapes { get; set; } |
| 11 | + /// <summary> |
| 12 | + /// create a single-dim generalized Tensor shape. |
| 13 | + /// </summary> |
| 14 | + /// <param name="dim"></param> |
| 15 | + public GeneralizedTensorShape(int dim) |
| 16 | + { |
| 17 | + Shapes = new TensorShapeConfig[] { new TensorShapeConfig() { Items = new long?[] { dim } } }; |
| 18 | + } |
| 19 | + |
| 20 | + public GeneralizedTensorShape(Shape shape) |
| 21 | + { |
| 22 | + Shapes = new TensorShapeConfig[] { shape }; |
| 23 | + } |
| 24 | + |
| 25 | + public GeneralizedTensorShape(TensorShapeConfig shape) |
| 26 | + { |
| 27 | + Shapes = new TensorShapeConfig[] { shape }; |
| 28 | + } |
| 29 | + |
| 30 | + public GeneralizedTensorShape(TensorShapeConfig[] shapes) |
| 31 | + { |
| 32 | + Shapes = shapes; |
| 33 | + } |
| 34 | + |
| 35 | + public GeneralizedTensorShape(IEnumerable<Shape> shape) |
| 36 | + { |
| 37 | + Shapes = shape.Select(x => (TensorShapeConfig)x).ToArray(); |
| 38 | + } |
| 39 | + |
| 40 | + public Shape ToSingleShape() |
| 41 | + { |
| 42 | + if (Shapes.Length != 1) |
| 43 | + { |
| 44 | + throw new ValueError("The generalized shape contains more than 1 dim."); |
| 45 | + } |
| 46 | + var shape_config = Shapes[0]; |
| 47 | + Debug.Assert(shape_config is not null); |
| 48 | + return new Shape(shape_config.Items.Select(x => x is null ? -1 : x.Value).ToArray()); |
| 49 | + } |
| 50 | + |
| 51 | + public long ToNumber() |
| 52 | + { |
| 53 | + if(Shapes.Length != 1 || Shapes[0].Items.Length != 1) |
| 54 | + { |
| 55 | + throw new ValueError("The generalized shape contains more than 1 dim."); |
| 56 | + } |
| 57 | + var res = Shapes[0].Items[0]; |
| 58 | + return res is null ? -1 : res.Value; |
| 59 | + } |
| 60 | + |
| 61 | + public Shape[] ToShapeArray() |
| 62 | + { |
| 63 | + return Shapes.Select(x => new Shape(x.Items.Select(y => y is null ? -1 : y.Value).ToArray())).ToArray(); |
| 64 | + } |
| 65 | + |
| 66 | + public IEnumerator<long?[]> GetEnumerator() |
| 67 | + { |
| 68 | + foreach (var shape in Shapes) |
| 69 | + { |
| 70 | + yield return shape.Items; |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + IEnumerator IEnumerable.GetEnumerator() |
| 75 | + { |
| 76 | + return GetEnumerator(); |
| 77 | + } |
| 78 | + } |
| 79 | +} |
0 commit comments