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.errorprone.annotations.CanIgnoreReturnValue;
023import org.jspecify.annotations.Nullable;
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 * {@snippet :
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 * }
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 */
074public final class NetworkBuilder<N, E> extends AbstractGraphBuilder<N> {
075  boolean allowsParallelEdges = false;
076  ElementOrder<? super E> edgeOrder = ElementOrder.insertion();
077  @Nullable Integer expectedEdgeCount = null;
078
079  /** Creates a new instance with the specified edge directionality. */
080  private NetworkBuilder(boolean directed) {
081    super(directed);
082  }
083
084  /** Returns a {@link NetworkBuilder} for building directed networks. */
085  public static NetworkBuilder<Object, Object> directed() {
086    return new NetworkBuilder<>(true);
087  }
088
089  /** Returns a {@link NetworkBuilder} for building undirected networks. */
090  public static NetworkBuilder<Object, Object> undirected() {
091    return new NetworkBuilder<>(false);
092  }
093
094  /**
095   * Returns a {@link NetworkBuilder} initialized with all properties queryable from {@code
096   * network}.
097   *
098   * <p>The "queryable" properties are those that are exposed through the {@link Network} interface,
099   * such as {@link Network#isDirected()}. Other properties, such as {@link
100   * #expectedNodeCount(int)}, are not set in the new builder.
101   */
102  public static <N, E> NetworkBuilder<N, E> from(Network<N, E> network) {
103    return new NetworkBuilder<N, E>(network.isDirected())
104        .allowsParallelEdges(network.allowsParallelEdges())
105        .allowsSelfLoops(network.allowsSelfLoops())
106        .nodeOrder(network.nodeOrder())
107        .edgeOrder(network.edgeOrder());
108  }
109
110  /**
111   * Returns an {@link ImmutableNetwork.Builder} with the properties of this {@link NetworkBuilder}.
112   *
113   * <p>The returned builder can be used for populating an {@link ImmutableNetwork}.
114   *
115   * @since 28.0
116   */
117  public <N1 extends N, E1 extends E> ImmutableNetwork.Builder<N1, E1> immutable() {
118    NetworkBuilder<N1, E1> castBuilder = cast();
119    return new ImmutableNetwork.Builder<>(castBuilder);
120  }
121
122  /**
123   * Specifies whether the network will allow parallel edges. Attempting to add a parallel edge to a
124   * network that does not allow them will throw an {@link UnsupportedOperationException}.
125   *
126   * <p>The default value is {@code false}.
127   */
128  @CanIgnoreReturnValue
129  public NetworkBuilder<N, E> allowsParallelEdges(boolean allowsParallelEdges) {
130    this.allowsParallelEdges = allowsParallelEdges;
131    return this;
132  }
133
134  /**
135   * Specifies whether the network will allow self-loops (edges that connect a node to itself).
136   * Attempting to add a self-loop to a network that does not allow them will throw an {@link
137   * UnsupportedOperationException}.
138   *
139   * <p>The default value is {@code false}.
140   */
141  @CanIgnoreReturnValue
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  @CanIgnoreReturnValue
153  public NetworkBuilder<N, E> expectedNodeCount(int expectedNodeCount) {
154    this.expectedNodeCount = checkNonNegative(expectedNodeCount);
155    return this;
156  }
157
158  /**
159   * Specifies the expected number of edges in the network.
160   *
161   * @throws IllegalArgumentException if {@code expectedEdgeCount} is negative
162   */
163  @CanIgnoreReturnValue
164  public NetworkBuilder<N, E> expectedEdgeCount(int expectedEdgeCount) {
165    this.expectedEdgeCount = checkNonNegative(expectedEdgeCount);
166    return this;
167  }
168
169  /**
170   * Specifies the order of iteration for the elements of {@link Network#nodes()}.
171   *
172   * <p>The default value is {@link ElementOrder#insertion() insertion order}.
173   */
174  public <N1 extends N> NetworkBuilder<N1, E> nodeOrder(ElementOrder<N1> nodeOrder) {
175    NetworkBuilder<N1, E> newBuilder = cast();
176    newBuilder.nodeOrder = checkNotNull(nodeOrder);
177    return newBuilder;
178  }
179
180  /**
181   * Specifies the order of iteration for the elements of {@link Network#edges()}.
182   *
183   * <p>The default value is {@link ElementOrder#insertion() insertion order}.
184   */
185  public <E1 extends E> NetworkBuilder<N, E1> edgeOrder(ElementOrder<E1> edgeOrder) {
186    NetworkBuilder<N, E1> newBuilder = cast();
187    newBuilder.edgeOrder = checkNotNull(edgeOrder);
188    return newBuilder;
189  }
190
191  /** Returns an empty {@link MutableNetwork} with the properties of this {@link NetworkBuilder}. */
192  public <N1 extends N, E1 extends E> MutableNetwork<N1, E1> build() {
193    return new StandardMutableNetwork<>(this);
194  }
195
196  @SuppressWarnings("unchecked")
197  private <N1 extends N, E1 extends E> NetworkBuilder<N1, E1> cast() {
198    return (NetworkBuilder<N1, E1>) this;
199  }
200}