Esempio n. 1
0
        private (double M1, double M2) M(Vector <double> pricesVector, Vector <double> weightsVector, NumericMatrix <double> correlationMatrix, Vector <double> volatilityVector)
        {
            Vector <double> pricesWeightsVector = pricesVector * weightsVector;
            double          m1 = pricesWeightsVector.Sum();

            NumericMatrix <double> volatilityMatrix = new NumericMatrix <double>(volatilityVector.Length, volatilityVector.Length, 0, 0);

            for (int i = 0; i < volatilityVector.Length; i++)
            {
                for (int j = 0; j < volatilityVector.Length; j++)
                {
                    volatilityMatrix[i, j] = volatilityVector[i] * volatilityVector[j] * correlationMatrix[i, j] * _t;
                }
            }

            NumericMatrix <double> expMatrix = volatilityMatrix.Exp();

            double m2 = 0;

            for (int row = 0; row < expMatrix.Rows; row++)
            {
                m2 += (pricesWeightsVector * expMatrix.getRow(row)).Sum() * weightsVector[row] * pricesVector[row];
            }

            return(m1, m2);
        }
Esempio n. 2
0
    // 13.12.4	Bilinear Interpolation
    public static void BilinearInterpolation1()
    {
        Console.WriteLine("Vectors initialised: ");

        // Create mesh arrays
        int startIndex = 0;

        int             N     = 1;
        Vector <double> x1arr = new Vector <double>(N + 1, startIndex, 0.0);

        x1arr[0] = 20.0; x1arr[1] = 21.0;

        Vector <double> x2arr = new Vector <double>(x1arr);

        x2arr[0] = 14.0; x2arr[1] = 15.0;

        Console.WriteLine(x1arr);
        Console.WriteLine(x2arr);

        // Control values;
        NumericMatrix <double> Control
            = new NumericMatrix <double>(N + 1, N + 1, startIndex, startIndex);

        Control[0, 0] = 91.0; Control[1, 1] = 95.0;
        Control[0, 1] = 210.0; Control[1, 0] = 162.0;

        BilinearInterpolator myInterpolator
            = new BilinearInterpolator(x1arr, x2arr, Control);

        double x = 20.2; double y = 14.5;  // 146.1

        double value = myInterpolator.Solve(x, y);

        Console.WriteLine("Interpolated value: {0}", value);
    }
Esempio n. 3
0
        static void Main(string[] args)
        {
            const string directoryPath = @"C:\Users\Káťa\Desktop\Diplomka\mesh\meshes";
            var          matrix        = loadFacesR(directoryPath);

            REngine.SetEnvironmentVariables();
            REngine       engine = REngine.GetInstance();
            NumericMatrix group1 = engine.CreateNumericMatrix(matrix);

            //List<float>[] faceMatrix = new List<float>[] { };
            //double[,] squere = new double[,] { { 13,  -4,    2 },
            //  {-4 ,  11  , -2},  {2 ,  -2  ,  8 } };
            //runR(squere);
            //int[] i = new int[] {};
            // pokus();


            // var matrix = getDataMatrix(directoryPath);

            // runR();


            //REngine.SetEnvironmentVariables();
            //REngine engine = REngine.GetInstance();
            //// REngine requires explicit initialization.
            //// You can set some parameters.
            //engine.Initialize();
            //NumericMatrix group1 = engine.CreateNumericMatrix(new double[,] {
            //        { 0, 0, 0, 0, 1 },
            //        { 0, 0, 0, 1, 1 },
            //        { 0, 0, 1, 1, 1 },
            //        { 0, 0, 0, 1, 1 },
            //        { 0, 0, 0, 0, 1 }
            //});
            //engine.SetSymbol("group1", group1);
            //GenericVector testResult = engine.Evaluate("eigen(group1)").AsList();
            //Console.WriteLine("P-value = {0}", group1);



            // //.NET Framework array to R vector.
            //NumericVector group1 = engine.CreateNumericVector(new double[] { 30.02, 29.99, 30.11, 29.97, 30.01, 29.99 });
            //engine.SetSymbol("group1", group1);
            //// Direct parsing from R script.
            //NumericVector group2 = engine.Evaluate("group2 <- c(29.89, 29.93, 29.72, 29.98, 30.02, 29.98)").AsNumeric();


            //// Test difference of mean and get the P-value.
            //GenericVector testResult = engine.Evaluate("t.test(group1, group2)").AsList();
            //double p = testResult["p.value"].AsNumeric().First();

            //Console.WriteLine("Group1: [{0}]", string.Join(", ", group1));
            //Console.WriteLine("Group2: [{0}]", string.Join(", ", group2));
            //Console.WriteLine("P-value = {0:0.000}", p);

            //you should always dispose of the REngine properly.
            // After disposing of the engine, you cannot reinitialize nor reuse it
            // engine.Dispose();
            Console.ReadLine();
        }
Esempio n. 4
0
    public void initMesh(int JSteps, int NSteps)
    {
        N = NSteps;
        J = JSteps;
        k = taxis.spread / N;
        h = xaxis.spread / J;

        h2 = h * h;

        // Other numbers
        DN  = N;
        DJ  = J;
        DJJ = J * J;

        // Allow range[ A, B ] in x direction and [ t1, T ] in t direction; create mesh arrays
        m    = new Mesher(xaxis.low, xaxis.high, taxis.low, taxis.high);
        xarr = m.xarr(J);
        tarr = m.yarr(N);

        // The 3 data structures should be 'compatible' with each other, indices
        vecOld = new Vector <double>(xarr.Size, xarr.MinIndex);
        vecNew = new Vector <double>(xarr.Size, xarr.MinIndex);

        res = new NumericMatrix <double>(tarr.Size, xarr.Size, tarr.MinIndex, xarr.MinIndex);
    }
Esempio n. 5
0
        private void frmSaveESFFull_Load(object sender, EventArgs e)
        {
            try
            {
                frmProgress pfrmProgress = new frmProgress();
                pfrmProgress.lblStatus.Text    = "Creating EVs:";
                pfrmProgress.pgbProgress.Style = ProgressBarStyle.Marquee;
                pfrmProgress.Show();

                m_pEngine.Evaluate("sample.n <- length(sample.nb)");
                m_pEngine.Evaluate("sample.listb <- nb2listw(sample.nb, style='B')");
                m_pEngine.Evaluate("B <- listw2mat(sample.listb); M <- diag(sample.n) - matrix(1/sample.n, sample.n, sample.n); MBM <- M%*%B%*%M");
                m_pEngine.Evaluate("eig <- eigen(MBM)");

                nmEVs    = m_pEngine.Evaluate("eig$vectors").AsNumericMatrix();
                cvEVName = m_pEngine.Evaluate("paste('EV', 1:sample.n, sep='')").AsCharacter();
                nvEValue = m_pEngine.Evaluate("eig$values").AsNumeric();

                intNEVs = nmEVs.RowCount;


                for (int i = 0; i < intNEVs; i++)
                {
                    string strItemName = cvEVName[i] + " (" + Math.Round(nvEValue[i], 3).ToString() + ")";
                    clistFields.Items.Add(strItemName);
                }
                //m_pEngine.Evaluate("rm(list = ls(all = TRUE))"); //Remove all items from memory.
                pfrmProgress.Close();
            }
            catch (Exception ex)
            {
                frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog();
                return;
            }
        }
Esempio n. 6
0
    public NumericMatrix <V> extract(SpreadSheetRange <AI1, AI2> range)
    {
        // Slice a matrix
        AI1 rmin = range.upperLeft.first;
        AI2 cmin = range.upperLeft.second;

        AI1 rmax = range.lowerRight.first;
        AI2 cmax = range.lowerRight.second;

        int Rmin = r[rmin]; int Rmax = r[rmax];
        int Cmin = c[cmin]; int Cmax = c[cmax];

        // Now must find the integer indices corresponding to these
        NumericMatrix <V> result = new NumericMatrix <V>(Rmax - Rmin + 1, Cmax - Cmin + 1, Rmin, Cmin);

        for (int ri = Rmin; ri <= Rmax; ri++)
        {
            for (int ci = Cmin; ci <= Cmax; ci++)
            {
                result[ri, ci] = mat[ri, ci];
            }
        }

        return(result);
    }
        private void ProblemViewModelChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            if (e.PropertyName != nameof(ProblemViewModel.ProblemCalculationViewModel))
            {
                return;
            }

            _correspondenceMatrix          = null;
            _globalStiffnessMatrix         = null;
            _compactedMatrix               = null;
            _compactedForcesVector         = null;
            _solvedDisplacementsVector     = null;
            _fullSolvedDisplacementsVector = null;
            _solvedReactionForces          = null;
            _canBeSolved = null;

            OnPropertyChanged(nameof(CorrespondenceMatrix));
            OnPropertyChanged(nameof(GlobalStiffnessMatrix));
            OnPropertyChanged(nameof(CompactedMatrix));
            OnPropertyChanged(nameof(CompactedForcesVector));
            OnPropertyChanged(nameof(SolvedDisplacementsVector));
            OnPropertyChanged(nameof(FullSolvedDisplacementsVector));
            OnPropertyChanged(nameof(SolvedReactionForces));
            OnPropertyChanged(nameof(CanBeSolved));
        }
Esempio n. 8
0
    public static void Main()
    {
        //  InstrumentFactory myFactory = new ConsoleInstrumentFactory(); //GetInstrumentFactory();
        // TwoFactorOption myOption = myFactory.CreateOption();

        int    type = 1; // Call/put
        double w1   = 1.0;
        double w2   = -1.0;
        double K    = 5.0;

        BasketStrategy myPayoff = new BasketStrategy(K, type, w1, w2);

        Range <double> r1 = new Range <double>(0.0, 200.0);
        int            N1 = 20;

        Range <double> r2 = new Range <double>(0.0, 200.0);
        int            N2 = 20;

        // Calling extension methods
        NumericMatrix <double> matrix = myPayoff.PayoffMatrix(r1, r2, N1, N2);

        Console.WriteLine("Starting Excel, please wait..");

        myPayoff.DisplayInExcel(r1, r2, N1, N2);
    }
Esempio n. 9
0
        static void Main(string[] args)
        {
            //Mediator med = new Mediator();
            //med.calculate();

            //Console.ReadLine();

            //convertible bond with option on equity basket chapter 7
            Vector <double>        pricesVector      = new Vector <double>(new double[] { 1, 2 }, 0);
            Vector <double>        weightsVector     = new Vector <double>(new double[] { 1, 2 }, 0);
            Vector <double>        volatilityVector  = new Vector <double>(new double[] { 1, 2 }, 0);
            NumericMatrix <double> correlationMatrix = new NumericMatrix <double>(2, 2, 0, 0);

            correlationMatrix.setRow(new Array <double>(new double[] { 1, 2 }, 0), 0);
            correlationMatrix.setRow(new Array <double>(new double[] { 1, 2 }, 0), 1);

            Option o = new Option(OptionType.Put, 2, 2, 3, pricesVector, weightsVector, correlationMatrix, volatilityVector);

            Console.WriteLine(o.Price());

            //dual currency linked bonds with exchange option chapter 7
            Option exchangeOption = new Option(OptionType.Call, 2, 2, 2, 3, 0.5, 0.4, 1);

            Console.WriteLine(exchangeOption.Price());

            Console.ReadLine();
        }
    public static void Main()
    {
        // Create and start the stopwatch
        Stopwatch stopWatch = new Stopwatch();

        stopWatch.Start();

        int N          = 10000;
        int StartIndex = 1;

        // Create a matrix
        NumericMatrix <double> A = new NumericMatrix <double>(N, N, StartIndex, StartIndex);

        for (int i = A.MinRowIndex; i <= A.MaxRowIndex; ++i)
        {
            for (int j = A.MinColumnIndex; j <= A.MaxColumnIndex; ++j)
            {
                A[i, j] = Math.Sqrt((double)(i + j));
            }
            A[i, i] = 4.0 * Math.Sqrt((double)(i + i));
        }

        stopWatch.Stop();
        // Get the elapsed time as a TimeSpan value.
        TimeSpan ts = stopWatch.Elapsed;

        // Format and display the TimeSpan value.
        string elapsedTime = String.Format("Elapsed time {0:00}:{1:00}:{2:00}.{3:00}",
                                           ts.Hours, ts.Minutes, ts.Seconds,
                                           ts.Milliseconds / 10);

        Console.WriteLine(elapsedTime, "RunTime");
    }
Esempio n. 11
0
    public void initMesh(int JSteps, int NSteps)
    {
        N = NSteps;
        J = JSteps;
        k = taxis.spread / N;
        h = xaxis.spread / J;

        h2 = h * h;

        // Other numbers
        DN  = N;
        DJ  = J;
        DJJ = J * J;

        // Allow range[ A, B ] in x direction and [ t1, T ] in t direction; create mesh arrays
        m    = new Mesher(xaxis.low, xaxis.high, taxis.low, taxis.high);
        xarr = m.xarr(J);
        tarr = m.yarr(N);

        tarr[tarr.MinIndex] = 0.0;
        tarr[tarr.MaxIndex] = taxis.high;

        for (int n = tarr.MinIndex + 1; n < tarr.MaxIndex - 1; n++)
        {
            tarr[n] = tarr[n - 1] + k;
        }

        // The 3 data structures should be 'compatible' with each other, indices
        vecOld = new Vector <double>(J + 1, 1);
        vecNew = new Vector <double>(J + 1, 1);
        res    = new NumericMatrix <double>(N + 1, J + 1, 1, 1);
    }
Esempio n. 12
0
        //get the dataset/datatable of the selected ID
        private DataTable DataFrameToDataTable()
        {
            string[] colnames = df.ColumnNames;
            int      ncol     = colnames.Length;
            int      nrow     = df.RowCount;

            NumericMatrix dfm = Engine.GetSymbol("df").AsNumericMatrix();

            //DataTable navdata = DataFrameToDataTable();
            DataSet ds = new DataSet("DB");

            DataTable dt = new DataTable("data");

            for (int i = 0; i < ncol; i++)
            {
                dt.Columns.Add(colnames[i]);
            }

            for (int i = 0; i < nrow; i++)
            {
                for (int j = 0; j < ncol; j++)
                {
                    dt.Rows.Add(dfm[i, j]);
                }
            }


            ds.Tables.Add(dt);
            return(dt);
            //return ds;
        }
Esempio n. 13
0
        /// <summary>
        /// Run PCA in R engine
        /// </summary>
        static void PCAR()
        {
            const string directoryPath = @"C:\Users\Káťa\Desktop\Diplomka\mesh\meshes";
            var          matrix        = loadFacesR(directoryPath);

            REngine.SetEnvironmentVariables();
            REngine       engine = REngine.GetInstance();
            NumericMatrix group1 = engine.CreateNumericMatrix(matrix);

            engine.SetSymbol("group1", group1);
            GenericVector testResult = engine.Evaluate("pr.out=prcomp(group1, scale=TRUE)").AsList();
            var           eigenVec   = testResult["x"].AsNumericMatrix();

            engine.Evaluate("pr.out$sdev");
            engine.Evaluate("pr.var = pr.out$sdev ^ 2");
            engine.Evaluate("pr.var");
            engine.Evaluate("pve = pr.var / sum(pr.var)");
            engine.Evaluate("pve");
            engine.Evaluate("plot(cumsum(pve), xlab='Principal Component', ylab='Cumulative Proportion of Variance Explained', ylim=c(0,1),type='b')");
            saveVector(eigenVec);

            // var eigenVec = testResult["pr.out&x"].AsNumericMatrix();

            Console.ReadLine();
        }
Esempio n. 14
0
 public AssocMatrix()
 {
     mat        = new NumericMatrix <V>(10, 10);
     r          = new AssocArray <AI1, int> ();
     c          = new AssocArray <AI2, int> ();
     keyRows    = new Set <AI1>();
     keyColumns = new Set <AI2>();
 }
    // initialise data member
    private void Ini(Vector <double> x1arr, Vector <double> x2arr, NumericMatrix <double> gridValues)
    {
        // Arrays must have the same size
        x1Arr = x1arr;
        x2Arr = x2arr;

        gridVals = gridValues;
    }
Esempio n. 16
0
    // Add Matrix to the spreadsheet with row and column labels.
    public void AddMatrix <T>(string name, NumericMatrix <T> matrix, List <string> rowLabels, List <string> columnLabels)
    {
        try
        {
            // Check label count vs. matrix.
            if (matrix.Columns != columnLabels.Count)
            {
                throw (new IndexOutOfRangeException("Count mismatch between # matrix columns and # column labels"));
            }
            if (matrix.Rows != rowLabels.Count)
            {
                throw (new IndexOutOfRangeException("Count mismatch between # matrix rows and # row labels"));
            }

            // Add sheet.
            Excel.Workbook  pWorkbook;
            Excel.Worksheet pSheet;
            if (pExcel.ActiveWorkbook == null)
            {
                pWorkbook = (Excel.Workbook)InvokeMethodInternational(pExcel.Workbooks, "Add", Excel.XlWBATemplate.xlWBATWorksheet);
                pSheet    = (Excel.Worksheet)pWorkbook.ActiveSheet;
            }
            else
            {
                pWorkbook = pExcel.ActiveWorkbook;
                pSheet    = (Excel.Worksheet)InvokeMethodInternational(pWorkbook.Worksheets, "Add", Type.Missing, Type.Missing, 1, Type.Missing);
            }
            pSheet.Name = name;

            // Current indeces in spreadsheet.
            long sheetRow    = 1;
            long sheetColumn = 1;

            // Add column labels starting at column 2.
            sheetColumn = 2;
            Excel.Range pRange = pSheet.Cells;
            for (int i = 0; i != columnLabels.Count; i++)
            {
                Excel.Range item = (Excel.Range)pSheet.Cells[sheetRow, sheetColumn];
                SetPropertyInternational(item, "Value2", columnLabels[i]);
                sheetColumn++;
            }

            // Add row labels + values.
            sheetColumn = 1;
            sheetRow    = 2;
            for (int i = matrix.MinRowIndex; i <= matrix.MaxRowIndex; i++)
            {
                Vector <T> row = createVector(matrix, i);
                ToSheetHorizontal(pSheet, sheetRow, sheetColumn, rowLabels[i - matrix.MinRowIndex], row);
                sheetRow++;
            }
        }
        catch (IndexOutOfRangeException e)
        {
            Console.WriteLine("Exception: " + e);
        }
    }
Esempio n. 17
0
    public AssocMatrix(AssocMatrix <AI1, AI2, V> mat2)
    {
        mat = new NumericMatrix <V>(mat2.mat);
        r   = new AssocArray <AI1, int>(mat2.r);
        c   = new AssocArray <AI2, int>(mat2.c);

        keyRows    = new Set <AI1>(mat2.keyRows);
        keyColumns = new Set <AI2>(mat2.keyColumns);
    }
Esempio n. 18
0
    //Default constructor everything starts at 1 and has length 1
    public Tensor()
    {
        m_tensor    = new Array <NumericMatrix <T> >(1, 1);
        m_tensor[1] = new NumericMatrix <T>(1, 1, 1, 1);

        m_rows    = 1;
        m_columns = 1;
        m_depth   = 1;
    }
 public Worker(NumericMatrix <double> A, int lower, int upper, double d,
               int nsimulations)
 {
     m_l  = lower;
     m_u  = upper;
     m_A  = A;
     m_d  = d;
     NSIM = nsimulations;
 }
Esempio n. 20
0
    public RecursiveDataStructure(NumericMatrix <double> mat1, NumericMatrix <double> mat2, NumericMatrix <double> mat3)
    {
        m1 = mat1;
        m2 = mat2;
        m3 = mat3;

        lock1 = new object();
        lock2 = new object();
    }
Esempio n. 21
0
    static double CreateMatrix(object val)
    {
        const int N          = 3000;
        const int StartIndex = 0;

        NumericMatrix <double> mat1 = new NumericMatrix <double>(N, N, StartIndex, StartIndex);

        mat1[mat1.MinRowIndex, mat1.MinColumnIndex] = Convert.ToDouble(val);

        return(mat1[mat1.MinRowIndex, mat1.MinColumnIndex]);
    }
Esempio n. 22
0
    // take only 2° and 3° column  fromDate and toDate of matrix
    public NumericMatrix <Date> GetShortScheduleDate()
    {
        Array <Date> myFromDateArray = this.FromDateArray();
        Array <Date> myToDateArray   = this.ToDateArray();

        NumericMatrix <Date> myOutMatrix = new NumericMatrix <Date>(myFromDateArray.Length, 2, 0, 0);

        myOutMatrix.Column(0, myFromDateArray);
        myOutMatrix.Column(1, myToDateArray);

        return(myOutMatrix);
    }
Esempio n. 23
0
 //constructor for option on the equity basket
 public Option(OptionType optionType, double expiry, double strike, double interest, Vector <double> pricesVector,
               Vector <double> weightsVector, NumericMatrix <double> correlationMatrix, Vector <double> volatilityVector)
 {
     _type            = optionType;
     _t               = expiry;
     _k               = strike;
     _b               = 0;
     _r               = interest;
     _sig             = VolatilityConvertibleBond(pricesVector, weightsVector, correlationMatrix, volatilityVector);
     _s               = expiry;
     _underlyingPrice = M(pricesVector, weightsVector, correlationMatrix, volatilityVector).M1;
 }
Esempio n. 24
0
    public static void Main()
    {
        // 1. Create the option (Factory Method pattern)
        Option myOption = CreateOption();

        // 2. Define the pde of concern (Bridge pattern)
        IIBVPImp pde = new BSIBVPImp(myOption);


        // 3. Discrete mesh sizes.
        int J = 325;
        int N = J;

        Console.Write("NS: ");
        J = Convert.ToInt32(Console.ReadLine());

        Console.Write("NT (NT ~ O(NS^2 for explicit, NT any value for implicit): ");
        N = Convert.ToInt32(Console.ReadLine());

        // 4. The domain in which the PDE is defined.
        Range <double> rangeX = new Range <double>(0.0, myOption.FarFieldCondition);
        Range <double> rangeT = new Range <double>(0.0, myOption.ExpiryDate);


        // 5. Create FDM Solver.

        Console.Write("Implicit [1] or Explicit Euler [2]: ");
        int choice = Convert.ToInt32(Console.ReadLine());

        IBVPFDM fdm = new ImplicitEulerIBVP(pde, rangeX, rangeT, J, N);

        if (choice != 1)
        {
            fdm = new ExplicitEulerIBVP(pde, rangeX, rangeT, J, N);
        }

        // 6. Calculate the matrix result.
        NumericMatrix <double> sol = fdm.result();


        // 7. Display the results in Excel.
        ExcelMechanisms exl = new ExcelMechanisms();

        try
        {
            exl.printOneExcel(fdm.XValues, fdm.vecNew, "Euler method", "Stock", "Value", "V");
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
    }
Esempio n. 25
0
    //Constructor with the ammount of rows, columns and depth, all startindexes are 1.
    public Tensor(int rows, int columns, int nthird)
    {
        m_tensor = new Array <NumericMatrix <T> >(nthird, 1);

        for (int i = m_tensor.MinIndex; i <= m_tensor.MaxIndex; i++)
        {
            m_tensor[i] = new NumericMatrix <T>(rows, columns, 1, 1);
        }

        m_rows    = rows;
        m_columns = columns;
        m_depth   = nthird;
    }
Esempio n. 26
0
        public List <Tuple <int, int> > GetPairings(int noScripts, int noPairings, string rScript)
        {
            REngineClass.GetREngine().Evaluate(@"source('REngine\\RScripts\\Generate\\" + rScript + "')");
            NumericMatrix matrix = REngineClass.GetREngine().Evaluate(string.Format("matrix <- generatePairings(noOfScripts = {0}, noOfPairings = {1})", noScripts, noPairings)).AsNumericMatrix();

            List <Tuple <int, int> > pairings = new List <Tuple <int, int> >();

            for (int i = 0; i < matrix.RowCount; i++)
            {
                pairings.Add(new Tuple <int, int>((int)matrix[i, 0], (int)matrix[i, 1]));
            }
            return(pairings);
        }
Esempio n. 27
0
    //Constructor with all sizes and startindexes
    public Tensor(int rows, int columns, int nthird, int rowStart, int columnStart, int thirdStart)
    {
        m_tensor = new Array <NumericMatrix <T> >(nthird, thirdStart);   // Size nthird, start index

        for (int i = m_tensor.MinIndex; i <= m_tensor.MaxIndex; i++)
        {
            m_tensor[i] = new NumericMatrix <T>(rows, columns, rowStart, columnStart);
        }

        m_rows    = rows;
        m_columns = columns;
        m_depth   = nthird;
    }
Esempio n. 28
0
        public static NumericMatrix <double> Exp <T>(this NumericMatrix <T> m) where T : IConvertible
        {
            NumericMatrix <double> expMatrix = new NumericMatrix <double>(m.Rows, m.Columns, 0, 0);

            for (int i = 0; i < m.Rows; i++)
            {
                for (int j = 0; j < m.Columns; j++)
                {
                    expMatrix[i, j] = Math.Exp(Convert.ToDouble(m[i, j]));
                }
            }

            return(expMatrix);
        }
Esempio n. 29
0
        public static int Main(string[] args)
        {
            var a = new NumericMatrix<int>(3, 3);
            a[0][0] = 11;
            a[0][1] = 12;
            a[0][2] = 13;

            a[1][0] = 21;
            a[1][1] = 22;
            a[1][2] = 23;

            a[2][0] = 31;
            a[2][1] = 32;
            a[2][2] = 33;

            var b = new NumericMatrix<int>(5, 3);

            b[0][0] = 11;
            b[0][1] = 12;
            b[0][2] = 13;

            b[1][0] = 21;
            b[1][1] = 22;
            b[1][2] = 23;

            b[2][0] = 31;
            b[2][1] = 32;
            b[2][2] = 33;

            b[3][0] = 41;
            b[3][1] = 42;
            b[3][2] = 43;

            b[4][0] = 51;
            b[4][1] = 52;
            b[4][2] = 53;

            Console.WriteLine("a: {0}\nb: {1}", a, b);
            Console.WriteLine("a.b is okay as of a: {0}", a.IsCompatibleBeingLeft(b));
            Console.WriteLine("b.a is okay as of a: {0}", a.IsCompatibleBeingRight(b));
            Console.WriteLine("a.b is okay as of b: {0}", b.IsCompatibleBeingRight(a));
            Console.WriteLine("b.a is okay as of b: {0}", b.IsCompatibleBeingLeft(a));

            var ba = b.MultiplyBy(a);
            Console.WriteLine("b.a: {0}", ba);
            Console.WriteLine("b.a^t: {0}", ba.Transposed() );

            return 0;
        }
    public static void Example10()
    {
        // I will pay 5% quarterly 30/360 for 5y starting from 5 Oct 09 on a nominal of 1.000.000 USD. I want to see
        // interest rates cash flows
        // input data
        Date   startDate        = new Date(2009, 10, 5);
        Date   endDate          = startDate.AddYears(5);
        int    paymentPerYear   = 4; // Quarterly
        bool   firstShortPeriod = true;
        double rate             = 0.05;

        // I use standard constructor
        DateSchedule myDS = new DateSchedule(startDate, endDate, paymentPerYear, firstShortPeriod);

        // I get start and end date schedule
        NumericMatrix <Date> myShortSchedule = myDS.GetShortScheduleDate();

        // my nominals
        Array <double> nominals = new Array <double>(myShortSchedule.Rows, 0, 1000000);

        // year fraction from/to according 30/360
        Array <double> yearFractions = new Array <double>(myShortSchedule.Rows, 0);

        // days from/to according 30/360
        Array <double> days = new Array <double>(myShortSchedule.Rows, 0);

        // interest to pay
        Array <double> interest = new Array <double>(myShortSchedule.Rows, 0);

        Console.WriteLine("{0},\t{1},\t{2},\t{3},\t{4}", "days", "yearFrac", "rate",
                          "nominals", "interest");

        // running sum
        double totalInterest = 0.0;

        // iterate interest calculation using schedule
        for (int i = 0; i < myShortSchedule.Rows; i++)
        {
            yearFractions[i] = myShortSchedule[i, 0].YF_30_360(myShortSchedule[i, 1]);
            days[i]          = myShortSchedule[i, 0].D_30_360(myShortSchedule[i, 1]);
            interest[i]      = yearFractions[i] * rate * nominals[i];

            Console.WriteLine("{0},\t{1:F5},\t{2:P},\t{3:C},\t{4:C}", days[i], yearFractions[i], rate,
                              nominals[i], interest[i]);
            totalInterest += interest[i];
        }

        Console.WriteLine("{0},\t{1:F2}", "Total interests: ", totalInterest);
    }
Esempio n. 31
0
    public static void Main()
    {
        AssocArray <int, double> assArr = new  AssocArray <int, double> ();

        assArr[0]    = 2.0;
        assArr[100]  = 3.0;
        assArr[10]   = 43.0;
        assArr[1000] = 34.0;

        Console.WriteLine(assArr[100]);
        foreach (KeyValuePair <int, double> kvp in assArr)
        {
            Console.WriteLine("{0}, {1}", kvp.Key, kvp.Value);
        }

        Set <string> RowNames = new Set <string>();

        RowNames.Insert("A1");
        RowNames.Insert("A2");
        RowNames.Insert("A3");
        RowNames.Insert("A4");
        RowNames.Insert("B1");

        Set <string> ColNames = new Set <string>();

        ColNames.Insert("C1");
        ColNames.Insert("C2");
        ColNames.Insert("C3");
        ColNames.Insert("C4");
        ColNames.Insert("C5");

        //double defaultValue = 10.0;

        // Contents of associative matrix (numeric values)
        NumericMatrix <double> mat1 = new NumericMatrix <double>(RowNames.Size(), ColNames.Size());

        mat1.initCells(3.0);

        AssocMatrix <string, string, double> myMat = new AssocMatrix <string, string, double>(RowNames, ColNames, mat1);

        Factory fs = new DoubleFactory();

        object b;

        b = fs.create();
        Set <double> s1 = (Set <double>)b;

        Console.WriteLine(s1.Size());
    }
Esempio n. 32
0
        public static int Main(string[] args)
        {
            var a = new NumericMatrix<int>(3, 3);
            a[0][0] = 101;
            a[0][1] = -102;
            a[0][2] = 103;

            a[1][0] = 201;
            a[1][1] = 202;
            a[1][2] = 203;

            a[2][0] = 301;
            a[2][1] = -302;
            a[2][2] = 303;

            Console.WriteLine("a: {0}; |a|: {1}", a, a.Det());
            var b = a.Transposed().MultiplyBy(2);
            Console.WriteLine("b: {0}; |b|: {1}", b, b.Det());

            return 0;
        }
Esempio n. 33
0
        public static int Main(string[] args)
        {
            var a = new NumericMatrix<double>(2, 3);
            a[0][0] = 1.5;
            a[0][1] = 2.5;
            a[0][2] = 3.5;

            a[1][0] = 3.5;
            a[1][1] = 2.5;
            a[1][2] = 1.5;

            var b = new NumericMatrix<double>(3, 4);

            b[0][0] = 1.5;
            b[0][1] = 2.5;
            b[0][2] = 3.5;
            b[0][3] = 4.5;

            b[1][0] = 4.5;
            b[1][1] = 3.5;
            b[1][2] = 2.5;
            b[1][3] = 1.5;

            b[2][0] = 5.5;
            b[2][1] = 6.5;
            b[2][2] = 7.5;
            b[2][3] = 8.5;

            Console.WriteLine("a: {0}\nb: {1}", a, b);
            Console.WriteLine("a.b is okay as of a: {0}", a.IsCompatibleBeingLeft(b));
            Console.WriteLine("b.a is okay as of a: {0}", a.IsCompatibleBeingRight(b));
            Console.WriteLine("a.b is okay as of b: {0}", b.IsCompatibleBeingRight(a));
            Console.WriteLine("b.a is okay as of b: {0}", b.IsCompatibleBeingLeft(a));

            var ab = a.MultiplyBy(b);
            Console.WriteLine("a.b: {0}", ab );
            var abt = a.Transposed();
            Console.WriteLine("a.b^t: {0}", abt );
            return 0;
        }
Esempio n. 34
0
 public cacheSolve(NumericMatrix matrix)
 {
     data = matrix;
 }
 public makeCacheMatrix(NumericMatrix Martix)
 {
    _matrix = Matrix;
 }
        /// <summary>
        /// Converts the specified expression to a NumericMatrix.
        /// </summary>
        /// <param name="expression">The expression.</param>
        /// <returns>The NumericMatrix. Returns <c>null</c> if the specified expression is not vector.</returns>
        public static NumericMatrix AsNumericMatrix(this SymbolicExpression expression)
        {
            if (!expression.IsVector())
            {
                return null;
            }

            int rowCount = 0;
            int columnCount = 0;

            if (expression.IsMatrix())
            {
                if (expression.Type == SymbolicExpressionType.NumericVector)
                {
                    return new NumericMatrix(expression.Engine, expression.DangerousGetHandle());
                }
                else
                {
                    rowCount = expression.GetFunction<Rf_nrows>()(expression.DangerousGetHandle());
                    columnCount = expression.GetFunction<Rf_ncols>()(expression.DangerousGetHandle());
                }
            }

            if (columnCount == 0)
            {
                rowCount = expression.GetFunction<Rf_length>()(expression.DangerousGetHandle());
                columnCount = 1;
            }

            IntPtr coerced = expression.GetFunction<Rf_coerceVector>()(expression.DangerousGetHandle(), SymbolicExpressionType.NumericVector);
            var dim = new IntegerVector(expression.Engine, new[] { rowCount, columnCount });
            SymbolicExpression dimSymbol = expression.Engine.GetPredefinedSymbol("R_DimSymbol");
            var matrix = new NumericMatrix(expression.Engine, coerced);
            matrix.SetAttribute(dimSymbol, dim);
            return matrix;
        }
 private Tuple<NumericVector, NumericVector> cluster(NumericMatrix matrix)
 {
     RConnector.Engine.SetSymbol("dataMatrix", matrix);
       if (0 == this.clusters.Value)
       {
     RConnector.Engine.Evaluate("dataCluster<-Mclust(dataMatrix)");
     var clusterAssignment = RConnector.Engine.Evaluate("dataCluster$classification").AsNumeric();
     return Tuple.Create<NumericVector, NumericVector>(clusterAssignment, null);
       }
       else
       {
     RConnector.Engine.Evaluate("dataMeans<-kmeans(dataMatrix," + this.clusters.Value + ")");
     var clusterAssignment = RConnector.Engine.Evaluate("dataMeans$cluster").AsNumeric();
     var clusterInfo = RConnector.Engine.Evaluate("dataMeans$withinss").AsNumeric();
     return Tuple.Create(clusterAssignment, clusterInfo);
       }
 }