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.checkArgument;
020import static com.google.common.base.Preconditions.checkNotNull;
021import static com.google.common.graph.Graphs.checkNonNegative;
022
023import com.google.common.annotations.Beta;
024import com.google.common.base.Optional;
025
026/**
027 * A builder for constructing instances of {@link MutableValueGraph} or {@link ImmutableValueGraph}
028 * with user-defined properties.
029 *
030 * <p>A graph built by this class will have the following properties by default:
031 *
032 * <ul>
033 *   <li>does not allow self-loops
034 *   <li>orders {@link Graph#nodes()} in the order in which the elements were added
035 * </ul>
036 *
037 * <p>Examples of use:
038 *
039 * <pre>{@code
040 * // Building a mutable value graph
041 * MutableValueGraph<String, Double> graph =
042 *     ValueGraphBuilder.undirected().allowsSelfLoops(true).build();
043 * graph.putEdgeValue("San Francisco", "San Francisco", 0.0);
044 * graph.putEdgeValue("San Jose", "San Jose", 0.0);
045 * graph.putEdgeValue("San Francisco", "San Jose", 48.4);
046 *
047 * // Building an immutable value graph
048 * ImmutableValueGraph<String, Double> immutableGraph =
049 *     ValueGraphBuilder.undirected()
050 *         .allowsSelfLoops(true)
051 *         .<String, Double>immutable()
052 *         .putEdgeValue("San Francisco", "San Francisco", 0.0)
053 *         .putEdgeValue("San Jose", "San Jose", 0.0)
054 *         .putEdgeValue("San Francisco", "San Jose", 48.4)
055 *         .build();
056 * }</pre>
057 *
058 * @author James Sexton
059 * @author Joshua O'Madadhain
060 * @param <N> The most general node type this builder will support. This is normally {@code Object}
061 *     unless it is constrained by using a method like {@link #nodeOrder}, or the builder is
062 *     constructed based on an existing {@code ValueGraph} using {@link #from(ValueGraph)}.
063 * @param <V> The most general value type this builder will support. This is normally {@code Object}
064 *     unless the builder is constructed based on an existing {@code Graph} using {@link
065 *     #from(ValueGraph)}.
066 * @since 20.0
067 */
068@Beta
069@ElementTypesAreNonnullByDefault
070public final class ValueGraphBuilder<N, V> extends AbstractGraphBuilder<N> {
071
072  /** Creates a new instance with the specified edge directionality. */
073  private ValueGraphBuilder(boolean directed) {
074    super(directed);
075  }
076
077  /** Returns a {@link ValueGraphBuilder} for building directed graphs. */
078  public static ValueGraphBuilder<Object, Object> directed() {
079    return new ValueGraphBuilder<>(true);
080  }
081
082  /** Returns a {@link ValueGraphBuilder} for building undirected graphs. */
083  public static ValueGraphBuilder<Object, Object> undirected() {
084    return new ValueGraphBuilder<>(false);
085  }
086
087  /**
088   * Returns a {@link ValueGraphBuilder} initialized with all properties queryable from {@code
089   * graph}.
090   *
091   * <p>The "queryable" properties are those that are exposed through the {@link ValueGraph}
092   * interface, such as {@link ValueGraph#isDirected()}. Other properties, such as {@link
093   * #expectedNodeCount(int)}, are not set in the new builder.
094   */
095  public static <N, V> ValueGraphBuilder<N, V> from(ValueGraph<N, V> graph) {
096    return new ValueGraphBuilder<N, V>(graph.isDirected())
097        .allowsSelfLoops(graph.allowsSelfLoops())
098        .nodeOrder(graph.nodeOrder())
099        .incidentEdgeOrder(graph.incidentEdgeOrder());
100  }
101
102  /**
103   * Returns an {@link ImmutableValueGraph.Builder} with the properties of this {@link
104   * ValueGraphBuilder}.
105   *
106   * <p>The returned builder can be used for populating an {@link ImmutableValueGraph}.
107   *
108   * <p>Note that the returned builder will always have {@link #incidentEdgeOrder} set to {@link
109   * ElementOrder#stable()}, regardless of the value that was set in this builder.
110   *
111   * @since 28.0
112   */
113  public <N1 extends N, V1 extends V> ImmutableValueGraph.Builder<N1, V1> immutable() {
114    ValueGraphBuilder<N1, V1> castBuilder = cast();
115    return new ImmutableValueGraph.Builder<>(castBuilder);
116  }
117
118  /**
119   * Specifies whether the graph will allow self-loops (edges that connect a node to itself).
120   * Attempting to add a self-loop to a graph that does not allow them will throw an {@link
121   * UnsupportedOperationException}.
122   *
123   * <p>The default value is {@code false}.
124   */
125  public ValueGraphBuilder<N, V> allowsSelfLoops(boolean allowsSelfLoops) {
126    this.allowsSelfLoops = allowsSelfLoops;
127    return this;
128  }
129
130  /**
131   * Specifies the expected number of nodes in the graph.
132   *
133   * @throws IllegalArgumentException if {@code expectedNodeCount} is negative
134   */
135  public ValueGraphBuilder<N, V> expectedNodeCount(int expectedNodeCount) {
136    this.expectedNodeCount = Optional.of(checkNonNegative(expectedNodeCount));
137    return this;
138  }
139
140  /**
141   * Specifies the order of iteration for the elements of {@link Graph#nodes()}.
142   *
143   * <p>The default value is {@link ElementOrder#insertion() insertion order}.
144   */
145  public <N1 extends N> ValueGraphBuilder<N1, V> nodeOrder(ElementOrder<N1> nodeOrder) {
146    ValueGraphBuilder<N1, V> newBuilder = cast();
147    newBuilder.nodeOrder = checkNotNull(nodeOrder);
148    return newBuilder;
149  }
150
151  /**
152   * Specifies the order of iteration for the elements of {@link ValueGraph#edges()}, {@link
153   * ValueGraph#adjacentNodes(Object)}, {@link ValueGraph#predecessors(Object)}, {@link
154   * ValueGraph#successors(Object)} and {@link ValueGraph#incidentEdges(Object)}.
155   *
156   * <p>The default value is {@link ElementOrder#unordered() unordered} for mutable graphs. For
157   * immutable graphs, this value is ignored; they always have a {@link ElementOrder#stable()
158   * stable} order.
159   *
160   * @throws IllegalArgumentException if {@code incidentEdgeOrder} is not either {@code
161   *     ElementOrder.unordered()} or {@code ElementOrder.stable()}.
162   * @since 29.0
163   */
164  public <N1 extends N> ValueGraphBuilder<N1, V> incidentEdgeOrder(
165      ElementOrder<N1> incidentEdgeOrder) {
166    checkArgument(
167        incidentEdgeOrder.type() == ElementOrder.Type.UNORDERED
168            || incidentEdgeOrder.type() == ElementOrder.Type.STABLE,
169        "The given elementOrder (%s) is unsupported. incidentEdgeOrder() only supports"
170            + " ElementOrder.unordered() and ElementOrder.stable().",
171        incidentEdgeOrder);
172    ValueGraphBuilder<N1, V> newBuilder = cast();
173    newBuilder.incidentEdgeOrder = checkNotNull(incidentEdgeOrder);
174    return newBuilder;
175  }
176  /**
177   * Returns an empty {@link MutableValueGraph} with the properties of this {@link
178   * ValueGraphBuilder}.
179   */
180  public <N1 extends N, V1 extends V> MutableValueGraph<N1, V1> build() {
181    return new StandardMutableValueGraph<>(this);
182  }
183
184  ValueGraphBuilder<N, V> copy() {
185    ValueGraphBuilder<N, V> newBuilder = new ValueGraphBuilder<>(directed);
186    newBuilder.allowsSelfLoops = allowsSelfLoops;
187    newBuilder.nodeOrder = nodeOrder;
188    newBuilder.expectedNodeCount = expectedNodeCount;
189    newBuilder.incidentEdgeOrder = incidentEdgeOrder;
190    return newBuilder;
191  }
192
193  @SuppressWarnings("unchecked")
194  private <N1 extends N, V1 extends V> ValueGraphBuilder<N1, V1> cast() {
195    return (ValueGraphBuilder<N1, V1>) this;
196  }
197}