Example #1
0
        public FunctionTermCurve(FunctionTerm function)
        {
            if (function == null)
            {
                throw new ArgumentNullException("function");
            }
            if (function.DomainDimension != 1)
            {
                throw new ArgumentException("parameter 'function' has wrong domain dimension.");
            }
            if (function.CodomainDimension != 2)
            {
                throw new ArgumentException("parameter 'function' has wrong codomain dimension.");
            }

            this.point        = function;
            this.velocity     = point.GetDerivatives().Single();
            this.acceleration = velocity.GetDerivatives().Single();
            this.jerk         = acceleration.GetDerivatives().Single();

            ValueTerm position = Terms.Variable("t");

            ValueTerm speedValue = Terms.Norm(velocity.Apply(position));

            this.speed = speedValue.Abstract(position);

            ValueTerm directionValue = Terms.Angle(velocity.Apply(position));

            this.direction = directionValue.Abstract(position);

            ValueTerm curvatureValue = Terms.Quotient(direction.GetDerivatives().Single().Apply(position), speedValue);

            this.curvature = curvatureValue.Abstract(position);
        }
Example #2
0
        public void Test4()
        {
            ObjectVariableTerm x = new ObjectVariable('x');

            IndividualConstantTerm <RationalNumber> half =
                (IndividualConstant <RationalNumber>)(new RationalNumber(1, 2));

            IndividualConstantTerm <RationalNumber>
            one = (IndividualConstant <RationalNumber>)(new RationalNumber(1, 1));

            var pr1 = new PredicateFormula(Predicates.More, x, half);
            var pr2 = new PredicateFormula(Predicates.Less, x, one);

            var f1 = new PropositionalConnectiveFormula(Conjunction.GetInstance(), pr1, pr2);
            var f2 = new QuantifierFormula(ExistentialQuantifier.GetInstance(), x, f1);


            IndividualConstantTerm <int> two = new IndividualConstant <int>(2);
            var xSqr = new FunctionTerm(Functions.Pow, x, two);

            var pr3 = new PredicateFormula(Predicates.MoreZero, xSqr);
            var pr4 = new PredicateFormula(Predicates.EqualZero, x);

            var f3 = new PropositionalConnectiveFormula(Disjunction.GetInstance(), pr3, pr4);

            var f      = new PropositionalConnectiveFormula(Conjunction.GetInstance(), f2, f3);
            var actual = SimpleTarskiAlgorithm.QuantifiersElimination(f);

            Formula expected  = f3;
            Formula expected1 = new PropositionalConnectiveFormula(Disjunction.GetInstance(), pr4, pr3);

            Assert.IsTrue(expected.Equals(actual) || expected1.Equals(actual));
        }
Example #3
0
        public static IFunction Normalize(this FunctionTerm functionTerm, int depth)
        {
            if (functionTerm == null)
            {
                throw new ArgumentNullException("functionTerm");
            }
            if (depth < 0)
            {
                throw new ArgumentOutOfRangeException("depth");
            }

            functionTerm = CompleteNormalization.Rewrite(functionTerm);
            //Console.WriteLine(new string(' ', (2 - depth) * 4) + functionTerm);
            Console.Write(".");

            if (depth == 0)
            {
                return(functionTerm);
            }

            return(new ExplicitFunction
                   (
                       functionTerm.DomainDimension,
                       functionTerm.CodomainDimension,
                       functionTerm.Evaluate,
                       (
                           from derivative in functionTerm.GetDerivatives()
                           select derivative.Normalize(depth - 1)
                       )
                       .ToArray()
                   ));
        }
Example #4
0
        protected FunctionTermCurveTemplate(FunctionTerm function)
        {
            if (function == null)
            {
                throw new ArgumentNullException("position");
            }
            if (function.DomainDimension < 1)
            {
                throw new ArgumentException("parameter 'function' has wrong dimension.");
            }

            this.function = function;
        }
Example #5
0
        public ApplicationSyntax(FunctionTerm function, ValueTerm parameter)
        {
            if (function == null)
            {
                throw new ArgumentNullException("function");
            }
            if (parameter == null)
            {
                throw new ArgumentNullException("parameter");
            }

            this.function  = function;
            this.parameter = parameter;
        }
Example #6
0
        static void RunTest <T>(T term, Rule rule) where T : VariableTerm <T>
        {
            Terminal.Write(string.Format("testing rule {0}...", rule.GetType().Name));

            T result = rule.Rewrite(term);

            if (result == null)
            {
                throw new InvalidOperationException();
            }

            if (term is ValueTerm)
            {
                if (!(result is ValueTerm))
                {
                    throw new InvalidOperationException();
                }

                ValueTerm termValueTerm   = (ValueTerm)(BaseTerm)term;
                ValueTerm resultValueTerm = (ValueTerm)(BaseTerm)result;

                if (termValueTerm.Dimension != resultValueTerm.Dimension)
                {
                    throw new InvalidOperationException();
                }
            }

            if (term is FunctionTerm)
            {
                if (!(result is FunctionTerm))
                {
                    throw new InvalidOperationException();
                }

                FunctionTerm termFunctionTerm   = (FunctionTerm)(BaseTerm)term;
                FunctionTerm resultFunctionTerm = (FunctionTerm)(BaseTerm)result;

                if (resultFunctionTerm.DomainDimension != termFunctionTerm.DomainDimension)
                {
                    throw new InvalidOperationException();
                }
                if (resultFunctionTerm.CodomainDimension != termFunctionTerm.CodomainDimension)
                {
                    throw new InvalidOperationException();
                }
            }

            Terminal.Write("success");
            Terminal.WriteLine();
        }
Example #7
0
        public Segment(FunctionTermCurve localCurve, FunctionTerm positionTransformation)
        {
            if (localCurve == null)
            {
                throw new ArgumentNullException("localCurve");
            }
            if (positionTransformation == null)
            {
                throw new ArgumentNullException("positionTransformation");
            }

            this.localCurve             = localCurve;
            this.globalCurve            = localCurve.TransformInput(positionTransformation);
            this.positionTransformation = positionTransformation;
        }
Example #8
0
        public Application(FunctionTerm function, ValueTerm parameter)
        {
            if (function == null)
            {
                throw new ArgumentNullException("function");
            }
            if (parameter == null)
            {
                throw new ArgumentNullException("parameter");
            }
            if (parameter.Dimension != function.DomainDimension)
            {
                throw new ArgumentException(string.Format("Dimension mismatch applying function '{0}' to parameter '{1}'.", function, parameter));
            }

            this.function  = function;
            this.parameter = parameter;
        }
Example #9
0
        public FunctionDefinition(string name, FunctionTerm function, Syntax syntax)
        {
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }
            if (function == null)
            {
                throw new ArgumentNullException("function");
            }
            if (function.GetFreeVariables().Any())
            {
                throw new ArgumentException("cannot create definition containing free variables.");
            }
            if (syntax == null)
            {
                throw new ArgumentNullException("syntax");
            }

            this.name     = name;
            this.function = function;
            this.syntax   = syntax;
        }
Example #10
0
        private static void CalcFunction(Function function, Stack <object> stack)
        {
            var args = new Term[function.Arity];

            if (stack.Count < function.Arity)
            {
                throw new ArgumentException(
                          $"expected {function.Arity} terms for the function {function}");
            }
            try
            {
                for (var i = args.Length - 1; i >= 0; i--)
                {
                    args[i] = (Term)stack.Pop();
                }
                var newTerm = new FunctionTerm(function, args);
                stack.Push(newTerm);
            }
            catch (Exception)
            {
                throw new ArgumentException(
                          $"expected {function.Arity} terms for the predicate {function}");
            }
        }
Example #11
0
        static double EvaluateScalar(FunctionTerm function, double value)
        {
            IEnumerable <double> result = function.Apply(Terms.Constant(value)).Evaluate();

            return(result.Single());
        }
 /// <summary>
 /// Constructor of the grammar node.
 /// </summary>
 /// <param name="p">Parent master grammar.</param>
 /// <param name="bForm">Block form.</param>
 public FunctionTermC(MasterGrammar p, BForm bForm) : base(p, bForm)
 {
     Rule = FunctionTerm.ConstructFunctionTermRule(p, bForm, IdentifierType.CONSTANT);
 }
Example #13
0
        public override T Rewrite <T>(T term)
        {
            T rewrittenTerm = rule.Rewrite(term);

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

            if (term is BasicValueTerm)
            {
                return(null);
            }
            if (term is BasicFunctionTerm)
            {
                return(null);
            }
            if (term is Variable)
            {
                return(null);
            }
            if (term is Abstraction)
            {
                Abstraction abstraction = (Abstraction)(BaseTerm)term;

                ValueTerm rewrittenAbstractionTerm = Rewrite(abstraction.Term);
                if (rewrittenAbstractionTerm != null)
                {
                    return((T)(BaseTerm) new Abstraction(abstraction.Variables, rewrittenAbstractionTerm));
                }

                return(null);
            }
            if (term is Application)
            {
                Application application = (Application)(BaseTerm)term;

                FunctionTerm rewrittenApplicationFunction = Rewrite(application.Function);
                if (rewrittenApplicationFunction != null)
                {
                    return((T)(BaseTerm) new Application(rewrittenApplicationFunction, application.Parameter));
                }

                ValueTerm rewrittenApplicationParameter = Rewrite(application.Parameter);
                if (rewrittenApplicationParameter != null)
                {
                    return((T)(BaseTerm) new Application(application.Function, rewrittenApplicationParameter));
                }

                return(null);
            }
            if (term is Vector)
            {
                Vector vector = (Vector)(BaseTerm)term;

                IEnumerable <ValueTerm> rewrittenVectorTerms = RewriteOne(vector.Terms);
                if (rewrittenVectorTerms != null)
                {
                    return((T)(BaseTerm) new Vector(rewrittenVectorTerms));
                }

                return(null);
            }
            if (term is Selection)
            {
                Selection selection = (Selection)(BaseTerm)term;

                ValueTerm rewrittenSelectionTerm = Rewrite(selection.Term);
                if (rewrittenSelectionTerm != null)
                {
                    return((T)(BaseTerm) new Selection(rewrittenSelectionTerm, selection.Index));
                }

                return(null);
            }

            throw new InvalidOperationException();
        }
Example #14
0
 public static ValueTerm Apply(this FunctionTerm function, IEnumerable <ValueTerm> parameters)
 {
     return(new Application(function, Vector(parameters)));
 }
    public static int Main(string[] args)
    {
        // Creates an SBMLNamespaces object with the given SBML level, version
        // package name, package version.
        SBMLNamespaces sbmlns = new SBMLNamespaces(3, 1, "qual", 1);

        // create the document
        SBMLDocument document = new SBMLDocument(sbmlns);

        // mark qual as required
        document.setPackageRequired("qual", true);

        // create the Model
        Model model = document.createModel();

        // create the Compartment
        Compartment compartment = model.createCompartment();

        compartment.setId("c");
        compartment.setConstant(true);

        // Get a QualModelPlugin object plugged in the model object.
        QualModelPlugin mplugin = (QualModelPlugin)(model.getPlugin("qual"));

        // create the QualitativeSpecies
        QualitativeSpecies qs = mplugin.createQualitativeSpecies();

        qs.setId("s1");
        qs.setCompartment("c");
        qs.setConstant(false);
        qs.setInitialLevel(1);
        qs.setMaxLevel(4);
        qs.setName("sss");

        // create the Transition
        Transition t = mplugin.createTransition();

        t.setId("d");
        t.setSBOTerm(1);

        Input i = t.createInput();

        i.setId("RD");
        i.setQualitativeSpecies("s1");
        i.setTransitionEffect(libsbml.INPUT_TRANSITION_EFFECT_NONE);
        i.setSign(libsbml.INPUT_SIGN_NEGATIVE);
        i.setThresholdLevel(2);
        i.setName("aa");

        Output o = t.createOutput();

        o.setId("wd");
        o.setQualitativeSpecies("s1");
        o.setTransitionEffect(libsbml.OUTPUT_TRANSITION_EFFECT_PRODUCTION);
        o.setOutputLevel(2);
        o.setName("aa");

        FunctionTerm ft   = t.createFunctionTerm();
        ASTNode      math = libsbml.parseL3Formula("geq(s1, 2)");

        ft.setResultLevel(1);
        ft.setMath(math);

        DefaultTerm dt = t.createDefaultTerm();

        dt.setResultLevel(2);

        int result = libsbml.writeSBML(document, "qual_example1.xml");

        if (result == 1)
        {
            Console.WriteLine("Wrote file");
            return(0);
        }
        else
        {
            Console.WriteLine("Failed to write");
            return(1);
        }
    }
Example #16
0
        OptimizationProblem(OptimizationSegments optimizationSegments, IEnumerable <CurveSpecification> curveSpecifications)
        {
            if (optimizationSegments == null)
            {
                throw new ArgumentNullException("segmentManager");
            }
            if (curveSpecifications == null)
            {
                throw new ArgumentNullException("curveSpecifications");
            }

            this.optimizationSegments = optimizationSegments;
            this.curveSpecifications  = curveSpecifications;

            this.curveLength = Terms.Variable("curveLength");

            this.pointSpecificationTemplates =
                (
                    from pointSpecificationIndex in Enumerable.Range(0, curveSpecifications.Count(curveSpecification => curveSpecification is PointCurveSpecification))
                    select SpecificationTemplate.CreatePointSpecificationTemplate(optimizationSegments.Segments, pointSpecificationIndex)
                )
                .ToArray();
            this.directionSpecificationTemplates =
                (
                    from directionSpecificationIndex in Enumerable.Range(0, curveSpecifications.Count(curveSpecification => curveSpecification is DirectionCurveSpecification))
                    select SpecificationTemplate.CreateDirectionSpecificationTemplate(optimizationSegments.Segments, curveLength, directionSpecificationIndex)
                )
                .ToArray();
            this.curvatureSpecificationTemplates =
                (
                    from curvatureSpecificationIndex in Enumerable.Range(0, curveSpecifications.Count(curveSpecification => curveSpecification is CurvatureCurveSpecification))
                    select SpecificationTemplate.CreateCurvatureSpecificationTemplate(optimizationSegments.Segments, curveLength, curvatureSpecificationIndex)
                )
                .ToArray();

            IEnumerable <ValueTerm> variables = optimizationSegments.Parameters;

            ValueTerm segmentLength = Terms.Quotient(curveLength, Terms.Constant(optimizationSegments.Segments.Count()));

            ValueTerm speedError = Terms.Sum
                                   (
                from segment in optimizationSegments.Segments
                let position                                                                                                             = Terms.Variable("t")
                                                                   let curve                                                             = segment.LocalCurve
                                                                                                       let speed                         = curve.Speed.Apply(position)
                                                                                                                               let error = Terms.Square(Terms.Difference(speed, segmentLength))
                                                                                                                                           select Terms.IntegrateTrapezoid(error.Abstract(position), new OrderedRange <double>(0, 1), 100)
                                   );

            ValueTerm fairnessError = Terms.Sum
                                      (
                from segment in optimizationSegments.Segments
                let position                                                          = Terms.Variable("t")
                                                      let curve                       = segment.LocalCurve
                                                                             let jerk = curve.Jerk.Apply(position)
                                                                                        let normal                         = Terms.Normal(curve.Velocity.Apply(position))
                                                                                                                 let error = Terms.Square(Terms.DotProduct(jerk, normal))
                                                                                                                             select Terms.IntegrateTrapezoid(error.Abstract(position), new OrderedRange <double>(0, 1), 100)
                                      );

//			ValueTerm pointSpecificationError = Terms.Sum
//			(
//				Enumerables.Concatenate
//				(
//					Enumerables.Create(Terms.Constant(0)),
//					from specificationTemplate in Enumerables.Concatenate(pointSpecificationTemplates)
//					select Terms.NormSquared
//					(
//						Terms.Difference
//						(
//							specificationTemplate.Constraint.Item,
//				            Terms.Vector(specificationTemplate.Constraint.Ranges.Select(range => range.Start))
//						)
//					)
//				)
//			);
//			ValueTerm directionSpecificationError = Terms.Sum
//			(
//				Enumerables.Concatenate
//				(
//					Enumerables.Create(Terms.Constant(0)),
//					from specificationTemplate in Enumerables.Concatenate(directionSpecificationTemplates)
//					select Terms.NormSquared
//					(
//						Terms.Difference
//						(
//							specificationTemplate.Constraint.Item,
//				            Terms.Vector(specificationTemplate.Constraint.Ranges.Select(range => range.Start))
//						)
//					)
//				)
//			);
//			ValueTerm curvatureSpecificationError = Terms.Sum
//			(
//				Enumerables.Concatenate
//				(
//					Enumerables.Create(Terms.Constant(0)),
//					from specificationTemplate in Enumerables.Concatenate(curvatureSpecificationTemplates)
//					select Terms.NormSquared
//					(
//						Terms.Difference
//						(
//							specificationTemplate.Constraint.Item,
//				            Terms.Vector(specificationTemplate.Constraint.Ranges.Select(range => range.Start))
//						)
//					)
//				)
//			);

            ValueTerm objectiveValue = Terms.Sum
                                       (
                Terms.Product(Terms.Exponentiation(segmentLength, Terms.Constant(-2)), Terms.Constant(100000.0), speedError),
                Terms.Product(Terms.Exponentiation(segmentLength, Terms.Constant(-4)), Terms.Constant(1), fairnessError)
//				Terms.Product(Terms.Exponentiation(segmentLength, Terms.Constant(0)), Terms.Constant(0.1), pointSpecificationError),
//				Terms.Product(Terms.Exponentiation(segmentLength, Terms.Constant(1)), Terms.Constant(10), directionSpecificationError),
//				Terms.Product(Terms.Exponentiation(segmentLength, Terms.Constant(2)), Terms.Constant(100), curvatureSpecificationError)
                                       )
                                       .Simplify();

            IEnumerable <Constraint <ValueTerm> > constraintValues =
                (
                    Enumerables.Concatenate
                    (
                        from pointSpecificationTemplate in pointSpecificationTemplates
                        select pointSpecificationTemplate.Constraint,
                        from directionSpecificationTemplate in directionSpecificationTemplates
                        select directionSpecificationTemplate.Constraint,
                        from curvatureSpecificationTemplate in curvatureSpecificationTemplates
                        select curvatureSpecificationTemplate.Constraint,

                        from segmentIndex in Enumerable.Range(0, optimizationSegments.Segments.Count() - 1)
                        let segment0CurvePoint = optimizationSegments.Segments.ElementAt(segmentIndex + 0).LocalCurve.Point
                                                 let segment1CurvePoint = optimizationSegments.Segments.ElementAt(segmentIndex + 1).LocalCurve.Point
                                                                          select Constraints.CreateEquality
                                                                          (
                            segment0CurvePoint.Apply(Terms.Constant(1)),
                            segment1CurvePoint.Apply(Terms.Constant(0))
                                                                          ),

                        from segmentIndex in Enumerable.Range(0, optimizationSegments.Segments.Count() - 1)
                        let segment0CurveVelocity = optimizationSegments.Segments.ElementAt(segmentIndex + 0).LocalCurve.Velocity
                                                    let segment1CurveVelocity = optimizationSegments.Segments.ElementAt(segmentIndex + 1).LocalCurve.Velocity
                                                                                select Constraints.CreateEquality
                                                                                (
                            segment0CurveVelocity.Apply(Terms.Constant(1)),
                            segment1CurveVelocity.Apply(Terms.Constant(0))
                                                                                ),

                        from segmentIndex in Enumerable.Range(0, optimizationSegments.Segments.Count() - 1)
                        let segment0CurveAcceleration = optimizationSegments.Segments.ElementAt(segmentIndex + 0).LocalCurve.Acceleration
                                                        let segment1CurveAcceleration = optimizationSegments.Segments.ElementAt(segmentIndex + 1).LocalCurve.Acceleration
                                                                                        select Constraints.CreateEquality
                                                                                        (
                            segment0CurveAcceleration.Apply(Terms.Constant(1)),
                            segment1CurveAcceleration.Apply(Terms.Constant(0))
                                                                                        )
                    )
                )
                .ToArray();

            Constraint <ValueTerm> constraint = Constraints.Merge(constraintValues);

            FunctionTerm objectiveFunction  = objectiveValue.Abstract(variables);
            FunctionTerm constraintFunction = constraint.Item.Abstract(variables);

            this.problem = IpoptProblem.Create(objectiveFunction, constraintFunction, constraint.Ranges);
        }
Example #17
0
        public FunctionTermCurve TransformInput(FunctionTerm transformation)
        {
            ValueTerm position = Terms.Variable("t");

            return(new FunctionTermCurve(point.Apply(transformation.Apply(position)).Abstract(position)));
        }
Example #18
0
 public static ValueTerm Apply(this FunctionTerm function, params ValueTerm[] parameters)
 {
     return(function.Apply((IEnumerable <ValueTerm>)parameters));
 }
Example #19
0
        static Vector2Double EvaluateVector(FunctionTerm function, double value)
        {
            IEnumerable <double> result = function.Apply(Terms.Constant(value)).Evaluate();

            return(new Vector2Double(result.ElementAt(0), result.ElementAt(1)));
        }
Example #20
0
        public static IEnumerable <FunctionTerm> GetDerivatives(this FunctionTerm term)
        {
            if (term is Sum)
            {
                Variable x = new Variable(1, "x");
                Variable y = new Variable(1, "y");

                return(Enumerables.Create
                       (
                           Term.Constant(1).Abstract(x, y),
                           Term.Constant(1).Abstract(x, y)
                       ));
            }
            if (term is Product)
            {
                Variable x = new Variable(1, "x");
                Variable y = new Variable(1, "y");

                return(Enumerables.Create
                       (
                           y.Abstract(x, y),
                           x.Abstract(x, y)
                       ));
            }
            if (term is Exponentiation)
            {
                Variable x = new Variable(1, "x");
                Variable y = new Variable(1, "y");

                return(Enumerables.Create
                       (
                           Term.Product(y, Term.Exponentiation(x, Term.Difference(y, Term.Constant(1)))).Abstract(x, y),
                           Term.Product(Term.Logarithm(x), Term.Exponentiation(x, y)).Abstract(x, y)
                       ));
            }
            if (term is Logarithm)
            {
                Variable x = new Variable(1, "x");

                return(Enumerables.Create(Term.Invert(x).Abstract(x)));
            }
            if (term is FunctionDefinition)
            {
                FunctionDefinition functionDefinitionTerm = (FunctionDefinition)term;

                IEnumerable <FunctionTerm> derivatives = GetDerivatives(functionDefinitionTerm.Function).ToArray();

                return
                    ((
                         from index in Enumerable.Range(0, derivatives.Count())
                         let derivative = derivatives.ElementAt(index)
                                          select new FunctionDefinition
                                          (
                             string.Format("{0}_d{1}", functionDefinitionTerm.Name, index),
                             Rewriting.CompleteNormalization.Rewrite(derivative),
                             new BasicSyntax(string.Format("{0}'{1}", functionDefinitionTerm.Syntax.GetText(), index.ToString().ToSuperscript()))
                                          )
                         )
                     .ToArray());
            }
            if (term is Abstraction)
            {
                Abstraction abstractionTerm = (Abstraction)term;

                return
                    ((
                         from variable in abstractionTerm.Variables
                         from derivative in GetDerivatives(abstractionTerm.Term, variable)
                         select derivative.Abstract(abstractionTerm.Variables)
                         )
                     .ToArray());
            }

            throw new InvalidOperationException();
        }