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