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