/*****************************************************************************
Copyright 2018 The TensorFlow.NET Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
******************************************************************************/
using NumSharp;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using NumSharp.Utilities;
namespace Tensorflow
{
///
/// Binding utilities to mimic python functions.
///
public static partial class Binding
{
public static T2 get(this Dictionary dict, T1 key)
=> key == null ?
default(T2) :
(dict.ContainsKey(key) ? dict[key] : default(T2));
public static void add(this IList list, T element)
=> list.Add(element);
public static void append(this IList list, T element)
=> list.Add(element);
public static void extend(this List list, IEnumerable elements)
=> list.AddRange(elements);
private static string _tostring(object obj)
{
switch (obj)
{
case NDArray nd:
return nd.ToString(false);
case Array arr:
if (arr.Rank!=1 || arr.GetType().GetElementType()?.IsArray == true)
arr = Arrays.Flatten(arr);
var objs = toObjectArray(arr);
return $"[{string.Join(", ", objs.Select(_tostring))}]";
default:
return obj?.ToString() ?? "null";
}
object[] toObjectArray(Array arr)
{
var len = arr.LongLength;
var ret = new object[len];
for (long i = 0; i < len; i++)
{
ret[i] = arr.GetValue(i);
}
return ret;
}
}
public static void print(object obj)
{
Console.WriteLine(_tostring(obj));
}
public static int len(object a)
{
switch (a)
{
case Array arr:
return arr.Length;
case IList arr:
return arr.Count;
case ICollection arr:
return arr.Count;
case NDArray ndArray:
return ndArray.ndim == 0 ? 1 : ndArray.shape[0];
case IEnumerable enumerable:
return enumerable.OfType