public override Operand Explode(ITranslator translator, Context context)
            {
                GeometricProduct geometricProduct = new GeometricProduct();

                for (int i = 0; i < Math.Abs(exponent); i++)
                {
                    InnerProduct innerProduct = new InnerProduct();
                    innerProduct.operandList.Add(translator.Translate(new Blade(this.vectorNameA), context));
                    innerProduct.operandList.Add(translator.Translate(new Blade(this.vectorNameB), context));

                    geometricProduct.operandList.Add(innerProduct);
                }

                if (exponent < 0)
                {
                    return(new Inverse(new List <Operand>()
                    {
                        geometricProduct
                    }));
                }

                return(geometricProduct);
            }
Esempio n. 2
0
        public override Operand EvaluationStep(Context context)
        {
            Operand operand = base.EvaluationStep(context);

            if (operand != null)
            {
                return(operand);
            }

            // To avoid infinite evaluation looping, we must apply...
            //   1) vB = v.B + v^B, and
            //   2) v^B = vB - v.B,
            // ...according to rules that dictate when and where they're appropriate.
            // Also to avoid infinite looping, the distributive property must take
            // precedence over anything we do here.

            // All reduction cases must be eliminated before it is safe to handle the expansion cases.
            for (int i = 0; i < operandList.Count - 1; i++)
            {
                Blade bladeA = operandList[i] as Blade;
                Blade bladeB = operandList[i + 1] as Blade;

                if (bladeA != null && bladeB != null && bladeA.Grade > 1 && bladeB.Grade > 1)
                {
                    GeometricProduct geometricProduct;

                    if (context.useOperandCache)
                    {
                        geometricProduct = new GeometricProduct(new List <Operand>()
                        {
                            new Blade(new NumericScalar(1.0), bladeA.vectorList.ToList()), new Blade(new NumericScalar(1.0), bladeB.vectorList.ToList())
                        });
                        string  key          = geometricProduct.Print(Format.PARSEABLE, context);
                        Operand cachedResult = null;
                        if (!context.operandCache.GetStorage(key, ref cachedResult))
                        {
                            context.useOperandCache = false;
                            cachedResult            = Operand.ExhaustEvaluation(geometricProduct, context);
                            context.useOperandCache = true;
                            context.operandCache.SetStorage(key, cachedResult);
                        }

                        return(new GeometricProduct(new List <Operand>()
                        {
                            bladeA.scalar, bladeB.scalar, cachedResult
                        }));
                    }

                    // Here our choice of which blade to reduce is arbitrary from a stand-point of correctness.
                    // However, we might converge faster by choosing the blade with smaller grade.
                    // Note there is also something arbitrary about how we're reducing the blades.
                    int   j        = bladeA.Grade <= bladeB.Grade ? i : i + 1;
                    Blade blade    = operandList[j] as Blade;
                    Blade subBlade = blade.MakeSubBlade(0);
                    Blade vector   = new Blade(blade.vectorList[0]);
                    geometricProduct = new GeometricProduct(new List <Operand>()
                    {
                        vector, subBlade
                    });
                    InnerProduct innerProduct = new InnerProduct(new List <Operand>()
                    {
                        vector.Copy(), subBlade.Copy()
                    });
                    operandList[j] = new Sum(new List <Operand>()
                    {
                        geometricProduct, new GeometricProduct(new List <Operand>()
                        {
                            new NumericScalar(-1.0), innerProduct
                        })
                    });
                    return(this);
                }
            }

            // All reduction cases eliminated, it is now safe to handle some expansion cases.
            for (int i = 0; i < operandList.Count - 1; i++)
            {
                Blade bladeA = operandList[i] as Blade;
                Blade bladeB = operandList[i + 1] as Blade;

                if (bladeA == null || bladeB == null)
                {
                    continue;
                }

                if ((bladeA.Grade == 1 && bladeB.Grade > 1) || (bladeA.Grade > 1 && bladeB.Grade == 1))
                {
                    InnerProduct innerProduct = new InnerProduct(new List <Operand>()
                    {
                        bladeA, bladeB
                    });
                    OuterProduct outerProduct = new OuterProduct(new List <Operand>()
                    {
                        bladeA.Copy(), bladeB.Copy()
                    });
                    operandList[i] = new Sum(new List <Operand>()
                    {
                        innerProduct, outerProduct
                    });
                    operandList.RemoveAt(i + 1);
                    return(this);
                }
            }

            // It is now safe to handle the remaining expansion cases.
            for (int i = 0; i < operandList.Count - 1; i++)
            {
                Blade bladeA = operandList[i] as Blade;
                Blade bladeB = operandList[i + 1] as Blade;

                if (bladeA == null || bladeB == null)
                {
                    continue;
                }

                if (bladeA.Grade == 1 && bladeB.Grade == 1)
                {
                    operandList.RemoveAt(i + 1);
                    GeometricProduct innerProduct = new GeometricProduct(new List <Operand>()
                    {
                        bladeA.scalar, bladeB.scalar, context.BilinearForm(bladeA.vectorList[0], bladeB.vectorList[0])
                    });
                    Blade outerProduct = new Blade(new GeometricProduct(new List <Operand>()
                    {
                        bladeA.scalar.Copy(), bladeB.scalar.Copy()
                    }));
                    outerProduct.vectorList.Add(bladeA.vectorList[0]);
                    outerProduct.vectorList.Add(bladeB.vectorList[0]);
                    operandList[i] = new Sum(new List <Operand>()
                    {
                        innerProduct, outerProduct
                    });
                    return(this);
                }
            }

            return(null);
        }
Esempio n. 3
0
        public override Operand EvaluationStep(Context context)
        {
            if (operandList.Count != 1)
            {
                throw new MathException(string.Format("Exponential function expected exactly 1 argument, got {0}.", operandList.Count));
            }

            Operand operand = base.EvaluationStep(context);

            if (operand != null)
            {
                return(operand);
            }

            Operand exponentOperand = operandList[0];

            if (exponentOperand is Sum sumExponent)
            {
                GeometricProduct geometricProduct = new GeometricProduct();

                for (int i = 0; i < sumExponent.operandList.Count; i++)
                {
                    geometricProduct.operandList.Add(new Exponent(new List <Operand>()
                    {
                        sumExponent.operandList[i]
                    }));
                }

                return(geometricProduct);
            }

            if (exponentOperand is NumericScalar numericScalar)
            {
                return(new NumericScalar(Math.Exp(numericScalar.value)));
            }
            else if (exponentOperand is Blade blade)
            {
                Blade        basisBlade   = new Blade(new NumericScalar(1.0), blade.vectorList.ToList());
                InnerProduct innerProduct = new InnerProduct();
                innerProduct.operandList.Add(new NumericScalar(-1.0));
                innerProduct.operandList.Add(basisBlade.Copy());
                innerProduct.operandList.Add(basisBlade.Copy());
                Operand result = Operand.ExhaustEvaluation(innerProduct, context);
                if (result.IsMultiplicativeIdentity)
                {
                    Sum sum = new Sum();
                    sum.operandList.Add(new Cosine(new List <Operand>()
                    {
                        blade.scalar.Copy()
                    }));
                    sum.operandList.Add(new GeometricProduct(new List <Operand>()
                    {
                        basisBlade.Copy(), new Sine(new List <Operand>()
                        {
                            blade.scalar.Copy()
                        })
                    }));
                    return(sum);
                }
                else if (result.IsAdditiveIdentity)
                {
                    // What if it's a null blade?
                }
                else
                {
                    // Hyperbolic cosine/sine?
                }
            }

            return(null);
        }
        public override Operand EvaluationStep(Context context)
        {
            Operand operand = base.EvaluationStep(context);

            if (operand != null)
            {
                return(operand);
            }

            if (operandList.Count == 2)
            {
                Blade bladeA = operandList[0] as Blade;
                Blade bladeB = operandList[1] as Blade;

                if (bladeA != null && bladeB != null)
                {
                    if (bladeA.Grade == 1 && bladeB.Grade == 1)
                    {
                        return(new GeometricProduct(new List <Operand>()
                        {
                            bladeA.scalar, bladeB.scalar, context.BilinearForm(bladeA.vectorList[0], bladeB.vectorList[0])
                        }));
                    }
                    else if (bladeA.Grade == 1 && bladeB.Grade > 1)
                    {
                        Sum sum = new Sum();

                        for (int i = 0; i < bladeB.vectorList.Count; i++)
                        {
                            Blade subBlade = bladeB.MakeSubBlade(i);
                            subBlade.scalar = new GeometricProduct(new List <Operand>()
                            {
                                new NumericScalar(i % 2 == 1 ? -1.0 : 1.0), bladeA.scalar, bladeB.scalar, context.BilinearForm(bladeA.vectorList[0], bladeB.vectorList[i])
                            });
                            sum.operandList.Add(subBlade);
                        }

                        return(sum);
                    }
                    else if (bladeA.Grade > 1 && bladeB.Grade == 1)
                    {
                        operandList[0] = bladeB;
                        operandList[1] = bladeA;

                        if (bladeA.Grade % 2 == 0)
                        {
                            operandList.Add(new NumericScalar(-1.0));
                        }

                        return(this);
                    }
                    else if (bladeA.Grade > 1 && bladeB.Grade > 1)
                    {
                        if (context.useOperandCache)
                        {
                            InnerProduct innerProduct = new InnerProduct(new List <Operand>()
                            {
                                new Blade(new NumericScalar(1.0), bladeA.vectorList.ToList()), new Blade(new NumericScalar(1.0), bladeB.vectorList.ToList())
                            });
                            string  key          = innerProduct.Print(Format.PARSEABLE, context);
                            Operand cachedResult = null;
                            if (!context.operandCache.GetStorage(key, ref cachedResult))
                            {
                                context.useOperandCache = false;
                                cachedResult            = Operand.ExhaustEvaluation(innerProduct, context);
                                context.useOperandCache = true;
                                context.operandCache.SetStorage(key, cachedResult);
                            }

                            return(new GeometricProduct(new List <Operand>()
                            {
                                bladeA.scalar, bladeB.scalar, cachedResult
                            }));
                        }

                        if (bladeA.Grade <= bladeB.Grade)
                        {
                            return(new InnerProduct(new List <Operand>()
                            {
                                bladeA.MakeSubBlade(bladeA.Grade - 1), new InnerProduct(new List <Operand>()
                                {
                                    new Blade(bladeA.vectorList[bladeA.Grade - 1]), bladeB
                                })
                            }));
                        }
                        else
                        {
                            return(new InnerProduct(new List <Operand>()
                            {
                                new InnerProduct(new List <Operand>()
                                {
                                    bladeA, new Blade(bladeB.vectorList[0])
                                }), bladeB.MakeSubBlade(0)
                            }));
                        }
                    }
                }
            }

            return(null);
        }
Esempio n. 5
0
        // Note that here that we do not consider unary operator precedence.
        // So for example, if we have -1~, we don't try to choose between (-1)~ and -(1~),
        // though both are the same in this particular case.  Also, we don't recognize unary
        // operator stacking.  E.g., -~1 will not parse as -(~1) would.  In short, working with
        // unary operators will sometimes requires parenthesis.
        public Operand BuildOperandTree(List <Token> tokenList)
        {
            while (tokenList.Count > 0)
            {
                int count = tokenList.Count;

                if (tokenList[0].kind == Token.Kind.LEFT_PARAN && tokenList[0].paranType == Token.ParanType.ROUND)
                {
                    int i = FindMatchingParan(tokenList, 0);
                    if (i == tokenList.Count - 1)
                    {
                        tokenList.RemoveAt(0);
                        tokenList.RemoveAt(tokenList.Count - 1);
                    }
                }

                if (tokenList.Count == count)
                {
                    break;
                }
            }

            if (tokenList.Count == 0)
            {
                throw new ParseException("Encountered empty token list.");
            }

            if (tokenList.Count == 1)
            {
                Token token = tokenList[0];
                switch (token.kind)
                {
                case Token.Kind.SYMBOL:
                {
                    if (token.data[0] == '@')
                    {
                        return(new Variable(token.data.Substring(1)));
                    }

                    if (token.data[0] == '$')
                    {
                        return(new SymbolicScalarTerm(token.data.Substring(1)));
                    }

                    string vectorName    = token.data;
                    bool   isBasisVector = false;

                    List <string> basisVectorList = context.ReturnBasisVectors();
                    if (basisVectorList != null)
                    {
                        isBasisVector = basisVectorList.Contains(vectorName);
                        if (basisVectorsOnly && !isBasisVector)
                        {
                            Sum sum = new Sum();

                            foreach (string basisVectorName in basisVectorList)
                            {
                                InnerProduct dot = new InnerProduct(new List <Operand>()
                                    {
                                        new Blade(vectorName), new Blade(basisVectorName)
                                    });
                                sum.operandList.Add(new GeometricProduct(new List <Operand>()
                                    {
                                        dot, new Blade(basisVectorName)
                                    }));
                            }

                            return(sum);
                        }
                    }

                    generatedSymbolicVector = !isBasisVector;
                    return(new Blade(vectorName));
                }

                case Token.Kind.NUMBER:
                {
                    double value;
                    if (!double.TryParse(token.data, out value))
                    {
                        throw new ParseException(string.Format("Encountered non-parsable number ({0}).", token.data));
                    }

                    return(new NumericScalar(value));
                }

                default:
                {
                    throw new ParseException(string.Format("Encountered lone token ({0}) that isn't handled.", token.data));
                }
                }
            }
            else if (tokenList[0].kind == Token.Kind.OPERATOR && (ParansMatch(tokenList, 1, tokenList.Count - 1) || tokenList.Count == 2 || IsFunctionPattern(tokenList.Skip(1).ToList())))
            {
                Token token = tokenList[0];

                if (token.data == "-")
                {
                    return(new GeometricProduct(new List <Operand>()
                    {
                        new Blade(-1.0), BuildOperandTree(tokenList.Skip(1).ToList())
                    }));
                }

                throw new ParseException(string.Format("Encounterd unary operator ({0}) that isn't recognized on the left.", token.data));
            }
            else if (tokenList[tokenList.Count - 1].kind == Token.Kind.OPERATOR && (ParansMatch(tokenList, 0, tokenList.Count - 2) || tokenList.Count == 2 || IsFunctionPattern(tokenList.Take(tokenList.Count - 1).ToList())))
            {
                Token token = tokenList[tokenList.Count - 1];

                if (token.data == "~")
                {
                    return(new Reverse(new List <Operand>()
                    {
                        BuildOperandTree(tokenList.Take(tokenList.Count - 1).ToList())
                    }));
                }

                throw new ParseException(string.Format("Encountered unary operator ({0}) that isn't recognized on the right.", token.data));
            }
            else if (IsFunctionPattern(tokenList))
            {
                Token token = tokenList[0];

                Operation operation = context.CreateFunction(token.data);
                if (operation == null)
                {
                    throw new ParseException(string.Format("Encountered unknown function \"{0}\".", token.data));
                }

                List <List <Token> > argumentList = ParseListOfTokenLists(tokenList.Skip(2).Take(tokenList.Count - 3).ToList());
                foreach (List <Token> subTokenList in argumentList)
                {
                    operation.operandList.Add(BuildOperandTree(subTokenList));
                }

                return(operation);
            }
            else if (tokenList[0].paranType == Token.ParanType.SQUARE && ParansMatch(tokenList, 0, tokenList.Count - 1))
            {
                List <List <Operand> > listOfOperandLists = new List <List <Operand> >();

                List <List <Token> > rowList = ParseListOfTokenLists(tokenList.Skip(1).Take(tokenList.Count - 2).ToList());
                foreach (List <Token> rowTokenList in rowList)
                {
                    listOfOperandLists.Add(new List <Operand>());

                    List <List <Token> > colList;
                    if (rowTokenList[0].paranType == Token.ParanType.SQUARE && ParansMatch(rowTokenList, 0, rowTokenList.Count - 1))
                    {
                        colList = ParseListOfTokenLists(rowTokenList.Skip(1).Take(rowTokenList.Count - 2).ToList());
                    }
                    else
                    {
                        colList = new List <List <Token> >()
                        {
                            rowTokenList
                        }
                    };

                    foreach (List <Token> subTokenList in colList)
                    {
                        listOfOperandLists[listOfOperandLists.Count - 1].Add(BuildOperandTree(subTokenList));
                    }
                }

                return(new Matrix(listOfOperandLists));
            }
            else
            {
                // Our goal here is to find an operator of lowest precedence.  It will never be
                // at the very beginning or end of the entire token sequence.
                List <Token> opTokenList = null;
                foreach (Token token in WalkTokensSkipSubexpressions(tokenList))
                {
                    if (token.kind != Token.Kind.OPERATOR)
                    {
                        continue;
                    }

                    // Only unary operators can be at the start or end of the token list.
                    if (tokenList.IndexOf(token) == 0 || tokenList.IndexOf(token) == tokenList.Count - 1)
                    {
                        continue;
                    }

                    // Ignore unary operators on left.
                    if (token.data == "-" && tokenList[tokenList.IndexOf(token) - 1].kind == Token.Kind.OPERATOR)
                    {
                        continue;
                    }

                    // Ignore unary operators on right.
                    if (token.data == "~" && tokenList[tokenList.IndexOf(token) + 1].kind == Token.Kind.OPERATOR)
                    {
                        continue;
                    }

                    // At this point we should be reasonably sure it's a binary operator we're looking at.
                    if (opTokenList == null || PrecedenceLevel(opTokenList[0].data) > PrecedenceLevel(token.data))
                    {
                        opTokenList = new List <Token>()
                        {
                            token
                        }
                    }
                    ;
                    else if (opTokenList != null && PrecedenceLevel(opTokenList[0].data) == PrecedenceLevel(token.data))
                    {
                        opTokenList.Add(token);
                    }
                }

                if (opTokenList == null)
                {
                    throw new ParseException("Did not encounter binary operator token.");
                }

                Token operatorToken = null;
                switch (OperatorAssociativity(opTokenList[0].data))
                {
                case Associativity.LEFT_TO_RIGHT:
                    operatorToken = opTokenList[opTokenList.Count - 1];
                    break;

                case Associativity.RIGHT_TO_LEFT:
                    operatorToken = opTokenList[0];
                    break;
                }

                Operation operation = null;

                if (operatorToken.data == ";")
                {
                    operation = new Sequence();
                }
                else if (operatorToken.data == "+" || operatorToken.data == "-")
                {
                    operation = new Sum();
                }
                else if (operatorToken.data == "*" || operatorToken.data == "/")
                {
                    operation = new GeometricProduct();
                }
                else if (operatorToken.data == ".")
                {
                    operation = new InnerProduct();
                }
                else if (operatorToken.data == "^")
                {
                    operation = new OuterProduct();
                }
                else if (operatorToken.data == "=")
                {
                    operation = new Assignment();
                }
                else if (operatorToken.data == ":=")
                {
                    operation = new Assignment(false);
                }

                if (operation == null)
                {
                    throw new ParseException(string.Format("Did not recognized operator token ({0}).", operatorToken.data));
                }

                int i = tokenList.IndexOf(operatorToken);

                Operand leftOperand  = BuildOperandTree(tokenList.Take(i).ToList());
                Operand rightOperand = BuildOperandTree(tokenList.Skip(i + 1).Take(tokenList.Count - 1 - i).ToList());

                operation.operandList.Add(leftOperand);

                if (operatorToken.data == "-")
                {
                    operation.operandList.Add(new GeometricProduct(new List <Operand>()
                    {
                        new NumericScalar(-1.0), rightOperand
                    }));
                }
                else if (operatorToken.data == "/")
                {
                    operation.operandList.Add(new Inverse(new List <Operand>()
                    {
                        rightOperand
                    }));
                }
                else
                {
                    operation.operandList.Add(rightOperand);
                }

                return(operation);
            }
        }