예제 #1
0
    public static IEnumerable <double> Momentum(int[,] d, Vector2[] X, double eta = .1, double beta = .9, int numIterations = 15)
    {
        int n = X.Length;

        // relax
        for (int k = 0; k < numIterations; k++)
        {
            var gradients = new Vector2[n];
            var momentums = new Vector2[n];
            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < i; j++)
                {
                    Vector2 gradient = Gradient(X[i], X[j], d[i, j]);

                    gradients[i] += gradient;
                    gradients[j] -= gradient;
                }
            }
            for (int i = 0; i < n; i++)
            {
                momentums[i] = momentums[i] * beta + gradients[i] * eta;
                X[i]        += momentums[i];
            }

            double stress = GraphIO.CalculateStress(d, X, n);
            yield return(stress);
        }
    }
예제 #2
0
    public static IEnumerable <double> Alternating(int[,] d, Vector2[] positions, IEnumerable <double> eta)
    {
        int n  = positions.Length;
        int nn = (n * (n - 1)) / 2;


        int[,] pairs1 = CreatePairs(n), pairs2 = CreatePairs(n);
        var rnd = new Random();

        GraphIO.FYShuffle2(pairs1, rnd);
        GraphIO.FYShuffle2(pairs2, rnd);

        // relax
        int k = 0;

        foreach (double c in eta)
        {
            int[,] pairs = k++ % 2 == 0 ? pairs1 : pairs2;
            for (int ij = 0; ij < nn; ij++)
            {
                int i = pairs[ij, 0], j = pairs[ij, 1];
                Satisfy(ref positions[i], ref positions[j], d[i, j], c);
            }

            yield return(GraphIO.CalculateStress(d, positions, n));
        }
    }
예제 #3
0
        public void ParseInputTest()
        {
            // Arrange
            var fromToLocations = new List <string>();

            for (int i = 0; i < 2; i++)
            {
                fromToLocations.Add(validLocations[i] + " " + validLocations[i + 1]);
            }

            using (var writer1 = new StreamWriter(PathToFile + graphFilename))
            {
                foreach (var fromTo in fromToLocations)
                {
                    writer1.WriteLine(fromTo + " 1");
                }
            }

            Dictionary <string, Node> expectedGraph = new Dictionary <string, Node>();

            expectedGraph.Add(validLocations[0], new Node(validLocations[0], validLocations[1], 1));
            expectedGraph.Add(validLocations[1], new Node(validLocations[1], validLocations[1], 0));
            expectedGraph[validLocations[1]].edges.Add(new Edge(new Node(validLocations[1]), new Node(validLocations[2]), 1));
            expectedGraph.Add(validLocations[2], new Node(validLocations[2], validLocations[2], 0));

            var graphIO = new GraphIO();

            // Act
            var graph = graphIO.ParseInput(PathToFile + graphFilename);

            // Assert
            Assert.AreEqual(expectedGraph.Keys, graph.Keys);
        }
예제 #4
0
        public static void Main(string[] args)
        {
            if (args == null || args.Length < 2)
            {
                Console.WriteLine("Usage: " +
                                  "dotnet dll_file_location graph_edges_file_path jobs_file_path routes_file_path");
                Environment.Exit(0);
            }

            // We could implement a strategy/factory design pattern for both the graph and the job IO, which would
            // give the possibility to retrieve their respective data from elsewhere (for instance, from a web service).
            var graphIO = new GraphIO();
            var graph   = graphIO.ParseInput(args[0]);

            var jobIO       = new JobIO();
            var pendingJobs = jobIO.ParseInput(args[1]);

            var resultFile = "";

            if (args.Length == 3)
            {
                resultFile = args[2];
            }

            var jobsResults = new List <List <string> >();
            var dijkstra    = new Dijkstra();

            foreach (var pendingJob in pendingJobs)
            {
                validateJob(graph, pendingJob);
                jobsResults.Add(dijkstra.CalculateShortestPath(graph, pendingJob));
            }

            jobIO.WriteToFile(jobsResults, resultFile);
        }
예제 #5
0
    public static IEnumerable <double> Modulo(int[,] d, Vector2[] positions, IEnumerable <double> eta)
    {
        int n  = positions.Length;
        int nn = (n * (n - 1)) / 2;

        // relax

        int prime = 646957;

        int[] primitives = new int[] { 5, 6, 7, 17, 18, 20, 21, 24, 26, 28, 45, 46, 50, 53, 55, 58, 66, 68, 72, 73 };

        int k = 0;

        foreach (double c in eta)
        {
            int primitive = primitives[k++];
            int modulo    = 1;
            for (int ij = 0; ij < prime; ij++)
            {
                modulo = (modulo * primitive) % prime;
                if (modulo > nn)
                {
                    continue;
                }

                int idx = modulo - 1;
                int i   = (int)((1 + Math.Sqrt(8 * idx + 1)) / 2);
                int j   = idx - (i * (i - 1)) / 2;

                Satisfy(ref positions[i], ref positions[j], d[i, j], c);
            }
            yield return(GraphIO.CalculateStress(d, positions, n));
        }
    }
예제 #6
0
파일: Ortmann.cs 프로젝트: tzw28/s_gd2
    public static void Main(string[] args)
    {
        string name = args[0];
        SparseMatrix <bool> adjMatrix = GraphIO.Read("data/" + name + ".txt");

        int numPivots = int.Parse(args[1]);
        var positions = SparseSGD(adjMatrix, numPivots, 15);

        GraphIO.Write("svg/ortmann/" + name + "_" + numPivots + ".svg", positions, adjMatrix, 10, 50);

        //int n = adjMatrix.MaxIdx()+1;
        //int[,] d_full = ShortestPaths.Bacon(adjMatrix, n);
        //int[] nums = new int[] { 10, 50, 100, 200 };
        //foreach (int numPivots in nums)
        //{
        //    double bestStress = double.MaxValue;
        //    for (int i=0; i<25; i++)
        //    {
        //        var positions = SparseMajorization(adjMatrix, numPivots, 100);
        //        Console.Error.WriteLine("finished run " + i);
        //        var stress = GraphIO.CalculateStress(d_full, positions, n);

        //        Console.Error.WriteLine("stress=" + stress);
        //        Console.WriteLine(numPivots + " " + stress);

        //        if (stress < bestStress)
        //            GraphIO.Write("svg/ortmann/" + name + "_" + numPivots + ".svg", positions, adjMatrix, 10, 50);

        //    }
        //    Console.WriteLine();
        //}
        //Console.ReadLine();
    }
예제 #7
0
    public static IEnumerable <double> Indices(int[,] d, Vector2[] positions, IEnumerable <double> eta)
    {
        int n = positions.Length;

        var indices = new int[n];

        for (int i = 0; i < n; i++)
        {
            indices[i] = i;
        }
        var rnd = new Random();

        //GraphIO.FYShuffle(indices, rnd);

        // relax
        foreach (double c in eta)
        {
            GraphIO.FYShuffle(indices, rnd);
            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < i; j++)
                {
                    Satisfy(ref positions[indices[i]], ref positions[indices[j]], d[indices[i], indices[j]], c);
                }
            }

            yield return(GraphIO.CalculateStress(d, positions, n));
        }
    }
예제 #8
0
 //!Zwraca instancję.
 public static GraphIO getInstance()
 {
     if (instance == null)
     {
         instance = new GraphIO();
     }
     return(instance);
 }
예제 #9
0
    public static IEnumerable <double> Convergence(int[,] d, Vector2[] positions, int expIter = 30, double eps = 0.03)
    {
        int n  = positions.Length;
        int nn = (n * (n - 1)) / 2;

        var pairs = CreatePairs(n);
        var rnd   = new Random();

        double etaMax = EtaMax(d), etaMin = .1;
        double lambda = -Math.Log(etaMin / etaMax) / (expIter - 1);

        double tSwitch = Math.Log(etaMax) / lambda;
        int    kSwitch = (int)tSwitch + 1;

        Console.Error.WriteLine(etaMax + " " + lambda + " " + tSwitch);

        for (int k = 0; k < kSwitch; k++)
        {
            GraphIO.FYShuffle2(pairs, rnd);
            double eta = etaMax * Math.Exp(-lambda * k);
            for (int ij = 0; ij < nn; ij++)
            {
                int i = pairs[ij, 0], j = pairs[ij, 1];
                Satisfy(ref positions[i], ref positions[j], d[i, j], eta);
            }
            //Console.Error.WriteLine("                  " + eta);
            double stress = GraphIO.CalculateStress(d, positions, n);
            yield return(stress);
        }

        for (int k = kSwitch; k < 1000; k++)
        {
            double maxMovement = 0;
            GraphIO.FYShuffle2(pairs, rnd);
            double eta = 1.0 / (1 + lambda * (k - tSwitch));
            for (int ij = 0; ij < nn; ij++)
            {
                int    i = pairs[ij, 0], j = pairs[ij, 1];
                double r = Satisfy(ref positions[i], ref positions[j], d[i, j], eta);

                r = Math.Abs(r);
                //r = r * r;
                if (r > maxMovement)
                {
                    maxMovement = r;
                }
            }
            //Console.Error.WriteLine("                  " + eta + " " + maxMovement);

            double stress = GraphIO.CalculateStress(d, positions, n);
            yield return(stress);

            if (maxMovement < eps)
            {
                yield break;
            }
        }
    }
예제 #10
0
 public FileReaderNode(GraphBuilder parent,
                       GraphIO <String> fullPath,
                       GraphIO <Int32> bufferSize)
 {
     DLoggerManager.Instance.Logger.Log(DFramework.Logging.Interfaces.LoggerMessageType.VerboseHigh | DFramework.Logging.Interfaces.LoggerMessageType.Information | DFramework.Logging.Interfaces.LoggerMessageType.Sensitive, "Creating instance of FileReaderNode.");
     _parent         = parent;
     _fullPath       = fullPath;
     _bufferSize     = bufferSize;
     _stringContents = new GraphIO <String>(String.Empty);
 }
예제 #11
0
        static void Main(string[] args)
        {
            var gr = new Graph();

            gr.AddVertex("0", "1", "2", "3", "4", "5", "6", "7");
            gr.AddEdge("0", "1");
            gr.AddEdge("0", "2");
            gr.AddEdge("1", "3");
            gr.AddEdge("1", "4");
            gr.AddEdge("1", "2");
            gr.AddEdge("2", "4");
            gr.AddEdge("2", "5");
            gr.AddEdge("3", "6");
            gr.AddEdge("4", "6");
            gr.AddEdge("4", "5");
            gr.AddEdge("7", "5");
            gr.AddEdge("7", "6");

            gr.RemoveEdge("0", "1");
            Console.WriteLine(gr.ToString());
            Console.WriteLine("+++++++++++++++++++++++++");
            Console.WriteLine(gr.DegreeOutput["0"]);
            Console.WriteLine(gr.DegreeOutput["1"]);
            Console.WriteLine(gr.DegreeOutput["2"]);
            Console.WriteLine(gr.DegreeOutput["3"]);
            Console.WriteLine(gr.DegreeOutput["4"]);
            Console.WriteLine(gr.DegreeOutput["5"]);
            Console.WriteLine(gr.DegreeOutput["6"]);
            Console.WriteLine(gr.DegreeOutput["7"]);

            GraphIO.ToFile("1.txt", gr);
            var r = GraphIO.FromFile <Graph>("1.txt");

            Console.WriteLine("+++++++++++++++++++++++++");
            Console.WriteLine(gr.ToString());

            var c = gr.GetBFS("1");
            var p = gr.Vertex.ToDictionary(q => q.Name, w => gr.GetBFS(w.Name).Select(ww => ww.Depth).Max() - 1);

            p.Where(w => w.Value == 3).Select(w => w.Key);
            var str = c.Aggregate("", (current, ver) => current + (ver.Name + " "));

            Console.WriteLine(str);

            c   = gr.GetDFS("1");
            str = c.Aggregate("", (current, ver) => current + (ver.Name + " "));
            Console.WriteLine(str);
            var f = r.IsConherenceOfGraph();

            Console.WriteLine(f);
            var ff = r.IsFullCount();

            Console.WriteLine(ff);
            Console.ReadLine();
        }
예제 #12
0
    //!Wczytuje plik.
    private void load()
    {
        if (fileName == "" || fileName == null)
        {
            return;
        }
        GraphIO graphIO = GraphIO.getInstance();

        graphIO.refreshData(view);
        graphIO.load(fileName);
    }
예제 #13
0
        public AESEncryptNode(GraphIO <String> plainText,
                              GraphIO <Byte[]> iv,
                              GraphIO <Byte[]> key)
        {
            DLoggerManager.Instance.Logger.Log(DFramework.Logging.Interfaces.LoggerMessageType.VerboseHigh | DFramework.Logging.Interfaces.LoggerMessageType.Information | DFramework.Logging.Interfaces.LoggerMessageType.Sensitive, "Creating instance of AESEncryptNode.");

            _plainText     = plainText;
            _iv            = iv;
            _key           = key;
            _encryptedData = new GraphIO <Byte[]>(null);
        }
예제 #14
0
        public AESDecryptNode(GraphIO <Byte[]> encryptedData,
                              GraphIO <Byte[]> iv,
                              GraphIO <Byte[]> key)
        {
            DLoggerManager.Instance.Logger.Log(DFramework.Logging.Interfaces.LoggerMessageType.VerboseHigh | DFramework.Logging.Interfaces.LoggerMessageType.Information | DFramework.Logging.Interfaces.LoggerMessageType.Sensitive, "Creating instance of AESDecryptNode.");

            _encryptedData   = encryptedData;
            _iv              = iv;
            _key             = key;
            _unencryptedData = new GraphIO <String>(String.Empty);
        }
예제 #15
0
 public Rfc2898DeriveBytesNode(GraphIO <String> password,
                               GraphIO <Int32> keyLength,
                               GraphIO <Byte[]> salt,
                               GraphIO <Int32> iterations)
 {
     DLoggerManager.Instance.Logger.Log(DFramework.Logging.Interfaces.LoggerMessageType.VerboseHigh | DFramework.Logging.Interfaces.LoggerMessageType.Information | DFramework.Logging.Interfaces.LoggerMessageType.Sensitive, "Creating instance of Rfc2898DeriveBytesNode.");
     _password   = password;
     _keyLength  = keyLength;
     _derivedKey = new GraphIO <Byte[]>(null);
     _salt       = salt;
     _iterations = iterations;
 }
예제 #16
0
        public void AESEncryptEncodeDecodeDecryptNodeTest()
        {
            Byte[] salt      = SimpleRandomGenerator.QuickGetRandomBytes(16);
            String password  = "******";
            String plainText = "Testing testing, 123.";

            GraphBuilder           encryptGraph         = new GraphBuilder();
            GraphIO <String>       passwordInput        = new GraphIO <String>(plainText);
            GraphIO <Int32>        keyLengthInput       = new GraphIO <Int32>(32);
            GraphIO <Byte[]>       saltInput            = new GraphIO <Byte[]>(salt);
            Rfc2898DeriveBytesNode deriveEncryptKeyNode = new Rfc2898DeriveBytesNode(passwordInput, keyLengthInput, saltInput, new GraphIO <Int32>(10000));
            AESEncryptNode         encryptNode          = new AESEncryptNode(new GraphIO <String>(plainText), new GraphIO <Byte[]>(null), deriveEncryptKeyNode.DervivedKey);
            Base64EncodeNode       encodeNode           = new Base64EncodeNode(encryptNode.EncryptedData);

            encryptGraph.AddNode("deriveNode", deriveEncryptKeyNode);
            encryptGraph.AddNode("encryptNode", encryptNode);
            encryptGraph.AddNode("encodeNode", encodeNode);
            encryptGraph.CreateRoute("encrypt",
                                     deriveEncryptKeyNode.Password,
                                     encodeNode.EncodedData,
                                     "deriveNode",
                                     new String[] { "deriveNode", "encryptNode", "encodeNode" });

            Object output = null;

            if (encryptGraph.Process(true, "encrypt", password, out output))
            {
                String encryptedEncoded = (String)output;

                GraphBuilder           decryptGraph          = new GraphBuilder();
                GraphIO <String>       encryptedEncodedInput = new GraphIO <String>(encryptedEncoded);
                Rfc2898DeriveBytesNode deriveDecryptKeyNode  = new Rfc2898DeriveBytesNode(new GraphIO <String>(String.Empty), new GraphIO <Int32>(32), new GraphIO <Byte[]>(salt), new GraphIO <Int32>(10000));
                Base64DecodeNode       decodeNode            = new Base64DecodeNode(encryptedEncodedInput);
                AESDecryptNode         decryptNode           = new AESDecryptNode(decodeNode.UnencodedData, new GraphIO <Byte[]>(null), deriveDecryptKeyNode.DervivedKey);

                decryptGraph.AddNode("deriveNode", deriveDecryptKeyNode);
                decryptGraph.AddNode("decodeNode", decodeNode);
                decryptGraph.AddNode("decryptNode", decryptNode);
                decryptGraph.CreateRoute("decrypt",
                                         deriveDecryptKeyNode.Password,
                                         decryptNode.UnencryptedData,
                                         "deriveNode",
                                         new String[] { "deriveNode", "decodeNode", "decryptNode" });

                if (decryptGraph.Process(true, "decrypt", password, out output))
                {
                    String decodedDecrypted = (String)output;
                    Assert.IsTrue(decodedDecrypted == plainText);
                }
            }
        }
예제 #17
0
파일: Program.cs 프로젝트: tzw28/s_gd2
    public static void Main(string[] args)
    {
        string graphDir = args[0];
        SparseMatrix <bool> adjMatrix = GraphIO.Read(graphDir);

        using (StreamWriter file = new StreamWriter(args[1]))
        {
            Vector2[] X = Stress((d, x) => Sgd2.Full(d, x, Sgd2.Schedule(d, 0.1, 15)), adjMatrix, file);
            //Vector2[] X = Stress((d, x) => Majorization.Chol(d, x), adjMatrix, file);
            //Vector2[] X = Stress((d, x) => Sgd2.Adaptive(d, x, 0.001), adjMatrix, file);
            //Vector2[] X = Stress((d, x) => GradientDescent.Full(d, x, .02, 100), adjMatrix, file);

            GraphIO.Write(args[2], X, adjMatrix);
        }
    }
예제 #18
0
 public SCryptDeriveBytesNode(GraphIO <String> password,
                              GraphIO <Int32> keyLength,
                              GraphIO <Byte[]> salt,
                              GraphIO <Int32> iterations,
                              GraphIO <Int32> blockSize,
                              GraphIO <Int32> threadCount)
 {
     DLoggerManager.Instance.Logger.Log(DFramework.Logging.Interfaces.LoggerMessageType.VerboseHigh | DFramework.Logging.Interfaces.LoggerMessageType.Information | DFramework.Logging.Interfaces.LoggerMessageType.Sensitive, "Creating instance of SCryptDeriveBytesNode.");
     _password    = password;
     _keyLength   = keyLength;
     _derivedKey  = new GraphIO <Byte[]>(null);
     _salt        = salt;
     _iterations  = iterations;
     _blockSize   = blockSize;
     _threadCount = threadCount;
 }
예제 #19
0
    public static IEnumerable <double> NoRand(int[,] d, Vector2[] positions, IEnumerable <double> eta)
    {
        int n = positions.Length;

        // relax
        foreach (double c in eta)
        {
            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < i; j++)
                {
                    Satisfy(ref positions[i], ref positions[j], d[i, j], c);
                }
            }

            yield return(GraphIO.CalculateStress(d, positions, n));
        }
    }
예제 #20
0
파일: Majorization.cs 프로젝트: tzw28/s_gd2
    public static IEnumerable <double> Local(int[,] d, Vector2[] positions, double eps = 0.0001, int maxIter = 100)
    {
        int n = positions.Length;

        double prevStress = GraphIO.CalculateStress(d, positions, n);

        // majorize
        for (int k = 0; k < maxIter; k++)
        {
            for (int i = 0; i < n; i++)
            {
                double topSumX = 0, topSumY = 0, botSum = 0;
                for (int j = 0; j < n; j++)
                {
                    if (i != j)
                    {
                        double d_ij      = d[i, j];
                        double w_ij      = 1 / (d_ij * d_ij);
                        double magnitude = (positions[i] - positions[j]).Magnitude();

                        topSumX += w_ij * (positions[j].x + d_ij * (positions[i].x - positions[j].x) / (magnitude));
                        topSumY += w_ij * (positions[j].y + d_ij * (positions[i].y - positions[j].y) / (magnitude));
                        botSum  += w_ij;
                    }
                }

                double newX = topSumX / botSum;
                double newY = topSumY / botSum;
                positions[i] = new Vector2(newX, newY);
            }

            double stress = GraphIO.CalculateStress(d, positions, n);
            yield return(stress);

            if ((prevStress - stress) / prevStress < eps)
            {
                yield break;
            }
            prevStress = stress;
        }
    }
예제 #21
0
    public static IEnumerable <double> Full(int[,] d, Vector2[] positions, IEnumerable <double> eta)
    {
        int n  = positions.Length;
        int nn = (n * (n - 1)) / 2;

        var pairs = CreatePairs(n);
        var rnd   = new Random();

        // relax
        foreach (double c in eta)
        {
            GraphIO.FYShuffle2(pairs, rnd);
            for (int ij = 0; ij < nn; ij++)
            {
                int i = pairs[ij, 0], j = pairs[ij, 1];
                Satisfy(ref positions[i], ref positions[j], d[i, j], c);
            }
            double stress = GraphIO.CalculateStress(d, positions, n);
            yield return(stress);
        }
    }
예제 #22
0
    public static IEnumerable <double> EveryPair(int[,] d, Vector2[] positions, IEnumerable <double> eta)
    {
        int n   = positions.Length;
        int nn  = (n * (n - 1)) / 2;
        var rnd = new Random();

        //var indices = CreatePairs(n);

        // relax
        foreach (double c in eta)
        {
            for (int ij = 0; ij < nn; ij++)
            {
                int idx = rnd.Next(nn);
                int i   = (int)((1 + Math.Sqrt(8 * idx + 1)) / 2);
                int j   = idx - (i * (i - 1)) / 2;
                //int i = indices[idx, 0], j = indices[idx, 1];

                Satisfy(ref positions[i], ref positions[j], d[i, j], c);
            }
            yield return(GraphIO.CalculateStress(d, positions, n));
        }
    }
예제 #23
0
파일: Majorization.cs 프로젝트: tzw28/s_gd2
    public static IEnumerable <double> Chol(int[,] d, Vector2[] positions, double eps = 0.0001, int maxIter = 1000)
    {
        int n = positions.Length;

        // first find the laplacian for the left hand side
        var laplacian_w = new double[n, n];

        WeightLaplacian(d, laplacian_w, n);

        // cut out the first row and column
        var cholesky_Lw = new double[n - 1, n - 1];

        for (int i = 1; i < n; i++)
        {
            for (int j = 1; j < n; j++)
            {
                cholesky_Lw[i - 1, j - 1] = laplacian_w[i, j];
            }
        }
        // p used to store diagonal values, as in Numerical Recipes
        var cholesky_p = new double[n - 1];

        Cholesky.Choldc(cholesky_Lw, cholesky_p);

        // delta = w_ij * d_ij as in Majorization, Gansner et al.
        var deltas = new double[n, n];

        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                double dist = d[i, j];
                deltas[i, j] = 1.0 / dist;
            }
        }

        var LXt    = new double[n, n];  // the laplacian for the right hand side
        var LXt_Xt = new double[n - 1]; // skip the first position as it's fixed to (0,0)
        var Xt1    = new double[n - 1]; // X(t+1)

        double prevStress = GraphIO.CalculateStress(d, positions, n);

        // majorize
        for (int k = 0; k < maxIter; k++)
        {
            PositionLaplacian(deltas, positions, LXt, n);

            // solve for x axis
            Multiply_x(LXt, positions, LXt_Xt);
            Cholesky.BackSubstitution(cholesky_Lw, cholesky_p, LXt_Xt, Xt1);
            for (int i = 1; i < n; i++)
            {
                positions[i].x = Xt1[i - 1];
            }

            // solve for y axis
            Multiply_y(LXt, positions, LXt_Xt);
            Cholesky.BackSubstitution(cholesky_Lw, cholesky_p, LXt_Xt, Xt1);
            for (int i = 1; i < n; i++)
            {
                positions[i].y = Xt1[i - 1];
            }

            double stress = GraphIO.CalculateStress(d, positions, n);
            yield return(stress);

            if ((prevStress - stress) / prevStress < eps)
            {
                yield break;
            }
            prevStress = stress;
        }
    }
예제 #24
0
파일: Majorization.cs 프로젝트: tzw28/s_gd2
    public static IEnumerable <double> Conj(int[,] d, Vector2[] positions, double eps = 0.0001, int maxIter = 1000)
    {
        int n = positions.Length;

        // first find the laplacian for the left hand side
        var laplacian_w = new double[n, n];

        Majorization.WeightLaplacian(d, laplacian_w, n);

        // cut out the first row and column
        var Lw = new double[n - 1, n - 1];

        for (int i = 1; i < n; i++)
        {
            for (int j = 1; j < n; j++)
            {
                Lw[i - 1, j - 1] = laplacian_w[i, j];
            }
        }

        // delta = w_ij * d_ij as in Majorization, Gansner et al.
        var deltas = new double[n, n];

        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n; j++)
            {
                double dist = d[i, j];
                deltas[i, j] = 1.0 / dist;
            }
        }

        var LXt    = new double[n, n];  // the laplacian for the right hand side
        var LXt_Xt = new double[n - 1]; // skip the first position as it's fixed to (0,0)
        var Xt1    = new double[n - 1]; // X(t+1)

        // temporary variables to speed up conjugate gradient
        var r  = new double[n - 1];
        var p  = new double[n - 1];
        var Ap = new double[n - 1];

        double prevStress = GraphIO.CalculateStress(d, positions, n);

        // majorize
        for (int k = 0; k < maxIter; k++)
        {
            PositionLaplacian(deltas, positions, LXt, n);

            // solve for x axis
            Multiply_x(LXt, positions, LXt_Xt);
            ConjugateGradient.Cg(Lw, Xt1, LXt_Xt, r, p, Ap, .1, 10);
            for (int i = 1; i < n; i++)
            {
                positions[i].x = Xt1[i - 1];
            }

            // solve for y axis
            Multiply_y(LXt, positions, LXt_Xt);
            ConjugateGradient.Cg(Lw, Xt1, LXt_Xt, r, p, Ap, .1, 10);
            for (int i = 1; i < n; i++)
            {
                positions[i].y = Xt1[i - 1];
            }

            double stress = GraphIO.CalculateStress(d, positions, n);
            yield return(stress);

            if ((prevStress - stress) / prevStress < eps)
            {
                yield break;
            }
            prevStress = stress;
        }
    }
예제 #25
0
        public object Write(
            object data, 
            string masterPassphrase,
            params KeyValuePair<string, string>[] parameters)
        {
            if (data.GetType() != typeof(Vault)) throw new ArgumentException("Data must be of type 'Vault'.", "data");

            DLoggerManager.Instance.Logger.Log(DFramework.Logging.Interfaces.LoggerMessageType.VerboseHigh | DFramework.Logging.Interfaces.LoggerMessageType.Information, "Writing Vault to AES encrypted byte array.");

            Dictionary<string, string> parametersDict = parameters.ToDictionary(x => x.Key, x => x.Value);

            Vault dataVault = (Vault)data;

            JSONVaultSerialiser jsonSerialiser = new JSONVaultSerialiser();
            JObject json = (JObject)jsonSerialiser.Write(dataVault, String.Empty, parameters);

            String jsonString = json.ToString(Newtonsoft.Json.Formatting.None, null);
            Byte[] salt = SimpleRandomGenerator.QuickGetRandomBytes(16);

            GraphBuilder decryptGraph = new GraphBuilder("AESEncryptedVaultSerialiser.Read");
            GraphIO<String> unencryptedInput = new GraphIO<String>(jsonString);
            GraphIO<Byte[]> saltInput = new GraphIO<Byte[]>(salt);

            //create derive node here
            IGraphNode keyDerivationNode = null;

            if (parametersDict.ContainsKey("KeyDerivationFunction"))
            {
                string keyDerivationFunction = parametersDict["KeyDerivationFunction"];
                switch (keyDerivationFunction)
                {
                    case "PBKDF2":
                        {
                            int iterationCount = int.Parse(parametersDict["IterationCount"]);
                            keyDerivationNode = new Rfc2898DeriveBytesNode(new GraphIO<String>(String.Empty), new GraphIO<Int32>(32), saltInput, new GraphIO<int>(iterationCount));
                            decryptGraph.AddNode("deriveNode", keyDerivationNode);
                            break;
                        }
                    case "SCRYPT":
                        {
                            int iterationCount = int.Parse(parametersDict["IterationCount"]);
                            int blockSize = int.Parse(parametersDict["BlockSize"]);
                            int threadCount = int.Parse(parametersDict["ThreadCount"]);
                            keyDerivationNode = new SCryptDeriveBytesNode(new GraphIO<String>(String.Empty), new GraphIO<Int32>(32), saltInput, new GraphIO<int>(iterationCount), new GraphIO<int>(blockSize), new GraphIO<int>(threadCount));
                            decryptGraph.AddNode("deriveNode", keyDerivationNode);
                            break;
                        }
                    default:
                        {
                            throw new InvalidOperationException(String.Format("Unknown key derivation function '{0}'.", keyDerivationFunction));
                        }
                }
            }
            else
            {
                //default setup
                keyDerivationNode = new Rfc2898DeriveBytesNode(new GraphIO<String>(String.Empty), new GraphIO<Int32>(32), saltInput, new GraphIO<int>(10000));
                decryptGraph.AddNode("deriveNode", keyDerivationNode);
            }

            AESEncryptNode encryptNode = new AESEncryptNode(unencryptedInput, new GraphIO<Byte[]>(null), keyDerivationNode.GetBytesIO("DerivedKey"));

            decryptGraph.AddNode("encryptNode", encryptNode);
            decryptGraph.CreateRoute("encrypt",
                keyDerivationNode.GetStringIO("Password"),
                encryptNode.EncryptedData,
                "deriveNode",
                new String[] { "deriveNode", "encryptNode" });

            Object output = null;
            if (decryptGraph.Process(true, "encrypt", masterPassphrase, out output))
            {
                byte[] encrypted = (byte[])output;
                byte[] encryptedWithSalt = encrypted.AppendBytes(salt);
                return (encryptedWithSalt);
            }
            else
            {
                throw new Exception("Failed to encrypt Vault.");
            }

            throw new NotImplementedException();
        }
예제 #26
0
        public object Read(
            object data, 
            string masterPassphrase,
            params KeyValuePair<string, string>[] parameters)
        {
            if (data.GetType() != typeof(Byte[])) throw new ArgumentException("Data must be of type 'Byte[]'.", "data");

            DLoggerManager.Instance.Logger.Log(DFramework.Logging.Interfaces.LoggerMessageType.VerboseHigh | DFramework.Logging.Interfaces.LoggerMessageType.Information, "Reading Vault from AES encrypted byte array.");

            Dictionary<string, string> parametersDict = parameters.ToDictionary(x => x.Key, x => x.Value);

            byte[] dataBytesWithSalt = (Byte[])data;
            byte[] dataBytes;
            byte[] salt;
            dataBytesWithSalt.RemoveFromEnd(16, out dataBytes, out salt);

            GraphBuilder decryptGraph = new GraphBuilder("AESEncryptedVaultSerialiser.Read");
            GraphIO<Byte[]> encryptedInput = new GraphIO<Byte[]>(dataBytes);
            GraphIO<Byte[]> saltInput = new GraphIO<Byte[]>(salt);

            IGraphNode keyDerivationNode = null;

            if(parametersDict.ContainsKey("KeyDerivationFunction"))
            {
                string keyDerivationFunction = parametersDict["KeyDerivationFunction"];
                switch (keyDerivationFunction)
                {
                    case "PBKDF2":
                        {
                            int iterationCount = int.Parse(parametersDict["IterationCount"]);
                            keyDerivationNode = new Rfc2898DeriveBytesNode(new GraphIO<String>(String.Empty), new GraphIO<Int32>(32), saltInput, new GraphIO<int>(iterationCount));
                            decryptGraph.AddNode("deriveNode", keyDerivationNode);
                            break;
                        }
                    case "SCRYPT":
                        {
                            int iterationCount = int.Parse(parametersDict["IterationCount"]);
                            int blockSize = int.Parse(parametersDict["BlockSize"]);
                            int threadCount = int.Parse(parametersDict["ThreadCount"]);
                            keyDerivationNode = new SCryptDeriveBytesNode(new GraphIO<String>(String.Empty), new GraphIO<Int32>(32), saltInput, new GraphIO<int>(iterationCount), new GraphIO<int>(blockSize), new GraphIO<int>(threadCount));
                            decryptGraph.AddNode("deriveNode", keyDerivationNode);
                            break;
                        }
                    default:
                        {
                            throw new InvalidOperationException(String.Format("Unknown key derivation function '{0}'.", keyDerivationFunction));
                        }
                }
            }
            else
            {
                keyDerivationNode = new Rfc2898DeriveBytesNode(new GraphIO<String>(String.Empty), new GraphIO<Int32>(32), saltInput, new GraphIO<Int32>(10000));
                decryptGraph.AddNode("deriveNode", keyDerivationNode);
            }

            AESDecryptNode decryptNode = new AESDecryptNode(encryptedInput, new GraphIO<Byte[]>(null), keyDerivationNode.GetBytesIO("DerivedKey"));

            decryptGraph.AddNode("decryptNode", decryptNode);
            decryptGraph.CreateRoute("decrypt",
                keyDerivationNode.GetStringIO("Password"),
                decryptNode.UnencryptedData,
                "deriveNode",
                new String[] { "deriveNode", "decryptNode" });

            Object output = null;
            if (decryptGraph.Process(true, "decrypt", masterPassphrase, out output))
            {
                String decryptedJSON = (String)output;
                JObject json = JObject.Parse(decryptedJSON);

                JSONVaultSerialiser jsonSerialiser = new JSONVaultSerialiser();
                Vault vault = (Vault)jsonSerialiser.Read(json, String.Empty);
                return (vault);
            }
            else
            {
                throw new Exception("Failed to decrypt Vault.");
            }
        }
예제 #27
0
 public Base64EncodeNode(GraphIO <Byte[]> unencodedData)
 {
     DLoggerManager.Instance.Logger.Log(DFramework.Logging.Interfaces.LoggerMessageType.VerboseHigh | DFramework.Logging.Interfaces.LoggerMessageType.Information | DFramework.Logging.Interfaces.LoggerMessageType.Sensitive, "Creating instance of Base64EncodeNode.");
     _unencodedData = unencodedData;
     _encodedData   = new GraphIO <String>(String.Empty);
 }