001/* 002 * Copyright (C) 2016 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package com.google.common.graph; 018 019import static com.google.common.base.Preconditions.checkArgument; 020import static com.google.common.base.Preconditions.checkNotNull; 021import static com.google.common.graph.GraphConstants.ENDPOINTS_MISMATCH; 022import static com.google.common.graph.GraphConstants.MULTIPLE_EDGES_CONNECTING; 023import static java.util.Collections.unmodifiableSet; 024 025import com.google.common.annotations.Beta; 026import com.google.common.base.Function; 027import com.google.common.base.Predicate; 028import com.google.common.collect.ImmutableSet; 029import com.google.common.collect.Iterators; 030import com.google.common.collect.Maps; 031import com.google.common.collect.Sets; 032import com.google.common.math.IntMath; 033import java.util.AbstractSet; 034import java.util.Iterator; 035import java.util.Map; 036import java.util.Set; 037import org.checkerframework.checker.nullness.compatqual.NullableDecl; 038 039/** 040 * This class provides a skeletal implementation of {@link Network}. It is recommended to extend 041 * this class rather than implement {@link Network} directly. 042 * 043 * <p>The methods implemented in this class should not be overridden unless the subclass admits a 044 * more efficient implementation. 045 * 046 * @author James Sexton 047 * @param <N> Node parameter type 048 * @param <E> Edge parameter type 049 * @since 20.0 050 */ 051@Beta 052public abstract class AbstractNetwork<N, E> implements Network<N, E> { 053 054 @Override 055 public Graph<N> asGraph() { 056 return new AbstractGraph<N>() { 057 @Override 058 public Set<N> nodes() { 059 return AbstractNetwork.this.nodes(); 060 } 061 062 @Override 063 public Set<EndpointPair<N>> edges() { 064 if (allowsParallelEdges()) { 065 return super.edges(); // Defer to AbstractGraph implementation. 066 } 067 068 // Optimized implementation assumes no parallel edges (1:1 edge to EndpointPair mapping). 069 return new AbstractSet<EndpointPair<N>>() { 070 @Override 071 public Iterator<EndpointPair<N>> iterator() { 072 return Iterators.transform( 073 AbstractNetwork.this.edges().iterator(), 074 new Function<E, EndpointPair<N>>() { 075 @Override 076 public EndpointPair<N> apply(E edge) { 077 return incidentNodes(edge); 078 } 079 }); 080 } 081 082 @Override 083 public int size() { 084 return AbstractNetwork.this.edges().size(); 085 } 086 087 // Mostly safe: We check contains(u) before calling successors(u), so we perform unsafe 088 // operations only in weird cases like checking for an EndpointPair<ArrayList> in a 089 // Network<LinkedList>. 090 @SuppressWarnings("unchecked") 091 @Override 092 public boolean contains(@NullableDecl Object obj) { 093 if (!(obj instanceof EndpointPair)) { 094 return false; 095 } 096 EndpointPair<?> endpointPair = (EndpointPair<?>) obj; 097 return isOrderingCompatible(endpointPair) 098 && nodes().contains(endpointPair.nodeU()) 099 && successors((N) endpointPair.nodeU()).contains(endpointPair.nodeV()); 100 } 101 }; 102 } 103 104 @Override 105 public ElementOrder<N> nodeOrder() { 106 return AbstractNetwork.this.nodeOrder(); 107 } 108 109 @Override 110 public ElementOrder<N> incidentEdgeOrder() { 111 // TODO(b/142723300): Return AbstractNetwork.this.incidentEdgeOrder() once Network has that 112 // method. 113 return ElementOrder.unordered(); 114 } 115 116 @Override 117 public boolean isDirected() { 118 return AbstractNetwork.this.isDirected(); 119 } 120 121 @Override 122 public boolean allowsSelfLoops() { 123 return AbstractNetwork.this.allowsSelfLoops(); 124 } 125 126 @Override 127 public Set<N> adjacentNodes(N node) { 128 return AbstractNetwork.this.adjacentNodes(node); 129 } 130 131 @Override 132 public Set<N> predecessors(N node) { 133 return AbstractNetwork.this.predecessors(node); 134 } 135 136 @Override 137 public Set<N> successors(N node) { 138 return AbstractNetwork.this.successors(node); 139 } 140 141 // DO NOT override the AbstractGraph *degree() implementations. 142 }; 143 } 144 145 @Override 146 public int degree(N node) { 147 if (isDirected()) { 148 return IntMath.saturatedAdd(inEdges(node).size(), outEdges(node).size()); 149 } else { 150 return IntMath.saturatedAdd(incidentEdges(node).size(), edgesConnecting(node, node).size()); 151 } 152 } 153 154 @Override 155 public int inDegree(N node) { 156 return isDirected() ? inEdges(node).size() : degree(node); 157 } 158 159 @Override 160 public int outDegree(N node) { 161 return isDirected() ? outEdges(node).size() : degree(node); 162 } 163 164 @Override 165 public Set<E> adjacentEdges(E edge) { 166 EndpointPair<N> endpointPair = incidentNodes(edge); // Verifies that edge is in this network. 167 Set<E> endpointPairIncidentEdges = 168 Sets.union(incidentEdges(endpointPair.nodeU()), incidentEdges(endpointPair.nodeV())); 169 return Sets.difference(endpointPairIncidentEdges, ImmutableSet.of(edge)); 170 } 171 172 @Override 173 public Set<E> edgesConnecting(N nodeU, N nodeV) { 174 Set<E> outEdgesU = outEdges(nodeU); 175 Set<E> inEdgesV = inEdges(nodeV); 176 return outEdgesU.size() <= inEdgesV.size() 177 ? unmodifiableSet(Sets.filter(outEdgesU, connectedPredicate(nodeU, nodeV))) 178 : unmodifiableSet(Sets.filter(inEdgesV, connectedPredicate(nodeV, nodeU))); 179 } 180 181 @Override 182 public Set<E> edgesConnecting(EndpointPair<N> endpoints) { 183 validateEndpoints(endpoints); 184 return edgesConnecting(endpoints.nodeU(), endpoints.nodeV()); 185 } 186 187 private Predicate<E> connectedPredicate(final N nodePresent, final N nodeToCheck) { 188 return new Predicate<E>() { 189 @Override 190 public boolean apply(E edge) { 191 return incidentNodes(edge).adjacentNode(nodePresent).equals(nodeToCheck); 192 } 193 }; 194 } 195 196 @Override 197 @NullableDecl 198 public E edgeConnectingOrNull(N nodeU, N nodeV) { 199 Set<E> edgesConnecting = edgesConnecting(nodeU, nodeV); 200 switch (edgesConnecting.size()) { 201 case 0: 202 return null; 203 case 1: 204 return edgesConnecting.iterator().next(); 205 default: 206 throw new IllegalArgumentException(String.format(MULTIPLE_EDGES_CONNECTING, nodeU, nodeV)); 207 } 208 } 209 210 @Override 211 @NullableDecl 212 public E edgeConnectingOrNull(EndpointPair<N> endpoints) { 213 validateEndpoints(endpoints); 214 return edgeConnectingOrNull(endpoints.nodeU(), endpoints.nodeV()); 215 } 216 217 @Override 218 public boolean hasEdgeConnecting(N nodeU, N nodeV) { 219 checkNotNull(nodeU); 220 checkNotNull(nodeV); 221 return nodes().contains(nodeU) && successors(nodeU).contains(nodeV); 222 } 223 224 @Override 225 public boolean hasEdgeConnecting(EndpointPair<N> endpoints) { 226 checkNotNull(endpoints); 227 if (!isOrderingCompatible(endpoints)) { 228 return false; 229 } 230 return hasEdgeConnecting(endpoints.nodeU(), endpoints.nodeV()); 231 } 232 233 /** 234 * Throws an IllegalArgumentException if the ordering of {@code endpoints} is not compatible with 235 * the directionality of this graph. 236 */ 237 protected final void validateEndpoints(EndpointPair<?> endpoints) { 238 checkNotNull(endpoints); 239 checkArgument(isOrderingCompatible(endpoints), ENDPOINTS_MISMATCH); 240 } 241 242 protected final boolean isOrderingCompatible(EndpointPair<?> endpoints) { 243 return endpoints.isOrdered() || !this.isDirected(); 244 } 245 246 @Override 247 public final boolean equals(@NullableDecl Object obj) { 248 if (obj == this) { 249 return true; 250 } 251 if (!(obj instanceof Network)) { 252 return false; 253 } 254 Network<?, ?> other = (Network<?, ?>) obj; 255 256 return isDirected() == other.isDirected() 257 && nodes().equals(other.nodes()) 258 && edgeIncidentNodesMap(this).equals(edgeIncidentNodesMap(other)); 259 } 260 261 @Override 262 public final int hashCode() { 263 return edgeIncidentNodesMap(this).hashCode(); 264 } 265 266 /** Returns a string representation of this network. */ 267 @Override 268 public String toString() { 269 return "isDirected: " 270 + isDirected() 271 + ", allowsParallelEdges: " 272 + allowsParallelEdges() 273 + ", allowsSelfLoops: " 274 + allowsSelfLoops() 275 + ", nodes: " 276 + nodes() 277 + ", edges: " 278 + edgeIncidentNodesMap(this); 279 } 280 281 private static <N, E> Map<E, EndpointPair<N>> edgeIncidentNodesMap(final Network<N, E> network) { 282 Function<E, EndpointPair<N>> edgeToIncidentNodesFn = 283 new Function<E, EndpointPair<N>>() { 284 @Override 285 public EndpointPair<N> apply(E edge) { 286 return network.incidentNodes(edge); 287 } 288 }; 289 return Maps.asMap(network.edges(), edgeToIncidentNodesFn); 290 } 291}