Extreme Optimization > QuickStart Samples > Sparse Matrices QuickStart Sample (C#)

Extreme Optimization QuickStart Samples

Sparse Matrices QuickStart Sample (C#)

Illustrates using sparse vectors and matrices using the classes in the Extreme.Mathematics.LinearAlgebra.Sparse namespace in C#.

VB.NET code Back to QuickStart Samples

using System;

namespace Extreme.Mathematics.QuickStart.CSharp
{
    // The sparse vector and matrix classes reside in the 
    // Extreme.Mathematics.LinearAlgebra.Sparse namespace.
    using Extreme.Mathematics.LinearAlgebra;
    using Extreme.Mathematics.LinearAlgebra.Sparse;

    /// <summary>
    /// Illustrates using sparse vectors and matrices using the classes
    /// in the Extreme.Mathematics.LinearAlgebra.Sparse namespace 
    /// of the Extreme Optimization Numerical Libraries for .NET.
    /// </summary>
    class SparseMatrices
    {
        static void Main(string[] args)
        {
            //
            // Sparse vectors
            //

            // The SparseGeneralVector class has three constructors. The
            // first simply takes the length of the vector. All components
            // are initially zero.
            SparseGeneralVector v1 = new SparseGeneralVector(1000000);

            // The second constructor lets you specify how many components
            // are expected to be nonzero. This 'fill factor' is a number
            // between 0 and 1.
            SparseGeneralVector v2 = new SparseGeneralVector(1000000, 1e-4);

            // The second constructor lets you specify how many components
            // are expected to be nonzero. This 'fill factor' is a number
            // between 0 and 1.
            SparseGeneralVector v3 = new SparseGeneralVector(1000000, 100);

            // The fourth constructor lets you specify the indexes of the nonzero
            // components and their values as arrays:
            int[] indexes = { 1, 10, 100, 1000, 10000 };
            double[] values = { 1.0, 10.0, 100.0, 1000.0, 10000.0 };
            SparseGeneralVector v4 = new SparseGeneralVector(1000000, indexes, values);

            // Components can be accessed individually:
            v1[1000] = 2.0;
            Console.WriteLine("v1[1000] = {0}", v1[1000]);

            // The NonzeroCount returns how many components are non zero:
            Console.WriteLine("v1 has {0} nonzeros", v1.NonzeroCount);
            Console.WriteLine("v4 has {0} nonzeros", v4.NonzeroCount);

            // The NonzeroComponents property returns a collection of 
            // IndexValuePair structures that you can use to iterate
            // over the components of the vector:
            Console.WriteLine("Nonzero components of v4:");
            foreach(IndexValuePair pair in v4.NonzeroComponents)
                Console.WriteLine("Component {0} = {1}",
                    pair.Index, pair.Value);

            // All other vector methods and properties are also available,
            // Their implementations take advantage of sparsity.
            Console.WriteLine("Norm(v4) = {0}", v4.Norm());
            Console.WriteLine("Sum(v4) = {0}", v4.GetSum());
            
            // Note that some operations convert a sparse vector to a
            // GeneralVector, causing memory to be allocated for all
            // components.
            
            //
            // Sparse Matrices
            //

            // All sparse matrix classes inherit from SparseMatrix. This is an abstract class.
            // There currently is only one implementation class:
            // SparseCompressedColumnMatrix. The class has 4 constructors:

            // The first constructor takes the number of rows and columns as arguments:
            SparseCompressedColumnMatrix m1 = new SparseCompressedColumnMatrix(100000, 100000);

            // The second constructor adds a fill factor:
            SparseCompressedColumnMatrix m2 =
                new SparseCompressedColumnMatrix(100000, 100000, 1e-5);

            // The third constructor uses the actual number of nonzero components rather than 
            // the fraction:
            SparseCompressedColumnMatrix m3
                = new SparseCompressedColumnMatrix(10000, 10000, 20000);

            // The fourth constructor lets you specify the locations and values of the
            // nonzero components:
            int[] rows = { 1, 11, 111, 1111 };
            int[] columns = { 2, 22, 222, 2222 };
            double[] matrixValues = { 3.0, 33.0, 333.0, 3333.0 };
            SparseCompressedColumnMatrix m4 =
                new SparseCompressedColumnMatrix(10000, 10000, rows, columns, matrixValues);

            // You can access components as before...
            Console.WriteLine("m4[111, 222] = {0}", m4[111, 222]);
            m4[99, 22] = 99.0;

            // A series of Insert methods lets you build a sparse matrix from scratch:
            // A single value:
            m1.InsertEntry(25.0, 200, 500);
            // Multiple values:
            m1.InsertEntries(matrixValues, rows, columns);
            // Multiple values all in the same column:
            m1.InsertColumn(33, values, indexes);
            // Multiple values all in the same row:
            m1.InsertRow(55, values, indexes);

            // A clique is a 2-dimensional submatrix with indexed rows and columns.
            GeneralMatrix clique = new GeneralMatrix(2, 2, new double[] {11, 12, 21, 22});
            int[] cliqueIndexes = new int[] { 5, 8 };
            m1.InsertClique(clique, cliqueIndexes, cliqueIndexes);

            // You can use the NonzeroComponents collection to iterate
            // over the nonzero components of the matrix. The items
            // are of type RowColumnValueTriplet:
            Console.WriteLine("Nonzero components of m1:");
            foreach(RowColumnValueTriplet triplet in m1.NonzeroComponents)
                Console.WriteLine("m1[{0},{1}] = {2}",
                    triplet.Row, triplet.Column, triplet.Value);

            // ... including rows and columns.
            SparseVector column = (SparseVector)m4.GetColumn(22);
            Console.WriteLine("Nonzero components in column 22 of m4:");
            foreach (IndexValuePair pair in column.NonzeroComponents)
                Console.WriteLine("Component {0} = {1}", pair.Index, pair.Value);

            // Many matrix methods have been optimized to take advantage of sparsity:
            Console.WriteLine("F-norm(m1) = {0}", m1.FrobeniusNorm());
            
            // But beware: some revert to a dense algorithm and will fail on huge matrices:
            try
            {
                Matrix inverse = m1.GetInverse();
            }
            catch (OutOfMemoryException e)
            {
                Console.WriteLine(e.Message);
            }

            Console.Write("Press Enter key to exit...");
            Console.ReadLine();
        }
    }
}
Overview
Introduction
Features
Documentation
QuickStart Samples
Sample Applications
Downloads
Get it now!
Download trial version
How to Buy
Information
Resources
Contact Us
Search

"The Extreme Optimization Statistics Library for .NET is a major boon for those doing statistical work in .NET. I strongly recommend this product."
- Marc Brooks

"I have made it my mission to institutionalize the value of good API design.  I strongly believe that this is key to making developers more productive and happy on our platform. It is clear that you value good API design in your work, and take to heart developer productivity and synergy with the .NET framework."
- Brad Abrams,
Lead Program Manager, Microsoft.

This is a partial list of companies who are using our libraries:
ABB Robotics
Allstate
Applied Materials
Arcam
Astra Schedule
Babson College
Canadian Council on Learning
Canyon Associates
Caxton Associates
CECity
Constellation Energy
CreditSights
DeepOcean
Duke University
Dynamotive
Elecsoft
Engelhard Corporation
Epcor
Equipoise Software
Galileo International
GAM UK
Gammex
GlaxoSmithKline
Global Matrix
The Hartford
Infinera Corporation
Intel
JDS Uniphase
LaBranche & Co.
Learning & Skills Council
Jacobs Consultancy
Litman Gregory
Lucas Systems
Malvern Instruments
Medrio
Merck & Co.
Mintera.
Monitor Software
MorningStar
NanoString Technologies
Paletta Invent
Parametric Portfolio Associates
Prosanos
RATA Associates
RiskShield
Ramboll
Standard & Poor's
Strategic Analysis Corporation
Univ. of Alicante
Univ. of South Carolina
vielife
Xerox
US Army