Esempio n. 1
0
        public void Init(double rsm_lb, double rsm_ub, int pc_b)
        {
            step            = 0.01;
            States          = new List <RTPState>();
            Observations    = new List <RTPObservation>();
            ModelSamples    = new List <Sample>();
            SystemSamples   = new List <Sample>();
            EstimateSamples = new List <Sample>();
            //TestEstimateSamples = new List<Sample>();

            MBuilder = Matrix <double> .Build;
            VBuilder = Vector <double> .Build;

            E = new Matrix <double> [N];
            F = new Matrix <double> [M];

            for (int i = 0; i < N; i++)
            {
                E[i]       = MBuilder.Dense(N, 1);
                E[i][i, 0] = 1;
            }
            for (int i = 0; i < M; i++)
            {
                F[i]       = MBuilder.Dense(M, 1);
                F[i][i, 0] = 1;
            }

            Matlab = new MLApp.MLApp();

            DefineStates(rsm_lb, rsm_ub);
            DefineObservations(pc_b);

            //ModelParamsInit();
        }
 public void InitialiseGeneral()
 {
     Means       = new Dictionary <DateTime, double[]>();
     CoVariances = new Dictionary <DateTime, double[, ]>();
     //Measurements = new Dictionary<TimeSpan, Vector<double>>();
     Mbuilder = Matrix <double> .Build;
     Vbuilder = Vector <double> .Build;
     rand     = new Random();
 }
Esempio n. 3
0
        /// <summary>
        /// 正規化した座標のリストを作成
        /// </summary>
        /// <param name="tail"></param>
        private void NormalizePoints(int listnum)
        {
            VectorBuilder <double> Vector = Vector <double> .Build;
            MatrixBuilder <double> Matrix = Matrix <double> .Build;

            for (int i = 0; i < listnum; i++)
            {
                //体が常に横を向くように正規化
                //HipRightからHipLeftへのびるXZ平面ベクトルに対して垂直なXZ平面ベクトルを計算
                double[] hip = new double[3] {
                    -(kinectPoints[12][i][2] - kinectPoints[16][i][2]),
                    0,
                    kinectPoints[12][i][0] - kinectPoints[16][i][0]
                };
                var VecHip = Vector.DenseOfArray(hip);
                //求めたベクトルの絶対値を1に
                var e_x = VecHip.Divide((float)VecHip.L2Norm());
                //e_y = (0,1,0)
                var e_y = Vector.DenseOfArray(new double[3] {
                    0, 1, 0
                });
                //e_z = e_x × e_y
                var e_z = Vector.DenseOfArray(new double[3] {
                    -e_x.At(2), 0, e_x.At(0)
                });

                //e_x,e_y,e_zを一つの行列に
                var      mat  = Matrix.DenseOfColumnVectors(new Vector <double>[] { e_x, e_y, e_z }).Inverse();
                double[] norm = new double[3];//正規化した座標を格納する三次元座標
                for (int j = 0; j < 21; j++)
                {
                    var VecJ = Vector.DenseOfArray(new double[3] {
                        kinectPoints[j][i][0] - kinectPoints[0][i][0],
                        kinectPoints[j][i][1] - kinectPoints[0][i][1],
                        kinectPoints[j][i][2] - kinectPoints[0][i][2]
                    });
                    var E = mat * VecJ;
                    for (int k = 0; k < 3; k++)
                    {
                        norm[k] = E.At(k);
                    }
                    kinectNormalizedPoints[j].Add((double[])norm.Clone());
                }
                //頭の高さを1として正規化
                double[] head    = kinectNormalizedPoints[3][i];
                double   headVec = Math.Sqrt(head[0] * head[0] + head[1] * head[1] + head[2] * head[2]);
                for (int j = 0; j < 21; j++)//jointnum:3 = head
                {
                    double[] points = kinectNormalizedPoints[j][i];
                    double   Vec    = Math.Sqrt(points[0] * points[0] + points[1] * points[1] + points[2] * points[2]);
                    Vec /= headVec;
                    //kinectNormalizedPoints[j][i][0] *= Vec;
                }
            }
        }
        public static Vector <T> SameAs <T>(this VectorBuilder <T> builder, Vector <T> example, Func <T> f) where T : struct, global::System.IEquatable <T>, global::System.IFormattable
        {
            Contract.Requires(builder != null);
            Contract.Requires(example != null);
            Contract.Requires(f != null);

            var result = builder.SameAs(example);

            Contract.Assume(result != null);

            result.MapInplace(x => f());
            return(result);
        }
Esempio n. 5
0
        public UserIndirectJump GetResults()
        {
            var vb      = new VectorBuilder(dlg.Services, dlg.Program, new DirectedGraphImpl <object>());
            var stride  = 4; //$TODO: get from dialog
            var entries = vb.BuildTable(dlg.VectorAddress, stride * (int)dlg.EntryCount.Value, null, stride, null);
            var table   = new ImageMapVectorTable(dlg.VectorAddress, entries.ToArray(), 0);

            return(new UserIndirectJump
            {
                Address = dlg.Instruction.Address,
                Table = table,
                IndexRegister = dlg.Program.Architecture.GetRegister(dlg.IndexRegister.SelectedValue.ToString())
            });
        }
Esempio n. 6
0
        private void BuildAddressTable()
        {
            var vectorBuilder = new VectorBuilder(null, dlg.Program, null);
            var addresses     = new List <Address>();

            if (dlg.Program.Platform.TryParseAddress(dlg.JumpTableStartAddress.Text, out Address addrTable))
            {
                var stride = TableStride();
                var state  = dlg.Program.Architecture.CreateProcessorState();
                state.InstructionPointer = dlg.Instruction.Address;
                addresses = vectorBuilder.BuildTable(addrTable, stride * (int)dlg.EntryCount.Value, null, stride, state);
            }
            dlg.Entries.DataSource    = addresses;
            dlg.Entries.SelectedIndex = addresses.Count - 1;
        }
Esempio n. 7
0
    // Use this for initialization
    void Start()
    {
        /*SparseMatrix A = SparseMatrix.OfRowArrays(new double[7][]
         * {
         *  new double[] {0, -1, -1, -1, -1, -1, -1},
         *  new double[] {-1, 1, 0, 0, 0, 0, 0},
         *  new double[] {-1, 0, 1, 0, 0, 0, 0},
         *  new double[] {-1, 0, 0, 1, 0, 0, 0},
         *  new double[] {-1, 0, 0, 0, 1, 0, 0},
         *  new double[] {-1, 0, 0, 0, 0, 1, 0},
         *  new double[] {-1, 0, 1, 0, 0, 0, 1}
         * });*/

        Func <int, int, double> init = cValues;
        SparseMatrix            A    = SparseMatrix.Create(7, 7, init);

        double lambda = -993f / (6f * 0.01f);

        lambda *= 1f - 5f / 7f;
        double nDefault = 5f;
        VectorBuilder <double> Builder = Vector <double> .Build;
        Vector <double>        B       = Builder.DenseOfArray(new double[7]
        {
            0,
            lambda,
            lambda,
            lambda,
            lambda,
            lambda,
            lambda,
        });

        VectorBuilder <double> resultB = Vector <double> .Build;
        Vector <double>        result  = resultB.Dense(7);

        A.Solve(B, result);

        Debug.Log("Matrix A is : " + A.ToString());
        Debug.Log("Matrix B is : " + B.ToString());
        Debug.Log("Lambda is : " + lambda);
        Debug.Log("The result vector3 is : " + result.ToString());
    }
Esempio n. 8
0
        public void Vb_CreateVector_ModifiesImageMap()
        {
            Given_Program(new byte[]
            {
                0x10, 0x00, 0x01, 0x00,
                0x11, 0x00, 0x01, 0x00,
                0x12, 0x00, 0x01, 0x00,
                0xCC, 0xCC, 0xCC, 0xCC,
                0xC3, 0xC3, 0xC3, 0xCC,
            });
            var scanner = new Mock <IScanner>();

            scanner.Setup(s => s.Services).Returns(sc);
            arch.Setup(s => s.CreateImageReader(this.mem, this.program.ImageMap.BaseAddress))
            .Returns(this.mem.CreateLeReader(0));
            var state = new FakeProcessorState(arch.Object);

            var vb     = new VectorBuilder(scanner.Object.Services, program, new DirectedGraphImpl <object>());
            var vector = vb.BuildTable(this.program.ImageMap.BaseAddress, 12, null, 4, state);

            Assert.AreEqual(3, vector.Count);
        }
Esempio n. 9
0
        public void Vb_CreateVector_ModifiesImageMap()
        {
            Given_Program(new byte[]
            {
                0x10, 0x00, 0x01, 0x00,
                0x11, 0x00, 0x01, 0x00,
                0x12, 0x00, 0x01, 0x00,
                0xCC, 0xCC, 0xCC, 0xCC,
                0xC3, 0xC3, 0xC3, 0xCC,
            });
            var scanner = mr.Stub <IScanner>();

            scanner.Stub((Function <IScanner, ImageReader>)(s => s.CreateReader((Address)this.program.ImageMap.BaseAddress)))
            .Return(this.mem.CreateLeReader(0));
            var state = mr.Stub <ProcessorState>();

            mr.ReplayAll();

            var vb     = new VectorBuilder(scanner, program, new DirectedGraphImpl <object>());
            var vector = vb.BuildTable((Address)this.program.ImageMap.BaseAddress, 12, null, 4, state);

            Assert.AreEqual(3, vector.Count);
        }
Esempio n. 10
0
        static void Main(string[] args)
        {
            //初始化一个矩阵和向量的构建对象
            var mb  = Matrix <double> .Build;
            var mb1 = Matrix <double> .Build;
            var vb  = Vector <double> .Build;

            DateTime time = new DateTime(2005, 12, 05);



            double[] AiC = { 1, 2, 3 };
            double[,] AiC1 = { { 1, 2, 3 }, { 1, 2, 3 }, { 1, 2, 3 } };
            double[]    AiR      = new double[3];
            DenseMatrix AiMatrix = DenseMatrix.OfArray(new[, ] {
                { 1.0, 2.0, 3.0 }, { 4.0, 5.0, 6.0 }, { 7.0, 8.0, 9.0 }
            });;                                                                                                             //创建一个对角矩阵对象
            VectorBuilder <double> vector = Vector <double> .Build;
            var t = vector.DenseOfArray(AiC);
            //var c = AiMatrix.DenseOfArray(AiC1);
            var r = t * AiMatrix;



            var matrixA = DenseMatrix.OfArray(new[, ] {
                { 1.0, 2.0, 3.0 }, { 4.0, 5.0, 6.0 }, { 7.0, 8.0, 9.0 }
            });
            var matrixB = DenseMatrix.OfArray(new[, ] {
                { 1.0, 3.0, 5.0 }, { 2.0, 4.0, 6.0 }, { 3.0, 5.0, 7.0 }
            });
            var s = matrixA * matrixB;



            string   str   = "20100531";
            DateTime dtime = DateTime.ParseExact(str, "yyyyMMdd", null);


            DateTime dtime1 = DateTime.Now;

            Dictionary <int, double> dic = new Dictionary <int, double>();

            dic.Add(0, 1);
            dic.Add(1, 2);
            dic.Add(2, 3);
            dic.Add(3, 4);
            //var matrix2 = mb.Dense(2, 3, (i, j) => 3 * i + j);
            var diagMaxtrix = mb.DenseDiagonal(4, 4, (i) => i);


            //先生成数据集合
            var chiSquare = new ChiSquared(5);

            Console.WriteLine(@"2. Generate 1000 samples of the ChiSquare(5) distribution");
            var data = new double[1000];
            //var data1 = new double[1000];
            //for (var i = 0; i < data.Length; i++)
            //{
            //    data[i] = chiSquare.Sample();
            //}
            List <double> a = new List <double>();
            List <double> b = new List <double>();

            //data1 = new double []{1,2,3,4,5};

            data[0] = 10;
            data[1] = 0;
            data[2] = 0;
            data[3] = 0;
            data[4] = 0;
            data[5] = 0;
            data[6] = 0;
            data[7] = 0;
            data[8] = 0;
            data[9] = -0.1;
            var data1 = new double[] { 1, 2, 3 };
            var data2 = new double[] { 1, 2, 6 };

            data1.Mean();
            data1.Variance();
            data2.Mean();
            var ss = data1.Covariance(data2);

            //使用扩展方法进行相关计算
            Console.WriteLine(@"3.使用扩展方法获取生成数据的基本统计结果");
            Console.WriteLine(@"{0} - 最大值", data.Maximum().ToString(" #0.00000;-#0.00000"));
            Console.WriteLine(@"{0} - 最小值", data.Minimum().ToString(" #0.00000;-#0.00000"));
            Console.WriteLine(@"{0} - 均值", data.Mean().ToString(" #0.00000;-#0.00000"));
            Console.WriteLine(@"{0} - 中间值", data.Median().ToString(" #0.00000;-#0.00000"));
            Console.WriteLine(@"{0} - 有偏方差", data.PopulationVariance().ToString(" #0.00000;-#0.00000"));
            Console.WriteLine(@"{0} - 无偏方差", data.Variance().ToString(" #0.00000;-#0.00000"));
            Console.WriteLine(@"{0} - 标准偏差", data.StandardDeviation().ToString(" #0.00000;-#0.00000"));
            Console.WriteLine(@"{0} - 标准有偏偏差", data.PopulationStandardDeviation().ToString(" #0.00000;-#0.00000"));
            Console.WriteLine();



            Console.WriteLine(@"4. 使用DescriptiveStatistics类进行基本的统计计算");
            var descriptiveStatistics = new DescriptiveStatistics(data);//使用数据进行类型的初始化

            //直接使用属性获取结果
            Console.WriteLine(@"{0} - Kurtosis", descriptiveStatistics.Kurtosis.ToString(" #0.00000;-#0.00000"));
            Console.WriteLine(@"{0} - Largest element", descriptiveStatistics.Maximum.ToString(" #0.00000;-#0.00000"));
            Console.WriteLine(@"{0} - Smallest element", descriptiveStatistics.Minimum.ToString(" #0.00000;-#0.00000"));
            Console.WriteLine(@"{0} - Mean", descriptiveStatistics.Mean.ToString(" #0.00000;-#0.00000"));
            Console.WriteLine(@"{0} - Variance", descriptiveStatistics.Variance.ToString(" #0.00000;-#0.00000"));
            Console.WriteLine(@"{0} - Standard deviation", descriptiveStatistics.StandardDeviation.ToString(" #0.00000;-#0.00000"));
            Console.WriteLine(@"{0} - Skewness", descriptiveStatistics.Skewness.ToString(" #0.00000;-#0.00000"));
            Console.WriteLine();
        }
Esempio n. 11
0
        private static DoubleCurve <T> Build(List <Contract <T> > contracts, Func <T, double> weighting,
                                             Func <T, double> multAdjustFunc, Func <T, double> addAdjustFunc, Func <T, T, double> timeFunc,
                                             double?frontFirstDerivative, double?backFirstDerivative)
        {
            if (contracts.Count < 2)
            {
                throw new ArgumentException("contracts must have at least two elements", nameof(contracts));
            }

            var curveStartPeriod = contracts[0].Start;

            int numGaps = 0;
            var timeToPolynomialBoundaries = new List <double>();

            // TODO optionally do/don't allow gaps in contracts
            for (int i = 0; i < contracts.Count - 1; i++)
            {
                var contractEnd       = contracts[i].End;
                var nextContractStart = contracts[i + 1].Start;

                if (contractEnd.CompareTo(nextContractStart) >= 0)
                {
                    throw new ArgumentException("contracts are overlapping");
                }
                timeToPolynomialBoundaries.Add(timeFunc(curveStartPeriod, nextContractStart));

                if (contractEnd.OffsetFrom(nextContractStart) < -1) // Gap in contracts
                {
                    numGaps++;
                    timeToPolynomialBoundaries.Add(timeFunc(curveStartPeriod, contractEnd.Next()));
                }
            }

            int numPolynomials         = contracts.Count + numGaps;
            int numCoefficientsToSolve = numPolynomials * 5;

            int numConstraints =
                (numPolynomials - 1) * 3   // Spline value, 1st derivative, and 2nd derivative constraints
                + numPolynomials - numGaps // Price constraints
                + (frontFirstDerivative.HasValue ? 1 : 0)
                + (backFirstDerivative.HasValue ? 1 : 0);

            MatrixBuilder <double> matrixBuilder = Matrix <double> .Build;
            VectorBuilder <double> vectorBuilder = Vector <double> .Build;

            var constraintMatrix = matrixBuilder.Dense(numConstraints, numCoefficientsToSolve);
            var vector           = vectorBuilder.Dense(numPolynomials * 5 + numConstraints);

            var twoHMatrix = matrixBuilder.Dense(numPolynomials * 5, numPolynomials * 5);

            int inputContractIndex = 0;

            bool gapFilled = false;

            int rowNum = 0;

            for (int i = 0; i < numPolynomials; i++)
            {
                int colOffset = i * 5;
                if (i < numPolynomials - 1)
                {
                    double timeToPolynomialBoundary     = timeToPolynomialBoundaries[i];
                    double timeToPolynomialBoundaryPow2 = Math.Pow(timeToPolynomialBoundary, 2);
                    double timeToPolynomialBoundaryPow3 = Math.Pow(timeToPolynomialBoundary, 3);
                    double timeToPolynomialBoundaryPow4 = Math.Pow(timeToPolynomialBoundary, 4);

                    // Polynomial equality at boundaries
                    constraintMatrix[rowNum, colOffset]     = 1.0;
                    constraintMatrix[rowNum, colOffset + 1] = timeToPolynomialBoundary;
                    constraintMatrix[rowNum, colOffset + 2] = timeToPolynomialBoundaryPow2;
                    constraintMatrix[rowNum, colOffset + 3] = timeToPolynomialBoundaryPow3;
                    constraintMatrix[rowNum, colOffset + 4] = timeToPolynomialBoundaryPow4;

                    constraintMatrix[rowNum, colOffset + 5] = -1.0;
                    constraintMatrix[rowNum, colOffset + 6] = -timeToPolynomialBoundary;
                    constraintMatrix[rowNum, colOffset + 7] = -timeToPolynomialBoundaryPow2;
                    constraintMatrix[rowNum, colOffset + 8] = -timeToPolynomialBoundaryPow3;
                    constraintMatrix[rowNum, colOffset + 9] = -timeToPolynomialBoundaryPow4;

                    // Polynomial first derivative equality at boundaries
                    constraintMatrix[rowNum + 1, colOffset]     = 0.0;
                    constraintMatrix[rowNum + 1, colOffset + 1] = 1.0;
                    constraintMatrix[rowNum + 1, colOffset + 2] = 2.0 * timeToPolynomialBoundary;
                    constraintMatrix[rowNum + 1, colOffset + 3] = 3.0 * timeToPolynomialBoundaryPow2;
                    constraintMatrix[rowNum + 1, colOffset + 4] = 4.0 * timeToPolynomialBoundaryPow3;

                    constraintMatrix[rowNum + 1, colOffset + 5] = 0.0;
                    constraintMatrix[rowNum + 1, colOffset + 6] = -1.0;
                    constraintMatrix[rowNum + 1, colOffset + 7] = -2.0 * timeToPolynomialBoundary;
                    constraintMatrix[rowNum + 1, colOffset + 8] = -3.0 * timeToPolynomialBoundaryPow2;
                    constraintMatrix[rowNum + 1, colOffset + 9] = -4.0 * timeToPolynomialBoundaryPow3;

                    // Polynomial second derivative equality at boundaries
                    constraintMatrix[rowNum + 2, colOffset]     = 0.0;
                    constraintMatrix[rowNum + 2, colOffset + 1] = 0.0;
                    constraintMatrix[rowNum + 2, colOffset + 2] = 2.0;
                    constraintMatrix[rowNum + 2, colOffset + 3] = 6.0 * timeToPolynomialBoundary;
                    constraintMatrix[rowNum + 2, colOffset + 4] = 12.0 * timeToPolynomialBoundaryPow2;

                    constraintMatrix[rowNum + 2, colOffset + 5] = 0.0;
                    constraintMatrix[rowNum + 2, colOffset + 6] = 0.0;
                    constraintMatrix[rowNum + 2, colOffset + 7] = -2.0;
                    constraintMatrix[rowNum + 2, colOffset + 8] = -6 * timeToPolynomialBoundary;
                    constraintMatrix[rowNum + 2, colOffset + 9] = -12.0 * timeToPolynomialBoundaryPow2;
                }

                // Contract price constraint
                if (i == 0 ||  // Can't be gap at the first position
                    contracts[inputContractIndex - 1].End.OffsetFrom(contracts[inputContractIndex].Start) ==
                    -1 ||      // No gap from previous
                    gapFilled) // Gap has already been dealt with
                {
                    Contract <T> contract              = contracts[inputContractIndex];
                    double       sumWeight             = 0.0;
                    double       sumWeightMult         = 0.0;
                    double       sumWeightMultTime     = 0.0;
                    double       sumWeightMultTimePow2 = 0.0;
                    double       sumWeightMultTimePow3 = 0.0;
                    double       sumWeightMultTimePow4 = 0.0;
                    double       sumWeightMultAdd      = 0.0;

                    foreach (T timePeriod in contract.Start.EnumerateTo(contract.End))
                    {
                        double timeToPeriod = timeFunc(curveStartPeriod, timePeriod);
                        double weight       = weighting(timePeriod);
                        double multAdjust   = multAdjustFunc(timePeriod);
                        double addAdjust    = addAdjustFunc(timePeriod);

                        sumWeight             += weight;
                        sumWeightMult         += weight * multAdjust;
                        sumWeightMultTime     += weight * multAdjust * timeToPeriod;
                        sumWeightMultTimePow2 += weight * multAdjust * Math.Pow(timeToPeriod, 2.0);
                        sumWeightMultTimePow3 += weight * multAdjust * Math.Pow(timeToPeriod, 3.0);
                        sumWeightMultTimePow4 += weight * multAdjust * Math.Pow(timeToPeriod, 4.0);
                        sumWeightMultAdd      += weight * multAdjust * addAdjust;
                    }

                    int priceConstraintRow = i == (numPolynomials - 1) ? rowNum : rowNum + 3;

                    constraintMatrix[priceConstraintRow, colOffset]     = sumWeightMult;         // Coefficient of a
                    constraintMatrix[priceConstraintRow, colOffset + 1] = sumWeightMultTime;     // Coefficient of b
                    constraintMatrix[priceConstraintRow, colOffset + 2] = sumWeightMultTimePow2; // Coefficient of c
                    constraintMatrix[priceConstraintRow, colOffset + 3] = sumWeightMultTimePow3; // Coefficient of d
                    constraintMatrix[priceConstraintRow, colOffset + 4] = sumWeightMultTimePow4; // Coefficient of e

                    vector[numPolynomials * 5 + priceConstraintRow] = sumWeight * contract.Price - sumWeightMultAdd;

                    twoHMatrix.SetSubMatrix(i * 5 + 2, i * 5 + 2,
                                            Create2HBottomRightSubMatrix(contract, curveStartPeriod, timeFunc));

                    inputContractIndex++;
                    rowNum   += 4;
                    gapFilled = false;
                }
                else
                {
                    // Gap in contracts
                    rowNum   += 3;
                    gapFilled = true;
                }
            }

            // TODO unit test first derivative constraints. How?
            rowNum -= 3;
            if (frontFirstDerivative.HasValue)
            {
                constraintMatrix[rowNum, 1]         = 1; // Coefficient of b
                vector[numPolynomials * 5 + rowNum] = frontFirstDerivative.Value;
                rowNum++;
            }

            if (backFirstDerivative.HasValue)
            {
                T      lastPeriod = contracts[contracts.Count - 1].End;
                double timeToEnd  = timeFunc(curveStartPeriod, lastPeriod.Offset(1));
                constraintMatrix[rowNum, numCoefficientsToSolve - 4] = 1;                          // Coefficient of b
                constraintMatrix[rowNum, numCoefficientsToSolve - 3] = 2 * timeToEnd;              // Coefficient of c
                constraintMatrix[rowNum, numCoefficientsToSolve - 2] = 3 * Math.Pow(timeToEnd, 2); // Coefficient of d
                constraintMatrix[rowNum, numCoefficientsToSolve - 1] = 4 * Math.Pow(timeToEnd, 3); // Coefficient of e
                vector[numPolynomials * 5 + rowNum] = backFirstDerivative.Value;
            }

            // Create system of equations to solve
            Matrix <double> tempMatrix1 = twoHMatrix.Append(constraintMatrix.Transpose());
            var             tempMatrix2 = constraintMatrix.Append(
                matrixBuilder.Dense(constraintMatrix.RowCount, constraintMatrix.RowCount));

            var matrix = tempMatrix1.Stack(tempMatrix2);

            Vector <double> solution = matrix.Solve(vector);

            // Read off results from polynomial
            T   curveEndPeriod      = contracts[contracts.Count - 1].End;
            int numOutputPeriods    = curveEndPeriod.OffsetFrom(curveStartPeriod) + 1;
            var outputCurvePeriods  = new T[numOutputPeriods];
            var outputCurvePrices   = new double[numOutputPeriods];
            int outputContractIndex = 0;

            gapFilled          = false;
            inputContractIndex = 0;

            for (int i = 0; i < numPolynomials; i++)
            {
                double EvaluateSpline(T timePeriod)
                {
                    double timeToPeriod = timeFunc(curveStartPeriod, timePeriod);

                    int    solutionOffset = i * 5;
                    double splineValue    = solution[solutionOffset] +
                                            solution[solutionOffset + 1] * timeToPeriod +
                                            solution[solutionOffset + 2] * Math.Pow(timeToPeriod, 2) +
                                            solution[solutionOffset + 3] * Math.Pow(timeToPeriod, 3) +
                                            solution[solutionOffset + 4] * Math.Pow(timeToPeriod, 4);

                    double multAdjust = multAdjustFunc(timePeriod);
                    double addAdjust  = addAdjustFunc(timePeriod);

                    return((splineValue + addAdjust) * multAdjust);
                }

                T start;
                T end;
                if (i == 0 ||                                                                                      // Can't be gap at the first position
                    contracts[inputContractIndex - 1].End.OffsetFrom(contracts[inputContractIndex].Start) == -1 || // No gap from previous
                    gapFilled)                                                                                     // Gap has already been dealt with
                {
                    Contract <T> contract = contracts[inputContractIndex];
                    start = contract.Start;
                    end   = contract.End;
                    inputContractIndex++;
                    gapFilled = false;
                }
                else
                {
                    start     = contracts[inputContractIndex - 1].End.Next();
                    end       = contracts[inputContractIndex].Start.Previous();
                    gapFilled = true;
                }

                foreach (var timePeriod in start.EnumerateTo(end))
                {
                    outputCurvePrices[outputContractIndex]  = EvaluateSpline(timePeriod);
                    outputCurvePeriods[outputContractIndex] = timePeriod;
                    outputContractIndex++;
                }
            }

            return(new DoubleCurve <T>(outputCurvePeriods, outputCurvePrices, weighting));
        }
Esempio n. 12
0
        /// <summary>
        /// Calculates a, b, c, d, e, and f using singular value decomposition.
        ///     lon = a*x + b*y + e;
        ///     lat = c*x + d*y + f;
        /// </summary>
        protected void createTransform()
        {
            Transform = null;
            if (DataList.Count < 3)
            {
                Utils.errMsg("Need at least three data points for calibration.");
                return;
            }

            // Define the matrices
            MatrixBuilder <double> M = Matrix <double> .Build;
            VectorBuilder <double> V = Vector <double> .Build;
            int             nPoints2 = 2 * DataList.Count;
            Matrix <double> aa       = M.Dense(nPoints2, 6);
            Vector <double> bb       = V.Dense(nPoints2);
            MapData         data     = null;
            int             row;

            for (int i = 0; i < DataList.Count; i++)
            {
                data       = DataList[i];
                row        = 2 * i;
                aa[row, 0] = data.X;
                aa[row, 1] = data.Y;
                aa[row, 4] = 1;
                bb[row]    = data.Lon;
                row++;
                aa[row, 2] = data.X;
                aa[row, 3] = data.Y;
                aa[row, 5] = 1;
                bb[row]    = data.Lat;
            }

            // Get the singular values
            try {
                Svd <double>    svd = aa.Svd(true);
                Matrix <double> u   = svd.U;
                Matrix <double> vt  = svd.VT;
                Matrix <double> w   = svd.W;
                Matrix <double> wi  = w.Clone();
                for (int i = 0; i < 6; i++)
                {
                    if (wi[i, i] != 0)
                    {
                        wi[i, i] = 1.0 / wi[i, i];
                    }
                }
                Matrix <double> aainv = vt.Transpose() * wi.Transpose() * u.Transpose();
                Vector <double> xx    = aainv * bb;
                double          a     = xx[0];
                double          b     = xx[1];
                double          c     = xx[2];
                double          d     = xx[3];
                double          e     = xx[4];
                double          f     = xx[5];
                Transform = new MapTransform(a, b, c, d, e, f);
            } catch (Exception ex) {
                Utils.excMsg("Failed to create calibration transform", ex);
                Transform = null;
            }
        }
Esempio n. 13
0
 public static Vector <double> Zero3(this VectorBuilder <double> b)
 {
     return(Vector <double> .Build.Dense(3));
 }
Esempio n. 14
0
 public static Vector <double> Quaternion(this VectorBuilder <double> b, double w, double x, double y, double z)
 {
     return(b.DenseOfArray(new double[] { w, x, y, z }));
 }
Esempio n. 15
0
 public static Vector <double> Quaternion(this VectorBuilder <double> b)
 {
     return(Quaternion(b, 1, 0, 0, 0));
 }
Esempio n. 16
0
 public static Vector <double> Dense3(this VectorBuilder <double> b, double x, double y, double z)
 {
     return(b.DenseOfArray(new double[] { x, y, z }));
 }