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.base.Preconditions.checkNotNull;
020import static com.google.common.graph.Graphs.checkNonNegative;
021
022import com.google.common.annotations.Beta;
023import com.google.common.base.Optional;
024
025/**
026 * A builder for constructing instances of {@link MutableNetwork} or {@link ImmutableNetwork} with
027 * user-defined properties.
028 *
029 * <p>A {@code Network} built by this class has the following default properties:
030 *
031 * <ul>
032 *   <li>does not allow parallel edges
033 *   <li>does not allow self-loops
034 *   <li>orders {@link Network#nodes()} and {@link Network#edges()} in the order in which the
035 *       elements were added (insertion order)
036 * </ul>
037 *
038 * <p>{@code Network}s built by this class also guarantee that each collection-returning accessor
039 * returns a <b>(live) unmodifiable view</b>; see <a
040 * href="https://github.com/google/guava/wiki/GraphsExplained#accessor-behavior">the external
041 * documentation</a> for details.
042 *
043 * <p>Examples of use:
044 *
045 * <pre>{@code
046 * // Building a mutable network
047 * MutableNetwork<String, Integer> network =
048 *     NetworkBuilder.directed().allowsParallelEdges(true).build();
049 * flightNetwork.addEdge("LAX", "ATL", 3025);
050 * flightNetwork.addEdge("LAX", "ATL", 1598);
051 * flightNetwork.addEdge("ATL", "LAX", 2450);
052 *
053 * // Building a immutable network
054 * ImmutableNetwork<String, Integer> immutableNetwork =
055 *     NetworkBuilder.directed()
056 *         .allowsParallelEdges(true)
057 *         .<String, Integer>immutable()
058 *         .addEdge("LAX", "ATL", 3025)
059 *         .addEdge("LAX", "ATL", 1598)
060 *         .addEdge("ATL", "LAX", 2450)
061 *         .build();
062 * }</pre>
063 *
064 * @author James Sexton
065 * @author Joshua O'Madadhain
066 * @param <N> The most general node type this builder will support. This is normally {@code Object}
067 *     unless it is constrained by using a method like {@link #nodeOrder}, or the builder is
068 *     constructed based on an existing {@code Network} using {@link #from(Network)}.
069 * @param <E> The most general edge type this builder will support. This is normally {@code Object}
070 *     unless it is constrained by using a method like {@link #edgeOrder}, or the builder is
071 *     constructed based on an existing {@code Network} using {@link #from(Network)}.
072 * @since 20.0
073 */
074@Beta
075@ElementTypesAreNonnullByDefault
076public final class NetworkBuilder<N, E> extends AbstractGraphBuilder<N> {
077  boolean allowsParallelEdges = false;
078  ElementOrder<? super E> edgeOrder = ElementOrder.insertion();
079  Optional<Integer> expectedEdgeCount = Optional.absent();
080
081  /** Creates a new instance with the specified edge directionality. */
082  private NetworkBuilder(boolean directed) {
083    super(directed);
084  }
085
086  /** Returns a {@link NetworkBuilder} for building directed networks. */
087  public static NetworkBuilder<Object, Object> directed() {
088    return new NetworkBuilder<>(true);
089  }
090
091  /** Returns a {@link NetworkBuilder} for building undirected networks. */
092  public static NetworkBuilder<Object, Object> undirected() {
093    return new NetworkBuilder<>(false);
094  }
095
096  /**
097   * Returns a {@link NetworkBuilder} initialized with all properties queryable from {@code
098   * network}.
099   *
100   * <p>The "queryable" properties are those that are exposed through the {@link Network} interface,
101   * such as {@link Network#isDirected()}. Other properties, such as {@link
102   * #expectedNodeCount(int)}, are not set in the new builder.
103   */
104  public static <N, E> NetworkBuilder<N, E> from(Network<N, E> network) {
105    return new NetworkBuilder<N, E>(network.isDirected())
106        .allowsParallelEdges(network.allowsParallelEdges())
107        .allowsSelfLoops(network.allowsSelfLoops())
108        .nodeOrder(network.nodeOrder())
109        .edgeOrder(network.edgeOrder());
110  }
111
112  /**
113   * Returns an {@link ImmutableNetwork.Builder} with the properties of this {@link NetworkBuilder}.
114   *
115   * <p>The returned builder can be used for populating an {@link ImmutableNetwork}.
116   *
117   * @since 28.0
118   */
119  public <N1 extends N, E1 extends E> ImmutableNetwork.Builder<N1, E1> immutable() {
120    NetworkBuilder<N1, E1> castBuilder = cast();
121    return new ImmutableNetwork.Builder<>(castBuilder);
122  }
123
124  /**
125   * Specifies whether the network will allow parallel edges. Attempting to add a parallel edge to a
126   * network that does not allow them will throw an {@link UnsupportedOperationException}.
127   *
128   * <p>The default value is {@code false}.
129   */
130  public NetworkBuilder<N, E> allowsParallelEdges(boolean allowsParallelEdges) {
131    this.allowsParallelEdges = allowsParallelEdges;
132    return this;
133  }
134
135  /**
136   * Specifies whether the network will allow self-loops (edges that connect a node to itself).
137   * Attempting to add a self-loop to a network that does not allow them will throw an {@link
138   * UnsupportedOperationException}.
139   *
140   * <p>The default value is {@code false}.
141   */
142  public NetworkBuilder<N, E> allowsSelfLoops(boolean allowsSelfLoops) {
143    this.allowsSelfLoops = allowsSelfLoops;
144    return this;
145  }
146
147  /**
148   * Specifies the expected number of nodes in the network.
149   *
150   * @throws IllegalArgumentException if {@code expectedNodeCount} is negative
151   */
152  public NetworkBuilder<N, E> expectedNodeCount(int expectedNodeCount) {
153    this.expectedNodeCount = Optional.of(checkNonNegative(expectedNodeCount));
154    return this;
155  }
156
157  /**
158   * Specifies the expected number of edges in the network.
159   *
160   * @throws IllegalArgumentException if {@code expectedEdgeCount} is negative
161   */
162  public NetworkBuilder<N, E> expectedEdgeCount(int expectedEdgeCount) {
163    this.expectedEdgeCount = Optional.of(checkNonNegative(expectedEdgeCount));
164    return this;
165  }
166
167  /**
168   * Specifies the order of iteration for the elements of {@link Network#nodes()}.
169   *
170   * <p>The default value is {@link ElementOrder#insertion() insertion order}.
171   */
172  public <N1 extends N> NetworkBuilder<N1, E> nodeOrder(ElementOrder<N1> nodeOrder) {
173    NetworkBuilder<N1, E> newBuilder = cast();
174    newBuilder.nodeOrder = checkNotNull(nodeOrder);
175    return newBuilder;
176  }
177
178  /**
179   * Specifies the order of iteration for the elements of {@link Network#edges()}.
180   *
181   * <p>The default value is {@link ElementOrder#insertion() insertion order}.
182   */
183  public <E1 extends E> NetworkBuilder<N, E1> edgeOrder(ElementOrder<E1> edgeOrder) {
184    NetworkBuilder<N, E1> newBuilder = cast();
185    newBuilder.edgeOrder = checkNotNull(edgeOrder);
186    return newBuilder;
187  }
188
189  /** Returns an empty {@link MutableNetwork} with the properties of this {@link NetworkBuilder}. */
190  public <N1 extends N, E1 extends E> MutableNetwork<N1, E1> build() {
191    return new StandardMutableNetwork<>(this);
192  }
193
194  @SuppressWarnings("unchecked")
195  private <N1 extends N, E1 extends E> NetworkBuilder<N1, E1> cast() {
196    return (NetworkBuilder<N1, E1>) this;
197  }
198}