Example #1
0
        private AType ConvertFloatToInt(AType argument)
        {
            AType result = AArray.Create(ATypes.AInteger);

            if (argument.IsArray)
            {
                foreach (AType item in argument)
                {
                    AType convertedItem = ConvertFloatToInt(item);

                    if (item.IsArray)
                    {
                        result.Add(convertedItem);
                    }
                    else
                    {
                        result.AddRange(convertedItem);
                    }
                }
            }
            else
            {
                int    destinationTypeSize = GetTypeSize(ATypes.AInteger);
                byte[] bytes = BitConverter.GetBytes(argument.asFloat);

                for (int i = 0; i < bytes.Length; i += destinationTypeSize)
                {
                    result.Add(AInteger.Create(BitConverter.ToInt32(bytes, i)));
                }
            }

            return(result);
        }
Example #2
0
        public AType BuildArray(List <int> shape, ref byte[] data, ATypes type, int index)
        {
            AType result = Utils.ANull();
            int   typeSize;
            ItemConstructDelegate itemConstruct;

            switch (type)
            {
            case ATypes.AInteger:
                typeSize      = sizeof(Int32);
                itemConstruct = ConstructAInteger;
                break;

            case ATypes.AChar:
                typeSize      = sizeof(Char) / 2; // FIXMEEE!!!!! sizeof(Char) == 2 in C#!!!!!
                itemConstruct = ConstructAChar;
                break;

            case ATypes.AFloat:
                typeSize      = sizeof(Double);
                itemConstruct = ConstructAFloat;
                break;

            default:
                throw new ADAPException(ADAPExceptionType.Import);
            }

            if (data.Length < (typeSize * shape.Product() + index))
            {
                throw new ADAPException(ADAPExceptionType.Import);
            }

            if (shape.Count == 0)
            {
                result = itemConstruct(ref data, index);
            }
            else if (shape.Count == 1)
            {
                for (int i = 0; i < shape[0]; i++)
                {
                    result.Add(itemConstruct(ref data, index));
                    index += typeSize;
                }
            }
            else
            {
                for (int i = 0; i < shape[0]; i++)
                {
                    List <int> nextShape          = shape.GetRange(1, shape.Count - 1);
                    int        subDimensionLength = nextShape.Product() * typeSize;

                    result.Add(BuildArray(nextShape, ref data, type, index));
                    index += subDimensionLength;
                }
            }

            return(result);
        }
Example #3
0
        public override DLR.Expression Generate(AplusScope scope)
        {
            if (this.list.Count == 1)
            {
                return(this.list.First.Value.Generate(scope));
            }

            AType items = null;

            if (this.type == ConstantType.Integer)
            {
                bool convertToFloat = false;
                items = AArray.Create(ATypes.AInteger);
                foreach (Constant item in this.list)
                {
                    AType value = item.AsNumericAType;
                    items.Add(value);

                    if (value.Type == ATypes.AFloat)
                    {
                        convertToFloat = true;
                    }
                }

                // Convert integer items in previous array to float
                if (convertToFloat)
                {
                    items.ConvertToFloat();
                }
            }
            // Treat the Infinite constants same as floats
            else if (this.type == ConstantType.Double ||
                     this.type == ConstantType.PositiveInfinity ||
                     this.type == ConstantType.NegativeInfinity)
            {
                items = AArray.Create(ATypes.AFloat);
                foreach (Constant item in this.list)
                {
                    items.Add(AFloat.Create(item.AsFloat));
                }
            }
            else if (this.type == ConstantType.Symbol)
            {
                items = AArray.Create(ATypes.ASymbol);
                foreach (Constant item in this.list)
                {
                    items.Add(ASymbol.Create(item.AsString));
                }
            }
            else
            {
                throw new Error.Parse(String.Format("Unknow ConstantType({0}) in current context", this.type));
            }

            DLR.Expression result = DLR.Expression.Constant(items, typeof(AType));
            // Example: .Constant<AplusCore.Types.AArray`1[AplusCore.Types.AInteger]>(1 2)
            return(result);
        }
Example #4
0
        private static AType PermissiveIndexingSubIndex(
            AType index, AType array, AType defaultItem, Aplus environment)
        {
            AType result = AArray.Create(array.Type);

            if (index.IsArray)
            {
                for (int i = 0; i < index.Length; i++)
                {
                    result.Add(PermissiveIndexingSubIndex(index[i], array, defaultItem, environment));
                }
            }
            else if (index.asInteger > array.Length - 1 || index.asInteger < 0)
            {
                if (defaultItem.Rank == 0 && array[0].Rank != 0)
                {
                    result = DyadicFunctionInstance.Reshape.Execute(defaultItem, array[0].Shape.ToAArray(), environment);
                }
                else
                {
                    result = defaultItem;
                }
            }
            else
            {
                result = array[index];
            }

            return(result);
        }
Example #5
0
        /// <summary>
        /// Builds ASymbol.
        /// </summary>
        /// <param name="shape">The shape of the AType.</param>
        /// <param name="symbolLengths">The lengths of the ASymbols contained by the AType.</param>
        /// <param name="info">The class containing the informations for importing.</param>
        /// <returns></returns>
        private AType BuildSymbolArray(List <int> shape, IEnumerable <int> symbolLengths, ImportInfo info)
        {
            AType result = Utils.ANull();

            if (shape.Count == 0)
            {
                StringBuilder toSymbol = new StringBuilder();
                int           length   = symbolLengths.First();

                for (int i = 0; i < length; i++)
                {
                    toSymbol.Append((char)info.Data[info.DataIndex]);
                    info.DataIndex++;
                }

                result = ASymbol.Create(toSymbol.ToString());
            }
            else
            {
                List <int> nextShape          = (shape.Count > 1) ? shape.GetRange(1, shape.Count - 1) : new List <int>();
                int        subDimensionLength = nextShape.Product();

                for (int i = 0; i < shape[0]; i++)
                {
                    IEnumerable <int> nextSymbolLengths = symbolLengths.Skip(i * subDimensionLength).Take(subDimensionLength);

                    result.Add(BuildSymbolArray(nextShape, nextSymbolLengths, info));
                    // advance the bytestream further.
                }
            }

            return(result);
        }
Example #6
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="indexers">List containing all of the indexes</param>
        /// <param name="indexpos"></param>
        /// <param name="currentIdx">Array containing the current indexes</param>
        /// <returns></returns>
        public static AType VectorIndexing(this AType input, List<AType> indexers, int indexpos, AType currentIdx, bool isAssign, bool isMemoryMapped)
        {
            if (currentIdx.Length == 0)
            {
                // A Null item found!, select all of the current items
                for (int i = 0; i < input.Length; i++)
                {
                    currentIdx.Add(AInteger.Create(i));
                }
            }

            // Create an array for the results
            AType result = AArray.Create(input.Type);

            // Iterate over the indexes
            foreach (AType index in currentIdx)
            {
                AType item =
                    index.IsArray ?
                    input.VectorIndexing(indexers, indexpos, index, isAssign, isMemoryMapped) :
                    input.SimpleIndex(indexers, indexpos, index, isAssign, isMemoryMapped);

                result.AddWithNoUpdate(item);
            }

            result.UpdateInfo();
            return result;
        }
Example #7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="indexers">List containing all of the indexes</param>
        /// <param name="indexpos"></param>
        /// <param name="currentIdx">Array containing the current indexes</param>
        /// <returns></returns>
        public static AType VectorIndexing(this AType input, List <AType> indexers, int indexpos, AType currentIdx, bool isAssign, bool isMemoryMapped)
        {
            if (currentIdx.Length == 0)
            {
                // A Null item found!, select all of the current items
                for (int i = 0; i < input.Length; i++)
                {
                    currentIdx.Add(AInteger.Create(i));
                }
            }

            // Create an array for the results
            AType result = AArray.Create(input.Type);

            // Iterate over the indexes
            foreach (AType index in currentIdx)
            {
                AType item =
                    index.IsArray ?
                    input.VectorIndexing(indexers, indexpos, index, isAssign, isMemoryMapped) :
                    input.SimpleIndex(indexers, indexpos, index, isAssign, isMemoryMapped);

                result.AddWithNoUpdate(item);
            }

            result.UpdateInfo();
            return(result);
        }
Example #8
0
        private AType ConvertNumberToChar(AType argument)
        {
            AType result = AArray.Create(ATypes.AChar);

            if (argument.IsArray)
            {
                foreach (AType item in argument)
                {
                    AType convertedItem = ConvertNumberToChar(item);

                    if (item.IsArray)
                    {
                        result.Add(convertedItem);
                    }
                    else
                    {
                        result.AddRange(convertedItem);
                    }
                }
            }
            else
            {
                byte[] bytes = (argument.Type == ATypes.AFloat)
                    ? BitConverter.GetBytes(argument.asFloat)
                    : BitConverter.GetBytes(argument.asInteger);

                result.AddRange(bytes.Select <byte, AType>(item => AChar.Create((char)item)));
            }

            return(result);
        }
Example #9
0
        private static AType ArrayInput(AType input)
        {
            AType result;
            AType titles   = AArray.Create(ATypes.ANull);
            AType elements = AArray.Create(ATypes.ANull);
            int   odd      = input.Length % 2;

            for (int i = 0; i < input.Length - odd; i += 2)
            {
                AType key   = MonadicFunctionInstance.Disclose.Execute(input[i]);
                AType value = input[i + 1];

                if (key.Type != ATypes.ASymbol)
                {
                    throw new Error.Domain("_alsf");
                }

                if (!value.IsBox)
                {
                    value = ABox.Create(value);
                }

                titles.Add(key);
                elements.Add(value);
            }

            AType lastItem;

            if (input.Length == 0)
            {
                lastItem = input;
            }
            else
            {
                lastItem = MonadicFunctionInstance.Disclose.Execute(input[input.Length - 1]);
            }

            if (odd != 0 && lastItem.Type != ATypes.ANull)
            {
                titles.Add(lastItem);
                elements.Add(ABox.Create(AArray.Create(ATypes.ANull)));
            }

            result = AArray.Create(ATypes.AType, ABox.Create(titles), ABox.Create(elements));

            return(result);
        }
Example #10
0
        public AType WhatIs(int handle)
        {
            AType          result     = AArray.Create(ATypes.ASymbol);
            AipcConnection connection = Lookup(handle);

            if (connection == null)
            {
                result.Add(ASymbol.Create(""));
                result.Add(ASymbol.Create(""));
            }
            else
            {
                result.Add(ASymbol.Create(connection.ConnectionAttributes.IsListener ? "listener" : "connector"));
                result.Add(connection.ConnectionAttributes.Protocol);
            }

            return(result);
        }
Example #11
0
        private AType VectorInverse(AType argument)
        {
            AType  result       = AArray.Create(ATypes.AFloat);
            double sqrmagnitude = argument.Sum(item => item.asFloat * item.asFloat);

            for (int i = 0; i < argument.Length; i++)
            {
                result.Add(AFloat.Create(argument[i].asFloat / sqrmagnitude));
            }

            return(result);
        }
Example #12
0
        public AType Roster()
        {
            AType result = AArray.Create(ATypes.AInteger);

            lock (mutex)
            {
                foreach (var item in this.roster)
                {
                    result.Add(AInteger.Create(item.Key));
                }
            }

            return(result);
        }
Example #13
0
        /// <summary>
        /// Creates an AArray from the input string with AChar type or
        /// a simple AChar if the input is of length 1
        /// </summary>
        /// <param name="text">input string</param>
        /// <returns>AArray of AChars or a single AChar</returns>
        public static AType BuildString(string text)
        {
            if (text.Length == 1)
            {
                return(AChar.Create(text[0]));
            }

            AType characterArray = AArray.Create(ATypes.AChar);

            foreach (char ch in text)
            {
                characterArray.Add(AChar.Create(ch));
            }
            characterArray.UpdateInfo();

            return(characterArray);
        }
Example #14
0
        internal static AType Loadfile(Aplus environment, AType filename)
        {
            string fileName = filename.ToString();

            if (filename.Type != ATypes.AChar)
            {
                throw new Error.Type("_loadfile");
            }

            if (!File.Exists(fileName))
            {
                throw new Error.Invalid("_loadfile");
            }

            AType result = AArray.Create(ATypes.AChar);

            using (FileStream fileStream = new FileStream(fileName, FileMode.Open))
            {
                int    blockReadSize      = 5 * 1024; // 5 KiB
                long   totalSize          = fileStream.Length;
                int    readLength         = blockReadSize < totalSize ? blockReadSize : (int)totalSize;
                byte[] filePartialContent = new byte[readLength];

                int sum = 0; // total number of bytes read
                int count;   // current number of bytes read

                // read until Read method returns 0 (end of the stream has been reached)
                while ((count = fileStream.Read(filePartialContent, 0, readLength)) > 0)
                {
                    sum += count;  // sum is a buffer offset for next reading

                    // build the array from the bytes that was read
                    for (int i = 0; i < count; i++)
                    {
                        result.Add(AChar.Create((char)filePartialContent[i]));
                    }

                    // calculate the next size of the read block
                    long leftover = totalSize - sum;
                    readLength = blockReadSize < leftover ? blockReadSize : (int)leftover;
                }

                return(result);
            }
        }
Example #15
0
        /// <summary>
        /// If right side length equal zero, then the result
        /// is (1 drop x) rho identity, where identity is scalar
        /// that depends on function.
        /// </summary>
        /// <param name="shape"></param>
        /// <returns></returns>
        private AType Fill(List <int> shape)
        {
            if (shape.Count > 0)
            {
                AType result = AArray.Create(this.type);

                for (int i = 0; i < shape[0]; i++)
                {
                    result.Add(Fill(shape.GetRange(1, shape.Count - 1)));
                }

                return(result);
            }
            else
            {
                return(fillerElement.Clone());
            }
        }
Example #16
0
        protected override AType ConvertToAObject(byte[] messageByte)
        {
            AType message = AArray.Create(ATypes.AChar);

            foreach (byte b in messageByte)
            {
                try
                {
                    message.Add(AChar.Create((char)b));
                }
                catch (InvalidCastException)
                {
                    throw new ADAPException(ADAPExceptionType.Import);
                }
            }

            return message;
        }
Example #17
0
        protected override AType ConvertToAObject(byte[] message)
        {
            AType result = Utils.ANull();

            for (int i = 0; i < message.Length; i++)
            {
                try
                {
                    result.Add(AChar.Create((char)message[i]));
                }
                catch (InvalidCastException)
                {
                    throw new ADAPException(ADAPExceptionType.Import);
                }
            }

            return(result);
        }
Example #18
0
        internal AType ToAType()
        {
            AType result = AArray.Create(ATypes.AFloat);

            for (int i = 0; i < this.Rows; i++)
            {
                AType row = AArray.Create(ATypes.AFloat);

                for (int j = 0; j < this.Columns; j++)
                {
                    row.Add(AFloat.Create(this[i, j]));
                }

                result.Add(row);
            }

            return(result);
        }
Example #19
0
        public override AType Execute(AType argument, Aplus environment = null)
        {
            AType result = AArray.Create(argument.Type);

            if (argument.IsArray)
            {
                ExtractItems(argument, result);

                result.Length = argument.Shape.Product();
                result.Shape  = new List <int>()
                {
                    result.Length
                };
                result.Rank = 1;
            }
            else
            {
                result.Add(argument);
            }

            return(result);
        }
Example #20
0
        private AType SolveEquation(AType constants, AType equations)
        {
            AType lhs;
            AType rhs;

            if (constants.TryFirstScalar(out lhs, true) && equations.TryFirstScalar(out rhs, true))
            {
                // both left and right values are one element arrays.
                return(AFloat.Create(lhs.asFloat / rhs.asFloat));
            }

            Matrix constantsArray    = new SimpleMatrix(ExtractConstants(constants));
            Matrix originalEquations = new SimpleMatrix(FloatFromAType(equations));

            int[]  rowsSequence;
            Matrix eliminatedConstants;

            GaussianElimination(originalEquations, constantsArray, out rowsSequence, out eliminatedConstants);

            AType result = AArray.Create(ATypes.AFloat);

            if (equations.Shape[0] == equations.Shape[1])
            {
                // square equation
                if (constants.Rank > 1)
                {
                    foreach (int item in rowsSequence)
                    {
                        AType subArray = AArray.Create(ATypes.AFloat);

                        for (int i = 0; i < eliminatedConstants.Columns; i++)
                        {
                            subArray.Add(AFloat.Create(eliminatedConstants[item, i]));
                        }

                        result.Add(subArray);
                    }
                }
                else
                {
                    foreach (int item in rowsSequence)
                    {
                        result.Add(AFloat.Create(eliminatedConstants[item, 0]));
                    }
                }
            }
            else
            {
                double[][] independentConstants = BuildIndependentConstants(rowsSequence, eliminatedConstants);
                double[]   beta;
                double[]   actualconstants;

                if (constants.Rank == 1)
                {
                    beta            = independentConstants.Select(item => item[0]).ToArray();
                    actualconstants = constants.Select(item => item.asFloat).ToArray();

                    double[] solution = OverDeterminedEquationSolve(beta, actualconstants, originalEquations);

                    foreach (double item in solution)
                    {
                        result.Add(AFloat.Create(item));
                    }
                }
                else
                {
                    for (int objective = 0; objective < constants.Shape[1]; objective++)
                    {
                        beta            = independentConstants.Select(item => item[objective]).ToArray();
                        actualconstants = constants.Select(item => item[objective].asFloat).ToArray();

                        double[] solution      = OverDeterminedEquationSolve(beta, actualconstants, originalEquations);
                        AType    solutionArray = AArray.Create(ATypes.AFloat);

                        foreach (double item in solution)
                        {
                            solutionArray.Add(AFloat.Create(item));
                        }

                        result.Add(solutionArray);
                    }
                }
            }

            return(result);
        }
Example #21
0
        private AType Compute(AType right, int dropCounter)
        {
            if (right.IsArray && dropCounter == 0)
            {
                return(right.Clone());
            }

            AType result = AArray.Create(ATypes.AType);

            if (right.IsArray)
            {
                if (right.Length - Math.Abs(dropCounter) > 0)
                {
                    if (dropCounter > 0)
                    {
                        for (int i = dropCounter; i < right.Length; i++)
                        {
                            result.AddWithNoUpdate(right[i].Clone());
                        }
                    }
                    else
                    {
                        for (int i = 0; i < right.Length + dropCounter; i++)
                        {
                            result.AddWithNoUpdate(right[i].Clone());
                        }
                    }
                    result.Length = right.Length - Math.Abs(dropCounter);
                    result.Shape  = new List <int>()
                    {
                        result.Length
                    };

                    if (right.Rank > 1)
                    {
                        result.Shape.AddRange(right.Shape.GetRange(1, right.Shape.Count - 1));
                    }

                    result.Rank = right.Rank;
                    result.Type = result[0].Type;
                }
                else
                {
                    result.Type = right.MixedType() ? ATypes.ANull : right.Type;
                }
            }
            else
            {
                if (dropCounter == 0)
                {
                    result.Add(right.Clone());
                    result.Length = 1;
                    result.Shape  = new List <int>()
                    {
                        1
                    };
                    result.Type = right.Type;
                }
                else
                {
                    result.Type = right.MixedType() ? ATypes.ANull : right.Type;
                }
            }
            return(result);
        }
Example #22
0
        private static AType AppendItem(AType value, AType target, Aplus environment)
        {
            if (target.Rank == 0)
            {
                throw new Error.Rank("assign");
            }

            if (!Utils.DifferentNumberType(target, value) && target.Type != value.Type)
            {
                // The target and value are not numbers and they are of a different type?
                throw new Error.Type("assign");
            }

            if (target.Shape.SequenceEqual<int>(value.Shape))
            {
                for (int i = 0; i < value.Length; i++)
                {
                    target.Add(value[i].Clone());
                }
            }
            else if (target.Shape.GetRange(1, target.Shape.Count - 1).SequenceEqual<int>(value.Shape))
            {
                target.Add(value.Clone());
            }
            else if (value.Rank == 0)
            {
                AType item = DyadicFunctionInstance.Reshape.Execute(
                    value,
                    target.Shape.GetRange(1, target.Shape.Count - 1).ToAArray()
                );
                target.Add(item);
            }
            else if (value.Rank == target.Rank)
            {
                for (int i = 0; i < value.Length; i++)
                {
                    target.Add(value[i].Clone());
                }
            }
            else
            {
                throw new Error.Length("assign");
            }

            return value;
        }
Example #23
0
        private static AType CalculateIndexes(AType value, AType target, Aplus environment, out AType indexes)
        {
            if (target.Rank == 0)
            {
                throw new Error.Rank("assign");
            }

            if (!Utils.DifferentNumberType(target, value) && target.Type != value.Type)
            {
                // The target and value are not numbers and they are of a different type?
                throw new Error.Type("assign");
            }

            int currentLength = target.Length;

            if (target.Shape.SequenceEqual<int>(value.Shape))
            {
                indexes = AArray.Create(ATypes.AInteger);

                for (int i = 0; i < value.Length; i++)
                {
                    indexes.Add(AInteger.Create(currentLength));
                    currentLength++;
                }
            }
            else if (target.Shape.GetRange(1, target.Shape.Count - 1).SequenceEqual<int>(value.Shape))
            {
                indexes = AInteger.Create(currentLength);
                currentLength++;
            }
            else if (value.Rank == 0)
            {
                indexes = AInteger.Create(currentLength);
                currentLength++;
            }
            else if (value.Rank == target.Rank)
            {
                indexes = AArray.Create(ATypes.AInteger);

                for (int i = 0; i < value.Length; i++)
                {
                    indexes.Add(AInteger.Create(currentLength));
                    currentLength++;
                }
            }
            else
            {
                throw new Error.Length("assign");
            }

            indexes = ABox.Create(indexes);

            return value;
        }
Example #24
0
        /// <summary>
        /// Creates the resulting AArray
        /// </summary>
        /// <param name="right"></param>
        /// <param name="left"></param>
        /// <returns>AArray containing the concatenated elements.</returns>
        private AType CreateResult(AType right, AType left)
        {
            AType result = AArray.Create(left.Type);
            // Create a clone from the arguments to avoid side effects
            AType clonedLeft  = left.Clone();
            AType clonedRight = right.Clone();


            if (!clonedLeft.IsArray && !clonedRight.IsArray)
            {
                // example input: 1 , 2

                result.AddWithNoUpdate(clonedLeft);
                result.Add(clonedRight);
            }
            else if (clonedLeft.IsArray && !clonedRight.IsArray)
            {
                // example input: 1 2 , 3

                result.AddRange(clonedLeft);
                AType item = PrepareItem(clonedRight, clonedLeft);

                result.Add(item);
            }
            else if (!clonedLeft.IsArray && clonedRight.IsArray)
            {
                // example input: 1 , 2 3

                result.AddWithNoUpdate(PrepareItem(clonedLeft, clonedRight));
                result.AddRange(clonedRight);
            }
            // now both left and right argument is an AArray

            else if (clonedLeft.Rank == clonedRight.Rank)
            {
                // example input: (iota 2 2) , (iota 2 2)

                CheckItemsShape(clonedLeft, clonedRight);

                if (clonedLeft.Length > 0)
                {
                    result.AddRange(clonedLeft);
                }
                if (clonedRight.Length > 0)
                {
                    result.AddRange(clonedRight);
                }
            }
            else if ((clonedLeft.Rank - clonedRight.Rank) == 1)
            {
                // example input: (iota 2 2 2) , (iota 2 2)

                CheckShape(clonedLeft.Shape.GetRange(1, clonedLeft.Shape.Count - 1), clonedRight.Shape);

                result.AddRange(clonedLeft);
                result.Add(clonedRight);
            }
            else if ((clonedLeft.Rank - clonedRight.Rank) == -1)
            {
                // example input: (iota 2 2) , (iota 2 2 2)

                CheckShape(clonedLeft.Shape, clonedRight.Shape.GetRange(1, clonedRight.Shape.Count - 1));

                result.AddWithNoUpdate(clonedLeft);
                result.AddRange(clonedRight);
            }
            else
            {
                // The rank difference was bigger than 1.
                throw new Error.Rank(this.RankErrorText);
            }

            return(result);
        }