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

4 years ago
6 years ago
4 years ago
6 years ago
4 years ago
6 years ago
6 years ago
6 years ago
6 years ago
4 years ago
4 years ago
4 years ago
5 years ago
6 years ago
4 years ago
6 years ago
6 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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 NumSharp.Utilities;
  15. using System;
  16. using System.Collections;
  17. using System.Collections.Generic;
  18. using System.ComponentModel;
  19. using System.Diagnostics;
  20. using System.IO;
  21. using System.Linq;
  22. namespace Tensorflow
  23. {
  24. /// <summary>
  25. /// Binding utilities to mimic python functions.
  26. /// </summary>
  27. public static partial class Binding
  28. {
  29. public static T2 get<T1, T2>(this Dictionary<T1, T2> dict, T1 key)
  30. => key == null ?
  31. default :
  32. (dict.ContainsKey(key) ? dict[key] : default);
  33. public static void Update<T>(this IList<T> list, T element)
  34. {
  35. var index = list.IndexOf(element);
  36. if (index < 0)
  37. list.Add(element);
  38. else
  39. {
  40. list[index] = element;
  41. }
  42. }
  43. public static void difference_update<T>(this IList<T> list, IList<T> list2)
  44. {
  45. foreach(var el in list2)
  46. {
  47. if (list.Contains(el))
  48. list.Remove(el);
  49. }
  50. }
  51. public static void add<T>(this IList<T> list, T element)
  52. => list.Add(element);
  53. public static void add<T>(this IList<T> list, IEnumerable<T> elements)
  54. {
  55. foreach (var ele in elements)
  56. list.Add(ele);
  57. }
  58. public static void append<T>(this IList<T> list, T element)
  59. => list.Insert(list.Count, element);
  60. public static void append<T>(this IList<T> list, IList<T> elements)
  61. {
  62. for (int i = 0; i < elements.Count(); i++)
  63. list.Insert(list.Count, elements[i]);
  64. }
  65. public static T[] concat<T>(this IList<T> list1, IList<T> list2)
  66. {
  67. var list = new List<T>();
  68. list.AddRange(list1);
  69. list.AddRange(list2);
  70. return list.ToArray();
  71. }
  72. public static void extend<T>(this List<T> list, IEnumerable<T> elements)
  73. => list.AddRange(elements);
  74. private static string _tostring(object obj)
  75. {
  76. switch (obj)
  77. {
  78. case NDArray nd:
  79. return nd.ToString(false);
  80. case Array arr:
  81. if (arr.Rank != 1 || arr.GetType().GetElementType()?.IsArray == true)
  82. arr = Arrays.Flatten(arr);
  83. var objs = toObjectArray(arr);
  84. return $"[{string.Join(", ", objs.Select(_tostring))}]";
  85. default:
  86. return obj?.ToString() ?? "null";
  87. }
  88. object[] toObjectArray(Array arr)
  89. {
  90. var len = arr.LongLength;
  91. var ret = new object[len];
  92. for (long i = 0; i < len; i++)
  93. {
  94. ret[i] = arr.GetValue(i);
  95. }
  96. return ret;
  97. }
  98. }
  99. private static TextWriter writer = null;
  100. public static TextWriter tf_output_redirect {
  101. set
  102. {
  103. var originWriter = writer ?? Console.Out;
  104. originWriter.Flush();
  105. if (originWriter is StringWriter)
  106. (originWriter as StringWriter).GetStringBuilder().Clear();
  107. writer = value;
  108. }
  109. get
  110. {
  111. return writer ?? Console.Out;
  112. }
  113. }
  114. public static void print(object obj)
  115. {
  116. tf_output_redirect.WriteLine(_tostring(obj));
  117. }
  118. public static void print(string format, params object[] objects)
  119. {
  120. if (!format.Contains("{}"))
  121. {
  122. tf_output_redirect.WriteLine(format + " " + string.Join(" ", objects.Select(x => x.ToString())));
  123. return;
  124. }
  125. foreach (var obj in objects)
  126. {
  127. }
  128. tf_output_redirect.WriteLine(format);
  129. }
  130. public static int len(object a)
  131. {
  132. switch (a)
  133. {
  134. case Tensor tensor:
  135. return tensor.shape[0];
  136. case Tensors arr:
  137. return arr.Length;
  138. case Array arr:
  139. return arr.Length;
  140. case IList arr:
  141. return arr.Count;
  142. case ICollection arr:
  143. return arr.Count;
  144. case NDArray ndArray:
  145. return ndArray.ndim == 0 ? 1 : ndArray.shape[0];
  146. case IEnumerable enumerable:
  147. return enumerable.OfType<object>().Count();
  148. case TensorShape arr:
  149. return arr.ndim;
  150. }
  151. throw new NotImplementedException("len() not implemented for type: " + a.GetType());
  152. }
  153. public static float min(float a, float b)
  154. => Math.Min(a, b);
  155. public static int max(int a, int b)
  156. => Math.Max(a, b);
  157. public static T[] list<T>(IEnumerable<T> list)
  158. => list.ToArray();
  159. public static IEnumerable<int> range(int end)
  160. {
  161. return Enumerable.Range(0, end);
  162. }
  163. public static IEnumerable<int> range(int start, int end)
  164. {
  165. return Enumerable.Range(start, end - start);
  166. }
  167. public static IEnumerable<T> reversed<T>(IList<T> values)
  168. {
  169. var len = values.Count;
  170. for (int i = len - 1; i >= 0; i--)
  171. yield return values[i];
  172. }
  173. public static T New<T>() where T : ITensorFlowObject, new()
  174. {
  175. var instance = new T();
  176. instance.__init__();
  177. return instance;
  178. }
  179. [DebuggerStepThrough]
  180. public static void tf_with(ITensorFlowObject py, Action<ITensorFlowObject> action)
  181. {
  182. try
  183. {
  184. py.__enter__();
  185. action(py);
  186. }
  187. finally
  188. {
  189. py.__exit__();
  190. py.Dispose();
  191. }
  192. }
  193. [DebuggerStepThrough]
  194. public static void tf_with<T>(T py, Action<T> action) where T : ITensorFlowObject
  195. {
  196. try
  197. {
  198. py.__enter__();
  199. action(py);
  200. }
  201. finally
  202. {
  203. py.__exit__();
  204. py.Dispose();
  205. }
  206. }
  207. [DebuggerStepThrough]
  208. public static TOut tf_with<TIn, TOut>(TIn py, Func<TIn, TOut> action) where TIn : ITensorFlowObject
  209. {
  210. try
  211. {
  212. py.__enter__();
  213. return action(py);
  214. }
  215. finally
  216. {
  217. py.__exit__();
  218. py.Dispose();
  219. }
  220. }
  221. public static float time()
  222. {
  223. return (float)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
  224. }
  225. public static IEnumerable<(T1, T2)> zip<T1, T2>((T1, T1) t1, (T2, T2) t2)
  226. {
  227. for (int i = 0; i < 2; i++)
  228. {
  229. if (i == 0)
  230. yield return (t1.Item1, t2.Item1);
  231. else
  232. yield return (t1.Item2, t2.Item2);
  233. }
  234. }
  235. public static IEnumerable<(T, T)> zip<T>(NDArray t1, NDArray t2)
  236. where T : unmanaged
  237. {
  238. var a = t1.AsIterator<T>();
  239. var b = t2.AsIterator<T>();
  240. while (a.HasNext() && b.HasNext())
  241. yield return (a.MoveNext(), b.MoveNext());
  242. }
  243. public static IEnumerable<(T1, T2)> zip<T1, T2>(IList<T1> t1, IList<T2> t2)
  244. {
  245. for (int i = 0; i < t1.Count; i++)
  246. yield return (t1[i], t2[i]);
  247. }
  248. public static IEnumerable<(T1, T2, T3)> zip<T1, T2, T3>(IList<T1> t1, IList<T2> t2, IList<T3> t3)
  249. {
  250. for (int i = 0; i < t1.Count; i++)
  251. yield return (t1[i], t2[i], t3[i]);
  252. }
  253. public static IEnumerable<(T1, T2)> zip<T1, T2>(NDArray t1, NDArray t2)
  254. where T1 : unmanaged
  255. where T2 : unmanaged
  256. {
  257. var a = t1.AsIterator<T1>();
  258. var b = t2.AsIterator<T2>();
  259. while (a.HasNext() && b.HasNext())
  260. yield return (a.MoveNext(), b.MoveNext());
  261. }
  262. public static IEnumerable<(T1, T2)> zip<T1, T2>(IEnumerable<T1> e1, IEnumerable<T2> e2)
  263. {
  264. return e1.Zip(e2, (t1, t2) => (t1, t2));
  265. }
  266. public static IEnumerable<(TKey, TValue)> enumerate<TKey, TValue>(Dictionary<TKey, TValue> values)
  267. {
  268. foreach (var item in values)
  269. yield return (item.Key, item.Value);
  270. }
  271. public static IEnumerable<(TKey, TValue)> enumerate<TKey, TValue>(KeyValuePair<TKey, TValue>[] values)
  272. {
  273. var len = values.Length;
  274. for (var i = 0; i < len; i++)
  275. {
  276. var item = values[i];
  277. yield return (item.Key, item.Value);
  278. }
  279. }
  280. public static IEnumerable<(int, T)> enumerate<T>(IList<T> values)
  281. {
  282. var len = values.Count;
  283. for (int i = 0; i < len; i++)
  284. yield return (i, values[i]);
  285. }
  286. public static IEnumerable<(int, T)> enumerate<T>(IEnumerable<T> values, int start = 0, int step = 1)
  287. {
  288. int i = 0;
  289. foreach (var val in values)
  290. {
  291. if (i++ < start)
  292. continue;
  293. yield return (i - 1, val);
  294. }
  295. }
  296. [DebuggerStepThrough]
  297. public static Dictionary<string, object> ConvertToDict(object dyn)
  298. {
  299. var dictionary = new Dictionary<string, object>();
  300. foreach (PropertyDescriptor propertyDescriptor in TypeDescriptor.GetProperties(dyn))
  301. {
  302. object obj = propertyDescriptor.GetValue(dyn);
  303. string name = propertyDescriptor.Name;
  304. dictionary.Add(name, obj);
  305. }
  306. return dictionary;
  307. }
  308. public static bool all(IEnumerable enumerable)
  309. {
  310. foreach (var e1 in enumerable)
  311. {
  312. if (!Convert.ToBoolean(e1))
  313. return false;
  314. }
  315. return true;
  316. }
  317. public static bool any(IEnumerable enumerable)
  318. {
  319. foreach (var e1 in enumerable)
  320. {
  321. if (Convert.ToBoolean(e1))
  322. return true;
  323. }
  324. return false;
  325. }
  326. public static double sum(IEnumerable enumerable)
  327. {
  328. var typedef = new Type[] { typeof(double), typeof(int), typeof(float) };
  329. var sum = 0.0d;
  330. foreach (var e1 in enumerable)
  331. {
  332. if (!typedef.Contains(e1.GetType()))
  333. throw new Exception("Numeric array expected");
  334. sum += (double)e1;
  335. }
  336. return sum;
  337. }
  338. public static float sum(IEnumerable<float> enumerable)
  339. => enumerable.Sum();
  340. public static int sum(IEnumerable<int> enumerable)
  341. => enumerable.Sum();
  342. public static double sum<TKey, TValue>(Dictionary<TKey, TValue> values)
  343. {
  344. return sum(values.Keys);
  345. }
  346. public static IEnumerable<double> slice(double start, double end, double step = 1)
  347. {
  348. for (double i = start; i < end; i += step)
  349. yield return i;
  350. }
  351. public static IEnumerable<float> slice(float start, float end, float step = 1)
  352. {
  353. for (float i = start; i < end; i += step)
  354. yield return i;
  355. }
  356. public static IEnumerable<int> slice(int start, int end, int step = 1)
  357. {
  358. for (int i = start; i < end; i += step)
  359. yield return i;
  360. }
  361. public static IEnumerable<int> slice(int range)
  362. {
  363. for (int i = 0; i < range; i++)
  364. yield return i;
  365. }
  366. public static bool hasattr(object obj, string key)
  367. {
  368. var __type__ = (obj).GetType();
  369. var __member__ = __type__.GetMembers();
  370. var __memberobject__ = __type__.GetMember(key);
  371. return (__memberobject__.Length > 0) ? true : false;
  372. }
  373. public static IEnumerable TupleToEnumerable(object tuple)
  374. {
  375. Type t = tuple.GetType();
  376. if (t.IsGenericType && (t.FullName.StartsWith("System.Tuple") || t.FullName.StartsWith("System.ValueTuple")))
  377. {
  378. var flds = t.GetFields();
  379. for (int i = 0; i < flds.Length; i++)
  380. {
  381. yield return flds[i].GetValue(tuple);
  382. }
  383. }
  384. else
  385. {
  386. throw new System.Exception("Expected Tuple.");
  387. }
  388. }
  389. public static bool isinstance(object Item1, Type Item2)
  390. {
  391. return Item1.GetType() == Item2;
  392. }
  393. public static bool isinstance(object Item1, object tuple)
  394. {
  395. foreach (var t in TupleToEnumerable(tuple))
  396. if (isinstance(Item1, (Type)t))
  397. return true;
  398. return false;
  399. }
  400. public static bool issubset<T>(this IEnumerable<T> subset, IEnumerable<T> src)
  401. {
  402. bool issubset = true;
  403. foreach (var element in subset)
  404. {
  405. if (!src.Contains(element))
  406. {
  407. issubset = false;
  408. continue;
  409. }
  410. }
  411. return true;
  412. }
  413. public static void extendleft<T>(this Queue<T> queue, IEnumerable<T> elements)
  414. {
  415. foreach (var element in elements.Reverse())
  416. queue.Enqueue(element);
  417. }
  418. public static bool empty<T>(this Queue<T> queue)
  419. => queue.Count == 0;
  420. public static TValue SetDefault<TKey, TValue>(this Dictionary<TKey, TValue> dic, TKey key, TValue defaultValue)
  421. {
  422. if (dic.ContainsKey(key))
  423. return dic[key];
  424. dic[key] = defaultValue;
  425. return defaultValue;
  426. }
  427. public static TValue Get<TKey, TValue>(this Dictionary<TKey, TValue> dic, TKey key, TValue defaultValue)
  428. {
  429. if (dic.ContainsKey(key))
  430. return dic[key];
  431. return defaultValue;
  432. }
  433. }
  434. }