You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

Binding.Util.cs 11 kB

6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. /*****************************************************************************
  2. Copyright 2018 The TensorFlow.NET Authors. All Rights Reserved.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ******************************************************************************/
  13. using NumSharp;
  14. using System;
  15. using System.Collections;
  16. using System.Collections.Generic;
  17. using System.ComponentModel;
  18. using System.Diagnostics;
  19. using System.Linq;
  20. using NumSharp.Utilities;
  21. namespace Tensorflow
  22. {
  23. /// <summary>
  24. /// Binding utilities to mimic python functions.
  25. /// </summary>
  26. public static partial class Binding
  27. {
  28. public static T2 get<T1, T2>(this Dictionary<T1, T2> dict, T1 key)
  29. => key == null ?
  30. default(T2) :
  31. (dict.ContainsKey(key) ? dict[key] : default(T2));
  32. public static void add<T>(this IList<T> list, T element)
  33. => list.Add(element);
  34. public static void append<T>(this IList<T> list, T element)
  35. => list.Add(element);
  36. public static void extend<T>(this List<T> list, IEnumerable<T> elements)
  37. => list.AddRange(elements);
  38. private static string _tostring(object obj)
  39. {
  40. switch (obj)
  41. {
  42. case NDArray nd:
  43. return nd.ToString(false);
  44. case Array arr:
  45. if (arr.Rank!=1 || arr.GetType().GetElementType()?.IsArray == true)
  46. arr = Arrays.Flatten(arr);
  47. var objs = toObjectArray(arr);
  48. return $"[{string.Join(", ", objs.Select(_tostring))}]";
  49. default:
  50. return obj?.ToString() ?? "null";
  51. }
  52. object[] toObjectArray(Array arr)
  53. {
  54. var len = arr.LongLength;
  55. var ret = new object[len];
  56. for (long i = 0; i < len; i++)
  57. {
  58. ret[i] = arr.GetValue(i);
  59. }
  60. return ret;
  61. }
  62. }
  63. public static void print(object obj)
  64. {
  65. Console.WriteLine(_tostring(obj));
  66. }
  67. public static int len(object a)
  68. {
  69. switch (a)
  70. {
  71. case Array arr:
  72. return arr.Length;
  73. case IList arr:
  74. return arr.Count;
  75. case ICollection arr:
  76. return arr.Count;
  77. case NDArray ndArray:
  78. return ndArray.ndim == 0 ? 1 : ndArray.shape[0];
  79. case IEnumerable enumerable:
  80. return enumerable.OfType<object>().Count();
  81. }
  82. throw new NotImplementedException("len() not implemented for type: " + a.GetType());
  83. }
  84. public static float min(float a, float b)
  85. => Math.Min(a, b);
  86. public static T[] list<T>(IEnumerable<T> list)
  87. => list.ToArray();
  88. public static IEnumerable<int> range(int end)
  89. {
  90. return Enumerable.Range(0, end);
  91. }
  92. public static IEnumerable<int> range(int start, int end)
  93. {
  94. return Enumerable.Range(start, end - start);
  95. }
  96. public static T New<T>() where T : IObjectLife, new()
  97. {
  98. var instance = new T();
  99. instance.__init__();
  100. return instance;
  101. }
  102. [DebuggerStepThrough]
  103. [DebuggerNonUserCode()] // with "Just My Code" enabled this lets the debugger break at the origin of the exception
  104. public static void tf_with(IObjectLife py, Action<IObjectLife> action)
  105. {
  106. try
  107. {
  108. py.__enter__();
  109. action(py);
  110. }
  111. finally
  112. {
  113. py.__exit__();
  114. py.Dispose();
  115. }
  116. }
  117. [DebuggerStepThrough]
  118. [DebuggerNonUserCode()] // with "Just My Code" enabled this lets the debugger break at the origin of the exception
  119. public static void tf_with<T>(T py, Action<T> action) where T : IObjectLife
  120. {
  121. try
  122. {
  123. py.__enter__();
  124. action(py);
  125. }
  126. finally
  127. {
  128. py.__exit__();
  129. py.Dispose();
  130. }
  131. }
  132. [DebuggerStepThrough]
  133. [DebuggerNonUserCode()] // with "Just My Code" enabled this lets the debugger break at the origin of the exception
  134. public static TOut tf_with<TIn, TOut>(TIn py, Func<TIn, TOut> action) where TIn : IObjectLife
  135. {
  136. try
  137. {
  138. py.__enter__();
  139. return action(py);
  140. }
  141. finally
  142. {
  143. py.__exit__();
  144. py.Dispose();
  145. }
  146. }
  147. public static float time()
  148. {
  149. return (float)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
  150. }
  151. public static IEnumerable<(T, T)> zip<T>(NDArray t1, NDArray t2)
  152. where T : unmanaged
  153. {
  154. var a = t1.AsIterator<T>();
  155. var b = t2.AsIterator<T>();
  156. while (a.HasNext() && b.HasNext())
  157. yield return (a.MoveNext(), b.MoveNext());
  158. }
  159. public static IEnumerable<(T1, T2)> zip<T1, T2>(IList<T1> t1, IList<T2> t2)
  160. {
  161. for (int i = 0; i < t1.Count; i++)
  162. yield return (t1[i], t2[i]);
  163. }
  164. public static IEnumerable<(T1, T2, T3)> zip<T1, T2, T3>(IList<T1> t1, IList<T2> t2, IList<T3> t3)
  165. {
  166. for (int i = 0; i < t1.Count; i++)
  167. yield return (t1[i], t2[i], t3[i]);
  168. }
  169. public static IEnumerable<(T1, T2)> zip<T1, T2>(NDArray t1, NDArray t2)
  170. where T1: unmanaged
  171. where T2: unmanaged
  172. {
  173. var a = t1.AsIterator<T1>();
  174. var b = t2.AsIterator<T2>();
  175. while(a.HasNext() && b.HasNext())
  176. yield return (a.MoveNext(), b.MoveNext());
  177. }
  178. public static IEnumerable<(T1, T2)> zip<T1, T2>(IEnumerable<T1> e1, IEnumerable<T2> e2)
  179. {
  180. return e1.Zip(e2, (t1, t2) => (t1, t2));
  181. }
  182. public static IEnumerable<(TKey, TValue)> enumerate<TKey, TValue>(Dictionary<TKey, TValue> values)
  183. {
  184. foreach (var item in values)
  185. yield return (item.Key, item.Value);
  186. }
  187. public static IEnumerable<(TKey, TValue)> enumerate<TKey, TValue>(KeyValuePair<TKey, TValue>[] values)
  188. {
  189. var len = values.Length;
  190. for (var i = 0; i < len; i++)
  191. {
  192. var item = values[i];
  193. yield return (item.Key, item.Value);
  194. }
  195. }
  196. public static IEnumerable<(int, T)> enumerate<T>(IList<T> values)
  197. {
  198. var len = values.Count;
  199. for (int i = 0; i < len; i++)
  200. yield return (i, values[i]);
  201. }
  202. [DebuggerStepThrough]
  203. public static Dictionary<string, object> ConvertToDict(object dyn)
  204. {
  205. var dictionary = new Dictionary<string, object>();
  206. foreach (PropertyDescriptor propertyDescriptor in TypeDescriptor.GetProperties(dyn))
  207. {
  208. object obj = propertyDescriptor.GetValue(dyn);
  209. string name = propertyDescriptor.Name;
  210. dictionary.Add(name, obj);
  211. }
  212. return dictionary;
  213. }
  214. public static bool all(IEnumerable enumerable)
  215. {
  216. foreach (var e1 in enumerable)
  217. {
  218. if (!Convert.ToBoolean(e1))
  219. return false;
  220. }
  221. return true;
  222. }
  223. public static bool any(IEnumerable enumerable)
  224. {
  225. foreach (var e1 in enumerable)
  226. {
  227. if (Convert.ToBoolean(e1))
  228. return true;
  229. }
  230. return false;
  231. }
  232. public static double sum(IEnumerable enumerable)
  233. {
  234. var typedef = new Type[] { typeof(double), typeof(int), typeof(float) };
  235. var sum = 0.0d;
  236. foreach (var e1 in enumerable)
  237. {
  238. if (!typedef.Contains(e1.GetType()))
  239. throw new Exception("Numeric array expected");
  240. sum += (double)e1;
  241. }
  242. return sum;
  243. }
  244. public static float sum(IEnumerable<float> enumerable)
  245. => enumerable.Sum();
  246. public static int sum(IEnumerable<int> enumerable)
  247. => enumerable.Sum();
  248. public static double sum<TKey, TValue>(Dictionary<TKey, TValue> values)
  249. {
  250. return sum(values.Keys);
  251. }
  252. public static IEnumerable<double> slice(double start, double end, double step = 1)
  253. {
  254. for (double i = start; i < end; i += step)
  255. yield return i;
  256. }
  257. public static IEnumerable<float> slice(float start, float end, float step = 1)
  258. {
  259. for (float i = start; i < end; i += step)
  260. yield return i;
  261. }
  262. public static IEnumerable<int> slice(int start, int end, int step = 1)
  263. {
  264. for (int i = start; i < end; i += step)
  265. yield return i;
  266. }
  267. public static IEnumerable<int> slice(int range)
  268. {
  269. for (int i = 0; i < range; i++)
  270. yield return i;
  271. }
  272. public static bool hasattr(object obj, string key)
  273. {
  274. var __type__ = (obj).GetType();
  275. var __member__ = __type__.GetMembers();
  276. var __memberobject__ = __type__.GetMember(key);
  277. return (__memberobject__.Length > 0) ? true : false;
  278. }
  279. public static IEnumerable TupleToEnumerable(object tuple)
  280. {
  281. Type t = tuple.GetType();
  282. if (t.IsGenericType && (t.FullName.StartsWith("System.Tuple") || t.FullName.StartsWith("System.ValueTuple")))
  283. {
  284. var flds = t.GetFields();
  285. for (int i = 0; i < flds.Length; i++)
  286. {
  287. yield return flds[i].GetValue(tuple);
  288. }
  289. } else
  290. {
  291. throw new System.Exception("Expected Tuple.");
  292. }
  293. }
  294. public static bool isinstance(object Item1, Type Item2)
  295. {
  296. return Item1.GetType() == Item2;
  297. }
  298. public static bool isinstance(object Item1, object tuple)
  299. {
  300. foreach (var t in TupleToEnumerable(tuple))
  301. if (isinstance(Item1, (Type) t))
  302. return true;
  303. return false;
  304. }
  305. }
  306. }