diff --git a/Docs/Internal/NumericalAnalysis/NumericalAnalysis_v6.47.pdf b/Docs/Internal/NumericalAnalysis/NumericalAnalysis_v6.49.pdf similarity index 59% rename from Docs/Internal/NumericalAnalysis/NumericalAnalysis_v6.47.pdf rename to Docs/Internal/NumericalAnalysis/NumericalAnalysis_v6.49.pdf index 85c1ce6e77b..cb102042fc9 100644 Binary files a/Docs/Internal/NumericalAnalysis/NumericalAnalysis_v6.47.pdf and b/Docs/Internal/NumericalAnalysis/NumericalAnalysis_v6.49.pdf differ diff --git a/Docs/Internal/NumericalAnalysis/Shruti/Source/NumericalAnalysis_v6.49.docx b/Docs/Internal/NumericalAnalysis/Shruti/Source/NumericalAnalysis_v6.49.docx new file mode 100644 index 00000000000..3afd280f4ff Binary files /dev/null and b/Docs/Internal/NumericalAnalysis/Shruti/Source/NumericalAnalysis_v6.49.docx differ diff --git a/IdeaDRIP/NumericalAnalysis/NA_v0.09 b/IdeaDRIP/NumericalAnalysis/NA_v0.09 new file mode 100644 index 00000000000..38649b3ae2a --- /dev/null +++ b/IdeaDRIP/NumericalAnalysis/NA_v0.09 @@ -0,0 +1,240 @@ + + -------------------------- + #1 - Successive Over-Relaxation + -------------------------- + -------------------------- + 1.1) Successive Over-Relaxation Method for A.x = b; A - n x n square matrix, x - unknown vector, b - RHS vector + 1.2) Decompose A into Diagonal, Lower, and upper Triangular Matrices; A = D + L + U + 1.3) SOR Scheme uses omega input + 1.4) Forward subsitution scheme to iteratively determine the x_i's + 1.5) SOR Scheme Linear System Convergence: Inputs A and D, Jacobi Iteration Matrix Spectral Radius, omega + - Construct Jacobi Iteration Matrix: C_Jacobian = I - (Inverse D) A + - Convergence Verification #1: Ensure that Jacobi Iteration Matrix Spectral Radius is < 1 + - Convergence Verification #2: Ensure omega between 0 and 2 + - Optimal Relaxation Parameter Expression in terms of Jacobi Iteration Matrix Spectral Radius + - Omega Based Convergence Rate Expression + - Gauss-Seidel omega = 1; corresponding Convergence Rate + - Optimal Omega Convergence Rate + 1.6) Generic Iterative Solver Method: + - Inputs: Iterator Function(x) and omega + - Unrelaxed Iterated variable: x_n+1 = f(x_n) + - SOR Based Iterated variable: x_n+1 = (1-omega).x_n + omega.f(x_n) + - SOR Based Iterated variable for Unknown Vector x: x_n+1 = (1-omega).x_n + omega.(L_star inverse)(b - U.x_n) + -------------------------- + + -------------------------- + #2 - Successive Over-Relaxation + -------------------------- + -------------------------- + 2.1) SSOR Algorithm - Inputs; A, omega, and gamma + - Decompose into D and L + - Pre-conditioner Matrix: Expression from SSOR + - Finally SSOR Iteration Formula + -------------------------- + + ---------------------------- + #7 - Tridiagonal matrix algorithm + ---------------------------- + ---------------------------- + 7.1) Is Tridiagonal Check + 7.2) Core Algorithm: + - C Prime's and D Prime's Calculation + - Back Substitution for the Result + - Modified better Book-keeping algorithm + 7.3) Sherman-Morrison Algorithm: + - Choice of gamma + - Construct Tridiagonal B from A and gamma + - u Column from gamma and c_n + - v Column from a_1 and gamma + - Solve for y from By=d + - Solve for q from Bq=u + - Use Sherman Morrison Formula to extract x + 7.4) Alternate Boundary Condition Algorithm: + - Solve Au=d for u + - Solve Av={-a_2, 0, ..., -c_n} for v + - Full solution is x_i = u_i + x_1 * v_i + - x_1 if computed using formula + ---------------------------- + + ---------------------------- + #8 - Triangular Matrix + ---------------------------- + ---------------------------- + 8.1) Description: + - Lower/Left Triangular Verification + - Upper/Right Triangular Verification + - Diagonal Matrix Verification + - Upper/Lower Trapezoidal Verification + 8.2) Forward/Back Substitution: + - Inputs => L and b + - Forward Substitution + - Inputs => U and b + - Back Substitution + 8.3) Properties: + - Is Matrix Normal, i.e., A times A transpose = A transpose times A + - Characteristic Polynomial + - Determinant/Permanent + 8.4) Special Forms: + - Upper/Lower Unitriangular Matrix Verification + - Upper/Lower Strictly Matrix Verification + - Upper/Lower Atomic Matrix Verification + ---------------------------- + + ---------------------------- + #9 - Sylvester Equation + ---------------------------- + ---------------------------- + 9.1) Matrix Form: + - Inputs: A, B, and C + - Size Constraints Verification + 9.2) Solution Criteria: + - Co-joint EigenSpectrum between A and B + 9.3) Numerical Solution: + - Decomposition of A/B using Schur Decomposition into Triangular Form + - Forward/Back Substitution + ---------------------------- + + ---------------------------- + #10 - Bartels-Stewart Algorithm + ---------------------------- + ---------------------------- + 10.1) Matrix Form: + - Inputs: A, B, and C + - Size Constraints Verification + 10.2) Schur Decompositions: + - R = U^T A U - emits U and R + - S = V^T B^T V - emits V and S + - F = U^T C V + - Y = U^T X V + - Solution to R.Y - Y.S^T = F + - Finally X = U.Y.V^T + 10.3) Computational Costs: + - Flops cost for Schur decomposition + - Flops cost overall + 10.4) Hessenberg-Schur Decompositions: + - R = U^T A U becomes H = Q^T A Q - thus emits Q and H (Upper Hessenberg) + - Computational Costs + ---------------------------- + + ---------------------------- + #11 - Gershgorin Circle Theorem + ---------------------------- + ---------------------------- + 11.1) Gershgorin Disc: + - Diagonal Entry + - Radius + - One disc per Row/Column in Square Matrix + - Optimal Disc based on Row/Column + 11.2) Tolerance based Gershgorin Convergence Criterion + 11.3) Joint and Disjoint Discs + 11.4) Gershgorin Strengthener + 11.5) Row/Column Diagonal Dominance + ---------------------------- + + ---------------------------- + #12 - Condition Number + ---------------------------- + ---------------------------- + 12.1) Condition Number Calculation: + - Absolute Error + - Relative Error + - Absolute Condition Number + - Relative Condition Number + 12.2) Matrix Condition Number Calculation: + - Condition Number as a Product of Regular and Inverse Norms + - L2 Norm + - L2 Norm for Normal Matrix + - L2 Norm for Unitary Matrix + - Default Condition Number + - L Infinity Norm + - L Infinity Norm Triangular Matrix + 12.3) Non-linear + - One Variable + - Basic Formula + - Condition Numbers for Common Functions + - Multi Variables + ---------------------------- + + ---------------------------- + #13 - Unitary Matrix + ---------------------------- + ---------------------------- + 13.1) Properties: + - U.U conjugate = I defines unitary matrix + - U.U conjugate = U conjugate.U = I + - det U = 1 + - Eigenvectors are orthogonal + - U conjugate = U inverse + - Norm (U.x) = Norm (x) + - Normal Matrix U + 13.2) 2x2 Elementary Matrices + - Wiki Representation #1 + - Wiki Representation #2 + - Wiki Representation #3 + - Wiki Representation #4 + ---------------------------- + + ---------------------------- + #14 - Spectral Radius + ---------------------------- + ---------------------------- + 14.1) Definition - Matrix: + - Spectral Radius - Max of the Eigenvalues + 14.2) Definition - Bounded Complex Linear Operators: + - Spectral Radius - Max of the Spectrum + - Gelfand Formula applies to Bounded Complex Linear Operators + 14.3) Definition - Graph: + - Function on Graph Vertex + - Square Integrability of Function across Vertexes + - Graph Function Map - Square Integrability Function Space across Vertexes 1 -> 2 + - Graph Adjacency Operator - Function Sum over edges of a vertex + 14.4)Upper bounds + - Upper bounds on the spectral radius of a matrix <= Power (Norm (A^k), 1/k) + - Upper bounds for spectral radius of a graph + 14.5) Jordan Normal Power Sequence + - J (m_i, lambda_i) + - J (m_i, lambda_i) power k + - Jordan Normal J Matrix + - Jordan Normal J Matrix power k + - A = V.J.V^-1 + - A^k = V.J^k.V^-1 + 14.6) Gelfand's formula + - The Formula + - Gelfand's formula for Commuting Matrices + ---------------------------- + + -------------------------- + #15 - Crank–Nicolson method + -------------------------- + -------------------------- + 15.1) von Neumann Stability Validator - Inputs; time-step, diffusivity, space step + - 1D => time step * diffusivity / space step ^2 < 0.5 + - nD => time step * diffusivity / (space step hypotenuse) ^ 2 < 0.5 + 15.2) Set up: + - Input: Spatial variable x + - Input: Time variable t + - Inputs: State variable u, du/dx, d2u/dx2 - all at time t + - Second Order, 1D => du/dt = F (u, x, t, du/dx, d2u/dx2) + 15.3) Finite Difference Evolution Scheme: + - Time Step delta_t, space step delta_x + - Forward Difference: F calculated at x + - Backward Difference: F calculated at x + delta_x + - Crank Nicolson: Average of Forward/Backward + 15.4) 1D Diffusion: + - Inputs: 1D von Neumann Stability Validator, Number of time/space steps + - Time Index n, Space Index i + - Explicit Tridiagonal form for the discretization - State concentration at n+1 given state concentration at n + - Non-linear diffusion coefficient: + - Linearization across x_i and x_i+1 + - Quasi-explicit forms accommodation + 15.5) 2D Diffusion: + - Inputs: 2D von Neumann Stability Validator, Number of time/space steps + - Time Index n, Space Index i, j + - Explicit Tridiagonal form for the discretization - State concentration at n+1 given state concentration at n + - Explicit Solution using the Alternative Difference Implicit Scheme + 15.6) Extension to Iterative Solver Schemes above: + - Input: State Space "velocity" dF/du + - Input: State "Step Size" delta_u + - Fixed Point Iterative Location Scheme + - Relaxation Scheme based Robustness => Input: Relaxation Parameter + -------------------------- diff --git a/NumericalAnalysisLibrary.md b/NumericalAnalysisLibrary.md index d371d3faab4..5ad7a0c7dcf 100644 --- a/NumericalAnalysisLibrary.md +++ b/NumericalAnalysisLibrary.md @@ -444,6 +444,21 @@ Numerical Analysis Library contains the supporting Functionality for Numerical M * Equivalence of Norms * Examples of Norm Equivalence * References + * Spectral Radius + * Introduction + * Definition + * Matrices + * Bounded Linear Operators + * Graphs + * Upper Bounds + * Upper Bounds on the Spectral Radius of a Matrix + * Upper Bounds on the Spectral Radius of a Graph + * Power Sequence + * Gelfand's Formula + * Theorem + * Proof + * Corollary + * References ## DROP Specifications diff --git a/ReleaseNotes/04_01_2024.txt b/ReleaseNotes/04_01_2024.txt new file mode 100644 index 00000000000..e3e8e6c11dc --- /dev/null +++ b/ReleaseNotes/04_01_2024.txt @@ -0,0 +1,27 @@ + +Features: + + - Component Eigen-output Spectral Radius (117, 118, 119) + - R^1 Square Matrix Spectral Radius (120) + + +Bug Fixes/Re-organization: + +Samples: + +IdeaDRIP: + + - Spectral Radius Gelfand's Formula - Proof #1 (1-9) + - Spectral Radius Gelfand's Formula - Corollary #1 (10, 11) + - Spectral Radius Introduction (12-15) + - Spectral Radius Definition - Matrices (16-31) + - Spectral Radius Definition - Bounded Linear Operators (32-41) + - Spectral Radius Definition - Graphs (42-51) + - Upper Bounds on the Spectral Radius of a Matrix (52-61) + - Upper Bounds on the Spectral Radius of a Graph (62-65) + - Spectral Radius Power Sequence (66-91) + - Spectral Radius Gelfand's Formula (92-93) + - Spectral Radius Gelfand's Formula - Theorem (94-97) + - Spectral Radius Gelfand's Formula - Proof #2 (98-113) + - Spectral Radius Gelfand's Formula - Corollary #2 (114-115) + - Spectral Radius (116) diff --git a/src/main/java/org/drip/numerical/eigen/EigenOutput.java b/src/main/java/org/drip/numerical/eigen/EigenOutput.java index cf46d03ecca..943dc79da35 100644 --- a/src/main/java/org/drip/numerical/eigen/EigenOutput.java +++ b/src/main/java/org/drip/numerical/eigen/EigenOutput.java @@ -252,4 +252,25 @@ public double conditionNumber() return maximumEigenvalue / minimumEigenvalue; } + + /** + * Compute the Spectral Radius using the Eigenvalue Array + * + * @return Spectral Radius + */ + + public double spectralRadius() + { + double spectralRadius = Math.abs (_eigenValueArray[0]); + + for (int i = 1; i < _eigenValueArray.length; ++i) { + double absoluteEigenvalue = Math.abs (_eigenValueArray[i]); + + if (spectralRadius < absoluteEigenvalue) { + spectralRadius = absoluteEigenvalue; + } + } + + return spectralRadius; + } } diff --git a/src/main/java/org/drip/numerical/matrix/R1Square.java b/src/main/java/org/drip/numerical/matrix/R1Square.java index 582a57bffc7..6d877e98592 100644 --- a/src/main/java/org/drip/numerical/matrix/R1Square.java +++ b/src/main/java/org/drip/numerical/matrix/R1Square.java @@ -400,4 +400,24 @@ public R1ToR1 characteristicPolynomial() return null == eigenOutput ? null : eigenOutput.characteristicPolynomial(); } + + /** + * Compute the Spectral Radius of the Matrix + * + * @return Spectral Radius of the Matrix + * + * @throws Exception Thrown if the Spectral Radius cannot be calculated + */ + + public double spectralRadius() + throws Exception + { + EigenOutput eigenOutput = QREigenComponentExtractor.Standard().eigenize (_r1Grid); + + if (null == eigenOutput) { + throw new Exception ("R1Square::spectralRadius => Cannot eigenize"); + } + + return eigenOutput.spectralRadius(); + } } diff --git a/src/main/java/org/drip/service/common/GraphUtil.java b/src/main/java/org/drip/service/common/GraphUtil.java index 750a5860bb9..b476cb3081b 100644 --- a/src/main/java/org/drip/service/common/GraphUtil.java +++ b/src/main/java/org/drip/service/common/GraphUtil.java @@ -1,6 +1,14 @@ package org.drip.service.common; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; + /* * -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ @@ -93,86 +101,9 @@ public class GraphUtil { - /** - * Check if the Graph is Bipartite - * - * @param graph Graph as an Adjacency List - * - * @return TRUE - The Graph is Bipartite - */ - - public static final boolean IsGraphBipartite ( - final int[][] graph) - { - java.util.Map> vertexEdgesMap = - new java.util.HashMap>(); - - for (int[] edge : graph) - { - if (vertexEdgesMap.containsKey(edge[0])) - { - vertexEdgesMap.get(edge[0]).add(edge[1]); - } - else - { - java.util.Set neighborSet = new java.util.HashSet(); - - neighborSet.add(edge[1]); - - vertexEdgesMap.put (edge[0], neighborSet); - } - - if (vertexEdgesMap.containsKey(edge[1])) - { - vertexEdgesMap.get(edge[1]).add(edge[0]); - } - else - { - java.util.Set neighborSet = new java.util.HashSet(); - - neighborSet.add(edge[0]); - - vertexEdgesMap.put (edge[1], neighborSet); - } - } - - java.util.List> vertexSetCluster = - new java.util.ArrayList>(); - - for (java.util.Map.Entry> vertexEdgesEntry : - vertexEdgesMap.entrySet()) - { - java.util.Set neighborSet = vertexEdgesEntry.getValue(); - - boolean vertexSetFound = false; - - for (java.util.Set vertexSet : vertexSetCluster) - { - for (int neighborVertex : neighborSet) - { - if (vertexSet.contains(neighborVertex)) - { - vertexSet.addAll(neighborSet); - - vertexSetFound = true; - break; - } - } - } - - if (!vertexSetFound) - { - vertexSetCluster.add(neighborSet); - } - } - - return 2 == vertexSetCluster.size() || graph.length <= vertexSetCluster.size(); - } - - private static final java.util.HashMap CharacterCodeMap() + private static final HashMap CharacterCodeMap() { - java.util.HashMap characterCodeMap = new - java.util.HashMap(); + HashMap characterCodeMap = new HashMap(); characterCodeMap.put ("1", 'A'); @@ -229,6 +160,69 @@ private static final java.util.HashMap Ch return characterCodeMap; } + /** + * Check if the Graph is Bipartite + * + * @param graph Graph as an Adjacency List + * + * @return TRUE - The Graph is Bipartite + */ + + public static final boolean IsGraphBipartite ( + final int[][] graph) + { + Map> vertexEdgesMap = new HashMap>(); + + for (int[] edge : graph) { + if (vertexEdgesMap.containsKey (edge[0])) { + vertexEdgesMap.get (edge[0]).add (edge[1]); + } else { + Set neighborSet = new HashSet(); + + neighborSet.add (edge[1]); + + vertexEdgesMap.put (edge[0], neighborSet); + } + + if (vertexEdgesMap.containsKey (edge[1])) { + vertexEdgesMap.get (edge[1]).add (edge[0]); + } else { + Set neighborSet = new HashSet(); + + neighborSet.add (edge[0]); + + vertexEdgesMap.put (edge[1], neighborSet); + } + } + + List> vertexSetCluster = new ArrayList>(); + + for (Map.Entry> vertexEdgesEntry : vertexEdgesMap.entrySet()) { + Set vertexNeighborSet = vertexEdgesEntry.getValue(); + + boolean vertexSetFound = false; + + for (Set vertexSet : vertexSetCluster) { + for (int neighborVertex : vertexNeighborSet) { + if (vertexSet.contains (neighborVertex)) { + vertexSet.addAll (vertexNeighborSet); + + vertexSetFound = true; + break; + } + } + } + + if (!vertexSetFound) { + vertexSetCluster.add (vertexNeighborSet); + } + } + + int vertexSetClusterSize = vertexSetCluster.size(); + + return 2 == vertexSetClusterSize || graph.length <= vertexSetClusterSize; + } + /** * Decode all possible Combinations of the Number * @@ -237,27 +231,27 @@ private static final java.util.HashMap Ch * @return All possible Combinations of the Number */ - public static final java.util.Set DecodeCombinations ( - final java.lang.String number) + public static final Set DecodeCombinations ( + final String number) { - java.util.HashMap characterCodeMap = CharacterCodeMap(); - - java.util.List combinationList = new java.util.ArrayList(); + HashMap characterCodeMap = CharacterCodeMap(); - java.util.Set combinationSet = new java.util.HashSet(); + List combinationList = new ArrayList(); - java.util.List indexList = new java.util.ArrayList(); + Set combinationSet = new HashSet(); - indexList.add (0); + List indexList = new ArrayList(); combinationList.add (""); + indexList.add (0); + while (!indexList.isEmpty()) { int queueTailIndex = indexList.size() - 1; int index = indexList.remove (queueTailIndex); - java.lang.String combination = combinationList.remove (queueTailIndex); + String combination = combinationList.remove (queueTailIndex); if (index >= number.length()) { combinationSet.add (combination); @@ -265,7 +259,7 @@ public static final java.util.Set DecodeCombinations ( continue; } - java.lang.String singleDigit = number.substring (index, index + 1); + String singleDigit = number.substring (index, index + 1); if (characterCodeMap.containsKey (singleDigit)) { combinationList.add (combination + characterCodeMap.get (singleDigit)); @@ -273,9 +267,11 @@ public static final java.util.Set DecodeCombinations ( indexList.add (index + 1); } - if (index == number.length() - 1) continue; + if (index == number.length() - 1) { + continue; + } - java.lang.String doubleDigit = number.substring (index, index + 2); + String doubleDigit = number.substring (index, index + 2); if (characterCodeMap.containsKey (doubleDigit)) { combinationList.add (combination + characterCodeMap.get (doubleDigit)); @@ -295,15 +291,14 @@ public static final java.util.Set DecodeCombinations ( * @return The Connected Components */ - public static final java.util.ArrayList> LargestGroup ( - java.util.List> itemListSequence) + public static final ArrayList> LargestGroup ( + List> itemListSequence) { - java.util.ArrayList> componentList = new - java.util.ArrayList>(); + ArrayList> componentList = new ArrayList>(); - for (java.util.List itemList : itemListSequence) { + for (List itemList : itemListSequence) { if (componentList.isEmpty()) { - java.util.HashSet itemSet = new java.util.HashSet(); + HashSet itemSet = new HashSet(); itemSet.addAll (itemList); @@ -312,30 +307,34 @@ public static final java.util.ArrayList> LargestGroup continue; } - java.util.ArrayList mergeList = new java.util.ArrayList(); + ArrayList mergeList = new ArrayList(); for (String item : itemList) { for (int componentIndex = 0; componentIndex < componentList.size(); ++componentIndex) { - if (componentList.get (componentIndex).contains (item)) mergeList.add (componentIndex); + if (componentList.get (componentIndex).contains (item)) { + mergeList.add (componentIndex); + } } } if (mergeList.isEmpty()) { - java.util.HashSet itemSet = new java.util.HashSet(); + HashSet itemSet = new HashSet(); itemSet.addAll (itemList); componentList.add (itemSet); } else { - java.util.HashSet component = componentList.get (mergeList.get (0)); + HashSet component = componentList.get (mergeList.get (0)); - for (int mergeListIndex = 1; mergeListIndex < mergeList.size(); ++mergeListIndex) + for (int mergeListIndex = 1; mergeListIndex < mergeList.size(); ++mergeListIndex) { component.addAll (componentList.get (mergeListIndex)); + } component.addAll (itemList); - for (int mergeListIndex = mergeList.size() - 1; mergeListIndex > 1 ; --mergeListIndex) + for (int mergeListIndex = mergeList.size() - 1; mergeListIndex > 1 ; --mergeListIndex) { componentList.remove (mergeListIndex); + } } } @@ -351,77 +350,80 @@ public static final java.util.ArrayList> LargestGroup * @return List of Critical Nodes */ - public static final java.util.ArrayList CriticalNodes ( + public static final ArrayList CriticalNodes ( final int[][] edgeArray) { - java.util.HashMap> neighborSetMap = new - java.util.HashMap>(); + HashMap> vertexNeighborSetMap = new HashMap>(); for (int[] edge : edgeArray) { - if (neighborSetMap.containsKey (edge[0])) - neighborSetMap.get (edge[0]).add (edge[1]); - else { - java.util.HashSet neighborSet = new java.util.HashSet(); + if (vertexNeighborSetMap.containsKey (edge[0])) { + vertexNeighborSetMap.get (edge[0]).add (edge[1]); + } else { + HashSet neighborSet = new HashSet(); neighborSet.add (edge[1]); - neighborSetMap.put (edge[0], neighborSet); + vertexNeighborSetMap.put (edge[0], neighborSet); } - if (neighborSetMap.containsKey (edge[1])) - neighborSetMap.get (edge[1]).add (edge[0]); - else { - java.util.HashSet neighborSet = new java.util.HashSet(); + if (vertexNeighborSetMap.containsKey (edge[1])) { + vertexNeighborSetMap.get (edge[1]).add (edge[0]); + } else { + HashSet neighborSet = new HashSet(); neighborSet.add (edge[0]); - neighborSetMap.put (edge[1], neighborSet); + vertexNeighborSetMap.put (edge[1], neighborSet); } } - java.util.HashSet intermediateNodeSet = new java.util.HashSet(); + HashSet intermediateVertexSet = new HashSet(); - for (int nodeID : neighborSetMap.keySet()) { - if (1 != neighborSetMap.get (nodeID).size()) intermediateNodeSet.add (nodeID); + for (int vertex : vertexNeighborSetMap.keySet()) { + if (1 != vertexNeighborSetMap.get (vertex).size()) intermediateVertexSet.add (vertex); } - java.util.ArrayList criticalNodeList = new java.util.ArrayList(); + ArrayList criticalVertexList = new ArrayList(); - for (int intermediateNodeID : intermediateNodeSet) { - java.util.HashMap> modifiedNeighborSetMap = new - java.util.HashMap>(); + for (int intermediateVertex : intermediateVertexSet) { + HashMap> modifiedVertexNeighborSetMap = + new HashMap>(); int startingVertex = -1; for (int[] edge : edgeArray) { - if (edge[0] == intermediateNodeID || edge[1] == intermediateNodeID) continue; + if (edge[0] == intermediateVertex || edge[1] == intermediateVertex) { + continue; + } - if (-1 == startingVertex) startingVertex = edge[0]; + if (-1 == startingVertex) { + startingVertex = edge[0]; + } - if (modifiedNeighborSetMap.containsKey (edge[0])) - modifiedNeighborSetMap.get (edge[0]).add (edge[1]); - else { - java.util.HashSet modifiedNeighborSet = new java.util.HashSet(); + if (modifiedVertexNeighborSetMap.containsKey (edge[0])) { + modifiedVertexNeighborSetMap.get (edge[0]).add (edge[1]); + } else { + HashSet modifiedNeighborSet = new HashSet(); modifiedNeighborSet.add (edge[1]); - modifiedNeighborSetMap.put (edge[0], modifiedNeighborSet); + modifiedVertexNeighborSetMap.put (edge[0], modifiedNeighborSet); } - if (modifiedNeighborSetMap.containsKey (edge[1])) - modifiedNeighborSetMap.get (edge[1]).add (edge[0]); - else { - java.util.HashSet modifiedNeighborSet = new java.util.HashSet(); + if (modifiedVertexNeighborSetMap.containsKey (edge[1])) { + modifiedVertexNeighborSetMap.get (edge[1]).add (edge[0]); + } else { + HashSet modifiedNeighborSet = new HashSet(); modifiedNeighborSet.add (edge[0]); - modifiedNeighborSetMap.put (edge[1], modifiedNeighborSet); + modifiedVertexNeighborSetMap.put (edge[1], modifiedNeighborSet); } } - java.util.HashSet visitedVertexSet = new java.util.HashSet(); + ArrayList bfsVertexStack = new ArrayList(); - java.util.ArrayList bfsVertexStack = new java.util.ArrayList(); + HashSet visitedVertexSet = new HashSet(); bfsVertexStack.add (startingVertex); @@ -430,28 +432,30 @@ public static final java.util.ArrayList CriticalNodes ( visitedVertexSet.add (vertexID); - java.util.HashSet modifiedNeighborSet = modifiedNeighborSetMap.get (vertexID); + HashSet modifiedNeighborSet = modifiedVertexNeighborSetMap.get (vertexID); - if (modifiedNeighborSet.isEmpty()) continue; + if (modifiedNeighborSet.isEmpty()) { + continue; + } - for (int modifiedNeighborID : modifiedNeighborSet) { - if (!visitedVertexSet.contains (modifiedNeighborID)) - bfsVertexStack.add (modifiedNeighborID); + for (int modifiedNeighbor : modifiedNeighborSet) { + if (!visitedVertexSet.contains (modifiedNeighbor)) + bfsVertexStack.add (modifiedNeighbor); } } - if (visitedVertexSet.size() != neighborSetMap.size() - 1) - criticalNodeList.add (intermediateNodeID); + if (visitedVertexSet.size() != vertexNeighborSetMap.size() - 1) + criticalVertexList.add (intermediateVertex); } - return criticalNodeList; + return criticalVertexList; } /** * There are N cities numbered from 1 to N. * * You are given connections, where each connections[i] = [city1, city2, cost] represents the cost to - * connect city1 and city2together. (A connection is bidirectional: connecting city1 and city2 is the + * connect city1 and city2 together. (A connection is bidirectional: connecting city1 and city2 is the * same as connecting city2 and city1.) * * Return the minimum cost so that for every pair of cities, there exists a path of connections (possibly @@ -466,17 +470,19 @@ public static final java.util.ArrayList CriticalNodes ( public static final int MSPCost ( final int[][] weightedEdgeArray) { - java.util.HashMap edgeWeightMap = new java.util.HashMap(); + HashMap edgeWeightMap = new HashMap(); - java.util.HashMap>> weightedGraph = - new java.util.HashMap>>(); + HashMap>> vertexNeighborSetWeightMap = + new HashMap>>(); for (int[] weightedEdge : weightedEdgeArray) { - weightedGraph.put (weightedEdge[0], new java.util.TreeMap>()); + if (!vertexNeighborSetWeightMap.containsKey (weightedEdge[0])) { + vertexNeighborSetWeightMap.put (weightedEdge[0], new TreeMap>()); + } - weightedGraph.put (weightedEdge[1], new java.util.TreeMap>()); + if (!vertexNeighborSetWeightMap.containsKey (weightedEdge[1])) { + vertexNeighborSetWeightMap.put (weightedEdge[1], new TreeMap>()); + } edgeWeightMap.put (weightedEdge[0] + "_" + weightedEdge[1], weightedEdge[2]); @@ -484,25 +490,25 @@ public static final int MSPCost ( } for (int[] weightedEdge : weightedEdgeArray) { - java.util.TreeMap> weightSortedNeighborSet = - weightedGraph.get (weightedEdge[0]); + TreeMap> weightSortedNeighborSet = + vertexNeighborSetWeightMap.get (weightedEdge[0]); - if (weightSortedNeighborSet.containsKey (weightedEdge[2])) + if (weightSortedNeighborSet.containsKey (weightedEdge[2])) { weightSortedNeighborSet.get (weightedEdge[2]).add (weightedEdge[1]); - else { - java.util.HashSet neighborSet = new java.util.HashSet(); + } else { + HashSet neighborSet = new HashSet(); neighborSet.add (weightedEdge[1]); weightSortedNeighborSet.put (weightedEdge[2], neighborSet); } - weightSortedNeighborSet = weightedGraph.get (weightedEdge[1]); + weightSortedNeighborSet = vertexNeighborSetWeightMap.get (weightedEdge[1]); - if (weightSortedNeighborSet.containsKey (weightedEdge[2])) + if (weightSortedNeighborSet.containsKey (weightedEdge[2])) { weightSortedNeighborSet.get (weightedEdge[2]).add (weightedEdge[0]); - else { - java.util.HashSet neighborSet = new java.util.HashSet(); + } else { + HashSet neighborSet = new HashSet(); neighborSet.add (weightedEdge[0]); @@ -513,74 +519,79 @@ public static final int MSPCost ( int cost = 0; int startingVertex = weightedEdgeArray[0][0]; - java.util.TreeMap> edgePriorityQueue = new - java.util.TreeMap>(); + TreeMap> edgeWeightPriorityQueue = + new TreeMap>(); - java.util.TreeMap> weightSortedNeighborSet = - weightedGraph.get (startingVertex); + TreeMap> weightSortedNeighborSetMap = + vertexNeighborSetWeightMap.get (startingVertex); - if (weightSortedNeighborSet.isEmpty()) return -1; + if (weightSortedNeighborSetMap.isEmpty()) { + return -1; + } - for (int edgeWeight : weightSortedNeighborSet.keySet()) { - for (int neighborVertex : weightSortedNeighborSet.get (edgeWeight)) { - if (edgePriorityQueue.containsKey (edgeWeight)) - edgePriorityQueue.get (edgeWeight).add (startingVertex + "_" + neighborVertex); - else { - java.util.ArrayList edgeList = new java.util.ArrayList(); + for (int edgeWeight : weightSortedNeighborSetMap.keySet()) { + for (int neighborVertex : weightSortedNeighborSetMap.get (edgeWeight)) { + if (edgeWeightPriorityQueue.containsKey (edgeWeight)) { + edgeWeightPriorityQueue.get (edgeWeight).add (startingVertex + "_" + neighborVertex); + } else { + ArrayList edgeList = new ArrayList(); edgeList.add (startingVertex + "_" + neighborVertex); - edgePriorityQueue.put (edgeWeight, edgeList); + edgeWeightPriorityQueue.put (edgeWeight, edgeList); } } } - java.util.ArrayList spanningEdgeList = new java.util.ArrayList(); + ArrayList spanningEdgeList = new ArrayList(); - java.util.HashSet visitedVertexSet = new java.util.HashSet(); + HashSet visitedVertexSet = new HashSet(); visitedVertexSet.add (startingVertex); - while (!edgePriorityQueue.isEmpty()) { - int shortestDistance = edgePriorityQueue.firstKey(); + while (!edgeWeightPriorityQueue.isEmpty()) { + int shortestDistance = edgeWeightPriorityQueue.firstKey(); - java.util.ArrayList edgeList = edgePriorityQueue.get (shortestDistance); + ArrayList edgeList = edgeWeightPriorityQueue.get (shortestDistance); String nextEdge = edgeList.remove (0); - if (edgeList.isEmpty()) edgePriorityQueue.remove (shortestDistance); + if (edgeList.isEmpty()) { + edgeWeightPriorityQueue.remove (shortestDistance); + } int nextVertex = Integer.parseInt (nextEdge.split ("_")[1]); if (!visitedVertexSet.contains (nextVertex)) { - visitedVertexSet.add (nextVertex); - spanningEdgeList.add (nextEdge); - weightSortedNeighborSet = weightedGraph.get (nextVertex); - - if (weightSortedNeighborSet.isEmpty()) continue; + visitedVertexSet.add (nextVertex); - for (int edgeWeight : weightSortedNeighborSet.keySet()) { - for (int neighborVertex : weightSortedNeighborSet.get (edgeWeight)) { - if (edgePriorityQueue.containsKey (edgeWeight)) - edgePriorityQueue.get (edgeWeight).add (nextVertex + "_" + neighborVertex); - else { - edgeList = new java.util.ArrayList(); + if ((weightSortedNeighborSetMap = vertexNeighborSetWeightMap.get (nextVertex)).isEmpty()) { + continue; + } - edgeList.add (nextVertex + "_" + neighborVertex); + for (int edgeWeight : weightSortedNeighborSetMap.keySet()) { + for (int neighborVertex : weightSortedNeighborSetMap.get (edgeWeight)) { + if (edgeWeightPriorityQueue.containsKey (edgeWeight)) { + edgeWeightPriorityQueue.get (edgeWeight).add (nextVertex + "_" + neighborVertex); + } else { + (edgeList = new ArrayList()).add (nextVertex + "_" + neighborVertex); - edgePriorityQueue.put (edgeWeight, edgeList); + edgeWeightPriorityQueue.put (edgeWeight, edgeList); } } } } } - if (visitedVertexSet.size() < weightedGraph.size()) return -1; + if (visitedVertexSet.size() < vertexNeighborSetWeightMap.size()) { + return -1; + } - for (String edge : spanningEdgeList) + for (String edge : spanningEdgeList) { cost = cost + edgeWeightMap.get (edge); + } return cost; } diff --git a/src/main/java/org/drip/service/common/PhoneLetterCombinationGenerator.java b/src/main/java/org/drip/service/common/PhoneLetterCombinationGenerator.java index 329fd85c6f6..67dbbcc90fc 100644 --- a/src/main/java/org/drip/service/common/PhoneLetterCombinationGenerator.java +++ b/src/main/java/org/drip/service/common/PhoneLetterCombinationGenerator.java @@ -1,6 +1,13 @@ package org.drip.service.common; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + /* * -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ @@ -96,15 +103,14 @@ public class PhoneLetterCombinationGenerator new java.util.HashMap(); /** - * Generate the Standard PhoneLetterCombinationGenerator + * Generate the Standard PhoneLetterCombinationGenerator * - * @return The Standard PhoneLetterCombinationGenerator + * @return The Standard PhoneLetterCombinationGenerator */ public static final PhoneLetterCombinationGenerator Standard() { - java.util.Map digitCharacterMap = new - java.util.HashMap(); + Map digitCharacterMap = new HashMap(); digitCharacterMap.put ('1', new char[] {'A', 'B', 'C'}); @@ -128,7 +134,7 @@ public static final PhoneLetterCombinationGenerator Standard() try { return new PhoneLetterCombinationGenerator (digitCharacterMap); - } catch (java.lang.Exception e) { + } catch (Exception e) { e.printStackTrace(); } @@ -140,15 +146,16 @@ public static final PhoneLetterCombinationGenerator Standard() * * @param digitCharacterMap The Digit To Character Array Map * - * @throws java.lang.Exception Thrown if the Input is Invalid + * @throws Exception Thrown if the Input is Invalid */ public PhoneLetterCombinationGenerator ( - final java.util.Map digitCharacterMap) - throws java.lang.Exception + final Map digitCharacterMap) + throws Exception { - if (null == (_digitCharacterMap = digitCharacterMap) || 0 == _digitCharacterMap.size()) - throw new java.lang.Exception ("PhoneLetterCombinationGenerator Constructor => Invalid Input"); + if (null == (_digitCharacterMap = digitCharacterMap) || 0 == _digitCharacterMap.size()) { + throw new Exception ("PhoneLetterCombinationGenerator Constructor => Invalid Input"); + } } /** @@ -157,7 +164,7 @@ public PhoneLetterCombinationGenerator ( * @return Digit to Character Array Map */ - public java.util.Map digitCharacterMap() + public Map digitCharacterMap() { return _digitCharacterMap; } @@ -171,21 +178,25 @@ public java.util.Map digitCharacterMap() * @return Set of Candidate Characters */ - public java.util.Set candidateCharacterSet ( + public Set candidateCharacterSet ( final char digit, final int count) { - if (!_digitCharacterMap.containsKey (digit)) return null; + if (!_digitCharacterMap.containsKey (digit)) { + return null; + } char[] charArray = _digitCharacterMap.get (digit); - if (count > charArray.length) return null; + if (count > charArray.length) { + return null; + } - java.util.Set candidateCharacterSet = new java.util.HashSet(); + Set candidateCharacterSet = new HashSet(); - if (1 == count) + if (1 == count) { candidateCharacterSet.add ("" + charArray[0]); - else if (2 == count) { + } else if (2 == count) { candidateCharacterSet.add (charArray[0] + "" + charArray[0]); candidateCharacterSet.add ("" + charArray[1]); @@ -210,17 +221,16 @@ else if (2 == count) { * @return The Candidate Sequence Sets */ - public java.util.Set sequenceSet ( - final java.lang.String number) + public Set sequenceSet ( + final String number) { - java.util.Set sequenceSet = new java.util.HashSet(); + Set sequenceSet = new HashSet(); char[] digitArray = number.toCharArray(); - java.util.List numberIndexQueue = new java.util.ArrayList(); + List numberIndexQueue = new ArrayList(); - java.util.List numberCombinationQueue = new - java.util.ArrayList(); + List numberCombinationQueue = new ArrayList(); numberIndexQueue.add (0); @@ -231,7 +241,7 @@ public java.util.Set sequenceSet ( int leftIndex = numberIndexQueue.remove (tailIndex); - java.lang.String combination = numberCombinationQueue.remove (tailIndex); + String combination = numberCombinationQueue.remove (tailIndex); if (leftIndex >= digitArray.length) { sequenceSet.add (combination); @@ -241,11 +251,11 @@ public java.util.Set sequenceSet ( int rightIndex = leftIndex; - while (rightIndex < digitArray.length && digitArray[leftIndex] == digitArray[rightIndex]) + while (rightIndex < digitArray.length && digitArray[leftIndex] == digitArray[rightIndex]) { ++rightIndex; + } - for (java.lang.String candidate : candidateCharacterSet (digitArray[leftIndex], rightIndex - - leftIndex)) { + for (String candidate : candidateCharacterSet (digitArray[leftIndex], rightIndex - leftIndex)) { numberIndexQueue.add (rightIndex); numberCombinationQueue.add (combination + candidate); @@ -261,7 +271,8 @@ public java.util.Set sequenceSet ( * @param args Input Arguments */ - public static final void main (String[] args) + public static final void main ( + final String[] argumentArray) { PhoneLetterCombinationGenerator phoneLetterCombinationGenerator = PhoneLetterCombinationGenerator.Standard();