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 9.7 kB

6 years ago
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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. namespace Tensorflow
  21. {
  22. /// <summary>
  23. /// Binding utilities to mimic python functions.
  24. /// </summary>
  25. public static partial class Binding
  26. {
  27. public static void print(object obj)
  28. {
  29. Console.WriteLine(obj.ToString());
  30. }
  31. public static int len(object a)
  32. {
  33. switch (a)
  34. {
  35. case Array arr:
  36. return arr.Length;
  37. case IList arr:
  38. return arr.Count;
  39. case ICollection arr:
  40. return arr.Count;
  41. case NDArray ndArray:
  42. return ndArray.shape[0];
  43. case IEnumerable enumerable:
  44. return enumerable.OfType<object>().Count();
  45. }
  46. throw new NotImplementedException("len() not implemented for type: " + a.GetType());
  47. }
  48. public static IEnumerable<int> range(int end)
  49. {
  50. return Enumerable.Range(0, end);
  51. }
  52. public static IEnumerable<int> range(int start, int end)
  53. {
  54. return Enumerable.Range(start, end - start);
  55. }
  56. public static T New<T>() where T : IObjectLife, new()
  57. {
  58. var instance = new T();
  59. instance.__init__();
  60. return instance;
  61. }
  62. [DebuggerNonUserCode()] // with "Just My Code" enabled this lets the debugger break at the origin of the exception
  63. public static void tf_with(IObjectLife py, Action<IObjectLife> action)
  64. {
  65. try
  66. {
  67. py.__enter__();
  68. action(py);
  69. }
  70. catch (Exception ex)
  71. {
  72. Console.WriteLine(ex.ToString());
  73. throw;
  74. }
  75. finally
  76. {
  77. py.__exit__();
  78. py.Dispose();
  79. }
  80. }
  81. [DebuggerNonUserCode()] // with "Just My Code" enabled this lets the debugger break at the origin of the exception
  82. public static void tf_with<T>(T py, Action<T> action) where T : IObjectLife
  83. {
  84. try
  85. {
  86. py.__enter__();
  87. action(py);
  88. }
  89. catch (Exception ex)
  90. {
  91. Console.WriteLine(ex.ToString());
  92. throw;
  93. }
  94. finally
  95. {
  96. py.__exit__();
  97. py.Dispose();
  98. }
  99. }
  100. [DebuggerNonUserCode()] // with "Just My Code" enabled this lets the debugger break at the origin of the exception
  101. public static TOut tf_with<TIn, TOut>(TIn py, Func<TIn, TOut> action) where TIn : IObjectLife
  102. {
  103. try
  104. {
  105. py.__enter__();
  106. return action(py);
  107. }
  108. catch (Exception ex)
  109. {
  110. Console.WriteLine(ex.ToString());
  111. return default(TOut);
  112. }
  113. finally
  114. {
  115. py.__exit__();
  116. py.Dispose();
  117. }
  118. }
  119. public static float time()
  120. {
  121. return (float)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
  122. }
  123. public static IEnumerable<(T, T)> zip<T>(NDArray t1, NDArray t2)
  124. where T : unmanaged
  125. {
  126. var a = t1.AsIterator<T>();
  127. var b = t2.AsIterator<T>();
  128. while (a.HasNext())
  129. yield return (a.MoveNext(), b.MoveNext());
  130. }
  131. public static IEnumerable<(T1, T2)> zip<T1, T2>(IList<T1> t1, IList<T2> t2)
  132. {
  133. for (int i = 0; i < t1.Count; i++)
  134. yield return (t1[i], t2[i]);
  135. }
  136. public static IEnumerable<(T1, T2)> zip<T1, T2>(NDArray t1, NDArray t2)
  137. where T1: unmanaged
  138. where T2: unmanaged
  139. {
  140. var a = t1.AsIterator<T1>();
  141. var b = t2.AsIterator<T2>();
  142. while(a.HasNext())
  143. yield return (a.MoveNext(), b.MoveNext());
  144. }
  145. public static IEnumerable<(T1, T2)> zip<T1, T2>(IEnumerable<T1> e1, IEnumerable<T2> e2)
  146. {
  147. var iter2 = e2.GetEnumerator();
  148. foreach (var v1 in e1)
  149. {
  150. iter2.MoveNext();
  151. var v2 = iter2.Current;
  152. yield return (v1, v2);
  153. }
  154. }
  155. public static IEnumerable<(TKey, TValue)> enumerate<TKey, TValue>(Dictionary<TKey, TValue> values)
  156. {
  157. foreach (var item in values)
  158. yield return (item.Key, item.Value);
  159. }
  160. public static IEnumerable<(TKey, TValue)> enumerate<TKey, TValue>(KeyValuePair<TKey, TValue>[] values)
  161. {
  162. var len = values.Length;
  163. for (var i = 0; i < len; i++)
  164. {
  165. var item = values[i];
  166. yield return (item.Key, item.Value);
  167. }
  168. }
  169. public static IEnumerable<(int, T)> enumerate<T>(IList<T> values)
  170. {
  171. var len = values.Count;
  172. for (int i = 0; i < len; i++)
  173. yield return (i, values[i]);
  174. }
  175. public static Dictionary<string, object> ConvertToDict(object dyn)
  176. {
  177. var dictionary = new Dictionary<string, object>();
  178. foreach (PropertyDescriptor propertyDescriptor in TypeDescriptor.GetProperties(dyn))
  179. {
  180. object obj = propertyDescriptor.GetValue(dyn);
  181. string name = propertyDescriptor.Name;
  182. dictionary.Add(name, obj);
  183. }
  184. return dictionary;
  185. }
  186. public static bool all(IEnumerable enumerable)
  187. {
  188. foreach (var e1 in enumerable)
  189. {
  190. if (!Convert.ToBoolean(e1))
  191. return false;
  192. }
  193. return true;
  194. }
  195. public static bool any(IEnumerable enumerable)
  196. {
  197. foreach (var e1 in enumerable)
  198. {
  199. if (Convert.ToBoolean(e1))
  200. return true;
  201. }
  202. return false;
  203. }
  204. public static double sum(IEnumerable enumerable)
  205. {
  206. var typedef = new Type[] { typeof(double), typeof(int), typeof(float) };
  207. var sum = 0.0d;
  208. foreach (var e1 in enumerable)
  209. {
  210. if (!typedef.Contains(e1.GetType()))
  211. throw new Exception("Numeric array expected");
  212. sum += (double)e1;
  213. }
  214. return sum;
  215. }
  216. public static double sum<TKey, TValue>(Dictionary<TKey, TValue> values)
  217. {
  218. return sum(values.Keys);
  219. }
  220. public static IEnumerable<double> slice(double start, double end, double step = 1)
  221. {
  222. for (double i = start; i < end; i += step)
  223. yield return i;
  224. }
  225. public static IEnumerable<float> slice(float start, float end, float step = 1)
  226. {
  227. for (float i = start; i < end; i += step)
  228. yield return i;
  229. }
  230. public static IEnumerable<int> slice(int start, int end, int step = 1)
  231. {
  232. for (int i = start; i < end; i += step)
  233. yield return i;
  234. }
  235. public static IEnumerable<int> slice(int range)
  236. {
  237. for (int i = 0; i < range; i++)
  238. yield return i;
  239. }
  240. public static bool hasattr(object obj, string key)
  241. {
  242. var __type__ = (obj).GetType();
  243. var __member__ = __type__.GetMembers();
  244. var __memberobject__ = __type__.GetMember(key);
  245. return (__memberobject__.Length > 0) ? true : false;
  246. }
  247. public static IEnumerable TupleToEnumerable(object tuple)
  248. {
  249. Type t = tuple.GetType();
  250. if (t.IsGenericType && (t.FullName.StartsWith("System.Tuple") || t.FullName.StartsWith("System.ValueTuple")))
  251. {
  252. var flds = t.GetFields();
  253. for (int i = 0; i < flds.Length; i++)
  254. {
  255. yield return flds[i].GetValue(tuple);
  256. }
  257. } else
  258. {
  259. throw new System.Exception("Expected Tuple.");
  260. }
  261. }
  262. public static bool isinstance(object Item1, Type Item2)
  263. {
  264. return Item1.GetType() == Item2;
  265. }
  266. public static bool isinstance(object Item1, object tuple)
  267. {
  268. foreach (var t in TupleToEnumerable(tuple))
  269. if (isinstance(Item1, (Type) t))
  270. return true;
  271. return false;
  272. }
  273. }
  274. }