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.graph.GraphConstants.MULTIPLE_EDGES_CONNECTING; 020import static java.util.Collections.unmodifiableSet; 021 022import com.google.common.annotations.Beta; 023import com.google.common.annotations.GwtIncompatible; 024import com.google.common.base.Function; 025import com.google.common.base.Predicate; 026import com.google.common.collect.ImmutableSet; 027import com.google.common.collect.Iterators; 028import com.google.common.collect.Maps; 029import com.google.common.collect.Sets; 030import com.google.common.math.IntMath; 031import java.util.AbstractSet; 032import java.util.Iterator; 033import java.util.Map; 034import java.util.Set; 035import javax.annotation.Nullable; 036 037/** 038 * This class provides a skeletal implementation of {@link Network}. It is recommended to extend 039 * this class rather than implement {@link Network} directly. 040 * 041 * <p>The methods implemented in this class should not be overridden unless the subclass admits a 042 * more efficient implementation. 043 * 044 * @author James Sexton 045 * @param <N> Node parameter type 046 * @param <E> Edge parameter type 047 * @since 20.0 048 */ 049@Beta 050@GwtIncompatible 051public abstract class AbstractNetwork<N, E> implements Network<N, E> { 052 053 @Override 054 public Graph<N> asGraph() { 055 return new AbstractGraph<N>() { 056 @Override 057 public Set<N> nodes() { 058 return AbstractNetwork.this.nodes(); 059 } 060 061 @Override 062 public Set<EndpointPair<N>> edges() { 063 if (allowsParallelEdges()) { 064 return super.edges(); // Defer to AbstractGraph implementation. 065 } 066 067 // Optimized implementation assumes no parallel edges (1:1 edge to EndpointPair mapping). 068 return new AbstractSet<EndpointPair<N>>() { 069 @Override 070 public Iterator<EndpointPair<N>> iterator() { 071 return Iterators.transform( 072 AbstractNetwork.this.edges().iterator(), 073 new Function<E, EndpointPair<N>>() { 074 @Override 075 public EndpointPair<N> apply(E edge) { 076 return incidentNodes(edge); 077 } 078 }); 079 } 080 081 @Override 082 public int size() { 083 return AbstractNetwork.this.edges().size(); 084 } 085 086 // Mostly safe: We check contains(u) before calling successors(u), so we perform unsafe 087 // operations only in weird cases like checking for an EndpointPair<ArrayList> in a 088 // Network<LinkedList>. 089 @SuppressWarnings("unchecked") 090 @Override 091 public boolean contains(@Nullable Object obj) { 092 if (!(obj instanceof EndpointPair)) { 093 return false; 094 } 095 EndpointPair<?> endpointPair = (EndpointPair<?>) obj; 096 return isDirected() == endpointPair.isOrdered() 097 && nodes().contains(endpointPair.nodeU()) 098 && successors((N) endpointPair.nodeU()).contains(endpointPair.nodeV()); 099 } 100 }; 101 } 102 103 @Override 104 public ElementOrder<N> nodeOrder() { 105 return AbstractNetwork.this.nodeOrder(); 106 } 107 108 @Override 109 public boolean isDirected() { 110 return AbstractNetwork.this.isDirected(); 111 } 112 113 @Override 114 public boolean allowsSelfLoops() { 115 return AbstractNetwork.this.allowsSelfLoops(); 116 } 117 118 @Override 119 public Set<N> adjacentNodes(N node) { 120 return AbstractNetwork.this.adjacentNodes(node); 121 } 122 123 @Override 124 public Set<N> predecessors(N node) { 125 return AbstractNetwork.this.predecessors(node); 126 } 127 128 @Override 129 public Set<N> successors(N node) { 130 return AbstractNetwork.this.successors(node); 131 } 132 133 // DO NOT override the AbstractGraph *degree() implementations. 134 }; 135 } 136 137 @Override 138 public int degree(N node) { 139 if (isDirected()) { 140 return IntMath.saturatedAdd(inEdges(node).size(), outEdges(node).size()); 141 } else { 142 return IntMath.saturatedAdd(incidentEdges(node).size(), edgesConnecting(node, node).size()); 143 } 144 } 145 146 @Override 147 public int inDegree(N node) { 148 return isDirected() ? inEdges(node).size() : degree(node); 149 } 150 151 @Override 152 public int outDegree(N node) { 153 return isDirected() ? outEdges(node).size() : degree(node); 154 } 155 156 @Override 157 public Set<E> adjacentEdges(E edge) { 158 EndpointPair<N> endpointPair = incidentNodes(edge); // Verifies that edge is in this network. 159 Set<E> endpointPairIncidentEdges = 160 Sets.union(incidentEdges(endpointPair.nodeU()), incidentEdges(endpointPair.nodeV())); 161 return Sets.difference(endpointPairIncidentEdges, ImmutableSet.of(edge)); 162 } 163 164 @Override 165 public Set<E> edgesConnecting(N nodeU, N nodeV) { 166 Set<E> outEdgesU = outEdges(nodeU); 167 Set<E> inEdgesV = inEdges(nodeV); 168 return outEdgesU.size() <= inEdgesV.size() 169 ? unmodifiableSet(Sets.filter(outEdgesU, connectedPredicate(nodeU, nodeV))) 170 : unmodifiableSet(Sets.filter(inEdgesV, connectedPredicate(nodeV, nodeU))); 171 } 172 173 private Predicate<E> connectedPredicate(final N nodePresent, final N nodeToCheck) { 174 return new Predicate<E>() { 175 @Override 176 public boolean apply(E edge) { 177 return incidentNodes(edge).adjacentNode(nodePresent).equals(nodeToCheck); 178 } 179 }; 180 } 181 182 @Override 183 @Nullable 184 public E edgeConnectingOrNull(N nodeU, N nodeV) { 185 Set<E> edgesConnecting = edgesConnecting(nodeU, nodeV); 186 switch (edgesConnecting.size()) { 187 case 0: 188 return null; 189 case 1: 190 return edgesConnecting.iterator().next(); 191 default: 192 throw new IllegalArgumentException(String.format(MULTIPLE_EDGES_CONNECTING, nodeU, nodeV)); 193 } 194 } 195 196 @Override 197 public boolean hasEdgeConnecting(N nodeU, N nodeV) { 198 return !edgesConnecting(nodeU, nodeV).isEmpty(); 199 } 200 201 @Override 202 public final boolean equals(@Nullable Object obj) { 203 if (obj == this) { 204 return true; 205 } 206 if (!(obj instanceof Network)) { 207 return false; 208 } 209 Network<?, ?> other = (Network<?, ?>) obj; 210 211 return isDirected() == other.isDirected() 212 && nodes().equals(other.nodes()) 213 && edgeIncidentNodesMap(this).equals(edgeIncidentNodesMap(other)); 214 } 215 216 @Override 217 public final int hashCode() { 218 return edgeIncidentNodesMap(this).hashCode(); 219 } 220 221 /** Returns a string representation of this network. */ 222 @Override 223 public String toString() { 224 return "isDirected: " 225 + isDirected() 226 + ", allowsParallelEdges: " 227 + allowsParallelEdges() 228 + ", allowsSelfLoops: " 229 + allowsSelfLoops() 230 + ", nodes: " 231 + nodes() 232 + ", edges: " 233 + edgeIncidentNodesMap(this); 234 } 235 236 private static <N, E> Map<E, EndpointPair<N>> edgeIncidentNodesMap(final Network<N, E> network) { 237 Function<E, EndpointPair<N>> edgeToIncidentNodesFn = 238 new Function<E, EndpointPair<N>>() { 239 @Override 240 public EndpointPair<N> apply(E edge) { 241 return network.incidentNodes(edge); 242 } 243 }; 244 return Maps.asMap(network.edges(), edgeToIncidentNodesFn); 245 } 246}