示例#1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="np1"></param>
        /// <param name="np2"></param>
        /// <typeparam name="TData"></typeparam>
        /// <returns></returns>
        public NDArray multi_dot(params NDArray[] np2Multi)
        {
            var np2 = np2Multi.Last();

            if ((this.ndim == 1) & (np2.ndim == 1))
            {
                if (this.shape[0] != np2.shape[0])
                {
                    throw new IncorrectShapeException();
                }
                else
                {
                    np2.Storage.Reshape(np2.Storage.GetData().Length, 1);
                    this.Storage.Reshape(1, this.Storage.GetData().Length);
                }
            }
            else
            if (this.shape[1] != np2.shape[0])
            {
                throw new IncorrectShapeException();
            }

            var prod = BackendFactory.GetEngine().Dot(this, np2Multi[0]);

            for (int idx = 1; idx < np2Multi.Length; idx++)
            {
                prod = BackendFactory.GetEngine().Dot(prod, np2Multi[idx]);
            }

            return(prod);
        }
示例#2
0
        public void CreateBackend_ForCompiler()
        {
            var backendFactory = new BackendFactory(Mock.Of <IMessageHandler>(), Mock.Of <ITimeProvider>());
            var backend        = backendFactory.CreateBackend("compile");

            backend.Should().BeOfType(typeof(CodeGenerator));
        }
示例#3
0
文件: Program.cs 项目: croese/wci
        static void Main(string[] args)
        {
            var result = Parser.Default.ParseArguments <Options>(args);

            result.WithParsed(o =>
            {
                try
                {
                    var source = new Source(new StreamReader(o.SourceFilePath));
                    source.AddMessageListener(new SourceMessageListener());

                    var parser = FrontendFactory.CreateParser("pascal", "top-down", source);
                    parser.AddMessageListener(new ParserMessageListener());

                    var backend = BackendFactory.CreateBackend(o.Operation);
                    backend.AddMessageListener(new BackendMessageListener());

                    parser.Parse();
                    source.Close();

                    var iCode  = parser.IntermediateCode;
                    var symTab = parser.SymbolTable;

                    backend.Process(iCode, symTab);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            });
        }
示例#4
0
        public void CreateBackend_ForExecute()
        {
            var backendFactory = new BackendFactory(Mock.Of <IMessageHandler>(), Mock.Of <ITimeProvider>());
            var backend        = backendFactory.CreateBackend("execute");

            backend.Should().BeOfType(typeof(Executor));
        }
示例#5
0
        public void FromMultiDimArray(Array dotNetArray)
        {
            if (dotNetArray.GetType().GetElementType().IsArray)
            {
                throw new Exception("Jagged arrays are not allowed here!");
            }

            int[] dims = new int[dotNetArray.Rank];

            for (int idx = 0; idx < dims.Length; idx++)
            {
                dims[idx] = dotNetArray.GetLength(idx);
            }

            Storage = BackendFactory.GetStorage(dotNetArray.GetType().GetElementType());

            Storage.Allocate(new Shape(dims));

            Array internalStrg = Storage.GetData();

            var pufferShape = new Shape(dims);

            pufferShape.ChangeTensorLayout();

            int[]  idxDims  = null;
            object valueIdx = null;

            for (int idx = 0; idx < Storage.Shape.Size; idx++)
            {
                idxDims  = pufferShape.GetDimIndexOutShape(idx);
                valueIdx = dotNetArray.GetValue(pufferShape.GetDimIndexOutShape(idx));
                internalStrg.SetValue(valueIdx, Storage.Shape.GetIndexInShape(idxDims));
            }
        }
示例#6
0
        public NDArray matrix_power(int power)
        {
            if (power < 0)
            {
                throw new Exception("matrix_power just work with int >= 0");
            }

            NDArray product = this.copy();

            for (int idx = 2; idx <= power; idx++)
            {
                product = BackendFactory.GetEngine().Dot(product, this);
            }

            product = (power == 0) ? np.eye(product.shape[0]) : product;

            return(product);
        }
        private Backend backend;  // backend

        public Pascal(string operation, string filePath, string flags)
        {
            try
            {
                bool intermediate = flags.IndexOf('i') > -1;
                bool xref         = flags.IndexOf('x') > -1;

                source = new Source(new StreamReader(filePath));
                source.addMessageListener(new SourceMessageListener());

                parser = FrontendFactory.createParser("Pascal", "top-down", source);
                parser.addMessageListener(new ParserMessageListener());

                backend = BackendFactory.createBackend(operation);
                backend.addMessageListener(new BackendMessageListener());

                parser.parse();
                source.close();

                iCode            = parser.iCode;
                symbolTableStack = Parser.symbolTableStack;

                if (xref)
                {
                    CrossReferencer crossReferencer = new CrossReferencer();
                    crossReferencer.Print(symbolTableStack);
                }

                if (intermediate)
                {
                    ParseTreePrinter treePrinter = new ParseTreePrinter(Console.Out);
                    treePrinter.Print(iCode);
                }
                backend.process(iCode, symbolTableStack);
            }

            catch (Exception e)
            {
                Console.WriteLine("***** Internal translator error. *****");
                Console.WriteLine(e.StackTrace);
            }
        }
示例#8
0
        public StorageTester()
        {
            strg1D = new UnmanagedStorage(np.float64)
            {
                Engine = BackendFactory.GetEngine()
            };
            strg1D.Allocate(new Shape(10));
            strg1D.ReplaceData(new double[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });

            strg2D = new UnmanagedStorage(np.int64)
            {
                Engine = BackendFactory.GetEngine()
            };
            strg2D.Allocate(new Shape(3, 3));
            strg2D.ReplaceData(new long[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 });

            strg2DNonFull = new UnmanagedStorage(np.float32)
            {
                Engine = BackendFactory.GetEngine()
            };
            strg2DNonFull.Allocate(new Shape(5, 2));
            strg2DNonFull.ReplaceData(new float[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
        }
示例#9
0
 public static NDArray operator -(NDArray x)
 => BackendFactory.GetEngine().Negate(x);     //access engine directly since there is no np.negate(x)
示例#10
0
 /// <summary>
 /// Constructor which initialize elements with 0
 /// type and shape are given.
 /// </summary>
 /// <param name="dtype">internal data type</param>
 /// <param name="shape">Shape of NDArray</param>
 public NDArray(Type dtype, Shape shape)
 {
     TensorEngine = BackendFactory.GetEngine();
     Storage      = new NDStorage(dtype);
     Storage.Allocate(shape);
 }
示例#11
0
 public static NDArray mean(NDArray nd, int axis = -1)
 => BackendFactory.GetEngine().Mean(nd, axis);
示例#12
0
        public void CreateBackend_ThrowsExceptionForUnknownOperation()
        {
            var backendFactory = new BackendFactory(Mock.Of <IMessageHandler>(), Mock.Of <ITimeProvider>());

            backendFactory.CreateBackend("unknown");
        }
示例#13
0
        /*public NDArray()
         * {
         *  throw new Exception("Don't use 0 parameter constructor.");
         * }*/

        /// <summary>
        /// Constructor for init data type
        /// internal storage is 1D with 1 element
        /// </summary>
        /// <param name="dtype">Data type of elements</param>
        public NDArray(Type dtype)
        {
            TensorEngine = BackendFactory.GetEngine();
            Storage      = new NDStorage(dtype);
        }
 /// <summary>
 /// Returns the index of the maximum value of the array.
 /// </summary>
 public static NDArray argmax(NDArray nd, int axis = -1)
 => BackendFactory.GetEngine().ArgMax(nd, axis: axis);
示例#15
0
 public static NDArray ndarray(Shape shape, Type dtype = null, Array buffer = null, string order = "F")
 => BackendFactory.GetEngine().NDArray(shape, dtype: dtype, buffer: buffer, order: order);
示例#16
0
 public static NDArray divide(NDArray x, NDArray y)
 => BackendFactory.GetEngine().Divide(x, y);
示例#17
0
 /// <summary>
 /// Test whether all array elements along a given axis evaluate to True.
 /// </summary>
 /// <param name="nd"></param>
 /// <param name="axis"></param>
 /// <returns>Returns an array of bools</returns>
 public static NDArray <bool> all(NDArray nd, int axis)
 => BackendFactory.GetEngine().All(nd, axis);
示例#18
0
 public static NDArray subtract(NDArray x, NDArray y)
 => BackendFactory.GetEngine().Sub(x, y);
示例#19
0
 /// <summary>
 /// Array elements raised to given powers, element-wise.
 /// </summary>
 public static NDArray power(NDArray x, ValueType y)
 => BackendFactory.GetEngine().Power(x, y);
示例#20
0
 public static NDArray ndarray(Shape shape, Type dtype = null, Array buffer = null, char order = 'F')
 => BackendFactory.GetEngine().CreateNDArray(shape, dtype: dtype, buffer: buffer, order: order);
示例#21
0
 /// <summary>
 /// Natural logarithm, element-wise.
 ///
 /// The natural logarithm log is the inverse of the exponential function, so that log(exp(x)) = x.The natural logarithm is logarithm in base e.
 /// </summary>
 /// <returns></returns>
 public NDArray log()
 => BackendFactory.GetEngine().Log(this);
示例#22
0
 /// <summary>
 /// Test element-wise for Not a Number.
 /// </summary>
 /// <param name="a"></param>
 /// <returns>The result is returned as a boolean array.</returns>
 public static NDArray <bool> isnan(NDArray a)
 => BackendFactory.GetEngine().IsNan(a);
示例#23
0
 /// <summary>
 /// Test element-wise for finiteness (not infinity or not Not a Number).
 /// </summary>
 /// <param name="a"></param>
 /// <returns>The result is returned as a boolean array.</returns>
 public static NDArray <bool> isfinite(NDArray a)
 => BackendFactory.GetEngine().IsFinite(a);
示例#24
0
 /// <summary>
 /// Returns a boolean array where two arrays are element-wise equal within a
 /// tolerance.
 /// The tolerance values are positive, typically very small numbers.The
 /// relative difference (`rtol` * abs(`b`)) and the absolute difference
 /// `atol` are added together to compare against the absolute difference
 /// between `a` and `b`.
 /// Warning: The default `atol` is not appropriate for comparing numbers
 /// that are much smaller than one(see Notes).
 ///
 /// See also <seealso cref="allclose"/>
 ///
 ///Notes:
 /// For finite values, isclose uses the following equation to test whether
 /// two floating point values are equivalent.
 /// <code>absolute(`a` - `b`) less than or equal to (`atol` + `rtol` * absolute(`b`))</code>
 /// Unlike the built-in `math.isclose`, the above equation is not symmetric
 /// in `a` and `b` -- it assumes `b` is the reference value -- so that
 /// `isclose(a, b)` might be different from `isclose(b, a)`. Furthermore,
 /// the default value of atol is not zero, and is used to determine what
 /// small values should be considered close to zero.The default value is
 /// appropriate for expected values of order unity: if the expected values
 /// are significantly smaller than one, it can result in false positives.
 /// `atol` should be carefully selected for the use case at hand. A zero value
 /// for `atol` will result in `False` if either `a` or `b` is zero.
 /// </summary>
 /// <param name="a">Input array to compare with b</param>
 /// <param name="b">Input array to compare with a.</param>
 /// <param name="rtol">The relative tolerance parameter(see Notes)</param>
 /// <param name="atol">The absolute tolerance parameter(see Notes)</param>
 /// <param name="equal_nan">Whether to compare NaN's as equal.  If True, NaN's in `a` will be
 ///considered equal to NaN's in `b` in the output array.</param>
 ///<returns>
 ///  Returns a boolean array of where `a` and `b` are equal within the
 /// given tolerance.If both `a` and `b` are scalars, returns a single
 /// boolean value.
 ///</returns>
 public static NDArray <bool> isclose(NDArray a, NDArray b, double rtol = 1.0E-5, double atol = 1.0E-8,
                                      bool equal_nan = false)
 => BackendFactory.GetEngine().IsClose(a, b, rtol, atol, equal_nan);
示例#25
0
 public static NDArray multiply(NDArray x, NDArray y)
 => BackendFactory.GetEngine().Multiply(x, y);
示例#26
0
 /// <summary>
 /// Test whether all array elements evaluate to True.
 /// </summary>
 /// <param name="nd"></param>
 /// <returns></returns>
 public static bool all(NDArray nd)
 => BackendFactory.GetEngine().All(nd);
示例#27
0
 /// <summary>
 /// Sum of array elements over a given axis.
 /// </summary>
 /// <param name="x"></param>
 /// <param name="axis"></param>
 /// <returns></returns>
 public static NDArray sum(NDArray x, int?axis = null)
 => BackendFactory.GetEngine().Sum(x, axis: axis);
示例#28
0
 /// <summary>
 /// Constructor for init data type
 /// internal storage is 1D with 1 element
 /// </summary>
 /// <param name="dtype">Data type of elements</param>
 /// <remarks>This constructor does not call allocation/></remarks>
 public NDArray(Type dtype) : this(dtype, BackendFactory.GetEngine()) { }
示例#29
0
 public static NDArray add(NDArray x, NDArray y)
 => BackendFactory.GetEngine().Add(x, y);
示例#30
0
 /// <summary>
 /// Constructor for init data type
 /// internal storage is 1D with 1 element
 /// </summary>
 /// <param name="typeCode">Data type of elements</param>
 /// <remarks>This constructor does not call allocation/></remarks>
 public NDArray(NPTypeCode typeCode) : this(typeCode, BackendFactory.GetEngine()) { }