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.Optional;
035import java.util.Set;
036import javax.annotation.Nullable;
037
038/**
039 * This class provides a skeletal implementation of {@link Network}. It is recommended to extend
040 * this class rather than implement {@link Network} directly.
041 *
042 * <p>The methods implemented in this class should not be overridden unless the subclass admits a
043 * more efficient implementation.
044 *
045 * @author James Sexton
046 * @param <N> Node parameter type
047 * @param <E> Edge parameter type
048 * @since 20.0
049 */
050@Beta
051@GwtIncompatible
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(@Nullable Object obj) {
093            if (!(obj instanceof EndpointPair)) {
094              return false;
095            }
096            EndpointPair<?> endpointPair = (EndpointPair<?>) obj;
097            return isDirected() == endpointPair.isOrdered()
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 boolean isDirected() {
111        return AbstractNetwork.this.isDirected();
112      }
113
114      @Override
115      public boolean allowsSelfLoops() {
116        return AbstractNetwork.this.allowsSelfLoops();
117      }
118
119      @Override
120      public Set<N> adjacentNodes(N node) {
121        return AbstractNetwork.this.adjacentNodes(node);
122      }
123
124      @Override
125      public Set<N> predecessors(N node) {
126        return AbstractNetwork.this.predecessors(node);
127      }
128
129      @Override
130      public Set<N> successors(N node) {
131        return AbstractNetwork.this.successors(node);
132      }
133
134      // DO NOT override the AbstractGraph *degree() implementations.
135    };
136  }
137
138  @Override
139  public int degree(N node) {
140    if (isDirected()) {
141      return IntMath.saturatedAdd(inEdges(node).size(), outEdges(node).size());
142    } else {
143      return IntMath.saturatedAdd(incidentEdges(node).size(), edgesConnecting(node, node).size());
144    }
145  }
146
147  @Override
148  public int inDegree(N node) {
149    return isDirected() ? inEdges(node).size() : degree(node);
150  }
151
152  @Override
153  public int outDegree(N node) {
154    return isDirected() ? outEdges(node).size() : degree(node);
155  }
156
157  @Override
158  public Set<E> adjacentEdges(E edge) {
159    EndpointPair<N> endpointPair = incidentNodes(edge); // Verifies that edge is in this network.
160    Set<E> endpointPairIncidentEdges =
161        Sets.union(incidentEdges(endpointPair.nodeU()), incidentEdges(endpointPair.nodeV()));
162    return Sets.difference(endpointPairIncidentEdges, ImmutableSet.of(edge));
163  }
164
165  @Override
166  public Set<E> edgesConnecting(N nodeU, N nodeV) {
167    Set<E> outEdgesU = outEdges(nodeU);
168    Set<E> inEdgesV = inEdges(nodeV);
169    return outEdgesU.size() <= inEdgesV.size()
170        ? unmodifiableSet(Sets.filter(outEdgesU, connectedPredicate(nodeU, nodeV)))
171        : unmodifiableSet(Sets.filter(inEdgesV, connectedPredicate(nodeV, nodeU)));
172  }
173
174  private Predicate<E> connectedPredicate(final N nodePresent, final N nodeToCheck) {
175    return new Predicate<E>() {
176      @Override
177      public boolean apply(E edge) {
178        return incidentNodes(edge).adjacentNode(nodePresent).equals(nodeToCheck);
179      }
180    };
181  }
182
183  @Override
184  public Optional<E> edgeConnecting(N nodeU, N nodeV) {
185    Set<E> edgesConnecting = edgesConnecting(nodeU, nodeV);
186    switch (edgesConnecting.size()) {
187      case 0:
188        return Optional.empty();
189      case 1:
190        return Optional.of(edgesConnecting.iterator().next());
191      default:
192        throw new IllegalArgumentException(String.format(MULTIPLE_EDGES_CONNECTING, nodeU, nodeV));
193    }
194  }
195
196  @Override
197  @Nullable
198  public E edgeConnectingOrNull(N nodeU, N nodeV) {
199    return edgeConnecting(nodeU, nodeV).orElse(null);
200  }
201
202  @Override
203  public boolean hasEdgeConnecting(N nodeU, N nodeV) {
204    return !edgesConnecting(nodeU, nodeV).isEmpty();
205  }
206
207  @Override
208  public final boolean equals(@Nullable Object obj) {
209    if (obj == this) {
210      return true;
211    }
212    if (!(obj instanceof Network)) {
213      return false;
214    }
215    Network<?, ?> other = (Network<?, ?>) obj;
216
217    return isDirected() == other.isDirected()
218        && nodes().equals(other.nodes())
219        && edgeIncidentNodesMap(this).equals(edgeIncidentNodesMap(other));
220  }
221
222  @Override
223  public final int hashCode() {
224    return edgeIncidentNodesMap(this).hashCode();
225  }
226
227  /** Returns a string representation of this network. */
228  @Override
229  public String toString() {
230    return "isDirected: "
231        + isDirected()
232        + ", allowsParallelEdges: "
233        + allowsParallelEdges()
234        + ", allowsSelfLoops: "
235        + allowsSelfLoops()
236        + ", nodes: "
237        + nodes()
238        + ", edges: "
239        + edgeIncidentNodesMap(this);
240  }
241
242  private static <N, E> Map<E, EndpointPair<N>> edgeIncidentNodesMap(final Network<N, E> network) {
243    Function<E, EndpointPair<N>> edgeToIncidentNodesFn =
244        new Function<E, EndpointPair<N>>() {
245          @Override
246          public EndpointPair<N> apply(E edge) {
247            return network.incidentNodes(edge);
248          }
249        };
250    return Maps.asMap(network.edges(), edgeToIncidentNodesFn);
251  }
252}