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 StandardNetwork but uses ImmutableMaps.
049@ElementTypesAreNonnullByDefault
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  @Deprecated
070  public static <N, E> ImmutableNetwork<N, E> copyOf(ImmutableNetwork<N, E> network) {
071    return checkNotNull(network);
072  }
073
074  @Override
075  public ImmutableGraph<N> asGraph() {
076    return new ImmutableGraph<>(super.asGraph()); // safe because the view is effectively immutable
077  }
078
079  private static <N, E> Map<N, NetworkConnections<N, E>> getNodeConnections(Network<N, E> network) {
080    // ImmutableMap.Builder maintains the order of the elements as inserted, so the map will have
081    // whatever ordering the network's nodes do, so ImmutableSortedMap is unnecessary even if the
082    // input nodes are sorted.
083    ImmutableMap.Builder<N, NetworkConnections<N, E>> nodeConnections = ImmutableMap.builder();
084    for (N node : network.nodes()) {
085      nodeConnections.put(node, connectionsOf(network, node));
086    }
087    return nodeConnections.buildOrThrow();
088  }
089
090  private static <N, E> Map<E, N> getEdgeToReferenceNode(Network<N, E> network) {
091    // ImmutableMap.Builder maintains the order of the elements as inserted, so the map will have
092    // whatever ordering the network's edges do, so ImmutableSortedMap is unnecessary even if the
093    // input edges are sorted.
094    ImmutableMap.Builder<E, N> edgeToReferenceNode = ImmutableMap.builder();
095    for (E edge : network.edges()) {
096      edgeToReferenceNode.put(edge, network.incidentNodes(edge).nodeU());
097    }
098    return edgeToReferenceNode.buildOrThrow();
099  }
100
101  private static <N, E> NetworkConnections<N, E> connectionsOf(Network<N, E> network, N node) {
102    if (network.isDirected()) {
103      Map<E, N> inEdgeMap = Maps.asMap(network.inEdges(node), sourceNodeFn(network));
104      Map<E, N> outEdgeMap = Maps.asMap(network.outEdges(node), targetNodeFn(network));
105      int selfLoopCount = network.edgesConnecting(node, node).size();
106      return network.allowsParallelEdges()
107          ? DirectedMultiNetworkConnections.ofImmutable(inEdgeMap, outEdgeMap, selfLoopCount)
108          : DirectedNetworkConnections.ofImmutable(inEdgeMap, outEdgeMap, selfLoopCount);
109    } else {
110      Map<E, N> incidentEdgeMap =
111          Maps.asMap(network.incidentEdges(node), adjacentNodeFn(network, node));
112      return network.allowsParallelEdges()
113          ? UndirectedMultiNetworkConnections.ofImmutable(incidentEdgeMap)
114          : UndirectedNetworkConnections.ofImmutable(incidentEdgeMap);
115    }
116  }
117
118  private static <N, E> Function<E, N> sourceNodeFn(Network<N, E> network) {
119    return (E edge) -> network.incidentNodes(edge).source();
120  }
121
122  private static <N, E> Function<E, N> targetNodeFn(Network<N, E> network) {
123    return (E edge) -> network.incidentNodes(edge).target();
124  }
125
126  private static <N, E> Function<E, N> adjacentNodeFn(Network<N, E> network, N node) {
127    return (E edge) -> network.incidentNodes(edge).adjacentNode(node);
128  }
129
130  /**
131   * A builder for creating {@link ImmutableNetwork} instances, especially {@code static final}
132   * networks. Example:
133   *
134   * <pre>{@code
135   * static final ImmutableNetwork<City, Train> TRAIN_NETWORK =
136   *     NetworkBuilder.undirected()
137   *         .allowsParallelEdges(true)
138   *         .<City, Train>immutable()
139   *         .addEdge(PARIS, BRUSSELS, Thalys.trainNumber("1111"))
140   *         .addEdge(PARIS, BRUSSELS, RegionalTrain.trainNumber("2222"))
141   *         .addEdge(LONDON, PARIS, Eurostar.trainNumber("3333"))
142   *         .addEdge(LONDON, BRUSSELS, Eurostar.trainNumber("4444"))
143   *         .addNode(REYKJAVIK)
144   *         .build();
145   * }</pre>
146   *
147   * <p>Builder instances can be reused; it is safe to call {@link #build} multiple times to build
148   * multiple networks in series. Each new network contains all the elements of the ones created
149   * before it.
150   *
151   * @since 28.0
152   */
153  public static class Builder<N, E> {
154
155    private final MutableNetwork<N, E> mutableNetwork;
156
157    Builder(NetworkBuilder<N, E> networkBuilder) {
158      this.mutableNetwork = networkBuilder.build();
159    }
160
161    /**
162     * Adds {@code node} if it is not already present.
163     *
164     * <p><b>Nodes must be unique</b>, just as {@code Map} keys must be. They must also be non-null.
165     *
166     * @return this {@code Builder} object
167     */
168    @CanIgnoreReturnValue
169    public ImmutableNetwork.Builder<N, E> addNode(N node) {
170      mutableNetwork.addNode(node);
171      return this;
172    }
173
174    /**
175     * Adds {@code edge} connecting {@code nodeU} to {@code nodeV}.
176     *
177     * <p>If the network is directed, {@code edge} will be directed in this network; otherwise, it
178     * will be undirected.
179     *
180     * <p><b>{@code edge} must be unique to this network</b>, just as a {@code Map} key must be. It
181     * must also be non-null.
182     *
183     * <p>If {@code nodeU} and {@code nodeV} are not already present in this network, this method
184     * will silently {@link #addNode(Object) add} {@code nodeU} and {@code nodeV} to the network.
185     *
186     * <p>If {@code edge} already connects {@code nodeU} to {@code nodeV} (in the specified order if
187     * this network {@link #isDirected()}, else in any order), then this method will have no effect.
188     *
189     * @return this {@code Builder} object
190     * @throws IllegalArgumentException if {@code edge} already exists in the network and does not
191     *     connect {@code nodeU} to {@code nodeV}
192     * @throws IllegalArgumentException if the introduction of the edge would violate {@link
193     *     #allowsParallelEdges()} or {@link #allowsSelfLoops()}
194     */
195    @CanIgnoreReturnValue
196    public ImmutableNetwork.Builder<N, E> addEdge(N nodeU, N nodeV, E edge) {
197      mutableNetwork.addEdge(nodeU, nodeV, edge);
198      return this;
199    }
200
201    /**
202     * Adds {@code edge} connecting {@code endpoints}. In an undirected network, {@code edge} will
203     * also connect {@code nodeV} to {@code nodeU}.
204     *
205     * <p>If this network is directed, {@code edge} will be directed in this network; if it is
206     * undirected, {@code edge} will be undirected in this network.
207     *
208     * <p>If this network is directed, {@code endpoints} must be ordered.
209     *
210     * <p><b>{@code edge} must be unique to this network</b>, just as a {@code Map} key must be. It
211     * must also be non-null.
212     *
213     * <p>If either or both endpoints are not already present in this network, this method will
214     * silently {@link #addNode(Object) add} each missing endpoint to the network.
215     *
216     * <p>If {@code edge} already connects an endpoint pair equal to {@code endpoints}, then this
217     * method will have no effect.
218     *
219     * @return this {@code Builder} object
220     * @throws IllegalArgumentException if {@code edge} already exists in the network and connects
221     *     some other endpoint pair that is not equal to {@code endpoints}
222     * @throws IllegalArgumentException if the introduction of the edge would violate {@link
223     *     #allowsParallelEdges()} or {@link #allowsSelfLoops()}
224     * @throws IllegalArgumentException if the endpoints are unordered and the network is directed
225     */
226    @CanIgnoreReturnValue
227    public ImmutableNetwork.Builder<N, E> addEdge(EndpointPair<N> endpoints, E edge) {
228      mutableNetwork.addEdge(endpoints, edge);
229      return this;
230    }
231
232    /**
233     * Returns a newly-created {@code ImmutableNetwork} based on the contents of this {@code
234     * Builder}.
235     */
236    public ImmutableNetwork<N, E> build() {
237      return ImmutableNetwork.copyOf(mutableNetwork);
238    }
239  }
240}