Ejemplo n.º 1
0
 /// <summary>
 /// Reduce produces a constraint from the operator and 
 /// any arguments. It takes the arguments from the constraint 
 /// stack and pushes the resulting constraint on it.
 /// </summary>
 /// <param name="stack"></param>
 public override void Reduce(ConstraintBuilder.ConstraintStack stack)
 {
     if (RightContext == null || RightContext is BinaryOperator)
         stack.Push(new PropertyExistsConstraint(name));
     else
         stack.Push(new PropertyConstraint(name, stack.Pop()));
 }
 internal static void AddComplexTypeRuleConstraints(ConstraintBuilder constraintBuilder)
 {
     constraintBuilder
         .AssertAll<ReferenceType>(t => t.IsEntity ^ t.HasComplexTypeAttribute)
         .AssertAll<ReferenceType>(t => !t.HasComplexTypeAttribute ^ t.ValueFields.All(vf => !vf.IsPrimaryKey))
         .AssertAll<ReferenceType>(t => !t.HasComplexTypeAttribute ^ (!t.HasCollectionFields && !t.HasSingleFields));
 }
Ejemplo n.º 3
0
 /// <summary>
 /// Reduce produces a constraint from the operator and 
 /// any arguments. It takes the arguments from the constraint 
 /// stack and pushes the resulting constraint on it.
 /// </summary>
 public override void Reduce(ConstraintBuilder.ConstraintStack stack)
 {
     if (RightContext == null || RightContext is BinaryOperator)
         stack.Push(new ThrowsConstraint(null));
     else
         stack.Push(new ThrowsConstraint(stack.Pop()));
 }
Ejemplo n.º 4
0
 /// <summary>
 /// Reduce produces a constraint from the operator and 
 /// any arguments. It takes the arguments from the constraint 
 /// stack and pushes the resulting constraint on it.
 /// </summary>
 public override void Reduce(ConstraintBuilder.ConstraintStack stack)
 {
     if (RightContext == null || RightContext is BinaryOperator)
         stack.Push(new AttributeExistsConstraint(type));
     else
         stack.Push(new AttributeConstraint(type, stack.Pop()));
 }
        public AssumptionHandler(ConstraintBuilder constraintBuilder, ClassAssumptions classAssumptions, PropertyAssumptions propertyAssumptions)
        {
            _constraintBuilder = constraintBuilder;

            _classAssumptions = classAssumptions;
            _propertyAssumptions = propertyAssumptions;
        }
 internal static void AddIndexRuleConstraints(ConstraintBuilder constraintBuilder, ValueType stringType)
 {
     constraintBuilder
         .AssertAll<ValueField>(vf => (!vf.HasIndexAttribute && !vf.HasMaxLengthAttribute)
                                      ^ (vf.HasIndexAttribute && vf.Type != stringType)
                                      ^ (vf.HasIndexAttribute && vf.HasMaxLengthAttribute))
         .AssertAll<ValueField>(vf => !(vf.HasKeyAttribute && vf.HasIndexAttribute));
 }
 internal static void AddNotMappedRuleConstraints(ConstraintBuilder constraintBuilder, IEnumerable<Metamodel.ValueType> collectionsOfValueType)
 {
     foreach (var collectionOfValueType in collectionsOfValueType)
     {
         constraintBuilder
             .AssertAll<ValueField>(vf => vf.Type != collectionOfValueType || vf.HasNotMappedAttribute);
     }
     constraintBuilder
         .AssertAll<CollectionField>(cf => !cf.Type.HasComplexTypeAttribute || cf.HasNotMappedAttribute);
 }
 internal static void AddDatabaseGeneratedRuleConstraints(
     ConstraintBuilder constraintBuilder, ValueType stringType, ValueType numberType, ValueType guidType)
 {
     constraintBuilder
         .AssertAll<ValueField>(f => (!f.IsPrimaryKey && f.DatabaseGeneratedAttribute == DatabaseGeneratedAttribute.None)
                                     ^
                                     (
                                         f.IsPrimaryKey
                                         &&
                                         (
                                             (f.Type == stringType && f.DatabaseGeneratedAttribute == DatabaseGeneratedAttribute.Computed)
                                             ^ (f.Type == numberType && f.DatabaseGeneratedAttribute != DatabaseGeneratedAttribute.Computed)
                                             ^ (f.Type == guidType && f.DatabaseGeneratedAttribute != DatabaseGeneratedAttribute.Identity)
                                         )
                                     )
                               );
 }
Ejemplo n.º 9
0
        public IErrorReporter ErrorDuplicateType()
        {
            NameResolver resolver = null;
            foreach (var mutability in Options.AllMutabilityModes)
            {
                var env = Environment.Create(new Options() { }.SetMutability(mutability));
                var root_ns = env.Root;

                root_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("Foo", "T", VarianceMode.None)));

                TypeDefinition second_type = root_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("Foo", "T", VarianceMode.None))
                    .Constraints(ConstraintBuilder.Create("T")
                        .SetModifier(EntityModifier.Const)));

                resolver = NameResolver.Create(env);

                Assert.AreEqual(1, resolver.ErrorManager.Errors.Count);
                Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.NameAlreadyExists, second_type));
            }

            return resolver;
        }
Ejemplo n.º 10
0
 internal static void AddPrimayKeyRuleConstraints(ConstraintBuilder constraintBuilder)
 {
     constraintBuilder
         .AssertAll<ReferenceType>(t => !t.IsEntity
                                         // Primary Key Convention: IdKeyDiscoveryConvention
                                         ^ t.ValueFields.Any(f => (f.Name == "Id" || f.Name == "ID") // TODO: Einschränkung - ohne: || f.Name == "EmployeeTypeId" || f.Name == "EmployeeTypeID"
                                             && f.IsPrimaryKey
                                             )
                                         // Primary Key Convention: KeyAttributeConvention
                                         ^ (t.ValueFields.All(fn => fn.Name != "Id" && fn.Name != "ID")
                                             &&
                                             t.ValueFields.Any(f1 =>
                                              f1.HasKeyAttribute
                                              && f1.IsPrimaryKey
                                              && t.ValueFields.All(f2 => f2 == f1 || !f2.HasKeyAttribute))
                                             ))
         // Each entity needs exactly one primary key field
         .AssertAll<ReferenceType>(t => !t.IsEntity
                                         || t.ValueFields.Any(f1 =>
                                             f1.IsPrimaryKey && t.ValueFields.All(f2 =>
                                                                 f2 == f1 || !f2.IsPrimaryKey)));
 }
Ejemplo n.º 11
0
        public IErrorReporter InferredTemplateArgumentsOnConstraints()
        {
            NameResolver resolver = null;

            foreach (var mutability in Options.AllMutabilityModes)
            {
                var env = Environment.Create(new Options()
                {
                }.SetMutability(mutability));
                var root_ns = env.Root;

                root_ns.AddBuilder(FunctionBuilder.Create("part",
                                                          TemplateParametersBuffer.Create("T", "X").Values,
                                                          NameFactory.UnitNameReference(),

                                                          Block.CreateStatement())
                                   .Parameters(FunctionParameter.Create("x", NameReference.Create("T"), ExpressionReadMode.CannotBeRead))
                                   .Constraints(ConstraintBuilder.Create("X")
                                                .BaseOf(NameReference.Create("T"))));

                FunctionCall call      = FunctionCall.Create(NameReference.Create("part"), Int64Literal.Create("5"));
                var          main_func = root_ns.AddBuilder(FunctionBuilder.Create(
                                                                "caller",
                                                                NameFactory.UnitNameReference(),
                                                                Block.CreateStatement(new IExpression[] {
                    call
                })));


                resolver = NameResolver.Create(env);

                Assert.AreEqual(0, resolver.ErrorManager.Errors.Count);
                Assert.AreEqual(env.Int64Type.InstanceOf, call.Name.TemplateArguments[0].TypeName.Evaluation.Components);
                Assert.AreEqual(env.Int64Type.InstanceOf, call.Name.TemplateArguments[1].TypeName.Evaluation.Components);
            }

            return(resolver);
        }
Ejemplo n.º 12
0
        private void OnBoxesChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.NewItems != null)
            {
                Height = m_Boxes.Sum(x => x.Height);
                m_CupboardConstraint.SteelCornerColors = ConstraintBuilder.GetAvailableSteelCornerColor(m_Height);
                foreach (Box newItem in e.NewItems)
                {
                    //Add listener for each item on PropertyChanged event
                    newItem.PropertyChanged += this.OnItemPropertyChanged;
                }
            }

            if (e.OldItems != null)
            {
                Height = m_Boxes.Sum(x => x.Height);
                m_CupboardConstraint.SteelCornerColors = ConstraintBuilder.GetAvailableSteelCornerColor(m_Height);
                foreach (Box oldItem in e.OldItems)
                {
                    oldItem.PropertyChanged -= this.OnItemPropertyChanged;
                }
            }
        }
Ejemplo n.º 13
0
        public IErrorReporter ErrorConflictingTypesConstraint()
        {
            NameResolver resolver = null;

            foreach (var mutability in Options.AllMutabilityModes)
            {
                var env = Environment.Create(new Options()
                {
                }.SetMutability(mutability));
                var root_ns = env.Root;

                root_ns.AddBuilder(TypeBuilder.Create("Parent")
                                   .SetModifier(EntityModifier.Base));
                root_ns.AddBuilder(TypeBuilder.Create("Child").Parents("Parent"));

                NameReference baseof_name = NameReference.Create("Parent");
                NameReference parent_name = NameReference.Create("Child");
                root_ns.AddBuilder(FunctionBuilder.Create("proxy",
                                                          TemplateParametersBuffer.Create().Add("T").Values,
                                                          ExpressionReadMode.CannotBeRead,
                                                          NameFactory.UnitNameReference(),

                                                          Block.CreateStatement())
                                   .Constraints(ConstraintBuilder.Create("T")
                                                .BaseOf(baseof_name)
                                                .Inherits(parent_name)));

                resolver = NameResolver.Create(env);

                Assert.AreEqual(2, resolver.ErrorManager.Errors.Count);
                Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.ConstraintConflictingTypeHierarchy, baseof_name));
                Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.InheritingSealedType, parent_name));
            }

            return(resolver);
        }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="builder"></param>
 public ConstraintDefinition(ConstraintBuilder builder)
 {
     if (builder == null)
     {
         return;
     }
     DisplayHint = builder.DisplayHint;
     if (builder.HasDefault && builder.Default != null)
     {
         DefaultValue = JsonConvert.SerializeObject(builder.Default);
     }
     if (builder.HasMin && builder.Min != null)
     {
         MinValue = JsonConvert.SerializeObject(builder.Min);
     }
     if (builder.HasMax && builder.Max != null)
     {
         MaxValue = JsonConvert.SerializeObject(builder.Max);
     }
     if (builder.HasPossibleValuesList)
     {
         PossibleValues = builder.Values?.Select(JsonConvert.SerializeObject).ToArray();
     }
 }
Ejemplo n.º 15
0
 /// <summary>
 /// Reduce produces a constraint from the operator and
 /// any arguments. It takes the arguments from the constraint
 /// stack and pushes the resulting constraint on it.
 /// </summary>
 /// <param name="stack"></param>
 public override void Reduce(ConstraintBuilder.ConstraintStack stack)
 {
     stack.Push(ApplyPrefix(stack.Pop()));
 }
 /// <summary>
 /// Create a new instance of ResolvableConstraintExpression,
 /// passing in a pre-populated ConstraintBuilder.
 /// </summary>
 public ResolvableConstraintExpression(ConstraintBuilder builder)
     : base(builder)
 {
 }
Ejemplo n.º 17
0
 /// <summary>
 /// Create a new instance of ResolvableConstraintExpression,
 /// passing in a pre-populated ConstraintBuilder.
 /// </summary>
 public ResolvableConstraintExpression(ConstraintBuilder builder)
     : base(builder)
 {
 }
Ejemplo n.º 18
0
 /// <summary>
 /// Initializes a new instance of the <see cref="T:ConstraintExpressionBase"/>
 /// class passing in a ConstraintBuilder, which may be pre-populated.
 /// </summary>
 /// <param name="builder">The builder.</param>
 public ConstraintExpressionBase(ConstraintBuilder builder)
 {
     this.builder = builder;
 }
Ejemplo n.º 19
0
 /// <summary>
 /// Implements the label inference algorithm by setting the <see cref="VariableLabel.CurrentUpperBound"/> on all variables.
 /// </summary>
 /// <param name="builder">A function that will generate new constraints while preserving meta-data.</param>
 /// <param name="constraints">The constraint-system that should be resolved.</param>
 /// <returns>
 /// A <see cref="InferenceResult{T}"/> representing the result of the method.
 /// <see cref="InferenceResult{T}.Succes"/> indicates if the constraints were successfully resolved.
 /// </returns>
 public static InferenceResult <T> Resolve(ConstraintBuilder <T> builder, params T[] constraints)
 {
     return(Resolve(builder, constraints as IEnumerable <T>));
 }
Ejemplo n.º 20
0
 public SliverLayoutBuilder(
     Key key = null,
     ConstraintBuilder builder = null
     ) : base(key: key, builder: builder)
 {
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="T:ConstraintExpressionBase"/> 
 /// class passing in a ConstraintBuilder, which may be pre-populated.
 /// </summary>
 /// <param name="builder">The builder.</param>
 public ConstraintExpressionBase(ConstraintBuilder builder)
 {
     this.builder = builder;
 }
Ejemplo n.º 22
0
 private ConstraintResolver(ConstraintBuilder <T> builder, IEnumerable <T> constraints)
 {
     this.constraints = new List <T>(constraints);
     this.steps       = new List <Step>();
     this.builder     = builder;
 }
Ejemplo n.º 23
0
 /// <summary>
 ///     Reduce produces a constraint from the operator and
 ///     any arguments. It takes the arguments from the constraint
 ///     stack and pushes the resulting constraint on it.
 /// </summary>
 /// <param name="stack"></param>
 internal abstract void Reduce(ConstraintBuilder.ConstraintStack stack);
Ejemplo n.º 24
0
        public IErrorReporter ErrorHasConstraint()
        {
            NameResolver resolver = null;

            foreach (var mutability in Options.AllMutabilityModes)
            {
                var env = Environment.Create(new Options()
                {
                    AllowInvalidMainResult = true, AllowProtocols = true
                }.SetMutability(mutability));
                var root_ns = env.Root;

                FunctionDefinition func_constraint = FunctionBuilder.CreateDeclaration("getMe",
                                                                                       ExpressionReadMode.ReadRequired, NameFactory.Int64NameReference());

                // this function accepts any parameter where parameter type has function "getMe"
                FunctionDefinition constrained_func = root_ns.AddBuilder(FunctionBuilder.Create("proxy",
                                                                                                TemplateParametersBuffer.Create().Add("T").Values,
                                                                                                ExpressionReadMode.ReadRequired, NameFactory.Int64NameReference(), Block.CreateStatement(new[] {
                    Return.Create(FunctionCall.Create(NameReference.Create("t", "getMe")))
                }))
                                                                         .Constraints(ConstraintBuilder.Create("T").Has(func_constraint))
                                                                         .Parameters(FunctionParameter.Create("t", NameFactory.PointerNameReference("T"))));

                // this type does NOT have function "getMe"
                TypeDefinition type_impl = root_ns.AddBuilder(TypeBuilder.Create("YMan")
                                                              .With(FunctionBuilder.Create("missing",
                                                                                           ExpressionReadMode.ReadRequired,
                                                                                           NameFactory.Int64NameReference(),
                                                                                           Block.CreateStatement(new[] {
                    Return.Create(Int64Literal.Create("2"))
                }))));

                FunctionCall call = FunctionCall.Create(NameReference.Create("proxy"), FunctionArgument.Create(NameReference.Create("y_man")));
                root_ns.AddBuilder(FunctionBuilder.Create(
                                       "main",
                                       ExpressionReadMode.OptionalUse,
                                       NameFactory.Int64NameReference(),
                                       Block.CreateStatement(new IExpression[] {
                    VariableDeclaration.CreateStatement("y_man", null, ExpressionFactory.HeapConstructor(NameReference.Create("YMan"))),
                    Return.Create(call)
                })));

                resolver = NameResolver.Create(env);

                Assert.AreEqual(1, resolver.ErrorManager.Errors.Count);
                Assert.IsTrue(resolver.ErrorManager.HasError(ErrorCode.ViolatedHasFunctionConstraint, call.Callee));
            }

            return(resolver);
        }
Ejemplo n.º 25
0
 /// <summary>
 /// Initializes a new instance of the <see cref="T:ConstraintExpressionBase"/> class.
 /// </summary>
 public ConstraintExpressionBase()
 {
     this.builder = new ConstraintBuilder();
 }
Ejemplo n.º 26
0
 /// <summary>
 /// Reduce produces a constraint from the operator and 
 /// any arguments. It takes the arguments from the constraint 
 /// stack and pushes the resulting constraint on it.
 /// </summary>
 /// <param name="stack"></param>
 public abstract void Reduce(ConstraintBuilder.ConstraintStack stack);
Ejemplo n.º 27
0
        public IErrorReporter ConstraintsMatching()
        {
            NameResolver resolver = null;

            foreach (var mutability in Options.AllMutabilityModes)
            {
                var env = Language.Environment.Create(new Options()
                {
                }.SetMutability(mutability));
                var root_ns   = env.Root;
                var system_ns = env.SystemNamespace;

                var base_type = system_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("Basic")));
                var abc_type  = system_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("ABC"))
                                                     .Parents(NameReference.Create("Basic")));
                var derived_type = system_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("Deriv"))
                                                        .Parents(NameReference.Create("ABC")));
                var foo_type = system_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("Foo",
                                                                                             TemplateParametersBuffer.Create().Add("V", VarianceMode.Out).Values))
                                                    .Constraints(ConstraintBuilder.Create("V").Inherits(NameReference.Create("ABC")))
                                                    .Parents(NameReference.Create("ABC")));
                var tuple_type = system_ns.AddBuilder(TypeBuilder.Create(NameDefinition.Create("Tuple",
                                                                                               TemplateParametersBuffer.Create().Add("T", VarianceMode.None).Values))
                                                      .Constraints(ConstraintBuilder.Create("T").BaseOf(NameReference.Create("ABC"))));

                var tuple_ok_type = TypeBuilder.Create(
                    NameDefinition.Create("TupleOK", TemplateParametersBuffer.Create().Add("U", VarianceMode.None).Values))
                                    .Constraints(ConstraintBuilder.Create("U").BaseOf(NameReference.Create("Basic")))
                                    .Parents(NameReference.Create("Tuple", NameReference.Create("U"))).Build();
                system_ns.AddNode(tuple_ok_type);
                var tuple_bad_type = TypeBuilder.Create(
                    NameDefinition.Create("TupleBad", TemplateParametersBuffer.Create().Add("L", VarianceMode.None).Values))
                                     .Parents(NameReference.Create("Tuple", NameReference.Create("L"))).Build();
                system_ns.AddNode(tuple_bad_type);

                var foo_deriv_ref   = system_ns.AddNode(NameReference.Create("Foo", NameReference.Create("Deriv")));
                var tuple_basic_ref = system_ns.AddNode(NameReference.Create("Tuple", NameReference.Create("Basic")));
                var foo_basic_ref   = system_ns.AddNode(NameReference.Create("Foo", NameReference.Create("Basic")));
                var tuple_deriv_ref = system_ns.AddNode(NameReference.Create("Tuple", NameReference.Create("Deriv")));

                resolver = NameResolver.Create(env);

                // constraints are matched
                Assert.AreEqual(1, foo_deriv_ref.Binding.Matches.Count());
                Assert.AreEqual(foo_type, foo_deriv_ref.Binding.Match.Instance.Target);

                Assert.AreEqual(1, tuple_basic_ref.Binding.Matches.Count());
                Assert.AreEqual(tuple_type, tuple_basic_ref.Binding.Match.Instance.Target);

                // failed on constraints
                Assert.AreEqual(0, foo_basic_ref.Binding.Matches.Count());

                Assert.AreEqual(0, tuple_deriv_ref.Binding.Matches.Count());

                // constraints matching other constraints
                Assert.AreEqual(1, tuple_ok_type.ParentNames.Single().Binding.Matches.Count);
                Assert.AreEqual(tuple_type, tuple_ok_type.ParentNames.Single().Binding.Match.Instance.Target);

                Assert.AreEqual(0, tuple_bad_type.ParentNames.Single().Binding.Matches.Count);
            }

            return(resolver);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="T:ConstraintExpressionBase"/> class.
 /// </summary>
 public ConstraintExpressionBase()
 {
     this.builder = new ConstraintBuilder();
 }
Ejemplo n.º 29
0
 /// <summary>
 /// Sets the ConstraintBuilder holding this constraint
 /// </summary>
 internal void SetBuilder(ConstraintBuilder builder)
 {
     this.builder = builder;
 }
 /// <summary>
 /// Create a new instance of ResolvableConstraintExpression,
 /// passing in a pre-populated ConstraintBuilder.
 /// </summary>
 /// <param name="builder"></param>
 public ItemsConstraintExpression(ConstraintBuilder builder)
     : base(builder)
 {
 }
Ejemplo n.º 31
0
 /// <summary>
 /// Create a new instance of ResolvableConstraintExpression,
 /// passing in a pre-populated ConstraintBuilder.
 /// </summary>
 /// <param name="builder"></param>
 public ItemsConstraintExpression(ConstraintBuilder builder)
     : base(builder) { }
Ejemplo n.º 32
0
 /// <summary>
 /// Reduce produces a constraint from the operator and
 /// any arguments. It takes the arguments from the constraint
 /// stack and pushes the resulting constraint on it.
 /// </summary>
 /// <param name="stack"></param>
 public override void Reduce(ConstraintBuilder.ConstraintStack stack)
 {
     Constraint right = stack.Pop();
     Constraint left = stack.Pop();
     stack.Push(ApplyOperator(left, right));
 }
Ejemplo n.º 33
0
        protected RpropResult RPropOptimizeFeasible(List <CNSAT.Var> constraints, AD.Term ut, AD.Variable[] args, double[] seed, bool precise)
        {
            //Compiled Term zusammenbauen
            AD.Term constr = AD.Term.True;
            foreach (CNSAT.Var v in constraints)
            {
                if (v.Assignment == Alica.Reasoner.CNSAT.Assignment.True)
                {
                    constr &= v.Term;
                }
                else
                {
                    constr &= ConstraintBuilder.Not(v.Term);
                }
            }
            AD.ConstraintUtility     cu   = new AD.ConstraintUtility(constr, ut);
            AD.ICompiledTerm         term = AD.TermUtils.Compile(cu, args);
            Tuple <double[], double> tup;

            //fertig zusammengebaut



            runCount++;
            InitialStepSize();
            double[]    curGradient;
            RpropResult ret = new RpropResult();

//			curGradient = InitialPoint(constraints, ret);

            if (seed != null)
            {
                curGradient = InitialPointFromSeed(constraints, ret, seed);
            }
            else
            {
                curGradient = InitialPoint(constraints, ret);
            }
            double curUtil = ret.initialUtil;

            double[] formerGradient = new double[dim];
            double[] curValue       = new double[dim];

            //Tuple<double[],double> tup;

            Buffer.BlockCopy(ret.initialValue, 0, curValue, 0, sizeof(double) * dim);
            formerGradient = curGradient;

            int itcounter  = 0;
            int badcounter = 0;

#if (GSOLVER_LOG)
            Log(curUtil, curValue);
#endif

            int    maxIter = 60;
            int    maxBad  = 30;
            double minStep = 1E-11;
            if (precise)
            {
                maxIter = 120;                 //110
                maxBad  = 60;                  //60
                minStep = 1E-15;               //15
            }
            int convergendDims = 0;

            while (itcounter++ < maxIter && badcounter < maxBad)
            {
                convergendDims = 0;
                for (int i = 0; i < dim; i++)
                {
                    if (curGradient[i] * formerGradient[i] > 0)
                    {
                        rpropStepWidth[i] *= 1.3;
                    }
                    else if (curGradient[i] * formerGradient[i] < 0)
                    {
                        rpropStepWidth[i] *= 0.5;
                    }
                    rpropStepWidth[i] = Math.Max(minStep, rpropStepWidth[i]);
                    //rpropStepWidth[i] = Math.Max(0.000001,rpropStepWidth[i]);
                    if (curGradient[i] > 0)
                    {
                        curValue[i] += rpropStepWidth[i];
                    }
                    else if (curGradient[i] < 0)
                    {
                        curValue[i] -= rpropStepWidth[i];
                    }

                    if (curValue[i] > limits[i, 1])
                    {
                        curValue[i] = limits[i, 1];
                    }
                    else if (curValue[i] < limits[i, 0])
                    {
                        curValue[i] = limits[i, 0];
                    }
                    //Console.Write("{0}\t",curValue[i]);
                    if (rpropStepWidth[i] < rpropStepConvergenceThreshold[i])
                    {
                        ++convergendDims;
                    }
                }
                //Abort if all dimensions are converged
                if (!precise && convergendDims >= dim)
                {
                    return(ret);
                }
                this.fevalsCount++;
                formerGradient = curGradient;
                tup            = term.Differentiate(curValue);

                bool allZero = true;
                for (int i = 0; i < dim; i++)
                {
                    if (Double.IsNaN(tup.Item1[i]))
                    {
                        ret.aborted = false;                      //true; //HACK!
#if (GSOLVER_LOG)
                        LogStep();
#endif
                        return(ret);
                    }
                    allZero &= (tup.Item1[i] == 0);
                }

                curUtil        = tup.Item2;
                formerGradient = curGradient;
                curGradient    = tup.Item1;
#if (GSOLVER_LOG)
                Log(curUtil, curValue);
#endif
                //Console.WriteLine("CurUtil: {0} Final {1}",curUtil,ret.finalUtil);

                if (curUtil > ret.finalUtil)
                {
                    badcounter = 0;                    //Math.Max(0,badcounter-1);


                    ret.finalUtil = curUtil;
                    Buffer.BlockCopy(curValue, 0, ret.finalValue, 0, sizeof(double) * dim);
                    //ret.finalValue = curValue;
                    if (curUtil > 0.75)
                    {
                        return(ret);
                    }
                }
                else
                {
                    badcounter++;
                }
                if (allZero)
                {
                    ret.aborted = false;
#if (GSOLVER_LOG)
                    LogStep();
#endif
                    return(ret);
                }
            }
#if (GSOLVER_LOG)
            LogStep();
#endif
            ret.aborted = false;
            return(ret);
        }