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