Example #1
0
        public void Clone()
        {
            var x = new Variable<int>("x")
                {
                    Values = {1, 2, 3},
                    Unit = new Unit("distance", "m"),
                    ExtrapolationType = ExtrapolationType.Constant,
                    InterpolationType = InterpolationType.Linear
                };

            var clone = (IVariable<int>)x.Clone();

            //Assert.IsTrue(clone.Values.SequenceEqual(new[] {1, 2, 3}));
            Assert.AreEqual(x.Name, clone.Name);
            Assert.AreNotEqual(x, clone);
            Assert.AreNotEqual(x.Store, clone.Store); // clone creates a new deep copy of the variable (in-memory)

            x.Values
                .Should("values must be copied").Have.SameSequenceAs(new[] { 1, 2, 3 });
            Assert.AreEqual(x.ExtrapolationType, clone.ExtrapolationType);
            Assert.AreEqual(x.InterpolationType, clone.InterpolationType);
            Assert.AreNotSame(x.Unit, clone.Unit);
            Assert.AreEqual(x.Unit.Name, clone.Unit.Name);
            Assert.AreEqual(x.Unit.Symbol, clone.Unit.Symbol);
        }
Example #2
0
        public void VerifyPropertiesOfVariableOfTypeShort()
        {
            Type declaredType = typeof(short);
            Variable<short> vInt = new Variable<short>(Guid.Empty);

            Assert.Equal(declaredType, vInt.DataType);
        }
 public Procedure(string name, VariableSequence valArgs, Variable resultArg, StatementSequence statements)
 {
     AddChild(valArgs);
     AddChild(resultArg);
     AddChild(statements);
     _name = name;
 }
        public void ShouldSolveSystemWith1EquationAnd2Variables()
        {
            //x+y=10    x=6; y=4
            //x-y=2
            var variableX = new Variable("x");
            var variableY = new Variable("y");

            var left1FirstEq = new Expression(1, variableX);
            var left2FirstEq = new Expression(1, variableY);
            var rightFirstEq = new Expression(10, Variable.NULL);

            var left1SecondEq = new Expression(1, variableX);
            var left2SecondEq = new Expression(-1, variableY);
            var rightSecondEq = new Expression(2, Variable.NULL);

            var firstEquation = new Equation(new List<Expression>() { left1FirstEq, left2FirstEq }, rightFirstEq);
            var secondEquation = new Equation(new List<Expression>() {left1SecondEq, left2SecondEq}, rightSecondEq);

            var target = new SystemOfEquations(new List<Equation>() {firstEquation, secondEquation});
            target.Solve();
            var resultX = variableX.Value;
            var resultY = variableY.Value;

            Assert.AreEqual(1, resultX.Count);
            Assert.AreEqual(1, resultY.Count);
            Assert.AreEqual(Variable.NULL, resultX.First().Variable);
            Assert.AreEqual(6, resultX.First().Coefficient);
            Assert.AreEqual(Variable.NULL, resultY.First().Variable);
            Assert.AreEqual(4, resultY.First().Coefficient);
        }
Example #5
0
        public void VerifyPropertiesOfVariableOfTypeBool()
        {
            Type declaredType = typeof(bool);
            Variable<bool> vInt = new Variable<bool>(Guid.Empty);

            Assert.Equal(declaredType, vInt.DataType);
        }
Example #6
0
 public void Test_Double_Variable_Value_Set()
 {
     Variable<double> testVar = new Variable<double>("testVar", default(double), false);
     testVar.SetValue(11.15623);
     double value = testVar.Value;
     Assert.AreEqual(11.15623, value, "Value setter does not work properly.<Double>");
 }
Example #7
0
 public LinkVariableAction(VariableInfo variableInfo, Variable linkedVariable)
 {
     VariableInfo = variableInfo;
     OldLink = variableInfo.Variable.Linked;
     OldValue = variableInfo.Value;
     NewLink = linkedVariable;
 }
Example #8
0
 /// <summary>
 /// Добавляет переменную в окружение
 /// </summary>
 /// <param name="var">Переменная</param>
 /// <param name="name">Имя переменной</param>
 public void Add(Variable var, string name)
 {
     EnvironsStuct es = new EnvironsStuct();
     es.name = name;
     es.value = var;
     enviroment.Add(es);
 }
        /// <summary>
        /// Visits the call.
        /// </summary>
        /// <param name="destination">The destination.</param>
        /// <param name="receiver">The receiver.</param>
        /// <param name="callee">The callee.</param>
        /// <param name="arguments">The arguments.</param>
        /// <param name="isVirtualCall">if set to <c>true</c> [is virtual call].</param>
        /// <param name="programContext">The program context.</param>
        /// <param name="stateBeforeInstruction">The state before instruction.</param>
        /// <param name="stateAfterInstruction">The state after instruction.</param>
        public override void VisitCall(
            Variable destination, 
            Variable receiver, 
            Method callee, 
            ExpressionList arguments, 
            bool isVirtualCall, 
            Microsoft.Fugue.IProgramContext programContext, 
            Microsoft.Fugue.IExecutionState stateBeforeInstruction, 
            Microsoft.Fugue.IExecutionState stateAfterInstruction)
        {
            if ((callee.DeclaringType.GetRuntimeType() == typeof(X509ServiceCertificateAuthentication) ||
                 callee.DeclaringType.GetRuntimeType() == typeof(X509ClientCertificateAuthentication)) &&
                 (callee.Name.Name.Equals("set_CertificateValidationMode", StringComparison.InvariantCultureIgnoreCase)))
            {
                IAbstractValue value = stateBeforeInstruction.Lookup((Variable)arguments[0]);
                IIntValue intValue = value.IntValue(stateBeforeInstruction);

                if (intValue != null)
                {
                    X509CertificateValidationMode mode = (X509CertificateValidationMode)intValue.Value;
                    if (mode != X509CertificateValidationMode.ChainTrust)
                    {
                        Resolution resolution = base.GetResolution(mode.ToString(), 
                            X509CertificateValidationMode.ChainTrust.ToString());
                        Problem problem = new Problem(resolution, programContext);
                        base.Problems.Add(problem);
                    }
                }
            }

            base.VisitCall(destination, receiver, callee, arguments, isVirtualCall, programContext, stateBeforeInstruction, stateAfterInstruction);
        }
        private double UpdateHelper(Message<GaussianDistribution> message1, Message<GaussianDistribution> message2,
            Variable<GaussianDistribution> variable1, Variable<GaussianDistribution> variable2)
        {
            GaussianDistribution message1Value = message1.Value.Clone();
            GaussianDistribution message2Value = message2.Value.Clone();

            GaussianDistribution marginal1 = variable1.Value.Clone();
            GaussianDistribution marginal2 = variable2.Value.Clone();

            double a = _Precision/(_Precision + marginal2.Precision - message2Value.Precision);

            GaussianDistribution newMessage = GaussianDistribution.FromPrecisionMean(
                a*(marginal2.PrecisionMean - message2Value.PrecisionMean),
                a*(marginal2.Precision - message2Value.Precision));

            GaussianDistribution oldMarginalWithoutMessage = marginal1/message1Value;

            GaussianDistribution newMarginal = oldMarginalWithoutMessage*newMessage;

            /// Update the message and marginal

            message1.Value = newMessage;
            variable1.Value = newMarginal;

            /// Return the difference in the new marginal
            return newMarginal - marginal1;
        }
Example #11
0
        public void TestAsArgument()
        {
            IVariable<IFeatureLocation> a = new Variable<IFeatureLocation>("argument");
            IVariable<double> c1 = new Variable<double>("value");
            IVariable<string> c2 = new Variable<string>("description");

            // f = (a, p)(h)
            IFunction f = new Function("rating curve");
            f.Arguments.Add(a);
            f.Components.Add(c1);
            f.Components.Add(c2);

            SimpleFeature simpleFeature = new SimpleFeature(10.0);
            IFeatureLocation featureLocation = new FeatureLocation { Feature = simpleFeature };

            // value based argument referencing.
            f[featureLocation] = new object[] { 1.0, "jemig de pemig" };

            IMultiDimensionalArray<double> c1Value = f.GetValues<double>(new ComponentFilter(f.Components[0]),
                                                                         new VariableValueFilter<IFeatureLocation>(
                                                                             f.Arguments[0],
                                                                             new FeatureLocation
                                                                                 {Feature = simpleFeature}));

            Assert.AreEqual(1.0, c1Value[0], 1.0e-6);

            //IMultiDimensionalArray<string> c2Value = f.GetValues<string>(new ComponentFilter(f.Components[1]),
            //                                                             new VariableValueFilter<IFeatureLocation>(
            //                                                                 f.Arguments[0], featureLocation));

            //Assert.AreEqual("jemig de pemig", c2Value[0]);
        }
Example #12
0
 public override bool TryGetMember(GetMemberBinder binder, out object result)
 {
     try
     {
         Variable variable;
         if(!variables.TryGetValue(binder.Name, out variable))
         {
             int idx = GetGlobalVarIndexByName(binder.Name);
             var ptr = GetAddressOfGlobalVar(idx);
             if(ptr == IntPtr.Zero)
             {
                 result = null;
                 return true;
             }
             int tid;
             GetGlobalVar(idx, out tid);
             var instance = ScriptEngine.GetVariable(ptr, tid);
             variables[binder.Name] = variable = new Variable(instance, ptr, tid);
         }
         result = ScriptEngine.GetVariable(variable.Address, variable.TypeId, variable.Instance);
         return true;
     }
     catch(Exception ex)
     {
         ScriptEngine.Log ("Exception caught while fetching '{0}' variable of module '{1}': {2}.", binder.Name, Name, ex.Message);
         result = null;
         return false;
     }
 }
Example #13
0
		public Window1()
		{
			InitializeComponent();

			//------------------------
			// The model
			//------------------------
			// c represents the position of the car
			c = Variable.DiscreteUniform(3).Named("Car");
			// p represents the pick. This will be observed
			p = Variable.DiscreteUniform(3).Named("Pick");
			// h represents the host pick.
			h = Variable.New<int>().Named("Host");
			// Whether the host is observed
			hostIsObserved = Variable.Observed<bool>(false);

			for (int a = 0; a < 3; a++) for (int b = 0; b < 3; b++)
				{
					double[] probs = { 1, 1, 1 };
					for (int ps = 0; ps < 3; ps++) if (ps == a || ps == b) probs[ps] = 0;
					using (Variable.Case(p, a)) using (Variable.Case(c, b)) h.SetTo(Variable.Discrete(probs));
				}
			using (Variable.If(hostIsObserved))
				Variable.ConstrainFalse(h == c);

			// Compile the model
			getProbs(h);

			OnReset();
		}
        /// <summary>
        /// Compute score for vectors, and constrain the score require to be the maximum 
        /// for the class inferred in model results
        /// </summary>
        protected void ComputeAndConstrainScores(Variable<Vector>[] variableVector)
        {
            using (Variable.ForEach(this.range))
            {
                var score = new Variable<double>[numOfClasses];
                var scorePlusNoise = new Variable<double>[numOfClasses];

                for (int i = 0; i < numOfClasses; i++)
                {
                    score[i] = Variable.InnerProduct(variableVector[i], this.featureVectors[this.range]);
                    scorePlusNoise[i] = Variable.GaussianFromMeanAndPrecision(score[i], Noise);
                }

                this.modelOutput[this.range] = Variable.DiscreteUniform(numOfClasses);

                for (int j = 0; j < numOfClasses; j++)
                {
                    using (Variable.Case(this.modelOutput[this.range], j))
                    {
                        for (int k = 0; k < scorePlusNoise.Length; k++)
                        {
                            if (k != j)
                            {
                                Variable.ConstrainPositive(scorePlusNoise[j] - scorePlusNoise[k]);
                            }
                        }
                    }
                }
            }
        }
 private void HandleFailure(Variable failure)
 {
     var defaultPair = DefaultPrivacyProvider.DefaultPair;
     var time = Group.EngineTimeData;
     Response = new ReportMessage(
         Request.Version,
         new Header(
             new Integer32(Request.MessageId()),
             new Integer32(Messenger.MaxMessageSize),
             0), // no need to encrypt.
         new SecurityParameters(
             Group.EngineId,
             new Integer32(time[0]),
             new Integer32(time[1]),
             Request.Parameters.UserName,
             defaultPair.AuthenticationProvider.CleanDigest,
             defaultPair.Salt),
         new Scope(
             Group.EngineId,
             OctetString.Empty,
             new ReportPdu(
                 Request.RequestId(),
                 ErrorCode.NoError,
                 0,
                 new List<Variable>(1) { failure })),
         defaultPair,
         null);
     if (TooBig)
     {
         GenerateTooBig();
     }
 }
        public void ConvertOneArgumentOfTwoDimensionalFunction()
        {
            IFunction func = new Function();
            IVariable<int> x = new Variable<int>("x");
            IVariable<DateTime> t = new Variable<DateTime>("t");
            var fx = new Variable<int>();
            func.Arguments.Add(x);
            func.Arguments.Add(t);
            func.Components.Add(fx);
            DateTime t0 = DateTime.Now;
            func[10,t0] = 4;

            IFunction convertedFunction = new ConvertedFunction<string, int>(func, x, Convert.ToInt32, Convert.ToString);
            //notice both argument and component are converted
            Assert.IsTrue(convertedFunction.Arguments[0] is IVariable<string>);
            Assert.IsTrue(convertedFunction.Components[0] is IVariable<int>);
            //notice the argument has been converted to a string variable
            Assert.AreEqual(4, convertedFunction["10",t0]);
            Assert.AreEqual(4, convertedFunction.Components[0].Values[0,0]);
            //arguments of components are converted as well :)
            Assert.AreEqual(4, convertedFunction.Components[0]["10",t0]);
            convertedFunction["30",t0] = 10;
            IMultiDimensionalArray<string> strings = (IMultiDimensionalArray<string>)convertedFunction.Arguments[0].Values;
            Assert.IsTrue(new[] { "10", "30" }.SequenceEqual(strings));
            
        }
Example #17
0
 public void SetDateTime()
 {
     IVariable<DateTime> var = new Variable<DateTime>();
     DateTime to = DateTime.Now;
     var.Values.Add(to);
     Assert.IsTrue(var.Values.Contains(to));
 }
        public void GetArgumentDependentVariables()
        {
            IFunction f = new Function();
            IVariable c1 = new Variable<int>("c1");
            IVariable c2 = new Variable<int>("c2");
            IVariable x = new Variable<int>("x");
            
            f.Components.Add(c1);
            f.Components.Add(c2);

            IDictionary<IVariable, IEnumerable<IVariable>> dependentVariables = MemoryFunctionStoreHelper.GetDependentVariables(f.Store.Functions);
            
            //no argument dependencies yet
            Assert.AreEqual(2, dependentVariables.Count);
            Assert.AreEqual(new IVariable[0],dependentVariables[c1].ToArray());
            Assert.AreEqual(new IVariable[0], dependentVariables[c2].ToArray());
            
            f.Arguments.Add(x);
            
            dependentVariables = MemoryFunctionStoreHelper.GetDependentVariables(f.Store.Functions);

            Assert.AreEqual(3, dependentVariables.Count);
            Assert.AreEqual(2, dependentVariables[x].Count());
            Assert.AreEqual(new[]{c1,c2},dependentVariables[x]);
            //Assert.IsTrue(dependentVariables[x].Contains(c1));
        }
Example #19
0
        public void SeriesChangesWhenFunctionBindingListChanges()
        {
            IFunction function = new Function();
            IVariable yVariable = new Variable<double>("y");
            IVariable xVariable = new Variable<double>("x");
            function.Arguments.Add(xVariable);
            function.Components.Add(yVariable);
            
            function[1.0] = 2.0;
            function[2.0] = 5.0;
            function[3.0] = 1.0;

            ILineChartSeries ls = ChartSeriesFactory.CreateLineSeries();
            ls.YValuesDataMember = function.Components[0].DisplayName;
            ls.XValuesDataMember = function.Arguments[0].DisplayName;

            var synchronizeObject = new Control();
            synchronizeObject.Show();

            var functionBindingList = new FunctionBindingList(function) { SynchronizeInvoke = synchronizeObject };
            ls.DataSource = functionBindingList;
            
            //a change in the function should change the series
            function[1.0] = 20.0;

            while(functionBindingList.IsProcessing)
            {
                Application.DoEvents();
            }
            
            Assert.AreEqual(20, ls.YValues[0]);
            
        }
 public ArrayAssignment(int lineNumber, Variable array, Variable index, Variable value)
     : base(lineNumber)
 {
     this.array = array;
     this.index = index;
     this.value = value;
 }
Example #21
0
        public SentimentIndex()
            : base("Sentiment Index")
        {
            numberOfTrainingItems = Variable.New<int>();
            var rangeOfTrainingItems = new Range(numberOfTrainingItems);
            trainingInputs = Variable.Array<Vector>(rangeOfTrainingItems);
            trainingOutputs = Variable.Array<bool>(rangeOfTrainingItems);

            weights = Variable.Random(new VectorGaussian(Vector.Zero(numberOfFeatures), PositiveDefiniteMatrix.Identity(numberOfFeatures)));

            using (Variable.ForEach(rangeOfTrainingItems))
            {
                trainingOutputs[rangeOfTrainingItems] = Variable.IsPositive(Variable.GaussianFromMeanAndVariance(Variable.InnerProduct(weights, trainingInputs[rangeOfTrainingItems]), noise));
            }

            trainingEngine = new InferenceEngine();
            trainingEngine.ShowProgress = false;

            numberOfTestingItems = Variable.New<int>();
            var rangeOfTestingItems = new Range(numberOfTestingItems);
            testingInputs = Variable.Array<Vector>(rangeOfTestingItems);
            testingOutputs = Variable.Array<bool>(rangeOfTestingItems);

            weightsPosteriorDistribution = Variable.New<VectorGaussian>();
            var testWeights = Variable<Vector>.Random(weightsPosteriorDistribution);

            using (Variable.ForEach(rangeOfTestingItems))
            {
                testingOutputs[rangeOfTestingItems] = Variable.IsPositive(Variable.GaussianFromMeanAndVariance(Variable.InnerProduct(testWeights, testingInputs[rangeOfTestingItems]), noise));
            }

            testingEngine = new InferenceEngine();
            testingEngine.ShowProgress = false;
        }
Example #22
0
    protected override void InitializeCulture()
    {
        string lang = "en";

        if ( Context.Request.QueryString["lang"] != null )
        {
            lang = Context.Request.QueryString["lang"];
            switch ( lang )
            {
                case "cz":
                case "cs":
                    Thread.CurrentThread.CurrentCulture = new CultureInfo("cs-CZ");
                    Thread.CurrentThread.CurrentUICulture = new CultureInfo("cs-CZ");
                    break;
                default:
                    Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
                    Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
                    break;
            }
        }
        else
        {
            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
            Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
        }

        // this code is invoked, when the form is posted back.
        // (after pressing the "OK" button)
        // The page is then redirected to a different URL
        if ( Context.Request.Form.Count > 0 )
        {
            Variable varInfo = new Variable(4);
            string ctlHeading = @"ctl00$cph_main$";
            string varName = Context.Request.Form[ctlHeading + "listbox_variable"];
            string stName = Context.Request.Form[ctlHeading + "txt_station"];

            //string periodStr = Context.Request.Form[ctlHeading + "listbox_period"];

            string yearStr = Context.Request.Form[ctlHeading + "listbox_year"];
            string monthStr = Context.Request.Form[ctlHeading + "listbox_month"];
            string dayStr = Context.Request.Form[ctlHeading + "listbox_day"];

            string yearStr2 = Context.Request.Form[ctlHeading + "listbox_year2"];
            string monthStr2 = Context.Request.Form[ctlHeading + "listbox_month2"];
            string dayStr2 = Context.Request.Form[ctlHeading + "listbox_day2"];

            string varUrl = ProcessVariable(varName, varInfo);
            string stUrl = ProcessStation(stName, varInfo);
            //string dateUrl = ProcessDate(yearStr, monthStr, dayStr);
            string periodUrl = ProcessPeriod(yearStr, monthStr, dayStr, yearStr2, monthStr2, dayStr2);

            // generate url of the new page!
            string newUrl =
                String.Format(@"~/{0}/{1}/{2}/{3}.aspx",
                lang, varUrl, stUrl, periodUrl);

            // redirect the browser to the new page!
            Context.Response.Redirect(newUrl);
        }
    }
 /// <summary>
 /// Initializes a new instance of the <see cref="WrongCodeTypeException" /> class.
 /// </summary>
 /// <param name="variable">The variable.</param>
 /// <param name="argumentName">Name of the argument.</param>
 /// <param name="expectedText">The expected text.</param>
 public WrongCodeTypeException(Variable variable, string argumentName, string expectedText)
     : base(string.Format("Wrong code type [{0}] of passed parameter '{1}'. Expected {2}.", variable.GetCodeType().Name, argumentName, expectedText))
 {
     Variable = variable;
     CodeType = variable.GetCodeType();
     ArgumentName = argumentName;
 }
Example #24
0
        public Variable CreateFLV(string name)
        {
            if (name == null) throw new ArgumentNullException("name");
            if (_variables.ContainsKey(name)) throw new Exception();

            return _variables[name] = new Variable();
        }
Example #25
0
        public void VerifyPropertiesOfVariableOfTypeGuid()
        {
            Type declaredType = typeof(Guid);
            Variable<Guid> vInt = new Variable<Guid>(Guid.Empty);

            Assert.Equal(declaredType, vInt.DataType);
        }
Example #26
0
        public void Test(string testDll, Variable<int> performed, 
		     Variable<int> total)
        {
            bool success = false;

              try
            {
              success = MakeTestFromCommandLine(_testDomain, testDll);
            }
              catch(System.IO.FileNotFoundException)
            {
              new Message("Failed opening " + testDll);
              return;
            }

              if (!success)
            {
              Console.Error.WriteLine("Unable to locate fixture");
              return;
            }

              total.Value = _testRunner.CountTestCases(TestFilter.Empty);

              var collector = new EventCollector(Console.Out, Console.Error, performed);
              var result = _testRunner.Run(collector);
        }
 internal static object DCArg(Variable v) {
     P6any o = v.Fetch();
     var s = o.mo.setting;
     if (o is BoxObject<object>)
         return Kernel.UnboxAny<object>(o);
     else if (o.IsDefined()) {
         if (o.Isa(s.StrMO))
             return (string) o.mo.mro_raw_Str.Get(v);
         else if (o.Isa(s.BoolMO))
             return (bool) o.mo.mro_raw_Bool.Get(v);
         else if (o.Isa(s.NumMO)) {
             double d = Kernel.UnboxAny<double>(o);
             if ((d % 1) == 0 && d <= int.MaxValue && d >= int.MinValue)
                 return (object)(int)d;
             return (object)d;
         } else if (o.Isa(s.ListMO)) {
             VarDeque it = o.mo.mro_raw_iterator.Get(v);
             var lo = new List<object>();
             while (Kernel.IterHasFlat(it, true))
                 lo.Add(DCArg(it.Shift()));
             return lo.ToArray();
         } else
             return (int) o.mo.mro_raw_Numeric.Get(v);
     } else
         return null;
 }
Example #28
0
        public static double Integral(string Expression, double LowerIndex, double UpperIndex, char IterationVariable, int Kind)
        {
            var parser = new MathParser();

            var Var = new Variable<double>(IterationVariable.ToString());

            parser.Variables.Add(Var);
            parser.Parse(Expression);

            Func<double,double> proc = x =>
                {
                    Var.Value = x;
                    return parser.Evaluate();
                };

            switch (Kind)
            {
                case 0:
                    return Integration.Trapezoidal(LowerIndex, UpperIndex, proc);

                case 1:
                    return Integration.LeftHand(LowerIndex, UpperIndex, proc);

                default:
                    return Integration.MidPoint(LowerIndex, UpperIndex, proc);
            }
        }
		void Initialize() {
			foreach (var variable in locals)
				variableToValue[variable] = new Variable();

			foreach (var block in allBlocks) {
				for (int i = 0; i < block.Instructions.Count; i++) {
					var instr = block.Instructions[i];

					switch (instr.OpCode.Code) {
					case Code.Stloc:
					case Code.Stloc_S:
					case Code.Stloc_0:
					case Code.Stloc_1:
					case Code.Stloc_2:
					case Code.Stloc_3:
						var variable = Instr.GetLocalVar(locals, instr);
						var val = variableToValue[variable];
						val.AddWrite();
						object obj;
						if (!GetValue(block, i, out obj))
							val.SetUnknown();
						val.Value = obj;
						break;

					default:
						break;
					}
				}
			}
		}
        public override void Train()
        {
            InitModel();

            // define variables
            var avg = Ratings.Average;
            var ub  = new Variable();
            var ib  = new Variable();
            var r   = new Variable();

            // define function to minimize
            var func = TermBuilder.Power(avg + ub + ib - r, 2);
            var func_compiled = func_min.Compile();

            double learn_rate = 0.0001;

            for (int i = 0; i < NumIter; i++)
                foreach (int j in Ratings.RandomIndex)
                {
                    // get data
                    var data = new double[] { user_bias[Ratings.Users[j]], item_bias[Ratings.Items[j]], Ratings[j] };

                    // compute gradient
                    var gradient = func_compiled.Differentiate(data);

                    // update
                    user_bias[Ratings.Users[j]] -= learn_rate * gradient[0];
                    item_bias[Ratings.Items[j]] -= learn_rate * gradient[1];
                }
        }