├── .gitignore ├── LICENSE.txt ├── README.md ├── build.sbt └── src ├── main └── scala │ └── soal │ ├── fastppr │ ├── FastPPR.scala │ └── FastPPRConfiguration.scala │ └── util │ └── MappedPriorityQueue.scala └── test ├── resources ├── test_graph.txt └── test_graph_true_pprs.txt └── scala └── soal ├── fastppr └── FastPPRSpec.scala └── util └── MappedPriorityQueueSpec.scala /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | *.log 3 | 4 | # sbt specific 5 | .cache/ 6 | .history/ 7 | .lib/ 8 | dist/* 9 | target/ 10 | lib_managed/ 11 | src_managed/ 12 | project/boot/ 13 | project/plugins/project/ 14 | 15 | # Scala-IDE specific 16 | .scala_dependencies 17 | .worksheet 18 | .idea/ 19 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | fast-ppr-scala 2 | ============== 3 | 4 | Personalized PageRank Algorithm described in the paper "FAST-PPR: Scaling Personalized PageRank Estimation for Large Graphs" 5 | -------------------------------------------------------------------------------- /build.sbt: -------------------------------------------------------------------------------- 1 | name := "fast-ppr" 2 | 3 | version := "1.0" 4 | 5 | libraryDependencies += "com.twitter" %% "cassovary" % "3.2.0" 6 | 7 | libraryDependencies += "org.scalatest" % "scalatest_2.10" % "2.0" % "test" -------------------------------------------------------------------------------- /src/main/scala/soal/fastppr/FastPPR.scala: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2014 Stanford Social Algorithms Lab 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package soal.fastppr 18 | 19 | import com.twitter.cassovary.graph.DirectedGraph 20 | import scala.collection.mutable 21 | import soal.util.HeapMappedPriorityQueue 22 | import scala.util.Random 23 | 24 | object FastPPR { 25 | 26 | /** Returns an estimate of ppr(start, target). Its accuracy depends on the parameters in config. If balanced is true, 27 | * it attempts to balanced forward and backward work to decrease running time without significantly changing the accuracy. 28 | */ 29 | def estimatePPR(graph: DirectedGraph, 30 | startId: Int, 31 | targetId: Int, 32 | config: FastPPRConfiguration, 33 | balanced: Boolean = true): Float = { 34 | val (inversePPREstimates, reversePPRSignificanceThreshold) = 35 | if (balanced) 36 | estimateInversePPRBalanced(graph, targetId, config) 37 | else { 38 | val reverseThreshold = math.sqrt(config.pprSignificanceThreshold).toFloat 39 | (estimateInversePPR(graph, targetId, config, config.reversePPRApproximationFactor * reverseThreshold), 40 | reverseThreshold) 41 | } 42 | val frontier = computeFrontier(graph, inversePPREstimates, reversePPRSignificanceThreshold) 43 | 44 | val forwardPPRSignificanceThreshold = config.pprSignificanceThreshold / reversePPRSignificanceThreshold 45 | 46 | val startNodeInTargetSet = (inversePPREstimates.getOrElse(startId, 0.0f) >= reversePPRSignificanceThreshold) 47 | if (startNodeInTargetSet || frontier.contains(startId)) 48 | return inversePPREstimates(startId) 49 | 50 | val pprEstimate = pprToFrontier(graph, startId, forwardPPRSignificanceThreshold, config, frontier, inversePPREstimates) 51 | 52 | pprEstimate 53 | } 54 | 55 | /** 56 | * Returns an estimate of the PPR from start to the frontier, using weights in inversePPREstimates. 57 | */ 58 | private def pprToFrontier(graph: DirectedGraph, 59 | startId: Int, 60 | forwardPPRSignificanceThreshold: Float, 61 | config: FastPPRConfiguration, 62 | frontier: mutable.Set[Int], 63 | inversePPREstimates: mutable.Map[Int, Float]): Float = { 64 | val walkCount = config.walkCount(forwardPPRSignificanceThreshold) 65 | var estimate = 0.0 66 | for (walkIndex <- 0 until walkCount) { 67 | var currentNode = graph.getNodeById(startId).get 68 | while (Random.nextFloat() > config.teleportProbability && 69 | currentNode.outboundCount > 0 && 70 | !frontier.contains(currentNode.id)) { 71 | currentNode = graph.getNodeById(currentNode.randomOutboundNode.get).get 72 | } 73 | if (frontier.contains(currentNode.id)) { 74 | estimate += 1.0 / walkCount * inversePPREstimates(currentNode.id) 75 | } 76 | 77 | } 78 | estimate.toFloat 79 | } 80 | 81 | def monteCarloPPR(graph: DirectedGraph, 82 | startId: Int, 83 | walkCount: Int, 84 | teleportProbability: Float): mutable.Map[Int, Float] = { 85 | 86 | var pprEstimates = mutable.HashMap[Int, Float]().withDefaultValue(0.0f) 87 | for (walkIndex <- 0 until walkCount) { 88 | var currentNode = graph.getNodeById(startId).get 89 | var hitDeadEnd = false 90 | while (Random.nextFloat() > teleportProbability && !hitDeadEnd) { 91 | if (currentNode.outboundCount > 0) { 92 | currentNode = graph.getNodeById(currentNode.randomOutboundNode.get).get 93 | } else { 94 | hitDeadEnd = true 95 | } 96 | } 97 | if (!hitDeadEnd) { 98 | pprEstimates(currentNode.id) += 1.0f / walkCount 99 | } 100 | } 101 | pprEstimates 102 | } 103 | 104 | /** Returns a map from nodeId to ppr(node, target) up to a fixed additive accuracy pprErrorTolerance. */ 105 | def estimateInversePPR( 106 | graph: DirectedGraph, 107 | targetId: Int, 108 | config: FastPPRConfiguration, 109 | pprErrorTolerance: Float): mutable.Map[Int, Float] = { 110 | // Use ArrayDequeue because it is more efficient than the linked-list based mutable.Queue 111 | val largeResidualNodes = new java.util.ArrayDeque[Int]() 112 | largeResidualNodes.add(targetId) 113 | 114 | // inversePPREstimates(uId) estimates ppr(u, target) 115 | val inversePPREstimates = mutable.HashMap[Int, Float]().withDefaultValue(0.0f) 116 | val inversePPRResiduals = mutable.HashMap[Int, Float]().withDefaultValue(0.0f) 117 | inversePPREstimates(targetId) = config.teleportProbability 118 | inversePPRResiduals(targetId) = config.teleportProbability 119 | 120 | val largeResidualThreshold = pprErrorTolerance * config.teleportProbability // inversePPRResiduals about this must be enqueued and pushed 121 | 122 | while (!largeResidualNodes.isEmpty) { 123 | val vId = largeResidualNodes.pollFirst() 124 | val vResidual = inversePPRResiduals(vId) 125 | inversePPRResiduals(vId) = 0.0f 126 | val v = graph.getNodeById(vId).get 127 | for (uId <- v.inboundNodes()) { 128 | val u = graph.getNodeById(uId).get 129 | val deltaPriority = (1.0f - config.teleportProbability) / u.outboundCount * vResidual 130 | inversePPRResiduals(uId) += deltaPriority 131 | inversePPREstimates(uId) += deltaPriority 132 | if (inversePPRResiduals(uId) >= largeResidualThreshold && inversePPRResiduals(uId) - deltaPriority < largeResidualThreshold) 133 | largeResidualNodes.add(uId) 134 | 135 | } 136 | } 137 | 138 | debias(graph, config, inversePPREstimates, pprErrorTolerance / config.reversePPRApproximationFactor, pprErrorTolerance) 139 | 140 | inversePPREstimates 141 | } 142 | 143 | 144 | /** Computes inversePPR to the target up to a dynamic accuracy with the goal of balancing forward and reverse work. 145 | * @return (inversePPREstimates, reversePPRSignificanceThreshold) 146 | */ 147 | def estimateInversePPRBalanced( 148 | graph: DirectedGraph, 149 | targetId: Int, 150 | config: FastPPRConfiguration): (mutable.Map[Int, Float], Float) = { 151 | val inversePPRResiduals = new HeapMappedPriorityQueue[Int]() 152 | val inversePPREstimates = mutable.HashMap[Int, Float]().withDefaultValue(0.0f) // inversePPREstimates(uId) estimates ppr(u, target) 153 | inversePPRResiduals.insert(targetId, config.teleportProbability) 154 | inversePPREstimates(targetId) = config.teleportProbability 155 | 156 | var reverseSteps = 0L 157 | 158 | def predictedForwardSteps(largestResidual: Float): Long = { 159 | val reverseThreshold = largestResidual / config.teleportProbability / config.reversePPRApproximationFactor 160 | if (reverseThreshold < config.pprSignificanceThreshold) 161 | return 0 // avoid division by 0 if reversePPRThreshold==0.0f 162 | else { 163 | val forwardThreshold = config.pprSignificanceThreshold / reverseThreshold 164 | (config.walkCount(forwardThreshold) / config.teleportProbability).toLong 165 | } 166 | } 167 | 168 | while( !inversePPRResiduals.isEmpty && 169 | predictedForwardSteps(inversePPRResiduals.maxPriority) * config.forwardStepsPerReverseStep >= reverseSteps) { 170 | val vPriority = inversePPRResiduals.maxPriority 171 | val vId = inversePPRResiduals.extractMax() 172 | val v = graph.getNodeById(vId).get 173 | for (uId <- v.inboundNodes()) { 174 | val u = graph.getNodeById(uId).get 175 | val deltaPriority = (1.0f - config.teleportProbability) / u.outboundCount * vPriority 176 | if (! inversePPRResiduals.contains(uId)) { 177 | inversePPRResiduals.insert(uId, 0.0f) 178 | } 179 | inversePPRResiduals.increasePriority(uId, inversePPRResiduals.getPriority(uId) + deltaPriority) 180 | inversePPREstimates(uId) = inversePPREstimates.getOrElse(uId, 0.0f) + deltaPriority 181 | reverseSteps += 1 182 | } 183 | } 184 | val pprErrorTolerance = 185 | if(inversePPRResiduals.isEmpty) 186 | 0.0f 187 | else 188 | inversePPRResiduals.maxPriority / config.teleportProbability 189 | val reversePPRSignificanceThreshold = pprErrorTolerance / config.reversePPRApproximationFactor 190 | 191 | debias(graph, config, inversePPREstimates, reversePPRSignificanceThreshold, pprErrorTolerance) 192 | 193 | (inversePPREstimates, reversePPRSignificanceThreshold) 194 | } 195 | 196 | /** 197 | * Modifies inversePPREstimates to remove the negative bias. 198 | * Given estimates are within an interval 199 | * estimate <= trueValue <= estimate + pprErrorTolerance 200 | * This function heuristically centers the estimates in the target set, and propagates those new estimates to the frontier. 201 | */ 202 | 203 | def debias( 204 | graph: DirectedGraph, 205 | config: FastPPRConfiguration, 206 | inversePPREstimates: mutable.Map[Int, Float], 207 | reversePPRSignificanceThreshold: Float, 208 | pprErrorTolerance: Float) { 209 | for (vId <- inversePPREstimates.keysIterator 210 | if inversePPREstimates(vId) > reversePPRSignificanceThreshold) { 211 | inversePPREstimates(vId) += pprErrorTolerance / 2.0f 212 | val v = graph.getNodeById(vId).get 213 | for (uId <- v.inboundNodes()) { 214 | val u = graph.getNodeById(uId).get 215 | inversePPREstimates(uId) += (1.0f - config.teleportProbability) / u.outboundCount * pprErrorTolerance / 2.0f 216 | } 217 | } 218 | } 219 | 220 | /** Returns the set of nodes with some out-neighbor in the target set (those nodes v with 221 | * ppr(v, target) > reversePPRSignificanceThreshold) 222 | */ 223 | 224 | def computeFrontier( 225 | graph: DirectedGraph, 226 | inversePPREstimates: mutable.Map[Int, Float], 227 | reversePPRSignificanceThreshold: Float): mutable.Set[Int] = { 228 | val frontier = new mutable.HashSet[Int]() 229 | for (vId <- inversePPREstimates.keysIterator) { 230 | val vInTargetSet = (inversePPREstimates(vId) >= reversePPRSignificanceThreshold) 231 | if (vInTargetSet) { 232 | val v = graph.getNodeById(vId).get 233 | for (uId <- v.inboundNodes()) { 234 | frontier.add(uId) 235 | } 236 | } 237 | } 238 | frontier 239 | } 240 | } -------------------------------------------------------------------------------- /src/main/scala/soal/fastppr/FastPPRConfiguration.scala: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2014 Stanford Social Algorithms Lab 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package soal.fastppr 18 | 19 | case class FastPPRConfiguration( 20 | teleportProbability: Float, 21 | /** In forward work, we will do nWalksConstant / forwardPPRSignificanceThreshold walks. */ 22 | nWalksConstant : Float, 23 | /** In reverse PPR computation, our additive bound is 24 | * reversePPRApproximationFactor * reversePPRSignificanceThreshold. 25 | * (beta in paper) */ 26 | reversePPRApproximationFactor: Float, 27 | /** PPR values above this threshold will be detected by Fast-PPR. 28 | * (delta in paper)*/ 29 | pprSignificanceThreshold: Float, 30 | /** The number of average forward steps (random edge visit) we can do 31 | * in the time it takes to do one average reverse step (priority queue update). 32 | * TODO(some automating tuning option)*/ 33 | forwardStepsPerReverseStep: Float 34 | ) { 35 | def walkCount(forwardPPRSignificanceThreshold: Float): Int = (nWalksConstant / forwardPPRSignificanceThreshold).toInt 36 | } 37 | 38 | object FastPPRConfiguration { 39 | val defaultConfiguration = FastPPRConfiguration( 40 | teleportProbability=0.2f, 41 | nWalksConstant=24 * math.log(1.0e6).toFloat, 42 | reversePPRApproximationFactor=1.0f / 6.0f, 43 | pprSignificanceThreshold=1.0e-6f, 44 | forwardStepsPerReverseStep=6.7f) 45 | } -------------------------------------------------------------------------------- /src/main/scala/soal/util/MappedPriorityQueue.scala: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2014 Stanford Social Algorithms Lab 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package soal.util 18 | 19 | import java.util.NoSuchElementException 20 | import scala.collection.mutable.ArrayBuffer 21 | import scala.collection.mutable 22 | 23 | /** A max prioity queue with the additional property that it is possible to increase and look-up 24 | * the priority of elements. 25 | * 26 | */ 27 | trait MappedPriorityQueue[A] { 28 | def insert(a: A, priority: Float): Unit 29 | def contains(a: A): Boolean 30 | def increasePriority(a: A, newPriority: Float): Unit 31 | def getPriority(a: A): Float // Returns 0.0 if a is not in the queue 32 | def maxPriority: Float 33 | def extractMax(): A 34 | def isEmpty: Boolean 35 | } 36 | 37 | /** Standard binary heap, based on Chapter 6 of CLRS Algorithms 2nd Ed. 38 | * */ 39 | class HeapMappedPriorityQueue[A] extends MappedPriorityQueue[A] { 40 | 41 | private val priorities = ArrayBuffer[Float](0.0f) //the first entry will be ignored to make arithmetic simpler 42 | 43 | private val itemToIndex = mutable.HashMap[A, Int]() 44 | private val indexToItem = ArrayBuffer[A](null.asInstanceOf[A]) //the first entry will be ignored to make arithmetic simpler 45 | 46 | private def parent(i: Int) = i / 2 47 | private def left(i: Int) = i * 2 48 | private def right(i: Int) = i * 2 + 1 49 | 50 | private def swap(i: Int, j: Int): Unit = { 51 | val temp = priorities(i) 52 | priorities(i) = priorities(j) 53 | priorities(j) = temp 54 | 55 | val itemI = indexToItem(i) 56 | val itemJ = indexToItem(j) 57 | itemToIndex(itemI) = j 58 | itemToIndex(itemJ) = i 59 | indexToItem(i) = itemJ 60 | indexToItem(j) = itemI 61 | } 62 | 63 | /** 64 | If the max-heap invariant is satisfied except for index i possibly being smaller than a child, restore the invariant. 65 | */ 66 | private def maxHeapify(i: Int): Unit = { 67 | var largest = i 68 | if (left(i) < priorities.size && priorities(left(i)) > priorities(i)) { 69 | largest = left(i) 70 | } 71 | if (right(i) < priorities.size && priorities(right(i)) > priorities(largest)) { 72 | largest = right(i) 73 | } 74 | if (largest != i) { 75 | swap(i, largest) 76 | maxHeapify(largest) 77 | } 78 | } 79 | 80 | override def insert(a: A, priority: Float): Unit = { 81 | itemToIndex(a) = indexToItem.size 82 | indexToItem.append(a) 83 | priorities.append(Float.NegativeInfinity) 84 | increasePriority(a, priority) 85 | } 86 | 87 | override def isEmpty: Boolean = { 88 | indexToItem.size == 1 // first entry is dummy entry 89 | } 90 | 91 | override def extractMax(): A = { 92 | if (isEmpty) 93 | throw new NoSuchElementException 94 | val maxItem = indexToItem(1) 95 | swap(1, priorities.size - 1) 96 | priorities.remove(priorities.size - 1) 97 | indexToItem.remove(indexToItem.size - 1) 98 | itemToIndex.remove(maxItem) 99 | 100 | maxHeapify(1) 101 | maxItem 102 | } 103 | 104 | override def maxPriority: Float = { 105 | if (isEmpty) 106 | throw new NoSuchElementException 107 | priorities(1) 108 | } 109 | 110 | override def getPriority(a: A): Float = { 111 | itemToIndex.get(a) match { 112 | case Some(i) => priorities(i) 113 | case None => 0.0f // Default priority is 0.0 114 | } 115 | } 116 | 117 | override def increasePriority(a: A, newPriority: Float): Unit = { 118 | assert(newPriority >= getPriority(a)) 119 | var i = itemToIndex(a) 120 | priorities(i) = newPriority 121 | while (i > 1 && priorities(i) > priorities(parent(i))) { 122 | swap(i, parent(i)) 123 | i = parent(i) 124 | } 125 | } 126 | 127 | override def contains(a: A): Boolean = itemToIndex.contains(a) 128 | } -------------------------------------------------------------------------------- /src/test/resources/test_graph.txt: -------------------------------------------------------------------------------- 1 | 0 2 2 | 1 3 | 2 4 | 1 2 5 | 0 6 | 2 7 | 2 4 8 | 0 9 | 1 10 | 3 11 | 9 12 | 3 1 13 | 0 14 | 9 1 15 | 0 16 | 4 2 17 | 2 18 | 3 19 | 5 2 20 | 3 21 | 4 22 | 6 2 23 | 1 24 | 3 25 | 7 2 26 | 0 27 | 5 28 | 8 2 29 | 2 30 | 3 31 | -------------------------------------------------------------------------------- /src/test/resources/test_graph_true_pprs.txt: -------------------------------------------------------------------------------- 1 | 0 0 0.421245 2 | 1 0 0.278388 3 | 2 0 0.274725 4 | 3 0 0.336996 5 | 7 0 0.261568 6 | 9 0 0.336996 7 | 4 0 0.244689 8 | 5 0 0.232674 9 | 6 0 0.246154 10 | 8 0 0.244689 11 | 1 1 0.362637 12 | 0 1 0.21978 13 | 2 1 0.186813 14 | 6 1 0.215385 15 | 3 1 0.175824 16 | 7 1 0.139253 17 | 9 1 0.175824 18 | 4 1 0.145055 19 | 5 1 0.128352 20 | 8 1 0.145055 21 | 2 2 0.384615 22 | 0 2 0.25641 23 | 1 2 0.25641 24 | 4 2 0.235897 25 | 8 2 0.235897 26 | 3 2 0.205128 27 | 7 2 0.173128 28 | 9 2 0.205128 29 | 6 2 0.184615 30 | 5 2 0.17641 31 | 3 3 0.241026 32 | 2 3 0.0769231 33 | 4 3 0.127179 34 | 5 3 0.147282 35 | 6 3 0.116923 36 | 8 3 0.127179 37 | 7 3 0.0794256 38 | 0 3 0.0512821 39 | 1 3 0.0512821 40 | 9 3 0.0410256 41 | 9 9 0.241026 42 | 2 9 0.0769231 43 | 0 9 0.0512821 44 | 1 9 0.0512821 45 | 4 9 0.0471795 46 | 8 9 0.0471795 47 | 3 9 0.0410256 48 | 7 9 0.0346256 49 | 6 9 0.0369231 50 | 5 9 0.0352821 51 | 4 4 0.2 52 | 5 4 0.08 53 | 7 4 0.032 54 | 5 5 0.2 55 | 7 5 0.08 56 | 6 6 0.2 57 | 7 7 0.2 58 | 8 8 0.2 -------------------------------------------------------------------------------- /src/test/scala/soal/fastppr/FastPPRSpec.scala: -------------------------------------------------------------------------------- 1 | package soal.fastppr 2 | 3 | import com.twitter.cassovary.graph.{DirectedGraph, StoredGraphDir} 4 | import com.twitter.cassovary.graph.StoredGraphDir.StoredGraphDir 5 | import org.scalatest.{Matchers, FlatSpec} 6 | import com.twitter.cassovary.util.io.AdjacencyListGraphReader 7 | import scala.io.Source 8 | 9 | class FastPPRSpec extends FlatSpec with Matchers { 10 | 11 | val reader = new AdjacencyListGraphReader("src/test/resources/", "test_graph.txt") { 12 | override def storedGraphDir: StoredGraphDir = StoredGraphDir.BothInOut 13 | } 14 | val graph = reader.toArrayBasedDirectedGraph() 15 | 16 | "FastPPR.frontier" should "be correct on the test graph" in { 17 | val config = FastPPRConfiguration.defaultConfiguration 18 | val pprErrorTolerance = 2.0e-6f 19 | for (line <- Source.fromFile("src/test/resources/test_graph_true_pprs.txt").getLines()) { 20 | val pieces = line.split("\t") 21 | val (startId, targetId, truePPR) = (pieces(0).toInt, pieces(1).toInt, pieces(2).toFloat) 22 | val inversePPRs = FastPPR.estimateInversePPR(graph, targetId, config, pprErrorTolerance) 23 | withClue ("(%d, %d)".format(startId, targetId)) {inversePPRs(startId) should equal (truePPR +- pprErrorTolerance)} 24 | } 25 | } 26 | 27 | "FastPPR.frontierBalanced" should "be correct on the test graph" in { 28 | var config = FastPPRConfiguration.defaultConfiguration 29 | config = config.copy(pprSignificanceThreshold = 1.0e-16f) // Choose tiny significance value to test correctness 30 | val pprErrorTolerance = 2.0e-6f 31 | for (line <- Source.fromFile("src/test/resources/test_graph_true_pprs.txt").getLines()) { 32 | val pieces = line.split("\t") 33 | val (startId, targetId, truePPR) = (pieces(0).toInt, pieces(1).toInt, pieces(2).toFloat) 34 | val (inversePPRs, epsilonR) = FastPPR.estimateInversePPRBalanced(graph, targetId, config) 35 | withClue ("(%d, %d)".format(startId, targetId)) {inversePPRs(startId) should equal (truePPR +- pprErrorTolerance)} 36 | } 37 | } 38 | 39 | "FastPPR.estimatePPR" should "be approximately correct on the test graph" in { 40 | var config = FastPPRConfiguration.defaultConfiguration 41 | config = config.copy(pprSignificanceThreshold = 0.03f) // smallested true PPR on test graph is 0.03 42 | val approximationRatio = 1.4f 43 | for (line <- Source.fromFile("src/test/resources/test_graph_true_pprs.txt").getLines()) { 44 | val pieces = line.split("\t") 45 | val (startId, targetId, truePPR) = (pieces(0).toInt, pieces(1).toInt, pieces(2).toFloat) 46 | for (balanced <- List(false, true)) { 47 | val estimate = FastPPR.estimatePPR(graph, startId, targetId, config, balanced) 48 | withClue("(%d, %d)".format(startId, targetId)) { 49 | assert(estimate > truePPR / approximationRatio) 50 | } 51 | withClue("(%d, %d)".format(startId, targetId)) { 52 | assert(estimate < truePPR * approximationRatio) 53 | } 54 | } 55 | } 56 | } 57 | 58 | } 59 | -------------------------------------------------------------------------------- /src/test/scala/soal/util/MappedPriorityQueueSpec.scala: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2014 Stanford Social Algorithms Lab 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | */ 16 | 17 | package soal.util 18 | 19 | import java.util.NoSuchElementException 20 | import org.scalatest.FlatSpec 21 | 22 | class MappedPriorityQueueSpec extends FlatSpec { 23 | "A MappedPriorityQueueSpec" should "store priorities" in { 24 | val q = new HeapMappedPriorityQueue[String] 25 | q.insert("one", 1.0f) 26 | assert(q.getPriority("one") == 1.0f) 27 | } 28 | 29 | it should "store give default priority 0.0" in { 30 | val q = new HeapMappedPriorityQueue[String] 31 | q.insert("one", 1.0f) 32 | assert(q.getPriority("new") == 0.0f) 33 | } 34 | 35 | it should "sort items" in { 36 | val q = new HeapMappedPriorityQueue[String] 37 | q.insert("two", 2.0f) 38 | q.insert("one", 1.0f) 39 | q.insert("negFive", -5.0f) 40 | q.insert("four", 4.0f) 41 | q.insert("three", 3.0f) 42 | assert(q.maxPriority == 4.0f) 43 | assert(q.extractMax() == "four") 44 | assert(q.extractMax() == "three") 45 | assert(q.extractMax() == "two") 46 | assert(q.extractMax() == "one") 47 | assert(q.extractMax() == "negFive") 48 | assert(q.isEmpty) 49 | //intecept[NoSuchElementException] { 50 | // q.extractMax() 51 | //} 52 | } 53 | it should "sort items respecting increased priorities" in { 54 | val q = new HeapMappedPriorityQueue[String] 55 | q.insert("two", 0.5f) 56 | q.insert("one", 1.0f) 57 | q.insert("four", 0.04f) 58 | q.insert("three", 0.3f) 59 | assert(q.maxPriority == 1.0f) 60 | q.increasePriority("two", 2.0f) 61 | q.increasePriority("four", 4.0f) 62 | q.increasePriority("three", 3.0f) 63 | assert(q.getPriority("three") == 3.0f) 64 | assert(q.maxPriority == 4.0f) 65 | assert(q.extractMax() == "four") 66 | assert(q.extractMax() == "three") 67 | assert(q.extractMax() == "two") 68 | assert(q.extractMax() == "one") 69 | assert(q.isEmpty) 70 | //intecept[NoSuchElementException] { 71 | // q.extractMax() 72 | //} 73 | } 74 | } 75 | --------------------------------------------------------------------------------