001/*
002 * Copyright (C) 2014 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.checkNotNull;
020
021import com.google.common.annotations.Beta;
022import com.google.common.base.Function;
023import com.google.common.collect.ImmutableMap;
024import com.google.common.collect.Maps;
025import com.google.errorprone.annotations.CanIgnoreReturnValue;
026import com.google.errorprone.annotations.Immutable;
027import java.util.Map;
028
029/**
030 * A {@link Network} whose elements and structural relationships will never change. Instances of
031 * this class may be obtained with {@link #copyOf(Network)}.
032 *
033 * <p>See the Guava User's Guide's <a
034 * href="https://github.com/google/guava/wiki/GraphsExplained#immutable-implementations">discussion
035 * of the {@code Immutable*} types</a> for more information on the properties and guarantees
036 * provided by this class.
037 *
038 * @author James Sexton
039 * @author Joshua O'Madadhain
040 * @author Omar Darwish
041 * @author Jens Nyman
042 * @param <N> Node parameter type
043 * @param <E> Edge parameter type
044 * @since 20.0
045 */
046@Beta
047@Immutable(containerOf = {"N", "E"})
048@SuppressWarnings("Immutable") // Extends ConfigurableNetwork but uses ImmutableMaps.
049public final class ImmutableNetwork<N, E> extends ConfigurableNetwork<N, E> {
050
051  private ImmutableNetwork(Network<N, E> network) {
052    super(
053        NetworkBuilder.from(network), getNodeConnections(network), getEdgeToReferenceNode(network));
054  }
055
056  /** Returns an immutable copy of {@code network}. */
057  public static <N, E> ImmutableNetwork<N, E> copyOf(Network<N, E> network) {
058    return (network instanceof ImmutableNetwork)
059        ? (ImmutableNetwork<N, E>) network
060        : new ImmutableNetwork<N, E>(network);
061  }
062
063  /**
064   * Simply returns its argument.
065   *
066   * @deprecated no need to use this
067   */
068  @Deprecated
069  public static <N, E> ImmutableNetwork<N, E> copyOf(ImmutableNetwork<N, E> network) {
070    return checkNotNull(network);
071  }
072
073  @Override
074  public ImmutableGraph<N> asGraph() {
075    return new ImmutableGraph<N>(super.asGraph()); // safe because the view is effectively immutable
076  }
077
078  private static <N, E> Map<N, NetworkConnections<N, E>> getNodeConnections(Network<N, E> network) {
079    // ImmutableMap.Builder maintains the order of the elements as inserted, so the map will have
080    // whatever ordering the network's nodes do, so ImmutableSortedMap is unnecessary even if the
081    // input nodes are sorted.
082    ImmutableMap.Builder<N, NetworkConnections<N, E>> nodeConnections = ImmutableMap.builder();
083    for (N node : network.nodes()) {
084      nodeConnections.put(node, connectionsOf(network, node));
085    }
086    return nodeConnections.build();
087  }
088
089  private static <N, E> Map<E, N> getEdgeToReferenceNode(Network<N, E> network) {
090    // ImmutableMap.Builder maintains the order of the elements as inserted, so the map will have
091    // whatever ordering the network's edges do, so ImmutableSortedMap is unnecessary even if the
092    // input edges are sorted.
093    ImmutableMap.Builder<E, N> edgeToReferenceNode = ImmutableMap.builder();
094    for (E edge : network.edges()) {
095      edgeToReferenceNode.put(edge, network.incidentNodes(edge).nodeU());
096    }
097    return edgeToReferenceNode.build();
098  }
099
100  private static <N, E> NetworkConnections<N, E> connectionsOf(Network<N, E> network, N node) {
101    if (network.isDirected()) {
102      Map<E, N> inEdgeMap = Maps.asMap(network.inEdges(node), sourceNodeFn(network));
103      Map<E, N> outEdgeMap = Maps.asMap(network.outEdges(node), targetNodeFn(network));
104      int selfLoopCount = network.edgesConnecting(node, node).size();
105      return network.allowsParallelEdges()
106          ? DirectedMultiNetworkConnections.ofImmutable(inEdgeMap, outEdgeMap, selfLoopCount)
107          : DirectedNetworkConnections.ofImmutable(inEdgeMap, outEdgeMap, selfLoopCount);
108    } else {
109      Map<E, N> incidentEdgeMap =
110          Maps.asMap(network.incidentEdges(node), adjacentNodeFn(network, node));
111      return network.allowsParallelEdges()
112          ? UndirectedMultiNetworkConnections.ofImmutable(incidentEdgeMap)
113          : UndirectedNetworkConnections.ofImmutable(incidentEdgeMap);
114    }
115  }
116
117  private static <N, E> Function<E, N> sourceNodeFn(final Network<N, E> network) {
118    return new Function<E, N>() {
119      @Override
120      public N apply(E edge) {
121        return network.incidentNodes(edge).source();
122      }
123    };
124  }
125
126  private static <N, E> Function<E, N> targetNodeFn(final Network<N, E> network) {
127    return new Function<E, N>() {
128      @Override
129      public N apply(E edge) {
130        return network.incidentNodes(edge).target();
131      }
132    };
133  }
134
135  private static <N, E> Function<E, N> adjacentNodeFn(final Network<N, E> network, final N node) {
136    return new Function<E, N>() {
137      @Override
138      public N apply(E edge) {
139        return network.incidentNodes(edge).adjacentNode(node);
140      }
141    };
142  }
143
144  /**
145   * A builder for creating {@link ImmutableNetwork} instances, especially {@code static final}
146   * networks. Example:
147   *
148   * <pre>{@code
149   * static final ImmutableNetwork<City, Train> TRAIN_NETWORK =
150   *     NetworkBuilder.undirected()
151   *         .allowsParallelEdges(true)
152   *         .<City, Train>immutable()
153   *         .addEdge(PARIS, BRUSSELS, Thalys.trainNumber("1111"))
154   *         .addEdge(PARIS, BRUSSELS, RegionalTrain.trainNumber("2222"))
155   *         .addEdge(LONDON, PARIS, Eurostar.trainNumber("3333"))
156   *         .addEdge(LONDON, BRUSSELS, Eurostar.trainNumber("4444"))
157   *         .addNode(REYKJAVIK)
158   *         .build();
159   * }</pre>
160   *
161   * <p>Builder instances can be reused; it is safe to call {@link #build} multiple times to build
162   * multiple networks in series. Each new network contains all the elements of the ones created
163   * before it.
164   *
165   * @since 28.0
166   */
167  public static class Builder<N, E> {
168
169    private final MutableNetwork<N, E> mutableNetwork;
170
171    Builder(NetworkBuilder<N, E> networkBuilder) {
172      this.mutableNetwork = networkBuilder.build();
173    }
174
175    /**
176     * Adds {@code node} if it is not already present.
177     *
178     * <p><b>Nodes must be unique</b>, just as {@code Map} keys must be. They must also be non-null.
179     *
180     * @return this {@code Builder} object
181     */
182    @CanIgnoreReturnValue
183    public ImmutableNetwork.Builder<N, E> addNode(N node) {
184      mutableNetwork.addNode(node);
185      return this;
186    }
187
188    /**
189     * Adds {@code edge} connecting {@code nodeU} to {@code nodeV}.
190     *
191     * <p>If the network is directed, {@code edge} will be directed in this network; otherwise, it
192     * will be undirected.
193     *
194     * <p><b>{@code edge} must be unique to this network</b>, just as a {@code Map} key must be. It
195     * must also be non-null.
196     *
197     * <p>If {@code nodeU} and {@code nodeV} are not already present in this network, this method
198     * will silently {@link #addNode(Object) add} {@code nodeU} and {@code nodeV} to the network.
199     *
200     * <p>If {@code edge} already connects {@code nodeU} to {@code nodeV} (in the specified order if
201     * this network {@link #isDirected()}, else in any order), then this method will have no effect.
202     *
203     * @return this {@code Builder} object
204     * @throws IllegalArgumentException if {@code edge} already exists in the network and does not
205     *     connect {@code nodeU} to {@code nodeV}
206     * @throws IllegalArgumentException if the introduction of the edge would violate {@link
207     *     #allowsParallelEdges()} or {@link #allowsSelfLoops()}
208     */
209    @CanIgnoreReturnValue
210    public ImmutableNetwork.Builder<N, E> addEdge(N nodeU, N nodeV, E edge) {
211      mutableNetwork.addEdge(nodeU, nodeV, edge);
212      return this;
213    }
214
215    /**
216     * Adds {@code edge} connecting {@code endpoints}. In an undirected network, {@code edge} will
217     * also connect {@code nodeV} to {@code nodeU}.
218     *
219     * <p>If this network is directed, {@code edge} will be directed in this network; if it is
220     * undirected, {@code edge} will be undirected in this network.
221     *
222     * <p>If this network is directed, {@code endpoints} must be ordered.
223     *
224     * <p><b>{@code edge} must be unique to this network</b>, just as a {@code Map} key must be. It
225     * must also be non-null.
226     *
227     * <p>If either or both endpoints are not already present in this network, this method will
228     * silently {@link #addNode(Object) add} each missing endpoint to the network.
229     *
230     * <p>If {@code edge} already connects an endpoint pair equal to {@code endpoints}, then this
231     * method will have no effect.
232     *
233     * @return this {@code Builder} object
234     * @throws IllegalArgumentException if {@code edge} already exists in the network and connects
235     *     some other endpoint pair that is not equal to {@code endpoints}
236     * @throws IllegalArgumentException if the introduction of the edge would violate {@link
237     *     #allowsParallelEdges()} or {@link #allowsSelfLoops()}
238     * @throws IllegalArgumentException if the endpoints are unordered and the network is directed
239     */
240    @CanIgnoreReturnValue
241    public ImmutableNetwork.Builder<N, E> addEdge(EndpointPair<N> endpoints, E edge) {
242      mutableNetwork.addEdge(endpoints, edge);
243      return this;
244    }
245
246    /**
247     * Returns a newly-created {@code ImmutableNetwork} based on the contents of this {@code
248     * Builder}.
249     */
250    public ImmutableNetwork<N, E> build() {
251      return ImmutableNetwork.copyOf(mutableNetwork);
252    }
253  }
254}