-
Notifications
You must be signed in to change notification settings - Fork 10.9k
/
AbstractNetwork.java
291 lines (256 loc) · 9.04 KB
/
AbstractNetwork.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
/*
* Copyright (C) 2016 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.graph;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.graph.GraphConstants.ENDPOINTS_MISMATCH;
import static com.google.common.graph.GraphConstants.MULTIPLE_EDGES_CONNECTING;
import static java.util.Collections.unmodifiableSet;
import com.google.common.annotations.Beta;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterators;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.math.IntMath;
import java.util.AbstractSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.checkerframework.checker.nullness.compatqual.NullableDecl;
/**
* This class provides a skeletal implementation of {@link Network}. It is recommended to extend
* this class rather than implement {@link Network} directly.
*
* <p>The methods implemented in this class should not be overridden unless the subclass admits a
* more efficient implementation.
*
* @author James Sexton
* @param <N> Node parameter type
* @param <E> Edge parameter type
* @since 20.0
*/
@Beta
public abstract class AbstractNetwork<N, E> implements Network<N, E> {
@Override
public Graph<N> asGraph() {
return new AbstractGraph<N>() {
@Override
public Set<N> nodes() {
return AbstractNetwork.this.nodes();
}
@Override
public Set<EndpointPair<N>> edges() {
if (allowsParallelEdges()) {
return super.edges(); // Defer to AbstractGraph implementation.
}
// Optimized implementation assumes no parallel edges (1:1 edge to EndpointPair mapping).
return new AbstractSet<EndpointPair<N>>() {
@Override
public Iterator<EndpointPair<N>> iterator() {
return Iterators.transform(
AbstractNetwork.this.edges().iterator(),
new Function<E, EndpointPair<N>>() {
@Override
public EndpointPair<N> apply(E edge) {
return incidentNodes(edge);
}
});
}
@Override
public int size() {
return AbstractNetwork.this.edges().size();
}
// Mostly safe: We check contains(u) before calling successors(u), so we perform unsafe
// operations only in weird cases like checking for an EndpointPair<ArrayList> in a
// Network<LinkedList>.
@SuppressWarnings("unchecked")
@Override
public boolean contains(@NullableDecl Object obj) {
if (!(obj instanceof EndpointPair)) {
return false;
}
EndpointPair<?> endpointPair = (EndpointPair<?>) obj;
return isOrderingCompatible(endpointPair)
&& nodes().contains(endpointPair.nodeU())
&& successors((N) endpointPair.nodeU()).contains(endpointPair.nodeV());
}
};
}
@Override
public ElementOrder<N> nodeOrder() {
return AbstractNetwork.this.nodeOrder();
}
@Override
public ElementOrder<N> incidentEdgeOrder() {
// TODO(b/142723300): Return AbstractNetwork.this.incidentEdgeOrder() once Network has that
// method.
return ElementOrder.unordered();
}
@Override
public boolean isDirected() {
return AbstractNetwork.this.isDirected();
}
@Override
public boolean allowsSelfLoops() {
return AbstractNetwork.this.allowsSelfLoops();
}
@Override
public Set<N> adjacentNodes(N node) {
return AbstractNetwork.this.adjacentNodes(node);
}
@Override
public Set<N> predecessors(N node) {
return AbstractNetwork.this.predecessors(node);
}
@Override
public Set<N> successors(N node) {
return AbstractNetwork.this.successors(node);
}
// DO NOT override the AbstractGraph *degree() implementations.
};
}
@Override
public int degree(N node) {
if (isDirected()) {
return IntMath.saturatedAdd(inEdges(node).size(), outEdges(node).size());
} else {
return IntMath.saturatedAdd(incidentEdges(node).size(), edgesConnecting(node, node).size());
}
}
@Override
public int inDegree(N node) {
return isDirected() ? inEdges(node).size() : degree(node);
}
@Override
public int outDegree(N node) {
return isDirected() ? outEdges(node).size() : degree(node);
}
@Override
public Set<E> adjacentEdges(E edge) {
EndpointPair<N> endpointPair = incidentNodes(edge); // Verifies that edge is in this network.
Set<E> endpointPairIncidentEdges =
Sets.union(incidentEdges(endpointPair.nodeU()), incidentEdges(endpointPair.nodeV()));
return Sets.difference(endpointPairIncidentEdges, ImmutableSet.of(edge));
}
@Override
public Set<E> edgesConnecting(N nodeU, N nodeV) {
Set<E> outEdgesU = outEdges(nodeU);
Set<E> inEdgesV = inEdges(nodeV);
return outEdgesU.size() <= inEdgesV.size()
? unmodifiableSet(Sets.filter(outEdgesU, connectedPredicate(nodeU, nodeV)))
: unmodifiableSet(Sets.filter(inEdgesV, connectedPredicate(nodeV, nodeU)));
}
@Override
public Set<E> edgesConnecting(EndpointPair<N> endpoints) {
validateEndpoints(endpoints);
return edgesConnecting(endpoints.nodeU(), endpoints.nodeV());
}
private Predicate<E> connectedPredicate(final N nodePresent, final N nodeToCheck) {
return new Predicate<E>() {
@Override
public boolean apply(E edge) {
return incidentNodes(edge).adjacentNode(nodePresent).equals(nodeToCheck);
}
};
}
@Override
@NullableDecl
public E edgeConnectingOrNull(N nodeU, N nodeV) {
Set<E> edgesConnecting = edgesConnecting(nodeU, nodeV);
switch (edgesConnecting.size()) {
case 0:
return null;
case 1:
return edgesConnecting.iterator().next();
default:
throw new IllegalArgumentException(String.format(MULTIPLE_EDGES_CONNECTING, nodeU, nodeV));
}
}
@Override
@NullableDecl
public E edgeConnectingOrNull(EndpointPair<N> endpoints) {
validateEndpoints(endpoints);
return edgeConnectingOrNull(endpoints.nodeU(), endpoints.nodeV());
}
@Override
public boolean hasEdgeConnecting(N nodeU, N nodeV) {
checkNotNull(nodeU);
checkNotNull(nodeV);
return nodes().contains(nodeU) && successors(nodeU).contains(nodeV);
}
@Override
public boolean hasEdgeConnecting(EndpointPair<N> endpoints) {
checkNotNull(endpoints);
if (!isOrderingCompatible(endpoints)) {
return false;
}
return hasEdgeConnecting(endpoints.nodeU(), endpoints.nodeV());
}
/**
* Throws an IllegalArgumentException if the ordering of {@code endpoints} is not compatible with
* the directionality of this graph.
*/
protected final void validateEndpoints(EndpointPair<?> endpoints) {
checkNotNull(endpoints);
checkArgument(isOrderingCompatible(endpoints), ENDPOINTS_MISMATCH);
}
protected final boolean isOrderingCompatible(EndpointPair<?> endpoints) {
return endpoints.isOrdered() || !this.isDirected();
}
@Override
public final boolean equals(@NullableDecl Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof Network)) {
return false;
}
Network<?, ?> other = (Network<?, ?>) obj;
return isDirected() == other.isDirected()
&& nodes().equals(other.nodes())
&& edgeIncidentNodesMap(this).equals(edgeIncidentNodesMap(other));
}
@Override
public final int hashCode() {
return edgeIncidentNodesMap(this).hashCode();
}
/** Returns a string representation of this network. */
@Override
public String toString() {
return "isDirected: "
+ isDirected()
+ ", allowsParallelEdges: "
+ allowsParallelEdges()
+ ", allowsSelfLoops: "
+ allowsSelfLoops()
+ ", nodes: "
+ nodes()
+ ", edges: "
+ edgeIncidentNodesMap(this);
}
private static <N, E> Map<E, EndpointPair<N>> edgeIncidentNodesMap(final Network<N, E> network) {
Function<E, EndpointPair<N>> edgeToIncidentNodesFn =
new Function<E, EndpointPair<N>>() {
@Override
public EndpointPair<N> apply(E edge) {
return network.incidentNodes(edge);
}
};
return Maps.asMap(network.edges(), edgeToIncidentNodesFn);
}
}