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.

Python.cs 10 kB

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