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