Unnamed: 0
int64 0
6.7k
| func
stringlengths 12
89.6k
| target
bool 2
classes | project
stringlengths 45
151
|
|---|---|---|---|
3,500
|
public class SchemaIndexWaitingAcceptanceTest
{
private final ControlledPopulationSchemaIndexProvider provider = new ControlledPopulationSchemaIndexProvider();
@Rule
public ImpermanentDatabaseRule rule = new ImpermanentDatabaseRule()
{
@Override
protected void configure( GraphDatabaseFactory databaseFactory )
{
List<KernelExtensionFactory<?>> extensions;
extensions = Arrays.<KernelExtensionFactory<?>>asList( singleInstanceSchemaIndexProviderFactory(
"test", provider ) );
databaseFactory.addKernelExtensions( extensions );
}
};
@Test
public void shouldTimeoutWatingForIndexToComeOnline() throws Exception
{
// given
GraphDatabaseService db = rule.getGraphDatabaseService();
DoubleLatch latch = provider.installPopulationJobCompletionLatch();
Transaction tx = db.beginTx();
IndexDefinition index = db.schema().indexFor( DynamicLabel.label( "Person" ) ).on( "name" ).create();
tx.success();
tx.finish();
latch.awaitStart();
tx = db.beginTx();
// when
try
{
// then
db.schema().awaitIndexOnline( index, 1, TimeUnit.MILLISECONDS );
fail( "Expected IllegalStateException to be thrown" );
}
catch ( IllegalStateException e )
{
// good
assertThat( e.getMessage(), containsString( "come online" ) );
}
finally
{
tx.finish();
latch.finish();
}
}
@Test
public void shouldTimeoutWatingForAllIndexesToComeOnline() throws Exception
{
// given
GraphDatabaseService db = rule.getGraphDatabaseService();
DoubleLatch latch = provider.installPopulationJobCompletionLatch();
Transaction tx = db.beginTx();
db.schema().indexFor( DynamicLabel.label( "Person" ) ).on( "name" ).create();
tx.success();
tx.finish();
latch.awaitStart();
tx = db.beginTx();
// when
try
{
// then
db.schema().awaitIndexesOnline( 1, TimeUnit.MILLISECONDS );
fail( "Expected IllegalStateException to be thrown" );
}
catch ( IllegalStateException e )
{
// good
assertThat( e.getMessage(), containsString( "come online" ) );
}
finally
{
latch.finish();
tx.finish();
}
}
}
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_SchemaIndexWaitingAcceptanceTest.java
|
3,501
|
public class GraphDatabaseFactory
{
private final GraphDatabaseFactoryState state;
public GraphDatabaseFactory()
{
this( new GraphDatabaseFactoryState() );
}
protected GraphDatabaseFactory(GraphDatabaseFactoryState state)
{
this.state = state;
}
protected GraphDatabaseFactoryState getCurrentState()
{
return state;
}
protected GraphDatabaseFactoryState getStateCopy()
{
return new GraphDatabaseFactoryState( getCurrentState() );
}
public GraphDatabaseService newEmbeddedDatabase( String path )
{
return newEmbeddedDatabaseBuilder( path ).newGraphDatabase();
}
public GraphDatabaseBuilder newEmbeddedDatabaseBuilder( final String path )
{
final GraphDatabaseFactoryState state = getStateCopy();
return new GraphDatabaseBuilder( new GraphDatabaseBuilder.DatabaseCreator()
{
@SuppressWarnings("deprecation")
@Override
public GraphDatabaseService newDatabase( Map<String, String> config )
{
config.put( "ephemeral", "false" );
Dependencies dependencies = state.databaseDependencies();
if ( TRUE.equalsIgnoreCase( config.get( read_only.name() ) ) )
{
return new EmbeddedReadOnlyGraphDatabase( path, config, dependencies );
}
else
{
return new EmbeddedGraphDatabase( path, config, dependencies );
}
}
} );
}
/**
* @deprecated Manipulating kernel extensions is deprecated and will be moved to internal components.
*/
@Deprecated
public Iterable<KernelExtensionFactory<?>> getKernelExtension()
{
return getCurrentState().getKernelExtension();
}
/**
* @deprecated Manipulating kernel extensions is deprecated and will be moved to internal components.
*/
@Deprecated
public GraphDatabaseFactory addKernelExtensions( Iterable<KernelExtensionFactory<?>> newKernelExtensions )
{
getCurrentState().addKernelExtensions( newKernelExtensions );
return this;
}
/**
* @deprecated Manipulating kernel extensions is deprecated and will be moved to internal components.
*/
@Deprecated
@SuppressWarnings( { "rawtypes", "unchecked" } )
public GraphDatabaseFactory addKernelExtension( KernelExtensionFactory<?> newKernelExtension )
{
List extensions = asList(newKernelExtension );
return addKernelExtensions( extensions );
}
/**
* @deprecated Manipulating kernel extensions is deprecated and will be moved to internal components.
*/
@Deprecated
public GraphDatabaseFactory setKernelExtensions( Iterable<KernelExtensionFactory<?>> newKernelExtensions )
{
getCurrentState().setKernelExtensions( newKernelExtensions );
return this;
}
/**
* @deprecated Manipulating cache providers is deprecated and will be moved to internal components.
*/
@Deprecated
public List<CacheProvider> getCacheProviders()
{
return getCurrentState().getCacheProviders();
}
/**
* @deprecated Manipulating cache providers is deprecated and will be moved to internal components.
*/
@Deprecated
public GraphDatabaseFactory setCacheProviders( Iterable<CacheProvider> newCacheProviders )
{
getCurrentState().setCacheProviders( newCacheProviders );
return this;
}
/**
* @deprecated Manipulating cache providers is deprecated and will be moved to internal components.
*/
@Deprecated
public List<TransactionInterceptorProvider> getTransactionInterceptorProviders()
{
return getCurrentState().getTransactionInterceptorProviders();
}
public GraphDatabaseFactory setTransactionInterceptorProviders( Iterable<TransactionInterceptorProvider> transactionInterceptorProviders )
{
getCurrentState().setTransactionInterceptorProviders( transactionInterceptorProviders );
return this;
}
}
| false
|
community_kernel_src_main_java_org_neo4j_graphdb_factory_GraphDatabaseFactory.java
|
3,502
|
public static class Delegator extends GraphDatabaseBuilder
{
private final GraphDatabaseBuilder actual;
public Delegator( GraphDatabaseBuilder actual )
{
super( null );
this.actual = actual;
}
@Override
public GraphDatabaseBuilder setConfig( Setting<?> setting, String value )
{
actual.setConfig( setting, value );
return this;
}
@Override
@SuppressWarnings("deprecation")
public GraphDatabaseBuilder setConfig( String name, String value )
{
actual.setConfig( name, value );
return this;
}
@Override
public GraphDatabaseBuilder setConfig( Map<String, String> config )
{
actual.setConfig( config );
return this;
}
@Override
public GraphDatabaseBuilder loadPropertiesFromFile( String fileName ) throws IllegalArgumentException
{
actual.loadPropertiesFromFile( fileName );
return this;
}
@Override
public GraphDatabaseBuilder loadPropertiesFromURL( URL url ) throws IllegalArgumentException
{
actual.loadPropertiesFromURL( url );
return this;
}
@Override
public GraphDatabaseService newGraphDatabase()
{
return actual.newGraphDatabase();
}
}
| false
|
community_kernel_src_main_java_org_neo4j_graphdb_factory_GraphDatabaseBuilder.java
|
3,503
|
public class GraphDatabaseBuilder
{
public interface DatabaseCreator
{
GraphDatabaseService newDatabase( Map<String, String> config );
}
protected DatabaseCreator creator;
protected Map<String, String> config = new HashMap<String, String>();
public GraphDatabaseBuilder( DatabaseCreator creator )
{
this.creator = creator;
}
/**
* Set a database setting to a particular value.
*
* @return the builder
*/
public GraphDatabaseBuilder setConfig( Setting<?> setting, String value )
{
if ( value == null )
{
config.remove( setting.name() );
}
else
{
// Test if we can get this setting with an updated config
Map<String, String> testValue = stringMap( setting.name(), value );
setting.apply( withDefaults( map( config ), map( testValue ) ) );
// No exception thrown, add it to existing config
config.put( setting.name(), value );
}
return this;
}
/**
* Set an unvalidated configuration option.
* @deprecated Use setConfig with explicit {@link Setting} instead
*/
@Deprecated
public GraphDatabaseBuilder setConfig( String name, String value )
{
if ( value == null )
{
config.remove( name );
}
else
{
config.put( name, value );
}
return this;
/* TODO When all settings are in GraphDatabaseSettings, then use this instead
try
{
GraphDatabaseSetting setting = (GraphDatabaseSetting) CommunityGraphDatabaseSetting.class.getField( name
).get( null );
setConfig( setting, value );
return this;
}
catch( IllegalAccessException e )
{
throw new IllegalArgumentException( "Unknown configuration setting:"+name );
}
catch( NoSuchFieldException e )
{
throw new IllegalArgumentException( "Unknown configuration setting:"+name );
}
*/
}
/**
* Set a map of config settings into the builder. Overwrites any existing values.
*
* @return the builder
* @deprecated Use setConfig with explicit {@link Setting} instead
*/
@Deprecated
@SuppressWarnings("deprecation")
public GraphDatabaseBuilder setConfig( Map<String, String> config )
{
for ( Map.Entry<String, String> stringStringEntry : config.entrySet() )
{
setConfig( stringStringEntry.getKey(), stringStringEntry.getValue() );
}
return this;
}
/**
* Load a Properties file from a given file, and add the settings to
* the builder.
*
* @return the builder
* @throws IllegalArgumentException if the builder was unable to load from the given filename
*/
public GraphDatabaseBuilder loadPropertiesFromFile( String fileName )
throws IllegalArgumentException
{
try
{
return loadPropertiesFromURL( new File( fileName ).toURI().toURL() );
}
catch ( MalformedURLException e )
{
throw new IllegalArgumentException( "Illegal filename:" + fileName );
}
}
/**
* Load Properties file from a given URL, and add the settings to
* the builder.
*
* @return the builder
*/
public GraphDatabaseBuilder loadPropertiesFromURL( URL url )
throws IllegalArgumentException
{
Properties props = new Properties();
try
{
InputStream stream = url.openStream();
try
{
props.load( stream );
}
finally
{
stream.close();
}
}
catch ( Exception e )
{
throw new IllegalArgumentException( "Unable to load " + url, e );
}
Set<Map.Entry<Object, Object>> entries = props.entrySet();
for ( Map.Entry<Object, Object> entry : entries )
{
String key = (String) entry.getKey();
String value = (String) entry.getValue();
setConfig( key, value );
}
return this;
}
/**
* Create a new database with the configuration registered
* through the builder.
*
* @return an instance of GraphDatabaseService
*/
public GraphDatabaseService newGraphDatabase()
{
return creator.newDatabase( config );
}
public static class Delegator extends GraphDatabaseBuilder
{
private final GraphDatabaseBuilder actual;
public Delegator( GraphDatabaseBuilder actual )
{
super( null );
this.actual = actual;
}
@Override
public GraphDatabaseBuilder setConfig( Setting<?> setting, String value )
{
actual.setConfig( setting, value );
return this;
}
@Override
@SuppressWarnings("deprecation")
public GraphDatabaseBuilder setConfig( String name, String value )
{
actual.setConfig( name, value );
return this;
}
@Override
public GraphDatabaseBuilder setConfig( Map<String, String> config )
{
actual.setConfig( config );
return this;
}
@Override
public GraphDatabaseBuilder loadPropertiesFromFile( String fileName ) throws IllegalArgumentException
{
actual.loadPropertiesFromFile( fileName );
return this;
}
@Override
public GraphDatabaseBuilder loadPropertiesFromURL( URL url ) throws IllegalArgumentException
{
actual.loadPropertiesFromURL( url );
return this;
}
@Override
public GraphDatabaseService newGraphDatabase()
{
return actual.newGraphDatabase();
}
}
}
| false
|
community_kernel_src_main_java_org_neo4j_graphdb_factory_GraphDatabaseBuilder.java
|
3,504
|
class Adapter<T> implements TransactionEventHandler<T>
{
@Override
public T beforeCommit( TransactionData data ) throws Exception
{
return null;
}
@Override
public void afterCommit( TransactionData data, T state )
{
}
@Override
public void afterRollback( TransactionData data, T state )
{
}
}
| false
|
community_kernel_src_main_java_org_neo4j_graphdb_event_TransactionEventHandler.java
|
3,505
|
public class TransactionFailureException extends RuntimeException
{
public TransactionFailureException( String msg )
{
super( msg );
}
public TransactionFailureException( String msg, Throwable cause )
{
super( msg, cause );
}
}
| false
|
community_kernel_src_main_java_org_neo4j_graphdb_TransactionFailureException.java
|
3,506
|
{
public boolean isStopNode( final TraversalPosition currentPosition )
{
return currentPosition.depth() >= 1;
}
};
| false
|
community_kernel_src_main_java_org_neo4j_graphdb_StopEvaluator.java
|
3,507
|
{
public boolean isStopNode( final TraversalPosition currentPosition )
{
return false;
}
};
| false
|
community_kernel_src_main_java_org_neo4j_graphdb_StopEvaluator.java
|
3,508
|
{
@Override
protected void configure( GraphDatabaseFactory databaseFactory )
{
List<KernelExtensionFactory<?>> extensions;
extensions = Arrays.<KernelExtensionFactory<?>>asList( singleInstanceSchemaIndexProviderFactory(
"test", provider ) );
databaseFactory.addKernelExtensions( extensions );
}
};
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_SchemaIndexWaitingAcceptanceTest.java
|
3,509
|
{
@Override
public void call( Schema self )
{
self.awaitIndexOnline( INDEX_DEFINITION, 1l, TimeUnit.SECONDS );
}
};
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_SchemaFacadeMethods.java
|
3,510
|
{
@Override
public void call( Schema self )
{
self.indexFor( LABEL );
}
};
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_SchemaFacadeMethods.java
|
3,511
|
{
@Override
public void call( Schema self )
{
self.getConstraints();
}
};
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_SchemaFacadeMethods.java
|
3,512
|
{
@Override
public void call( Schema self )
{
self.getConstraints( LABEL );
}
};
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_SchemaFacadeMethods.java
|
3,513
|
{
@Override
public void call( Schema self )
{
self.constraintFor( LABEL );
}
};
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_SchemaFacadeMethods.java
|
3,514
|
{
@Override
public void call( Schema self )
{
self.getIndexFailure( INDEX_DEFINITION );
}
};
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_SchemaFacadeMethods.java
|
3,515
|
{
@Override
public void call( Schema self )
{
self.getIndexState( INDEX_DEFINITION );
}
};
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_SchemaFacadeMethods.java
|
3,516
|
{
@Override
public void call( Schema self )
{
self.getIndexes();
}
};
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_SchemaFacadeMethods.java
|
3,517
|
{
@Override
public void call( Schema self )
{
self.getIndexes( LABEL );
}
};
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_SchemaFacadeMethods.java
|
3,518
|
{
@Override
public void call( Schema self )
{
self.awaitIndexesOnline( 1l, TimeUnit.SECONDS );
}
};
| false
|
community_kernel_src_test_java_org_neo4j_graphdb_SchemaFacadeMethods.java
|
3,519
|
public class LuceneLabelScanStoreIT extends LabelScanStoreIT
{
// Just extending the IT from kernel which pulls in the same tests, but with the important difference
// that the LuceneLasbelScanStore is on the class path, and will therefore be selected instead of
// an in-memory store.
}
| false
|
community_lucene-index_src_test_java_org_neo4j_graphdb_LuceneLabelScanStoreIT.java
|
3,520
|
{
@Override
public void run( FileSystemAbstraction fs, File storeDirectory )
{
try
{
int filesCorrupted = 0;
for ( File file : labelScanStoreIndexDirectory( storeDirectory ).listFiles() )
{
scrambleFile( file );
filesCorrupted++;
}
assertTrue( "No files found to corrupt", filesCorrupted > 0 );
}
catch ( IOException e )
{
throw new RuntimeException( e );
}
}
};
| false
|
community_lucene-index_src_test_java_org_neo4j_graphdb_LuceneLabelScanStoreChaosIT.java
|
3,521
|
{
public int compare( HeapObject o1, HeapObject o2 )
{
return costComparator.compare( o1.getCost(), o2.getCost() );
}
} );
| false
|
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_shortestpath_DijkstraPriorityQueueFibonacciImpl.java
|
3,522
|
public class TestDijkstra extends Neo4jAlgoTestCase
{
private Relationship createGraph( boolean includeOnes )
{
/* Layout:
* (y)
* ^
* [2] _____[1]___
* \ v |
* (start)--[1]->(a)--[9]-->(x)<- (e)--[2]->(f)
* | ^ ^^ \ ^
* [1] ---[7][5][3] -[3] [1]
* v / | / \ /
* (b)--[1]-->(c)--[1]->(d)
*/
Map<String, Object> propertiesForOnes = includeOnes ? map( "cost", (double) 1 ) : map();
graph.makeEdge( "start", "a", "cost", (double) 1 );
graph.makeEdge( "a", "x", "cost", (double) 9 );
graph.makeEdge( "a", "b", propertiesForOnes );
graph.makeEdge( "b", "x", "cost", (double) 7 );
graph.makeEdge( "b", "c", propertiesForOnes );
graph.makeEdge( "c", "x", "cost", (double) 5 );
Relationship shortCTOXRelationship = graph.makeEdge( "c", "x", "cost", (double) 3 );
graph.makeEdge( "c", "d", propertiesForOnes );
graph.makeEdge( "d", "x", "cost", (double) 3 );
graph.makeEdge( "d", "e", propertiesForOnes );
graph.makeEdge( "e", "x", propertiesForOnes );
graph.makeEdge( "e", "f", "cost", (double) 2 );
graph.makeEdge( "x", "y", "cost", (double) 2 );
return shortCTOXRelationship;
}
@Test
public void testSmallGraph()
{
Relationship shortCTOXRelationship = createGraph( true );
PathFinder<WeightedPath> finder = GraphAlgoFactory.dijkstra(
Traversal.expanderForTypes( MyRelTypes.R1, Direction.OUTGOING ), "cost" );
PathFinder<WeightedPath> finder2 = GraphAlgoFactory.dijkstra(
Traversal.expanderForTypes( MyRelTypes.R1, Direction.OUTGOING ),
CommonEvaluators.doubleCostEvaluator( "cost" ) );
// Assert that there are two matching paths
Node startNode = graph.getNode( "start" );
Node endNode = graph.getNode( "x" );
assertPaths( finder.findAllPaths( startNode, endNode ),
"start,a,b,c,x", "start,a,b,c,d,e,x" );
assertPaths( finder2.findAllPaths( startNode, endNode ),
"start,a,b,c,x", "start,a,b,c,d,e,x" );
// Assert that for the shorter one it picked the correct relationship
// of the two from (c) --> (x)
for ( WeightedPath path : finder.findAllPaths( startNode, endNode ) )
{
if ( getPathDef( path ).equals( "start,a,b,c,x" ) )
{
assertContainsRelationship( path, shortCTOXRelationship );
}
}
}
@Test
public void testSmallGraphWithDefaults()
{
Relationship shortCTOXRelationship = createGraph( true );
PathFinder<WeightedPath> finder = GraphAlgoFactory.dijkstra(
Traversal.expanderForTypes( MyRelTypes.R1, Direction.OUTGOING ),
CommonEvaluators.doubleCostEvaluator( "cost", 1.0d ) );
// Assert that there are two matching paths
Node startNode = graph.getNode( "start" );
Node endNode = graph.getNode( "x" );
assertPaths( finder.findAllPaths( startNode, endNode ),
"start,a,b,c,x", "start,a,b,c,d,e,x" );
// Assert that for the shorter one it picked the correct relationship
// of the two from (c) --> (x)
for ( WeightedPath path : finder.findAllPaths( startNode, endNode ) )
{
if ( getPathDef( path ).equals( "start,a,b,c,x" ) )
{
assertContainsRelationship( path, shortCTOXRelationship );
}
}
}
private void assertContainsRelationship( WeightedPath path,
Relationship relationship )
{
for ( Relationship rel : path.relationships() )
{
if ( rel.equals( relationship ) )
{
return;
}
}
fail( path + " should've contained " + relationship );
}
@Ignore( "See issue #627" )
@Test
public void determineLongestPath() throws Exception
{
/*
* --------
* | \
* | --(0)-[-0.1]->(1)
* | | \ |
* [-0.1] | [-0.1] [-0.1]
* | | \ v
* | [-1.0] ------>(2)
* | \ |
* v --v |
* (4)<-[-0.1]-(3)<-[-1.0]-
*
* Shortest path: 0->1->2->3->4
*/
RelationshipType type = DynamicRelationshipType.withName( "EDGE" );
graph.setCurrentRelType( type );
graph.makeEdgeChain( "0,1,2,3,4" );
graph.makeEdge( "0", "2" );
graph.makeEdge( "0", "3" );
graph.makeEdge( "0", "4" );
setWeight( "0", "1", -0.1 );
setWeight( "1", "2", -0.1 );
setWeight( "2", "3", -1.0 );
setWeight( "3", "4", -0.1 );
setWeight( "0", "2", -0.1 );
setWeight( "0", "3", -1.0 );
setWeight( "0", "4", -0.1 );
Node node0 = graph.getNode( "0" );
Node node1 = graph.getNode( "1" );
Node node2 = graph.getNode( "2" );
Node node3 = graph.getNode( "3" );
Node node4 = graph.getNode( "4" );
PathFinder<WeightedPath> pathFinder = GraphAlgoFactory.dijkstra(
Traversal.expanderForTypes( type, Direction.OUTGOING ), "weight" );
WeightedPath wPath = pathFinder.findSinglePath( node0, node4 );
assertPath( wPath, node0, node1, node2, node3, node4 );
}
@Test
public void withState() throws Exception
{
/* Graph
*
* (a)-[1]->(b)-[2]->(c)-[5]->(d)
*/
graph.makeEdgeChain( "a,b,c,d" );
setWeight( "a", "b", 1 );
setWeight( "b", "c", 2 );
setWeight( "c", "d", 5 );
InitialBranchState<Integer> state = new InitialBranchState.State<Integer>( 0, 0 );
final Map<Node, Integer> encounteredState = new HashMap<Node, Integer>();
PathExpander<Integer> expander = new PathExpander<Integer>()
{
@Override
public Iterable<Relationship> expand( Path path, BranchState<Integer> state )
{
if ( path.length() > 0 )
{
int newState = state.getState() + ((Number)path.lastRelationship().getProperty( "weight" )).intValue();
state.setState( newState );
encounteredState.put( path.endNode(), newState );
}
return path.endNode().getRelationships();
}
@Override
public PathExpander<Integer> reverse()
{
return this;
}
};
assertPaths( dijkstra( expander, state, "weight" ).findAllPaths( graph.getNode( "a" ), graph.getNode( "d" ) ),
"a,b,c,d" );
assertEquals( 1, encounteredState.get( graph.getNode( "b" ) ).intValue() );
assertEquals( 3, encounteredState.get( graph.getNode( "c" ) ).intValue() );
assertEquals( 8, encounteredState.get( graph.getNode( "d" ) ).intValue() );
}
private void setWeight( String start, String end, double weight )
{
Node startNode = graph.getNode( start );
Node endNode = graph.getNode( end );
for ( Relationship rel : startNode.getRelationships() )
{
if ( rel.getOtherNode( startNode ).equals( endNode ) )
{
rel.setProperty( "weight", weight );
return;
}
}
throw new RuntimeException( "No relationship between nodes " + start + " and " + end );
}
}
| false
|
community_graph-algo_src_test_java_org_neo4j_graphalgo_path_TestDijkstra.java
|
3,523
|
public class TestAllPaths extends Neo4jAlgoTestCase
{
protected PathFinder<Path> instantiatePathFinder( int maxDepth )
{
return allPaths( expanderForAllTypes(), maxDepth );
}
@Test
public void testCircularGraph()
{
/* Layout
*
* (a)---(b)===(c)---(e)
* \ /
* (d)
*/
graph.makeEdge( "a", "b" );
graph.makeEdge( "b", "c" );
graph.makeEdge( "b", "c" );
graph.makeEdge( "b", "d" );
graph.makeEdge( "c", "d" );
graph.makeEdge( "c", "e" );
PathFinder<Path> finder = instantiatePathFinder( 10 );
Iterable<Path> paths = finder.findAllPaths( graph.getNode( "a" ), graph.getNode( "e" ) );
assertPaths( paths, "a,b,c,e", "a,b,c,e", "a,b,d,c,e", "a,b,c,d,b,c,e", "a,b,c,d,b,c,e",
"a,b,c,b,d,c,e", "a,b,c,b,d,c,e", "a,b,d,c,b,c,e", "a,b,d,c,b,c,e" );
}
@Test
public void testTripleRelationshipGraph()
{
/* Layout
* ___
* (a)---(b)===(c)---(d)
*/
graph.makeEdge( "a", "b" );
graph.makeEdge( "b", "c" );
graph.makeEdge( "b", "c" );
graph.makeEdge( "b", "c" );
graph.makeEdge( "c", "d" );
PathFinder<Path> finder = instantiatePathFinder( 10 );
Iterable<Path> paths = finder.findAllPaths( graph.getNode( "a" ), graph.getNode( "d" ) );
assertPaths( paths, "a,b,c,d", "a,b,c,d", "a,b,c,d",
"a,b,c,b,c,d", "a,b,c,b,c,d", "a,b,c,b,c,d", "a,b,c,b,c,d",
"a,b,c,b,c,d", "a,b,c,b,c,d" );
}
}
| false
|
community_graph-algo_src_test_java_org_neo4j_graphalgo_path_TestAllPaths.java
|
3,524
|
{
@Override
public Double getCost( Node node, Node goal )
{
double dx = (Double) node.getProperty( "x" )
- (Double) goal.getProperty( "x" );
double dy = (Double) node.getProperty( "y" )
- (Double) goal.getProperty( "y" );
double result = Math.sqrt( Math.pow( dx, 2 ) + Math.pow( dy, 2 ) );
return result;
}
};
| false
|
community_graph-algo_src_test_java_org_neo4j_graphalgo_path_TestAStar.java
|
3,525
|
{
@Override
public Double getCost( Node node, Node goal )
{
return ((Double)node.getProperty( "estimate" ));
}
};
| false
|
community_graph-algo_src_test_java_org_neo4j_graphalgo_path_TestAStar.java
|
3,526
|
{
@Override
public Iterable<Relationship> expand( Path path, BranchState<Double> state )
{
double newState = state.getState();
if ( path.length() > 0 )
{
newState += (Double) path.lastRelationship().getProperty( "length" );
state.setState( newState );
}
seenBranchStates.put( path.endNode(), newState );
return path.endNode().getRelationships( OUTGOING );
}
@Override
public PathExpander<Double> reverse()
{
throw new UnsupportedOperationException();
}
};
| false
|
community_graph-algo_src_test_java_org_neo4j_graphalgo_path_TestAStar.java
|
3,527
|
@RunWith( Parameterized.class )
public class TestAStar extends Neo4jAlgoTestCase
{
@Test
public void wikipediaExample() throws Exception
{
/* GIVEN
*
* (start)---2--->(d)
* \ \
* 1.5 .\
* v 3
* (a)-\ v
* -2-\ (e)
* ->(b) \
* / \
* /-- 2
* /-3- v
* v --4------->(end)
* (c)------/
*/
Node start = graph.makeNode( "start", "x", 0d, "y", 0d );
graph.makeNode( "a", "x", 0.3d, "y", 1d );
graph.makeNode( "b", "x", 2d, "y", 2d );
graph.makeNode( "c", "x", 0d, "y", 3d );
graph.makeNode( "d", "x", 2d, "y", 0d );
graph.makeNode( "e", "x", 3d, "y", 1.5d );
Node end = graph.makeNode( "end", "x", 3.3d, "y", 2.8d );
graph.makeEdge( "start", "a", "length", 1.5d );
graph.makeEdge( "a", "b", "length", 2d );
graph.makeEdge( "b", "c", "length", 3d );
graph.makeEdge( "c", "end", "length", 4d );
graph.makeEdge( "start", "d", "length", 2d );
graph.makeEdge( "d", "e", "length", 3d );
graph.makeEdge( "e", "end", "length", 2d );
// WHEN
WeightedPath path = finder.findSinglePath( start, end );
// THEN
assertPathDef( path, "start", "d", "e", "end" );
}
/**
* <pre>
* 01234567
* +-------->x A - C: 10
* 0|A C A - B: 2 (x2)
* 1| B B - C: 6
* V
* y
* </pre>
*/
@Test
public void testSimplest()
{
Node nodeA = graph.makeNode( "A", "x", 0d, "y", 0d );
Node nodeB = graph.makeNode( "B", "x", 2d, "y", 1d );
Node nodeC = graph.makeNode( "C", "x", 7d, "y", 0d );
Relationship relAB = graph.makeEdge( "A", "B", "length", 2d );
Relationship relAB2 = graph.makeEdge( "A", "B", "length", 2d );
Relationship relBC = graph.makeEdge( "B", "C", "length", 3d );
Relationship relAC = graph.makeEdge( "A", "C", "length", 10d );
int counter = 0;
for ( WeightedPath path : finder.findAllPaths( nodeA, nodeC ) )
{
assertEquals( (Double)5d, (Double)path.weight() );
assertPath( path, nodeA, nodeB, nodeC );
counter++;
}
assertEquals( 1, counter );
}
/**
* <pre>
* 01234567
* +-------->x A - C: 10
* 0|A C A - B: 2 (x2)
* 1| B B - C: 6
* V
* y
* </pre>
*/
@Ignore( "A* doesn't return multiple equal paths" )
@Test
public void canGetMultiplePathsInTriangleGraph() throws Exception
{
Node nodeA = graph.makeNode( "A", "x", 0d, "y", 0d );
Node nodeB = graph.makeNode( "B", "x", 2d, "y", 1d );
Node nodeC = graph.makeNode( "C", "x", 7d, "y", 0d );
Set<Relationship> expectedFirsts = new HashSet<Relationship>();
expectedFirsts.add( graph.makeEdge( "A", "B", "length", 2d ) );
expectedFirsts.add( graph.makeEdge( "A", "B", "length", 2d ) );
Relationship expectedSecond = graph.makeEdge( "B", "C", "length", 6d );
graph.makeEdge( "A", "C", "length", 10d );
Iterator<WeightedPath> paths = finder.findAllPaths( nodeA, nodeC ).iterator();
for ( int foundCount = 0; foundCount < 2; foundCount++ )
{
assertTrue( "expected more paths (found: " + foundCount + ")", paths.hasNext() );
Path path = paths.next();
assertPath( path, nodeA, nodeB, nodeC );
Iterator<Relationship> relationships = path.relationships().iterator();
assertTrue( "found shorter path than expected",
relationships.hasNext() );
assertTrue( "path contained unexpected relationship",
expectedFirsts.remove( relationships.next() ) );
assertTrue( "found shorter path than expected",
relationships.hasNext() );
assertEquals( expectedSecond, relationships.next() );
assertFalse( "found longer path than expected",
relationships.hasNext() );
}
assertFalse( "expected at most two paths", paths.hasNext() );
}
/**
* <pre>
* 012345 A - B: 2
* +------>x A - C: 2.5
* 0| C C - D: 7.3
* 1|A F B - D: 2.5
* 2| B D D - E: 3
* 3| E C - E: 5
* V E - F: 5
* x C - F: 12
* A - F: 25
* </pre>
*/
@Ignore( "A* doesn't return multiple equal paths" )
@Test
public void canGetMultiplePathsInASmallRoadNetwork() throws Exception
{
Node nodeA = graph.makeNode( "A", "x", 1d, "y", 0d );
Node nodeB = graph.makeNode( "B", "x", 2d, "y", 1d );
Node nodeC = graph.makeNode( "C", "x", 0d, "y", 2d );
Node nodeD = graph.makeNode( "D", "x", 2d, "y", 3d );
Node nodeE = graph.makeNode( "E", "x", 3d, "y", 4d );
Node nodeF = graph.makeNode( "F", "x", 1d, "y", 5d );
graph.makeEdge( "A", "B", "length", 2d );
graph.makeEdge( "A", "C", "length", 2.5d );
graph.makeEdge( "C", "D", "length", 7.3d );
graph.makeEdge( "B", "D", "length", 2.5d );
graph.makeEdge( "D", "E", "length", 3d );
graph.makeEdge( "C", "E", "length", 5d );
graph.makeEdge( "E", "F", "length", 5d );
graph.makeEdge( "C", "F", "length", 12d );
graph.makeEdge( "A", "F", "length", 25d );
// Try the search in both directions.
for ( Node[] nodes : new Node[][] { { nodeA, nodeF }, { nodeF, nodeA } } )
{
int found = 0;
Iterator<WeightedPath> paths = finder.findAllPaths( nodes[0], nodes[1] ).iterator();
for ( int foundCount = 0; foundCount < 2; foundCount++ )
{
assertTrue( "expected more paths (found: " + foundCount + ")", paths.hasNext() );
Path path = paths.next();
if ( path.length() != found && path.length() == 3 )
{
assertContains( path.nodes(), nodeA, nodeC, nodeE, nodeF );
}
else if ( path.length() != found && path.length() == 4 )
{
assertContains( path.nodes(), nodeA, nodeB, nodeD, nodeE,
nodeF );
}
else
{
fail( "unexpected path length: " + path.length() );
}
found = path.length();
}
assertFalse( "expected at most two paths", paths.hasNext() );
}
}
@SuppressWarnings( { "rawtypes", "unchecked" } )
@Test
public void canUseBranchState() throws Exception
{
// This test doesn't use the predefined finder, which only means an unnecessary instantiation
// if such an object. And this test will be run twice (once for each finder type in data()).
Node nodeA = graph.makeNode( "A", "x", 0d, "y", 0d );
Node nodeB = graph.makeNode( "B", "x", 2d, "y", 1d );
Node nodeC = graph.makeNode( "C", "x", 7d, "y", 0d );
graph.makeEdge( "A", "B", "length", 2d );
graph.makeEdge( "A", "B", "length", 2d );
graph.makeEdge( "B", "C", "length", 3d );
graph.makeEdge( "A", "C", "length", 10d );
final Map<Node, Double> seenBranchStates = new HashMap<Node, Double>();
PathExpander<Double> expander = new PathExpander<Double>()
{
@Override
public Iterable<Relationship> expand( Path path, BranchState<Double> state )
{
double newState = state.getState();
if ( path.length() > 0 )
{
newState += (Double) path.lastRelationship().getProperty( "length" );
state.setState( newState );
}
seenBranchStates.put( path.endNode(), newState );
return path.endNode().getRelationships( OUTGOING );
}
@Override
public PathExpander<Double> reverse()
{
throw new UnsupportedOperationException();
}
};
double initialStateValue = 0D;
PathFinder<WeightedPath> traversalFinder = new TraversalAStar( expander,
new InitialBranchState.State( initialStateValue, initialStateValue ),
doubleCostEvaluator( "length" ), ESTIMATE_EVALUATOR );
WeightedPath path = traversalFinder.findSinglePath( nodeA, nodeC );
assertEquals( (Double) 5.0D, (Double) path.weight() );
assertPathDef( path, "A", "B", "C" );
assertEquals( MapUtil.<Node,Double>genericMap( nodeA, 0D, nodeB, 2D, nodeC, 5D ), seenBranchStates );
}
@Test
public void betterTentativePath() throws Exception
{
// GIVEN
EstimateEvaluator<Double> estimator = new EstimateEvaluator<Double>()
{
@Override
public Double getCost( Node node, Node goal )
{
return ((Double)node.getProperty( "estimate" ));
}
};
PathFinder<WeightedPath> finder = aStar( pathExpanderForAllTypes(),
doubleCostEvaluator( "weight", 0d ), estimator );
final Node node1 = graph.makeNode( "1", "estimate", 0.003d );
final Node node2 = graph.makeNode( "2", "estimate", 0.002d );
final Node node3 = graph.makeNode( "3", "estimate", 0.001d );
final Node node4 = graph.makeNode( "4", "estimate", 0d );
graph.makeEdge( "1", "3", "weight", 0.253d );
graph.makeEdge( "1", "2", "weight", 0.018d );
graph.makeEdge( "2", "4", "weight", 0.210d );
graph.makeEdge( "2", "3", "weight", 0.180d );
graph.makeEdge( "2", "3", "weight", 0.024d );
graph.makeEdge( "3", "4", "weight", 0.135d );
graph.makeEdge( "3", "4", "weight", 0.013d );
// WHEN
WeightedPath best1_4 = finder.findSinglePath( node1, node4 );
// THEN
assertPath( best1_4, node1, node2, node3, node4 );
}
static EstimateEvaluator<Double> ESTIMATE_EVALUATOR = new EstimateEvaluator<Double>()
{
@Override
public Double getCost( Node node, Node goal )
{
double dx = (Double) node.getProperty( "x" )
- (Double) goal.getProperty( "x" );
double dy = (Double) node.getProperty( "y" )
- (Double) goal.getProperty( "y" );
double result = Math.sqrt( Math.pow( dx, 2 ) + Math.pow( dy, 2 ) );
return result;
}
};
@Parameters
public static Collection<Object[]> data()
{
return Arrays.asList( new Object[][]
{
{
GraphAlgoFactory.aStar( expanderForAllTypes(), doubleCostEvaluator( "length" ), ESTIMATE_EVALUATOR )
},
{
new TraversalAStar( pathExpanderForAllTypes(), doubleCostEvaluator( "length" ), ESTIMATE_EVALUATOR )
}
} );
}
private final PathFinder<WeightedPath> finder;
public TestAStar( PathFinder<WeightedPath> finder )
{
this.finder = finder;
}
}
| false
|
community_graph-algo_src_test_java_org_neo4j_graphalgo_path_TestAStar.java
|
3,528
|
{
@Override
public Double getCost( Node node, Node goal )
{
return 1D;
}
};
| false
|
community_graph-algo_src_test_java_org_neo4j_graphalgo_path_PathExplosionIT.java
|
3,529
|
{
@Override
public Double getCost( Relationship relationship, Direction direction )
{
return 1D;
}
};
| false
|
community_graph-algo_src_test_java_org_neo4j_graphalgo_path_PathExplosionIT.java
|
3,530
|
@Ignore( "Not a test, merely a performance measurement. Convert into a proper performance benchmark at some point" )
public class PathExplosionIT
{
private static final boolean FIND_MULTIPLE_PATHS = false;
private static final int MIN_PATH_LENGTH = 2;
private static final int MAX_PATH_LENGTH = 10;
private static final int MIN_PATH_WIDTH = 2;
private static final int MAX_PATH_WIDTH = 6;
private static final int WARMUP_RUNS = 2;
private static final long TOLERATED_DURATION = 10000;
@Test
public void aStarShouldFinishWithinToleratedDuration() throws IOException
{
assertPathFinderCompletesWithinToleratedDuration( TOLERATED_DURATION,
GraphAlgoFactory.aStar( expander, constantEvaluator, estimateEvaluator ) );
}
@Test
public void dijkstraShouldFinishWithinToleratedDuration() throws IOException
{
assertPathFinderCompletesWithinToleratedDuration( TOLERATED_DURATION,
GraphAlgoFactory.dijkstra( expander, constantEvaluator ) );
}
@Test
public void shortestPathShouldFinishWithinToleratedDuration() throws IOException
{
assertPathFinderCompletesWithinToleratedDuration( TOLERATED_DURATION,
GraphAlgoFactory.shortestPath( expander, Integer.MAX_VALUE ) );
}
@Rule
public TargetDirectory.TestDirectory testDir = TargetDirectory.testDirForTest( getClass() );
void assertPathFinderCompletesWithinToleratedDuration( long toleratedRuntime, PathFinder<? extends Path> pathFinder )
throws IOException
{
for ( int pathWidth = MIN_PATH_WIDTH; pathWidth <= MAX_PATH_WIDTH; pathWidth++ )
{
for ( int pathLength = MIN_PATH_LENGTH; pathLength <= MAX_PATH_LENGTH; pathLength++ )
{
FileUtils.deleteRecursively( testDir.directory() );
GraphDatabaseService db = new TestGraphDatabaseFactory().newImpermanentDatabase();
try
{
long[] startEndNodeIds = createPathGraphAndReturnStartAndEnd( pathLength, pathWidth, db );
long runTime = findPath( startEndNodeIds[0], startEndNodeIds[1], db, pathFinder, WARMUP_RUNS );
System.out.println( String.format( "Runtime[pathWidth:%s, pathLength:%s] = %s", pathWidth, pathLength,
runTime ) );
assertTrue( runTime < toleratedRuntime );
}
finally
{
db.shutdown();
}
}
}
}
long findPath( long startId, long endId, GraphDatabaseService db, PathFinder<? extends Path> pathFinder,
int warmUpRuns )
{
long runTime = -1;
Transaction tx = db.beginTx();
try
{
Node startNode = db.getNodeById( startId );
Node endNode = db.getNodeById( endId );
for ( int run = 0; run < warmUpRuns; run++ )
{
runPathOnce( startNode, endNode, db, pathFinder );
}
runTime = runPathOnce( startNode, endNode, db, pathFinder );
tx.success();
}
catch ( Exception e )
{
tx.failure();
throw new RuntimeException(e);
}
finally
{
tx.finish();
}
return runTime;
}
long runPathOnce( Node startNode, Node endNode, GraphDatabaseService db, PathFinder<? extends Path> pathFinder )
{
long startTime = currentTimeMillis();
Path path = FIND_MULTIPLE_PATHS ?
// call findAllPaths, but just grab the first one
toList( pathFinder.findAllPaths( startNode, endNode ) ).get( 0 ) :
// call findinglePath
pathFinder.findSinglePath( startNode, endNode );
// iterate through the path
count( path );
return currentTimeMillis() - startTime;
}
long[] createPathGraphAndReturnStartAndEnd( int length, int width, GraphDatabaseService db )
{
long startId = -1;
long endId = -1;
Transaction tx = db.beginTx();
try
{
Node startNode = null;
Node endNode = db.createNode();
startId = endNode.getId();
for ( int l = 0; l < length; l++ )
{
startNode = endNode;
endNode = db.createNode();
for ( int w = 0; w < width; w++ )
{
startNode.createRelationshipTo( endNode, RelTypes.SomeRelType );
}
}
endId = endNode.getId();
tx.success();
}
finally
{
tx.finish();
}
return new long[] { startId, endId };
}
private enum RelTypes implements RelationshipType
{
SomeRelType
}
private final PathExpander<?> expander = pathExpanderForAllTypes( Direction.BOTH );
private final CostEvaluator<Double> constantEvaluator = new CostEvaluator<Double>()
{
@Override
public Double getCost( Relationship relationship, Direction direction )
{
return 1D;
}
};
private final EstimateEvaluator<Double> estimateEvaluator = new EstimateEvaluator<Double>()
{
@Override
public Double getCost( Node node, Node goal )
{
return 1D;
}
};
}
| false
|
community_graph-algo_src_test_java_org_neo4j_graphalgo_path_PathExplosionIT.java
|
3,531
|
private static class PositionedNode
{
private final long node;
private final double x, y;
PositionedNode( long node, double x, double y )
{
this.node = node;
this.x = x;
this.y = y;
}
public double distanceTo( PositionedNode other )
{
return sqrt( pow( abs( x - other.x ), 2 ) + pow( abs( y - other.y ), 2 ) );
}
}
| false
|
community_graph-algo_src_test_java_org_neo4j_graphalgo_path_GeoDataGenerator.java
|
3,532
|
private class Grid
{
private final int cellsX, cellsY;
private final double sizeX, sizeY;
private final Cell[][] cells;
private final Map<String, Object> nodePropertyScratchMap = new HashMap<String, Object>();
private final Map<String, Object> relationshipPropertyScratchMap = new HashMap<String, Object>();
Grid()
{
this.cellsX = 100;
this.cellsY = 100;
this.sizeX = (double)width / cellsX;
this.sizeY = (double)height / cellsY;
this.cells = new Cell[cellsX][cellsY];
for ( int x = 0; x < cellsX; x++ )
{
for ( int y = 0; y < cellsY; y++ )
{
cells[x][y] = new Cell();
}
}
}
void createNodeAtRandomLocation( Random random, BatchInserter inserter )
{
double x = random.nextInt( width-1 ) + random.nextFloat();
double y = random.nextInt( height-1 ) + random.nextFloat();
nodePropertyScratchMap.put( "x", x );
nodePropertyScratchMap.put( "y", y );
long node = inserter.createNode( nodePropertyScratchMap );
cells[(int)(x/sizeX)][(int)(y/sizeY)].add( new PositionedNode( node, x, y ) );
}
void createConnection( Random random, BatchInserter inserter )
{
// pick a cell
int firstCellX = random.nextInt( cellsX );
int firstCellY = random.nextInt( cellsY );
int otherCellX = vicinity( random, firstCellX, cellsX );
int otherCellY = vicinity( random, firstCellY, cellsY );
// pick another cell at max distance 3
Cell firstCell = cells[firstCellX][firstCellY];
Cell otherCell = cells[otherCellX][otherCellY];
// connect a random node from the first to a random node to the other
// with a reasonable weight (roughly distance +/- random)
PositionedNode firstNode = firstCell.get( random );
PositionedNode otherNode = otherCell.get( random );
relationshipPropertyScratchMap.put( "weight", factor( random, firstNode.distanceTo( otherNode ), 0.5d ) );
inserter.createRelationship( firstNode.node, otherNode.node, RelationshipTypes.CONNECTION,
relationshipPropertyScratchMap );
}
private int vicinity( Random random, int position, int maxPosition )
{
int distance = distance( random, maxDistance );
int result = position + distance * (random.nextBoolean() ? 1 : -1);
if ( result < 0 )
{
result = 0;
}
if ( result >= maxPosition )
{
result = maxPosition-1;
}
return result;
}
private int distance( Random random, int max )
{
for ( int i = 0; i < max; i++ )
{
if ( random.nextFloat() < neighborConnectionFactor )
{
return i;
}
}
return max;
}
private double factor( Random random, double value, double maxDivergence )
{
double divergence = random.nextDouble()*maxDivergence;
divergence = random.nextBoolean() ? 1d - divergence : 1d + divergence;
return value * divergence;
}
}
| false
|
community_graph-algo_src_test_java_org_neo4j_graphalgo_path_GeoDataGenerator.java
|
3,533
|
private static class FlatEstimateEvaluator implements EstimateEvaluator<Double>
{
private double[] cachedGoal;
@Override
public Double getCost( Node node, Node goal )
{
if ( cachedGoal == null )
{
cachedGoal = new double[] {
(Double)goal.getProperty( "x" ),
(Double)goal.getProperty( "y" )
};
}
double x = (Double)node.getProperty( "x" ), y = (Double)node.getProperty( "y" );
double deltaX = abs( x - cachedGoal[0] ), deltaY = abs( y - cachedGoal[1] );
return sqrt( pow( deltaX, 2 ) + pow( deltaY, 2 ) );
}
};
| false
|
community_graph-algo_src_test_java_org_neo4j_graphalgo_path_GeoDataGenerator.java
|
3,534
|
private static class Cell
{
private final List<PositionedNode> nodes = new ArrayList<PositionedNode>();
void add( PositionedNode node )
{
nodes.add( node );
}
PositionedNode get( Random random )
{
return nodes.get( random.nextInt( nodes.size() ) );
}
}
| false
|
community_graph-algo_src_test_java_org_neo4j_graphalgo_path_GeoDataGenerator.java
|
3,535
|
public class GeoDataGenerator
{
private final Random random = new Random();
private final int numberOfNodes;
private final int numberOfConnections;
private final int width, height;
private int maxDistance = 3;
private double neighborConnectionFactor = 0.6;
public GeoDataGenerator( int numberOfNodes, double connectionDensity, int width, int height )
{
this.numberOfNodes = numberOfNodes;
this.numberOfConnections = (int) (numberOfNodes * connectionDensity);
this.width = width;
this.height = height;
}
public GeoDataGenerator withMaxNeighborDistance( int maxDistance, double neighborConnectionFactor )
{
this.maxDistance = maxDistance;
this.neighborConnectionFactor = neighborConnectionFactor;
return this;
}
public void generate( File storeDir )
{
BatchInserter inserter = inserter( storeDir.getAbsolutePath() );
Grid grid = new Grid();
try
{
for ( int i = 0; i < numberOfNodes; i++ )
{
grid.createNodeAtRandomLocation( random, inserter );
}
for ( int i = 0; i < numberOfConnections; i++ )
{
grid.createConnection( random, inserter );
}
}
finally
{
inserter.shutdown();
}
}
private static class PositionedNode
{
private final long node;
private final double x, y;
PositionedNode( long node, double x, double y )
{
this.node = node;
this.x = x;
this.y = y;
}
public double distanceTo( PositionedNode other )
{
return sqrt( pow( abs( x - other.x ), 2 ) + pow( abs( y - other.y ), 2 ) );
}
}
private static class Cell
{
private final List<PositionedNode> nodes = new ArrayList<PositionedNode>();
void add( PositionedNode node )
{
nodes.add( node );
}
PositionedNode get( Random random )
{
return nodes.get( random.nextInt( nodes.size() ) );
}
}
private class Grid
{
private final int cellsX, cellsY;
private final double sizeX, sizeY;
private final Cell[][] cells;
private final Map<String, Object> nodePropertyScratchMap = new HashMap<String, Object>();
private final Map<String, Object> relationshipPropertyScratchMap = new HashMap<String, Object>();
Grid()
{
this.cellsX = 100;
this.cellsY = 100;
this.sizeX = (double)width / cellsX;
this.sizeY = (double)height / cellsY;
this.cells = new Cell[cellsX][cellsY];
for ( int x = 0; x < cellsX; x++ )
{
for ( int y = 0; y < cellsY; y++ )
{
cells[x][y] = new Cell();
}
}
}
void createNodeAtRandomLocation( Random random, BatchInserter inserter )
{
double x = random.nextInt( width-1 ) + random.nextFloat();
double y = random.nextInt( height-1 ) + random.nextFloat();
nodePropertyScratchMap.put( "x", x );
nodePropertyScratchMap.put( "y", y );
long node = inserter.createNode( nodePropertyScratchMap );
cells[(int)(x/sizeX)][(int)(y/sizeY)].add( new PositionedNode( node, x, y ) );
}
void createConnection( Random random, BatchInserter inserter )
{
// pick a cell
int firstCellX = random.nextInt( cellsX );
int firstCellY = random.nextInt( cellsY );
int otherCellX = vicinity( random, firstCellX, cellsX );
int otherCellY = vicinity( random, firstCellY, cellsY );
// pick another cell at max distance 3
Cell firstCell = cells[firstCellX][firstCellY];
Cell otherCell = cells[otherCellX][otherCellY];
// connect a random node from the first to a random node to the other
// with a reasonable weight (roughly distance +/- random)
PositionedNode firstNode = firstCell.get( random );
PositionedNode otherNode = otherCell.get( random );
relationshipPropertyScratchMap.put( "weight", factor( random, firstNode.distanceTo( otherNode ), 0.5d ) );
inserter.createRelationship( firstNode.node, otherNode.node, RelationshipTypes.CONNECTION,
relationshipPropertyScratchMap );
}
private int vicinity( Random random, int position, int maxPosition )
{
int distance = distance( random, maxDistance );
int result = position + distance * (random.nextBoolean() ? 1 : -1);
if ( result < 0 )
{
result = 0;
}
if ( result >= maxPosition )
{
result = maxPosition-1;
}
return result;
}
private int distance( Random random, int max )
{
for ( int i = 0; i < max; i++ )
{
if ( random.nextFloat() < neighborConnectionFactor )
{
return i;
}
}
return max;
}
private double factor( Random random, double value, double maxDivergence )
{
double divergence = random.nextDouble()*maxDivergence;
divergence = random.nextBoolean() ? 1d - divergence : 1d + divergence;
return value * divergence;
}
}
public static enum RelationshipTypes implements RelationshipType
{
CONNECTION;
}
public static EstimateEvaluator<Double> estimateEvaluator()
{
return new FlatEstimateEvaluator();
}
private static class FlatEstimateEvaluator implements EstimateEvaluator<Double>
{
private double[] cachedGoal;
@Override
public Double getCost( Node node, Node goal )
{
if ( cachedGoal == null )
{
cachedGoal = new double[] {
(Double)goal.getProperty( "x" ),
(Double)goal.getProperty( "y" )
};
}
double x = (Double)node.getProperty( "x" ), y = (Double)node.getProperty( "y" );
double deltaX = abs( x - cachedGoal[0] ), deltaY = abs( y - cachedGoal[1] );
return sqrt( pow( deltaX, 2 ) + pow( deltaY, 2 ) );
}
};
}
| false
|
community_graph-algo_src_test_java_org_neo4j_graphalgo_path_GeoDataGenerator.java
|
3,536
|
public class DijkstraTest extends Neo4jAlgoTestCase
{
@Test
public void canGetPathsInTriangleGraph() throws Exception
{
Node nodeA = graph.makeNode( "A" );
Node nodeB = graph.makeNode( "B" );
Node nodeC = graph.makeNode( "C" );
graph.makeEdge( "A", "B", "length", 2d );
graph.makeEdge( "B", "C", "length", 3d );
graph.makeEdge( "A", "C", "length", 10d );
Dijkstra algo = new Dijkstra( Traversal.expanderForAllTypes(),
CommonEvaluators.doubleCostEvaluator( "length" ) );
Iterator<WeightedPath> paths = algo.findAllPaths( nodeA, nodeC ).iterator();
assertTrue( "expected at least one path", paths.hasNext() );
assertPath( paths.next(), nodeA, nodeB, nodeC );
assertFalse( "expected at most one path", paths.hasNext() );
assertPath( algo.findSinglePath( nodeA, nodeC ), nodeA, nodeB, nodeC );
}
@Test
public void canGetMultiplePathsInTriangleGraph() throws Exception
{
Node nodeA = graph.makeNode( "A" );
Node nodeB = graph.makeNode( "B" );
Node nodeC = graph.makeNode( "C" );
Set<Relationship> expectedFirsts = new HashSet<Relationship>();
expectedFirsts.add( graph.makeEdge( "A", "B", "length", 1d ) );
expectedFirsts.add( graph.makeEdge( "A", "B", "length", 1d ) );
Relationship expectedSecond = graph.makeEdge( "B", "C", "length", 2d );
graph.makeEdge( "A", "C", "length", 5d );
Dijkstra algo = new Dijkstra( Traversal.expanderForAllTypes(),
CommonEvaluators.doubleCostEvaluator( "length" ) );
Iterator<WeightedPath> paths = algo.findAllPaths( nodeA, nodeC ).iterator();
for ( int i = 0; i < 2; i++ )
{
assertTrue( "expected more paths", paths.hasNext() );
Path path = paths.next();
assertPath( path, nodeA, nodeB, nodeC );
Iterator<Relationship> relationships = path.relationships().iterator();
assertTrue( "found shorter path than expected",
relationships.hasNext() );
assertTrue( "path contained unexpected relationship",
expectedFirsts.remove( relationships.next() ) );
assertTrue( "found shorter path than expected",
relationships.hasNext() );
assertEquals( expectedSecond, relationships.next() );
assertFalse( "found longer path than expected",
relationships.hasNext() );
}
assertFalse( "expected at most two paths", paths.hasNext() );
}
@Test
public void canGetMultiplePathsInASmallRoadNetwork() throws Exception
{
Node nodeA = graph.makeNode( "A" );
Node nodeB = graph.makeNode( "B" );
Node nodeC = graph.makeNode( "C" );
Node nodeD = graph.makeNode( "D" );
Node nodeE = graph.makeNode( "E" );
Node nodeF = graph.makeNode( "F" );
graph.makeEdge( "A", "B", "length", 2d );
graph.makeEdge( "A", "C", "length", 2.5d );
graph.makeEdge( "C", "D", "length", 7.3d );
graph.makeEdge( "B", "D", "length", 2.5d );
graph.makeEdge( "D", "E", "length", 3d );
graph.makeEdge( "C", "E", "length", 5d );
graph.makeEdge( "E", "F", "length", 5d );
graph.makeEdge( "C", "F", "length", 12d );
graph.makeEdge( "A", "F", "length", 25d );
Dijkstra algo = new Dijkstra( Traversal.expanderForAllTypes(),
CommonEvaluators.doubleCostEvaluator( "length" ) );
// Try the search in both directions.
for ( Node[] nodes : new Node[][] { { nodeA, nodeF }, { nodeF, nodeA } } )
{
int found = 0;
Iterator<WeightedPath> paths = algo.findAllPaths( nodes[0],
nodes[1] ).iterator();
for ( int i = 0; i < 2; i++ )
{
assertTrue( "expected more paths", paths.hasNext() );
Path path = paths.next();
if ( path.length() != found && path.length() == 3 )
{
assertContains( path.nodes(), nodeA, nodeC, nodeE, nodeF );
}
else if ( path.length() != found && path.length() == 4 )
{
assertContains( path.nodes(), nodeA, nodeB, nodeD, nodeE,
nodeF );
}
else
{
fail( "unexpected path length: " + path.length() );
}
found = path.length();
}
assertFalse( "expected at most two paths", paths.hasNext() );
}
}
}
| false
|
community_graph-algo_src_test_java_org_neo4j_graphalgo_path_DijkstraTest.java
|
3,537
|
@Ignore( "Not a test, just nice to have" )
public class AStarPerformanceIT
{
private static final boolean REBUILD = true;
private final File directory;
public AStarPerformanceIT()
{
if (REBUILD)
{
directory = forTest( getClass() ).cleanDirectory( "graph-db" );
}
else
{
directory = forTest( getClass() ).existingDirectory( "graph-db" );
}
}
@Test
public void somePerformanceTesting() throws Exception
{
// GIVEN
int numberOfNodes = 200000;
if ( REBUILD )
{
GeoDataGenerator generator = new GeoDataGenerator( numberOfNodes, 5d, 1000, 1000 );
generator.generate( directory );
}
// WHEN
long[][] points = new long[][] {
new long[] {9415, 158154},
new long[] {89237, 192863},
new long[] {68072, 150484},
new long[] {186309, 194495},
new long[] {152097, 99289},
new long[] {92150, 161182},
new long[] {188446, 115873},
new long[] {85033, 7772},
new long[] {291, 86707},
new long[] {188345, 158468}
};
GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase( directory.getAbsolutePath() );
PathFinder<WeightedPath> algo = aStar( pathExpanderForAllTypes(),
doubleCostEvaluator( "weight", 0 ), GeoDataGenerator.estimateEvaluator() );
for ( int i = 0; i < 10; i++ )
{
System.out.println( "----- " + i );
for ( long[] p : points )
{
Transaction tx = db.beginTx();
try
{
Node start = db.getNodeById( p[0] );
Node end = db.getNodeById( p[1] );
long time = currentTimeMillis();
WeightedPath path = algo.findSinglePath( start, end );
time = currentTimeMillis() - time;
System.out.println( "time: " + time + ", len:" + path.length() + ", weight:" + path.weight() );
tx.success();
}
finally
{
tx.finish();
}
}
}
// THEN
db.shutdown();
}
}
| false
|
community_graph-algo_src_test_java_org_neo4j_graphalgo_path_AStarPerformanceIT.java
|
3,538
|
public class WeightedPathImpl implements WeightedPath
{
private final Path path;
private final double weight;
public WeightedPathImpl( CostEvaluator<Double> costEvaluator, Path path )
{
this.path = path;
double cost = 0;
for ( Relationship relationship : path.relationships() )
{
cost += costEvaluator.getCost( relationship, Direction.OUTGOING );
}
this.weight = cost;
}
public WeightedPathImpl( double weight, Path path )
{
this.path = path;
this.weight = weight;
}
public double weight()
{
return weight;
}
public Node startNode()
{
return path.startNode();
}
public Node endNode()
{
return path.endNode();
}
public Relationship lastRelationship()
{
return path.lastRelationship();
}
public int length()
{
return path.length();
}
public Iterable<Node> nodes()
{
return path.nodes();
}
@Override
public Iterable<Node> reverseNodes()
{
return path.reverseNodes();
}
public Iterable<Relationship> relationships()
{
return path.relationships();
}
@Override
public Iterable<Relationship> reverseRelationships()
{
return path.reverseRelationships();
}
@Override
public String toString()
{
return path.toString() + " weight:" + this.weight;
}
public Iterator<PropertyContainer> iterator()
{
return path.iterator();
}
}
| false
|
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_util_WeightedPathImpl.java
|
3,539
|
public class TestPriorityMap
{
@Test
public void testIt()
{
PriorityMap<Integer, Integer, Double> map =
PriorityMap.<Integer, Double>withSelfKeyNaturalOrder();
map.put( 0, 5d );
map.put( 1, 4d );
map.put( 1, 4d );
map.put( 1, 3d );
assertEntry( map.pop(), 1, 3d );
assertEntry( map.pop(), 0, 5d );
assertNull( map.pop() );
int start = 0, a = 1, b = 2, c = 3, d = 4, e = 6, f = 7, y = 8, x = 9;
map.put( start, 0d );
map.put( a, 1d );
// get start
// get a
map.put( x, 10d );
map.put( b, 2d );
// get b
map.put( x, 9d );
map.put( c, 3d );
// get c
map.put( x, 8d );
map.put( x, 6d );
map.put( d, 4d );
// get d
map.put( x, 7d );
map.put( e, 5d );
// get e
map.put( x, 6d );
map.put( f, 7d );
// get x
map.put( y, 8d );
// get x
// map.put(
}
@Test
public void shouldReplaceIfBetter() throws Exception
{
// GIVEN
PriorityMap<Integer, Integer, Double> map = PriorityMap.<Integer, Double>withSelfKeyNaturalOrder();
map.put( 1, 2d );
// WHEN
boolean putResult = map.put( 1, 1.5d );
// THEN
assertTrue( putResult );
Entry<Integer, Double> top = map.pop();
assertNull( map.peek() );
assertEquals( 1, top.getEntity().intValue() );
assertEquals( 1.5d, top.getPriority().doubleValue(), 0d );
}
private void assertEntry( Entry<Integer, Double> entry, Integer entity,
Double priority )
{
assertNotNull( entry );
assertEquals( entity, entry.getEntity() );
assertEquals( priority, entry.getPriority() );
}
}
| false
|
community_graph-algo_src_test_java_org_neo4j_graphalgo_impl_util_TestPriorityMap.java
|
3,540
|
public class StopAfterWeightIterator extends PrefetchingIterator<WeightedPath>
{
private final Iterator<Path> paths;
private final CostEvaluator<Double> costEvaluator;
private Double foundWeight;
public StopAfterWeightIterator( Iterator<Path> paths,
CostEvaluator<Double> costEvaluator )
{
this.paths = paths;
this.costEvaluator = costEvaluator;
}
@Override
protected WeightedPath fetchNextOrNull()
{
if ( !paths.hasNext() )
{
return null;
}
WeightedPath path = new WeightedPathImpl( costEvaluator, paths.next() );
if ( foundWeight != null && path.weight() > foundWeight )
{
return null;
}
foundWeight = path.weight();
return path;
}
}
| false
|
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_util_StopAfterWeightIterator.java
|
3,541
|
private static class Node<E, P>
{
Link<E> head;
final P priority;
Node( E entity, P priority )
{
this.head = new Link<E>( entity, null );
this.priority = priority;
}
}
| false
|
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_util_PriorityMap.java
|
3,542
|
public class TestAllSimplePaths extends Neo4jAlgoTestCase
{
protected PathFinder<Path> instantiatePathFinder( int maxDepth )
{
return GraphAlgoFactory.allSimplePaths( Traversal.expanderForAllTypes(), maxDepth );
}
@Test
public void testCircularGraph()
{
/* Layout
*
* (a)---(b)===(c)---(e)
* \ /
* (d)
*/
graph.makeEdge( "a", "b" );
graph.makeEdge( "b", "c" );
graph.makeEdge( "b", "c" );
graph.makeEdge( "b", "d" );
graph.makeEdge( "c", "d" );
graph.makeEdge( "c", "e" );
PathFinder<Path> finder = instantiatePathFinder( 10 );
Iterable<Path> paths = finder.findAllPaths( graph.getNode( "a" ), graph.getNode( "e" ) );
assertPaths( paths, "a,b,c,e", "a,b,c,e", "a,b,d,c,e" );
}
@Test
public void testTripleRelationshipGraph()
{
/* Layout
* ___
* (a)---(b)===(c)---(d)
*/
graph.makeEdge( "a", "b" );
graph.makeEdge( "b", "c" );
graph.makeEdge( "b", "c" );
graph.makeEdge( "b", "c" );
graph.makeEdge( "c", "d" );
PathFinder<Path> finder = instantiatePathFinder( 10 );
Iterable<Path> paths = finder.findAllPaths( graph.getNode( "a" ), graph.getNode( "d" ) );
assertPaths( paths, "a,b,c,d", "a,b,c,d", "a,b,c,d" );
}
}
| false
|
community_graph-algo_src_test_java_org_neo4j_graphalgo_path_TestAllSimplePaths.java
|
3,543
|
{
@Override
public Iterable<Relationship> expand( Path path, BranchState<Integer> state )
{
if ( path.length() > 0 )
{
int newState = state.getState() + ((Number)path.lastRelationship().getProperty( "weight" )).intValue();
state.setState( newState );
encounteredState.put( path.endNode(), newState );
}
return path.endNode().getRelationships();
}
@Override
public PathExpander<Integer> reverse()
{
return this;
}
};
| false
|
community_graph-algo_src_test_java_org_neo4j_graphalgo_path_TestDijkstra.java
|
3,544
|
private static class Link<E>
{
final E entity;
final Link<E> next;
Link( E entity, Link<E> next )
{
this.entity = entity;
this.next = next;
}
}
| false
|
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_util_PriorityMap.java
|
3,545
|
public class TestExactDepthPathFinder extends Neo4jAlgoTestCase
{
@Before
public void createGraph()
{
graph.makeEdgeChain( "SOURCE,a,b,TARGET" );
graph.makeEdgeChain( "SOURCE,SUPER,c,d" );
graph.makeEdgeChain( "SUPER,e,f" );
graph.makeEdgeChain( "SUPER,g,h,i,j,SPIDER" );
graph.makeEdgeChain( "SUPER,k,l,m,SPIDER" );
graph.makeEdgeChain( "SUPER,r,SPIDER" );
graph.makeEdgeChain( "SPIDER,n,o" );
graph.makeEdgeChain( "SPIDER,p,q" );
graph.makeEdgeChain( "SPIDER,TARGET" );
graph.makeEdgeChain( "SUPER,s,t,u,SPIDER" );
graph.makeEdgeChain( "SUPER,v,w,x,y,SPIDER" );
graph.makeEdgeChain( "SPIDER,1,2" );
graph.makeEdgeChain( "SPIDER,3,4" );
graph.makeEdgeChain( "SUPER,5,6" );
graph.makeEdgeChain( "SUPER,7,8" );
graph.makeEdgeChain( "SOURCE,z,9,0,TARGET" );
}
private PathFinder<Path> newFinder()
{
return new ExactDepthPathFinder( Traversal.expanderForAllTypes(), 4, 4 );
}
@Test
public void testSingle()
{
PathFinder<Path> finder = newFinder();
Path path = finder.findSinglePath( graph.getNode( "SOURCE" ), graph.getNode( "TARGET" ) );
assertNotNull( path );
assertPathDef( path, "SOURCE", "z", "9", "0", "TARGET" );
}
@Test
public void testAll()
{
assertPaths( newFinder().findAllPaths( graph.getNode( "SOURCE" ), graph.getNode( "TARGET" ) ),
"SOURCE,z,9,0,TARGET", "SOURCE,SUPER,r,SPIDER,TARGET" );
}
}
| false
|
community_graph-algo_src_test_java_org_neo4j_graphalgo_path_TestExactDepthPathFinder.java
|
3,546
|
private static class LengthCheckingExpanderWrapper implements PathExpander<Object> {
private PathExpander expander;
LengthCheckingExpanderWrapper( PathExpander expander )
{
this.expander = expander;
}
@Override
@SuppressWarnings("unchecked")
public Iterable<Relationship> expand( Path path, BranchState<Object> state )
{
if ( path.startNode().equals(path.endNode()) )
{
assertTrue( "Path length must be zero", path.length() == 0 );
}
else
{
assertTrue( "Path length must be positive", path.length() > 0 );
}
return expander.expand( path, state );
}
@Override
public PathExpander<Object> reverse()
{
return new LengthCheckingExpanderWrapper( expander.reverse() );
}
}
| false
|
community_graph-algo_src_test_java_org_neo4j_graphalgo_path_TestShortestPath.java
|
3,547
|
{
@Override
public void test( PathFinder<Path> finder )
{
assertPaths( finder.findAllPaths( graph.getNode( "a" ), graph.getNode( "c" ) ) );
assertPaths( finder.findAllPaths( graph.getNode( "a" ), graph.getNode( "d" ) ) );
}
}, Traversal.emptyExpander(), 1 );
| false
|
community_graph-algo_src_test_java_org_neo4j_graphalgo_path_TestShortestPath.java
|
3,548
|
{
@Override
public void test( PathFinder<Path> finder )
{
assertPaths( finder.findAllPaths( graph.getNode( "a" ), graph.getNode( "b" ) ) );
}
}, Traversal.emptyExpander(), 0 );
| false
|
community_graph-algo_src_test_java_org_neo4j_graphalgo_path_TestShortestPath.java
|
3,549
|
{
@Override
public void test( PathFinder<Path> finder )
{
assertPaths( finder.findAllPaths( a, d ), "a,g,h,d" );
}
}, Traversal.expanderForAllTypes().addNodeFilter( filter ), 10 );
| false
|
community_graph-algo_src_test_java_org_neo4j_graphalgo_path_TestShortestPath.java
|
3,550
|
{
@Override
public boolean accept( Node item )
{
boolean skip = (Boolean) item.getProperty( "skip", false );
return !skip;
}
};
| false
|
community_graph-algo_src_test_java_org_neo4j_graphalgo_path_TestShortestPath.java
|
3,551
|
{
@Override
public void test( PathFinder<Path> finder )
{
Node a = graph.getNode( "a" );
Node e = graph.getNode( "e" );
assertPaths( finder.findAllPaths( a, e ), "a,b,c,e", "a,b,c,e" );
}
}, expanderForTypes( R1, BOTH ), 6 );
| false
|
community_graph-algo_src_test_java_org_neo4j_graphalgo_path_TestShortestPath.java
|
3,552
|
{
@Override
public void test( PathFinder<Path> finder )
{
assertPaths( finder.findAllPaths( graph.getNode( "a" ), graph.getNode( "j" ) ), "a,g,h,i,j" );
}
}, expanderForTypes( R1, OUTGOING ), 4 );
| false
|
community_graph-algo_src_test_java_org_neo4j_graphalgo_path_TestShortestPath.java
|
3,553
|
{
@Override
public void test( PathFinder<Path> finder )
{
assertPaths( finder.findAllPaths( graph.getNode( "s" ), graph.getNode( "t" ) ),
"s,1,2,t", "s,1,4,t", "s,3,2,t", "s,3,4,t" );
}
}, expanderForTypes( R1, BOTH ), 3 );
| false
|
community_graph-algo_src_test_java_org_neo4j_graphalgo_path_TestShortestPath.java
|
3,554
|
{
@Override
public void test( PathFinder<Path> finder )
{
Iterable<Path> paths = finder.findAllPaths( graph.getNode( "s" ), graph.getNode( "t" ) );
assertPaths( paths, "s,m,o,t", "s,n,o,t" );
}
}, expanderForTypes( R1, BOTH ), 6 );
| false
|
community_graph-algo_src_test_java_org_neo4j_graphalgo_path_TestShortestPath.java
|
3,555
|
{
@Override
public void test( PathFinder<Path> finder )
{
assertPathDef( finder.findSinglePath( c, a ), "c", "a" );
}
}, expanderForTypes( R1, INCOMING ), 2 );
| false
|
community_graph-algo_src_test_java_org_neo4j_graphalgo_path_TestShortestPath.java
|
3,556
|
{
@Override
public void test( PathFinder<Path> finder )
{
assertPathDef( finder.findSinglePath( a, c ), "a", "c" );
}
}, expanderForTypes( R1, OUTGOING ), 2 );
| false
|
community_graph-algo_src_test_java_org_neo4j_graphalgo_path_TestShortestPath.java
|
3,557
|
{
@Override
public void test( PathFinder<Path> finder )
{
assertEquals( count, count( finder.findAllPaths( a, e ) ) );
}
}, expander, 10, count );
| false
|
community_graph-algo_src_test_java_org_neo4j_graphalgo_path_TestShortestPath.java
|
3,558
|
{
@Override
public void test( PathFinder<Path> finder )
{
assertEquals( 4, count( finder.findAllPaths( a, e ) ) );
}
}, expander, 10, 10 );
| false
|
community_graph-algo_src_test_java_org_neo4j_graphalgo_path_TestShortestPath.java
|
3,559
|
{
@Override
public void test( PathFinder<Path> finder )
{
assertPaths( finder.findAllPaths( graph.getNode( "m" ), graph.getNode( "p" ) ), "m,s,n,p", "m,o,n,p" );
}
}, expanderForTypes( R1, BOTH ), 3 );
| false
|
community_graph-algo_src_test_java_org_neo4j_graphalgo_path_TestShortestPath.java
|
3,560
|
{
@Override
public void test( PathFinder<Path> finder )
{
Node start = graph.getNode( "a" );
Node end = graph.getNode( "i" );
assertPaths( finder.findAllPaths( start, end ), "a,b,c,d,e,f,g,i", "a,b,c,d,e,f,h,i" );
}
}, expanderForTypes( R1, INCOMING ), 10 );
| false
|
community_graph-algo_src_test_java_org_neo4j_graphalgo_path_TestShortestPath.java
|
3,561
|
{
@Override
protected Collection<Node> filterNextLevelNodes( Collection<Node> nextNodes )
{
for ( Node node : nextNodes )
{
if ( !allowedNodes.contains( node ) )
{
fail( "Node " + node.getProperty( KEY_ID ) + " shouldn't be expanded" );
}
}
return nextNodes;
}
};
| false
|
community_graph-algo_src_test_java_org_neo4j_graphalgo_path_TestShortestPath.java
|
3,562
|
{
@Override
public void test( PathFinder<Path> finder )
{
assertPaths( finder.findAllPaths( graph.getNode( "a" ), graph.getNode( "d" ) ) );
assertPaths( finder.findAllPaths( graph.getNode( "a" ), graph.getNode( "e" ) ) );
}
}, Traversal.emptyExpander(), 2 );
| false
|
community_graph-algo_src_test_java_org_neo4j_graphalgo_path_TestShortestPath.java
|
3,563
|
{
@Override
public void test( PathFinder<Path> finder )
{
Iterable<Path> paths = finder.findAllPaths( graph.getNode( "s" ), graph.getNode( "t" ) );
assertPaths( paths, "s,t", "s,t" );
assertPaths( asList( finder.findSinglePath( graph.getNode( "s" ), graph.getNode( "t" ) ) ), "s,t" );
}
}, expanderForTypes( R1, BOTH ), 1 );
| false
|
community_graph-algo_src_test_java_org_neo4j_graphalgo_path_TestShortestPath.java
|
3,564
|
public class TestShortestPath extends Neo4jAlgoTestCase
{
// protected PathFinder<Path> instantiatePathFinder( int maxDepth )
// {
// return instantiatePathFinder( Traversal.expanderForTypes( MyRelTypes.R1,
// Direction.BOTH ), maxDepth );
// }
//
// protected PathFinder<Path> instantiatePathFinder( RelationshipExpander expander, int maxDepth )
// {
//// return GraphAlgoFactory.shortestPath( expander, maxDepth );
// return new TraversalShortestPath( expander, maxDepth );
// }
@Test
public void testSimplestGraph()
{
// Layout:
// __
// / \
// (s) (t)
// \__/
graph.makeEdge( "s", "t" );
graph.makeEdge( "s", "t" );
testShortestPathFinder( new PathFinderTester()
{
@Override
public void test( PathFinder<Path> finder )
{
Iterable<Path> paths = finder.findAllPaths( graph.getNode( "s" ), graph.getNode( "t" ) );
assertPaths( paths, "s,t", "s,t" );
assertPaths( asList( finder.findSinglePath( graph.getNode( "s" ), graph.getNode( "t" ) ) ), "s,t" );
}
}, expanderForTypes( R1, BOTH ), 1 );
}
@Test
public void testAnotherSimpleGraph()
{
// Layout:
// (m)
// / \
// (s) (o)---(t)
// \ / \
// (n)---(p)---(q)
graph.makeEdge( "s", "m" );
graph.makeEdge( "m", "o" );
graph.makeEdge( "s", "n" );
graph.makeEdge( "n", "p" );
graph.makeEdge( "p", "q" );
graph.makeEdge( "q", "t" );
graph.makeEdge( "n", "o" );
graph.makeEdge( "o", "t" );
testShortestPathFinder( new PathFinderTester()
{
@Override
public void test( PathFinder<Path> finder )
{
Iterable<Path> paths = finder.findAllPaths( graph.getNode( "s" ), graph.getNode( "t" ) );
assertPaths( paths, "s,m,o,t", "s,n,o,t" );
}
}, expanderForTypes( R1, BOTH ), 6 );
}
@Test
public void testCrossedCircle()
{
// Layout:
// (s)
// / \
// (3) (1)
// | \ / |
// | / \ |
// (4) (2)
// \ /
// (t)
graph.makeEdge( "s", "1" );
graph.makeEdge( "s", "3" );
graph.makeEdge( "1", "2" );
graph.makeEdge( "1", "4" );
graph.makeEdge( "3", "2" );
graph.makeEdge( "3", "4" );
graph.makeEdge( "2", "t" );
graph.makeEdge( "4", "t" );
testShortestPathFinder( new PathFinderTester()
{
@Override
public void test( PathFinder<Path> finder )
{
assertPaths( finder.findAllPaths( graph.getNode( "s" ), graph.getNode( "t" ) ),
"s,1,2,t", "s,1,4,t", "s,3,2,t", "s,3,4,t" );
}
}, expanderForTypes( R1, BOTH ), 3 );
}
@Test
public void testDirectedFinder()
{
// Layout:
//
// (a)->(b)->(c)->(d)->(e)->(f)-------\
// \ v
// >(g)->(h)->(i)->(j)->(k)->(l)->(m)
//
graph.makeEdgeChain( "a,b,c,d,e,f,m" );
graph.makeEdgeChain( "a,g,h,i,j,k,l,m" );
testShortestPathFinder( new PathFinderTester()
{
@Override
public void test( PathFinder<Path> finder )
{
assertPaths( finder.findAllPaths( graph.getNode( "a" ), graph.getNode( "j" ) ), "a,g,h,i,j" );
}
}, expanderForTypes( R1, OUTGOING ), 4 );
}
@Test
public void testExactDepthFinder()
{
// Layout (a to k):
//
// (a)--(c)--(g)--(k)
// / /
// (b)-----(d)------(j)
// | \ /
// (e)--(f)--(h)--(i)
//
graph.makeEdgeChain( "a,c,g,k" );
graph.makeEdgeChain( "a,b,d,j,k" );
graph.makeEdgeChain( "b,e,f,h,i,j" );
graph.makeEdgeChain( "d,h" );
RelationshipExpander expander = Traversal.expanderForTypes( MyRelTypes.R1, Direction.OUTGOING );
Node a = graph.getNode( "a" );
Node k = graph.getNode( "k" );
assertPaths( GraphAlgoFactory.pathsWithLength( expander, 3 ).findAllPaths( a, k ), "a,c,g,k" );
assertPaths( GraphAlgoFactory.pathsWithLength( expander, 4 ).findAllPaths( a, k ), "a,b,d,j,k" );
assertPaths( GraphAlgoFactory.pathsWithLength( expander, 5 ).findAllPaths( a, k ) );
assertPaths( GraphAlgoFactory.pathsWithLength( expander, 6 ).findAllPaths( a, k ), "a,b,d,h,i,j,k" );
assertPaths( GraphAlgoFactory.pathsWithLength( expander, 7 ).findAllPaths( a, k ), "a,b,e,f,h,i,j,k" );
assertPaths( GraphAlgoFactory.pathsWithLength( expander, 8 ).findAllPaths( a, k ) );
}
@Test
public void makeSureShortestPathsReturnsNoLoops()
{
// Layout:
//
// (a)-->(b)==>(c)-->(e)
// ^ /
// \ v
// (d)
//
graph.makeEdgeChain( "a,b,c,d,b,c,e" );
testShortestPathFinder( new PathFinderTester()
{
@Override
public void test( PathFinder<Path> finder )
{
Node a = graph.getNode( "a" );
Node e = graph.getNode( "e" );
assertPaths( finder.findAllPaths( a, e ), "a,b,c,e", "a,b,c,e" );
}
}, expanderForTypes( R1, BOTH ), 6 );
}
@Test
public void testExactDepthPathsReturnsNoLoops()
{
// Layout:
//
// (a)-->(b)==>(c)-->(e)
// ^ /
// \ v
// (d)
//
graph.makeEdgeChain( "a,b,c,d,b,c,e" );
Node a = graph.getNode( "a" );
Node e = graph.getNode( "e" );
assertPaths( GraphAlgoFactory.pathsWithLength(
Traversal.expanderForTypes( MyRelTypes.R1 ), 3 ).findAllPaths( a, e ), "a,b,c,e", "a,b,c,e" );
assertPaths( GraphAlgoFactory.pathsWithLength(
Traversal.expanderForTypes( MyRelTypes.R1 ), 4 ).findAllPaths( a, e ), "a,b,d,c,e" );
assertPaths( GraphAlgoFactory.pathsWithLength(
Traversal.expanderForTypes( MyRelTypes.R1 ), 6 ).findAllPaths( a, e ) );
}
@Test
public void withFilters() throws Exception
{
// Layout:
//
// (a)-->(b)-->(c)-->(d)
// \ ^
// -->(g)-->(h)--/
//
graph.makeEdgeChain( "a,b,c,d" );
graph.makeEdgeChain( "a,g,h,d" );
final Node a = graph.getNode( "a" );
final Node d = graph.getNode( "d" );
final Node b = graph.getNode( "b" );
b.setProperty( "skip", true );
Predicate<Node> filter = new Predicate<Node>()
{
@Override
public boolean accept( Node item )
{
boolean skip = (Boolean) item.getProperty( "skip", false );
return !skip;
}
};
testShortestPathFinder( new PathFinderTester()
{
@Override
public void test( PathFinder<Path> finder )
{
assertPaths( finder.findAllPaths( a, d ), "a,g,h,d" );
}
}, Traversal.expanderForAllTypes().addNodeFilter( filter ), 10 );
}
@Test
public void testFinderShouldNotFindAnythingBeyondLimit()
{
// Layout:
//
// (a)-->(b)-->(c)-->(d)-->(e)
//
graph.makeEdgeChain( "a,b,c,d,e" );
testShortestPathFinder( new PathFinderTester()
{
@Override
public void test( PathFinder<Path> finder )
{
assertPaths( finder.findAllPaths( graph.getNode( "a" ), graph.getNode( "b" ) ) );
}
}, Traversal.emptyExpander(), 0 );
testShortestPathFinder( new PathFinderTester()
{
@Override
public void test( PathFinder<Path> finder )
{
assertPaths( finder.findAllPaths( graph.getNode( "a" ), graph.getNode( "c" ) ) );
assertPaths( finder.findAllPaths( graph.getNode( "a" ), graph.getNode( "d" ) ) );
}
}, Traversal.emptyExpander(), 1 );
testShortestPathFinder( new PathFinderTester()
{
@Override
public void test( PathFinder<Path> finder )
{
assertPaths( finder.findAllPaths( graph.getNode( "a" ), graph.getNode( "d" ) ) );
assertPaths( finder.findAllPaths( graph.getNode( "a" ), graph.getNode( "e" ) ) );
}
}, Traversal.emptyExpander(), 2 );
}
@Test
public void makeSureDescentStopsWhenPathIsFound() throws Exception
{
/*
* (a)==>(b)==>(c)==>(d)==>(e)
* \
* v
* (f)-->(g)-->(h)-->(i)
*/
graph.makeEdgeChain( "a,b,c,d,e" );
graph.makeEdgeChain( "a,b,c,d,e" );
graph.makeEdgeChain( "a,f,g,h,i" );
Node a = graph.getNode( "a" );
Node b = graph.getNode( "b" );
Node c = graph.getNode( "c" );
final Set<Node> allowedNodes = new HashSet<Node>( Arrays.asList( a, b, c ) );
PathFinder<Path> finder = new ShortestPath( 100, Traversal.expanderForAllTypes( Direction.OUTGOING ) )
{
@Override
protected Collection<Node> filterNextLevelNodes( Collection<Node> nextNodes )
{
for ( Node node : nextNodes )
{
if ( !allowedNodes.contains( node ) )
{
fail( "Node " + node.getProperty( KEY_ID ) + " shouldn't be expanded" );
}
}
return nextNodes;
}
};
finder.findAllPaths( a, c );
}
@Test
public void makeSureRelationshipNotConnectedIssueNotThere() throws Exception
{
/*
* (g)
* / ^
* v \
* (a)<--(b)<--(c)<--(d)<--(e)<--(f) (i)
* ^ /
* \ v
* (h)
*/
graph.makeEdgeChain( "i,g,f,e,d,c,b,a" );
graph.makeEdgeChain( "i,h,f" );
testShortestPathFinder( new PathFinderTester()
{
@Override
public void test( PathFinder<Path> finder )
{
Node start = graph.getNode( "a" );
Node end = graph.getNode( "i" );
assertPaths( finder.findAllPaths( start, end ), "a,b,c,d,e,f,g,i", "a,b,c,d,e,f,h,i" );
}
}, expanderForTypes( R1, INCOMING ), 10 );
}
@Test
public void makeSureShortestPathCanBeFetchedEvenIfANodeHasLoops() throws Exception
{
// Layout:
//
// = means loop :)
//
// (m)
// / \
// (s) (o)=
// \ /
// (n)=
// |
// (p)
graph.makeEdgeChain( "m,s,n,p" );
graph.makeEdgeChain( "m,o,n" );
graph.makeEdge( "o", "o" );
graph.makeEdge( "n", "n" );
testShortestPathFinder( new PathFinderTester()
{
@Override
public void test( PathFinder<Path> finder )
{
assertPaths( finder.findAllPaths( graph.getNode( "m" ), graph.getNode( "p" ) ), "m,s,n,p", "m,o,n,p" );
}
}, expanderForTypes( R1, BOTH ), 3 );
}
@Test
public void makeSureAMaxResultCountIsObeyed()
{
// Layout:
//
// (a)--(b)--(c)--(d)--(e)
// | / | \
// (f)--(g)---------(h) | \
// | | |
// (i)-----------------(j) |
// | |
// (k)----------------------
//
graph.makeEdgeChain( "a,b,c,d,e" );
graph.makeEdgeChain( "a,f,g,h,e" );
graph.makeEdgeChain( "f,i,j,e" );
graph.makeEdgeChain( "i,k,e" );
final Node a = graph.getNode( "a" );
final Node e = graph.getNode( "e" );
RelationshipExpander expander = expanderForTypes( R1, OUTGOING );
testShortestPathFinder( new PathFinderTester()
{
@Override
public void test( PathFinder<Path> finder )
{
assertEquals( 4, count( finder.findAllPaths( a, e ) ) );
}
}, expander, 10, 10 );
for ( int i = 4; i >= 1; i-- )
{
final int count = i;
testShortestPathFinder( new PathFinderTester()
{
@Override
public void test( PathFinder<Path> finder )
{
assertEquals( count, count( finder.findAllPaths( a, e ) ) );
}
}, expander, 10, count );
}
}
@Test
public void unfortunateRelationshipOrderingInTriangle()
{
/*
* (b)
* ^ \
* / v
* (a)---->(c)
*
* Relationships are created in such a way that they are iterated in the worst order,
* i.e. (S) a-->b, (E) c<--b, (S) a-->c
*/
graph.makeEdgeChain( "a,b,c" );
graph.makeEdgeChain( "a,c" );
final Node a = graph.getNode( "a" );
final Node c = graph.getNode( "c" );
testShortestPathFinder( new PathFinderTester()
{
@Override
public void test( PathFinder<Path> finder )
{
assertPathDef( finder.findSinglePath( a, c ), "a", "c" );
}
}, expanderForTypes( R1, OUTGOING ), 2 );
testShortestPathFinder( new PathFinderTester()
{
@Override
public void test( PathFinder<Path> finder )
{
assertPathDef( finder.findSinglePath( c, a ), "c", "a" );
}
}, expanderForTypes( R1, INCOMING ), 2 );
}
@Ignore("Exposes a problem where the expected path isn't returned")
@Test
public void pathsWithLengthProblem() throws Exception
{
/*
*
* (a)-->(b)-->(c)<--(f)
* \ ^ |
* v / v
* (d) (e)
*
*/
graph.makeEdgeChain( "f,c" );
graph.makeEdgeChain( "c,e" );
graph.makeEdgeChain( "a,b,c" );
graph.makeEdgeChain( "a,d,b" );
Node a = graph.getNode( "a" );
Node c = graph.getNode( "c" );
assertPaths( new ShortestPath( 3, expanderForTypes( R1 ), 10, true ).findAllPaths( a, c ), "a,d,b,c" );
}
@Test
public void shouldFindShortestPathWhenOneSideFindsLongerPathFirst() throws Exception
{
/*
The order in which nodes are created matters when reproducing the original problem
*/
graph.makeEdge( "start", "c" );
graph.makeEdge( "start", "a" );
graph.makeEdge( "b", "end" );
graph.makeEdge( "d", "end" );
graph.makeEdge( "c", "e" );
graph.makeEdge( "f", "end" );
graph.makeEdge( "c", "b" );
graph.makeEdge( "e", "end" );
graph.makeEdge( "a", "end" );
Node start = graph.getNode( "start" );
Node end = graph.getNode( "end" );
assertThat( new ShortestPath( 2, expanderForAllTypes(), 42 ).findSinglePath( start, end ).length(), is( 2 ) );
assertThat( new ShortestPath( 3, expanderForAllTypes(), 42 ).findSinglePath( start, end ).length(), is( 2 ) );
}
private void testShortestPathFinder( PathFinderTester tester, RelationshipExpander expander, int maxDepth )
{
testShortestPathFinder( tester, expander, maxDepth, null );
}
private void testShortestPathFinder( PathFinderTester tester, RelationshipExpander expander, int maxDepth,
Integer maxResultCount )
{
LengthCheckingExpanderWrapper lengthChecker = new LengthCheckingExpanderWrapper( StandardExpander.toPathExpander( expander ) );
List<PathFinder<Path>> finders = new ArrayList<PathFinder<Path>>();
finders.add( maxResultCount != null ? shortestPath( lengthChecker, maxDepth, maxResultCount ) : shortestPath(
lengthChecker, maxDepth ) );
finders.add( maxResultCount != null ? new TraversalShortestPath( lengthChecker, maxDepth,
maxResultCount ) : new TraversalShortestPath( lengthChecker, maxDepth ) );
for ( PathFinder<Path> finder : finders )
{
tester.test( finder );
}
}
private interface PathFinderTester
{
void test( PathFinder<Path> finder );
}
private static class LengthCheckingExpanderWrapper implements PathExpander<Object> {
private PathExpander expander;
LengthCheckingExpanderWrapper( PathExpander expander )
{
this.expander = expander;
}
@Override
@SuppressWarnings("unchecked")
public Iterable<Relationship> expand( Path path, BranchState<Object> state )
{
if ( path.startNode().equals(path.endNode()) )
{
assertTrue( "Path length must be zero", path.length() == 0 );
}
else
{
assertTrue( "Path length must be positive", path.length() > 0 );
}
return expander.expand( path, state );
}
@Override
public PathExpander<Object> reverse()
{
return new LengthCheckingExpanderWrapper( expander.reverse() );
}
}
}
| false
|
community_graph-algo_src_test_java_org_neo4j_graphalgo_path_TestShortestPath.java
|
3,565
|
private static class NaturalPriority<P extends Comparable<P>> implements
Comparator<P>
{
private final boolean reversed;
NaturalPriority( boolean reversed )
{
this.reversed = reversed;
}
@Override
public int compare( P o1, P o2 )
{
if ( reversed )
{
return o2.compareTo( o1 );
}
else
{
return o1.compareTo( o2 );
}
}
}
| false
|
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_util_PriorityMap.java
|
3,566
|
public static final class Entry<E, P>
{
private final E entity;
private final P priority;
private Entry( E entity, P priority )
{
this.entity = entity;
this.priority = priority;
}
Entry( Node<E, P> node )
{
this( node.head.entity, node.priority );
}
public E getEntity()
{
return entity;
}
public P getPriority()
{
return priority;
}
}
| false
|
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_util_PriorityMap.java
|
3,567
|
public class LuceneLabelScanStoreChaosIT
{
@Test
public void shouldRebuildDeletedLabelScanStoreOnStartup() throws Exception
{
// GIVEN
Node node1 = createLabeledNode( Labels.First );
Node node2 = createLabeledNode( Labels.First );
Node node3 = createLabeledNode( Labels.First );
deleteNode( node2 ); // just to create a hole in the store
// WHEN
// TODO how do we make sure it was deleted and then fully rebuilt? I mean if we somehow deleted
// the wrong directory here then it would also work, right?
dbRule.restartDatabase( deleteTheLabelScanStoreIndex() );
// THEN
assertEquals(
asSet( node1, node3 ),
getAllNodesWithLabel( Labels.First ) );
}
@Test
public void shouldPreventCorruptedLabelScanStoreToStartup() throws Exception
{
// GIVEN
createLabeledNode( Labels.First );
// WHEN
// TODO how do we make sure it was deleted and then fully rebuilt? I mean if we somehow deleted
// the wrong directory here then it would also work, right?
try
{
dbRule.restartDatabase( corruptTheLabelScanStoreIndex() );
fail( "Shouldn't be able to start up" );
}
catch ( RuntimeException e )
{
// THEN
@SuppressWarnings( "unchecked" )
Throwable ioe = peel( e, exceptionsOfType( RuntimeException.class ) );
assertThat( ioe.getMessage(), containsString( "Label scan store is corrupted" ) );
}
}
private RestartAction corruptTheLabelScanStoreIndex()
{
return new RestartAction()
{
@Override
public void run( FileSystemAbstraction fs, File storeDirectory )
{
try
{
int filesCorrupted = 0;
for ( File file : labelScanStoreIndexDirectory( storeDirectory ).listFiles() )
{
scrambleFile( file );
filesCorrupted++;
}
assertTrue( "No files found to corrupt", filesCorrupted > 0 );
}
catch ( IOException e )
{
throw new RuntimeException( e );
}
}
};
}
private RestartAction deleteTheLabelScanStoreIndex()
{
return new RestartAction()
{
@Override
public void run( FileSystemAbstraction fs, File storeDirectory )
{
try
{
File directory = labelScanStoreIndexDirectory( storeDirectory );
assertTrue( "We seem to want to delete the wrong directory here", directory.exists() );
assertTrue( "No index files to delete", directory.listFiles().length > 0 );
deleteRecursively( directory );
}
catch ( IOException e )
{
throw new RuntimeException( e );
}
}
};
}
private File labelScanStoreIndexDirectory( File storeDirectory )
{
File directory = new File( new File( new File( storeDirectory, "schema" ), "label" ), "lucene" );
return directory;
}
private Node createLabeledNode( Label... labels )
{
try ( Transaction tx = dbRule.getGraphDatabaseService().beginTx() )
{
Node node = dbRule.getGraphDatabaseService().createNode( labels );
tx.success();
return node;
}
}
private Set<Node> getAllNodesWithLabel( Label label )
{
try ( Transaction tx = dbRule.getGraphDatabaseService().beginTx() )
{
return asSet( GlobalGraphOperations.at( dbRule.getGraphDatabaseService() ).getAllNodesWithLabel( label ) );
}
}
private void deleteNode( Node node )
{
try ( Transaction tx = dbRule.getGraphDatabaseService().beginTx() )
{
node.delete();
tx.success();
}
}
private void scrambleFile( File file ) throws IOException
{
try ( RandomAccessFile fileAccess = new RandomAccessFile( file, "rw" );
FileChannel channel = fileAccess.getChannel() )
{
// The files will be small, so OK to allocate a buffer for the full size
byte[] bytes = new byte[(int) channel.size()];
putRandomBytes( bytes );
ByteBuffer buffer = ByteBuffer.wrap( bytes );
channel.position( 0 );
channel.write( buffer );
}
}
private void putRandomBytes( byte[] bytes )
{
for ( int i = 0; i < bytes.length; i++ )
{
bytes[i] = (byte) random.nextInt();
}
}
private static enum Labels implements Label
{
First,
Second,
Third;
}
public final @Rule DatabaseRule dbRule = new EmbeddedDatabaseRule( getClass() );
private final Random random = new Random();
}
| false
|
community_lucene-index_src_test_java_org_neo4j_graphdb_LuceneLabelScanStoreChaosIT.java
|
3,568
|
public class FibonacciHeapNode
{
FibonacciHeapNode left, right, parent, child;
boolean marked = false;
KeyType key;
int degree = 0;
public FibonacciHeapNode( KeyType key )
{
super();
this.key = key;
left = this;
right = this;
}
/**
* @return the key
*/
public KeyType getKey()
{
return key;
}
}
| false
|
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_util_FibonacciHeap.java
|
3,569
|
public class DoubleEvaluatorWithDefault implements CostEvaluator<Double>
{
private String costPropertyName;
private final double defaultCost;
public DoubleEvaluatorWithDefault( String costPropertyName, double defaultCost )
{
super();
this.costPropertyName = costPropertyName;
this.defaultCost = defaultCost;
}
public Double getCost( Relationship relationship, Direction direction )
{
return (Double) relationship.getProperty( costPropertyName, defaultCost );
}
}
| false
|
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_util_DoubleEvaluatorWithDefault.java
|
3,570
|
public class DoubleEvaluator implements CostEvaluator<Double>
{
private String costpropertyName;
public DoubleEvaluator( String costpropertyName )
{
super();
this.costpropertyName = costpropertyName;
}
public Double getCost( Relationship relationship, Direction direction )
{
Object costProp = relationship.getProperty( costpropertyName );
if(costProp instanceof Double)
{
return (Double)costProp;
} else if (costProp instanceof Integer)
{
return (double)(Integer)costProp;
} else
{
return Double.parseDouble( costProp.toString() );
}
}
}
| false
|
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_util_DoubleEvaluator.java
|
3,571
|
public class DoubleComparator implements Comparator<Double>
{
public int compare(Double o1, Double o2) {
Double d = o1 - o2;
return d > 0 ? 1 : (d < 0 ? -1 : 0);
}
}
| false
|
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_util_DoubleComparator.java
|
3,572
|
public class DoubleAdder implements CostAccumulator<Double>
{
public Double addCosts(Double c1, Double c2) {
return c1 + c2;
}
}
| false
|
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_util_DoubleAdder.java
|
3,573
|
private static class Visit<P extends Comparable<P>> implements Comparable<P>
{
private P cost;
private boolean visited;
public Visit( P cost )
{
this.cost = cost;
}
@Override
public int compareTo( P o )
{
return cost.compareTo( o );
}
}
| false
|
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_util_BestFirstSelectorFactory.java
|
3,574
|
public final class BestFirstSelector implements BranchSelector
{
private final PriorityMap<TraversalBranch, Node, P> queue =
PriorityMap.withNaturalOrder( CONVERTER );
private TraversalBranch current;
private P currentAggregatedValue;
private final PathExpander expander;
private final Map<Long, Visit<P>> visits = new HashMap<Long, Visit<P>>();
public BestFirstSelector( TraversalBranch source, P startData, PathExpander expander )
{
this.current = source;
this.currentAggregatedValue = startData;
this.expander = expander;
}
@Override
public TraversalBranch next( TraversalContext metadata )
{
// Exhaust current if not already exhausted
while ( true )
{
TraversalBranch next = current.next( expander, metadata );
if ( next == null )
{
break;
}
long endNodeId = next.endNode().getId();
Visit<P> stay = visits.get( endNodeId );
if ( stay == null || !stay.visited )
{
D cost = calculateValue( next );
P newPriority = addPriority( next, currentAggregatedValue, cost );
boolean newStay = stay == null;
if ( newStay )
{
stay = new Visit<P>( newPriority );
visits.put( endNodeId, stay );
}
if ( newStay || interestPredicate.apply( stay, newPriority ) )
{ // If the priority map already contains a traversal branch with this end node with
// a lower cost, then don't bother adding it to the priority map
queue.put( next, newPriority );
stay.cost = newPriority;
}
}
}
// Pop the top from priorityMap
Entry<TraversalBranch, P> entry = queue.pop();
if ( entry != null )
{
current = entry.getEntity();
currentAggregatedValue = entry.getPriority();
visits.get( current.endNode().getId() ).visited = true;
return current;
}
return null;
}
}
| false
|
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_util_BestFirstSelectorFactory.java
|
3,575
|
{
@Override
public Node convert( TraversalBranch source )
{
return source.endNode();
}
};
| false
|
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_util_BestFirstSelectorFactory.java
|
3,576
|
{
@Override
public Boolean apply( Visit<P> from1, P from2 )
{
return from1.compareTo( from2 ) > 0;
}
};
| false
|
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_util_BestFirstSelectorFactory.java
|
3,577
|
{
@Override
public Boolean apply( Visit<P> from1, P from2 )
{
return from1.compareTo( from2 ) >= 0;
}
}
| false
|
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_util_BestFirstSelectorFactory.java
|
3,578
|
public abstract class BestFirstSelectorFactory<P extends Comparable<P>, D>
implements BranchOrderingPolicy
{
private final Function2<Visit<P>, P, Boolean> interestPredicate;
public BestFirstSelectorFactory( boolean forMultiplePaths )
{
// If we are interested in multiple paths then we must keep around branches that have the same
// cost to any same end node, but if we're only interested in a single path then we can skip
// branches that have the same cost to any given end node and only keep one of the lowest cost branches.
this.interestPredicate = forMultiplePaths ?
new Function2<Visit<P>,P,Boolean>()
{
@Override
public Boolean apply( Visit<P> from1, P from2 )
{
return from1.compareTo( from2 ) >= 0;
}
}
:
new Function2<Visit<P>,P,Boolean>()
{
@Override
public Boolean apply( Visit<P> from1, P from2 )
{
return from1.compareTo( from2 ) > 0;
}
};
}
@Override
public BranchSelector create( TraversalBranch startSource, PathExpander expander )
{
return new BestFirstSelector( startSource, getStartData(), expander );
}
public BranchSelector create( TraversalBranch startSource, RelationshipExpander expander )
{
return new BestFirstSelector( startSource, getStartData(), toPathExpander( expander ) );
}
protected abstract P getStartData();
private static class Visit<P extends Comparable<P>> implements Comparable<P>
{
private P cost;
private boolean visited;
public Visit( P cost )
{
this.cost = cost;
}
@Override
public int compareTo( P o )
{
return cost.compareTo( o );
}
}
public final class BestFirstSelector implements BranchSelector
{
private final PriorityMap<TraversalBranch, Node, P> queue =
PriorityMap.withNaturalOrder( CONVERTER );
private TraversalBranch current;
private P currentAggregatedValue;
private final PathExpander expander;
private final Map<Long, Visit<P>> visits = new HashMap<Long, Visit<P>>();
public BestFirstSelector( TraversalBranch source, P startData, PathExpander expander )
{
this.current = source;
this.currentAggregatedValue = startData;
this.expander = expander;
}
@Override
public TraversalBranch next( TraversalContext metadata )
{
// Exhaust current if not already exhausted
while ( true )
{
TraversalBranch next = current.next( expander, metadata );
if ( next == null )
{
break;
}
long endNodeId = next.endNode().getId();
Visit<P> stay = visits.get( endNodeId );
if ( stay == null || !stay.visited )
{
D cost = calculateValue( next );
P newPriority = addPriority( next, currentAggregatedValue, cost );
boolean newStay = stay == null;
if ( newStay )
{
stay = new Visit<P>( newPriority );
visits.put( endNodeId, stay );
}
if ( newStay || interestPredicate.apply( stay, newPriority ) )
{ // If the priority map already contains a traversal branch with this end node with
// a lower cost, then don't bother adding it to the priority map
queue.put( next, newPriority );
stay.cost = newPriority;
}
}
}
// Pop the top from priorityMap
Entry<TraversalBranch, P> entry = queue.pop();
if ( entry != null )
{
current = entry.getEntity();
currentAggregatedValue = entry.getPriority();
visits.get( current.endNode().getId() ).visited = true;
return current;
}
return null;
}
}
protected abstract P addPriority( TraversalBranch source,
P currentAggregatedValue, D value );
protected abstract D calculateValue( TraversalBranch next );
public static final Converter<Node, TraversalBranch> CONVERTER =
new Converter<Node, TraversalBranch>()
{
@Override
public Node convert( TraversalBranch source )
{
return source.endNode();
}
};
}
| false
|
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_util_BestFirstSelectorFactory.java
|
3,579
|
public static class PathCounter
{
Map<Node,List<Relationship>> predecessors;
Map<Node,Integer> pathCounts = new HashMap<Node,Integer>();
public PathCounter( Map<Node,List<Relationship>> predecessors )
{
super();
this.predecessors = predecessors;
}
public int getNumberOfPathsToNode( Node node )
{
Integer i = pathCounts.get( node );
if ( i != null )
{
return i;
}
List<Relationship> preds = predecessors.get( node );
if ( preds == null || preds.size() == 0 )
{
return 1;
}
int result = 0;
for ( Relationship relationship : preds )
{
result += getNumberOfPathsToNode( relationship
.getOtherNode( node ) );
}
pathCounts.put( node, result );
return result;
}
}
| false
|
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_shortestpath_Util.java
|
3,580
|
public class Util
{
/**
* Constructs a path to a given node, for a given set of predecessors
* @param node
* The start node
* @param predecessors
* The predecessors set
* @param includeNode
* Boolean which determines if the start node should be included
* in the paths
* @param backwards
* Boolean, if true the order of the nodes in the paths will be
* reversed
* @return A path as a list of nodes.
*/
public static List<Node> constructSinglePathToNodeAsNodes( Node node,
Map<Node,List<Relationship>> predecessors, boolean includeNode,
boolean backwards )
{
List<PropertyContainer> singlePathToNode = constructSinglePathToNode(
node, predecessors, includeNode, backwards );
Iterator<PropertyContainer> iterator = singlePathToNode.iterator();
// When going backwards and not including the node the first element is
// a relationship. Thus skip it.
if ( backwards && !includeNode && iterator.hasNext() )
{
iterator.next();
}
LinkedList<Node> path = new LinkedList<Node>();
while ( iterator.hasNext() )
{
path.addLast( (Node) iterator.next() );
if ( iterator.hasNext() )
{
iterator.next();
}
}
return path;
}
/**
* Constructs a path to a given node, for a given set of predecessors
* @param node
* The start node
* @param predecessors
* The predecessors set
* @param backwards
* Boolean, if true the order of the nodes in the paths will be
* reversed
* @return A path as a list of relationships.
*/
public static List<Relationship> constructSinglePathToNodeAsRelationships(
Node node, Map<Node,List<Relationship>> predecessors, boolean backwards )
{
List<PropertyContainer> singlePathToNode = constructSinglePathToNode(
node, predecessors, true, backwards );
Iterator<PropertyContainer> iterator = singlePathToNode.iterator();
// Skip the first, it is a node
if ( iterator.hasNext() )
{
iterator.next();
}
LinkedList<Relationship> path = new LinkedList<Relationship>();
while ( iterator.hasNext() )
{
path.addLast( (Relationship) iterator.next() );
if ( iterator.hasNext() )
{
iterator.next();
}
}
return path;
}
/**
* Constructs a path to a given node, for a given set of predecessors. The
* result is a list of alternating Node/Relationship.
* @param node
* The start node
* @param predecessors
* The predecessors set
* @param includeNode
* Boolean which determines if the start node should be included
* in the paths
* @param backwards
* Boolean, if true the order of the nodes in the paths will be
* reversed
* @return A path as a list of alternating Node/Relationship.
*/
public static List<PropertyContainer> constructSinglePathToNode( Node node,
Map<Node,List<Relationship>> predecessors, boolean includeNode,
boolean backwards )
{
LinkedList<PropertyContainer> path = new LinkedList<PropertyContainer>();
if ( includeNode )
{
if ( backwards )
{
path.addLast( node );
}
else
{
path.addFirst( node );
}
}
Node currentNode = node;
List<Relationship> currentPreds = predecessors.get( currentNode );
// Traverse predecessors until we have added a node without predecessors
while ( currentPreds != null && currentPreds.size() != 0 )
{
// Get next node
Relationship currentRelationship = currentPreds.get( 0 );
currentNode = currentRelationship.getOtherNode( currentNode );
// Add current
if ( backwards )
{
path.addLast( currentRelationship );
path.addLast( currentNode );
}
else
{
path.addFirst( currentRelationship );
path.addFirst( currentNode );
}
// Continue with the next node
currentPreds = predecessors.get( currentNode );
}
return path;
}
/**
* Constructs all paths to a given node, for a given set of predecessors
* @param node
* The start node
* @param predecessors
* The predecessors set
* @param includeNode
* Boolean which determines if the start node should be included
* in the paths
* @param backwards
* Boolean, if true the order of the nodes in the paths will be
* reversed
* @return
*/
public static List<List<Node>> constructAllPathsToNodeAsNodes( Node node,
Map<Node,List<Relationship>> predecessors, boolean includeNode,
boolean backwards )
{
return new LinkedList<List<Node>>(
constructAllPathsToNodeAsNodeLinkedLists( node, predecessors,
includeNode, backwards ) );
}
/**
* Same as constructAllPathsToNodeAsNodes, but different return type
*/
protected static List<LinkedList<Node>> constructAllPathsToNodeAsNodeLinkedLists(
Node node, Map<Node,List<Relationship>> predecessors,
boolean includeNode, boolean backwards )
{
List<LinkedList<Node>> paths = new LinkedList<LinkedList<Node>>();
List<Relationship> current = predecessors.get( node );
// First build all paths to this node's predecessors
if ( current != null )
{
for ( Relationship r : current )
{
Node n = r.getOtherNode( node );
paths.addAll( constructAllPathsToNodeAsNodeLinkedLists( n,
predecessors, true, backwards ) );
}
}
// If no paths exists to this node, just create an empty one (which will
// have this node added to it)
if ( paths.isEmpty() )
{
paths.add( new LinkedList<Node>() );
}
// Then add this node to all those paths
if ( includeNode )
{
for ( LinkedList<Node> path : paths )
{
if ( backwards )
{
path.addFirst( node );
}
else
{
path.addLast( node );
}
}
}
return paths;
}
/**
* Constructs all paths to a given node, for a given set of predecessors
* @param node
* The start node
* @param predecessors
* The predecessors set
* @param includeNode
* Boolean which determines if the start node should be included
* in the paths
* @param backwards
* Boolean, if true the order of the nodes in the paths will be
* reversed
* @return List of lists of alternating Node/Relationship.
*/
public static List<List<PropertyContainer>> constructAllPathsToNode(
Node node, Map<Node,List<Relationship>> predecessors,
boolean includeNode, boolean backwards )
{
return new LinkedList<List<PropertyContainer>>(
constructAllPathsToNodeAsLinkedLists( node, predecessors,
includeNode, backwards ) );
}
/**
* Same as constructAllPathsToNode, but different return type
*/
protected static List<LinkedList<PropertyContainer>> constructAllPathsToNodeAsLinkedLists(
Node node, Map<Node,List<Relationship>> predecessors,
boolean includeNode, boolean backwards )
{
List<LinkedList<PropertyContainer>> paths = new LinkedList<LinkedList<PropertyContainer>>();
List<Relationship> current = predecessors.get( node );
// First build all paths to this node's predecessors
if ( current != null )
{
for ( Relationship r : current )
{
Node n = r.getOtherNode( node );
List<LinkedList<PropertyContainer>> newPaths = constructAllPathsToNodeAsLinkedLists(
n, predecessors, true, backwards );
paths.addAll( newPaths );
// Add the relationship
for ( LinkedList<PropertyContainer> path : newPaths )
{
if ( backwards )
{
path.addFirst( r );
}
else
{
path.addLast( r );
}
}
}
}
// If no paths exists to this node, just create an empty one (which will
// have this node added to it)
if ( paths.isEmpty() )
{
paths.add( new LinkedList<PropertyContainer>() );
}
// Then add this node to all those paths
if ( includeNode )
{
for ( LinkedList<PropertyContainer> path : paths )
{
if ( backwards )
{
path.addFirst( node );
}
else
{
path.addLast( node );
}
}
}
return paths;
}
/**
* Constructs all paths to a given node, for a given set of predecessors.
* @param node
* The start node
* @param predecessors
* The predecessors set
* @param backwards
* Boolean, if true the order of the nodes in the paths will be
* reversed
* @return List of lists of relationships.
*/
public static List<List<Relationship>> constructAllPathsToNodeAsRelationships(
Node node, Map<Node,List<Relationship>> predecessors, boolean backwards )
{
return new LinkedList<List<Relationship>>(
constructAllPathsToNodeAsRelationshipLinkedLists( node,
predecessors, backwards ) );
}
/**
* Same as constructAllPathsToNodeAsRelationships, but different return type
*/
protected static List<LinkedList<Relationship>> constructAllPathsToNodeAsRelationshipLinkedLists(
Node node, Map<Node,List<Relationship>> predecessors, boolean backwards )
{
List<LinkedList<Relationship>> paths = new LinkedList<LinkedList<Relationship>>();
List<Relationship> current = predecessors.get( node );
// First build all paths to this node's predecessors
if ( current != null )
{
for ( Relationship r : current )
{
Node n = r.getOtherNode( node );
List<LinkedList<Relationship>> newPaths = constructAllPathsToNodeAsRelationshipLinkedLists(
n, predecessors, backwards );
paths.addAll( newPaths );
// Add the relationship
for ( LinkedList<Relationship> path : newPaths )
{
if ( backwards )
{
path.addFirst( r );
}
else
{
path.addLast( r );
}
}
}
}
// If no paths exists to this node, just create an empty one
if ( paths.isEmpty() )
{
paths.add( new LinkedList<Relationship>() );
}
return paths;
}
/**
* This can be used for counting the number of paths from the start node
* (implicit from the predecessors) and some target nodes.
*/
public static class PathCounter
{
Map<Node,List<Relationship>> predecessors;
Map<Node,Integer> pathCounts = new HashMap<Node,Integer>();
public PathCounter( Map<Node,List<Relationship>> predecessors )
{
super();
this.predecessors = predecessors;
}
public int getNumberOfPathsToNode( Node node )
{
Integer i = pathCounts.get( node );
if ( i != null )
{
return i;
}
List<Relationship> preds = predecessors.get( node );
if ( preds == null || preds.size() == 0 )
{
return 1;
}
int result = 0;
for ( Relationship relationship : preds )
{
result += getNumberOfPathsToNode( relationship
.getOtherNode( node ) );
}
pathCounts.put( node, result );
return result;
}
}
/**
* This can be used to generate the inverse of a structure with
* predecessors, i.e. the successors.
* @param predecessors
* @return
*/
public static Map<Node,List<Relationship>> reversedPredecessors(
Map<Node,List<Relationship>> predecessors )
{
Map<Node,List<Relationship>> result = new HashMap<Node,List<Relationship>>();
Set<Node> keys = predecessors.keySet();
for ( Node node : keys )
{
List<Relationship> preds = predecessors.get( node );
for ( Relationship relationship : preds )
{
Node otherNode = relationship.getOtherNode( node );
// We add node as a predecessor to otherNode, instead of the
// other way around
List<Relationship> otherPreds = result.get( otherNode );
if ( otherPreds == null )
{
otherPreds = new LinkedList<Relationship>();
result.put( otherNode, otherPreds );
}
otherPreds.add( relationship );
}
}
return result;
}
}
| false
|
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_shortestpath_Util.java
|
3,581
|
public class SingleSourceShortestPathDijkstra<CostType> extends
Dijkstra<CostType> implements SingleSourceShortestPath<CostType>
{
DijstraIterator dijstraIterator;
/**
* @see Dijkstra
*/
public SingleSourceShortestPathDijkstra( CostType startCost,
Node startNode, CostEvaluator<CostType> costEvaluator,
CostAccumulator<CostType> costAccumulator,
Comparator<CostType> costComparator, Direction relationDirection,
RelationshipType... costRelationTypes )
{
super( startCost, startNode, null, costEvaluator, costAccumulator,
costComparator, relationDirection, costRelationTypes );
reset();
}
protected HashMap<Node,CostType> distances = new HashMap<Node,CostType>();
@Override
public void reset()
{
super.reset();
distances = new HashMap<Node,CostType>();
HashMap<Node,CostType> seen1 = new HashMap<Node,CostType>();
HashMap<Node,CostType> seen2 = new HashMap<Node,CostType>();
HashMap<Node,CostType> dists2 = new HashMap<Node,CostType>();
dijstraIterator = new DijstraIterator( startNode, predecessors1, seen1,
seen2, distances, dists2, false );
}
/**
* Same as calculate(), but will set the flag to calculate all shortest
* paths. It sets the flag and then calls calculate.
* @return
*/
public boolean calculateMultiple( Node targetNode )
{
if ( !calculateAllShortestPaths )
{
reset();
calculateAllShortestPaths = true;
}
return calculate( targetNode );
}
@Override
public boolean calculate()
{
return calculate( null );
}
/**
* Internal calculate method that will run the calculation until either the
* limit is reached or a result has been generated for a given node.
*/
public boolean calculate( Node targetNode )
{
while ( (targetNode == null || !distances.containsKey( targetNode ))
&& dijstraIterator.hasNext() && !limitReached() )
{
dijstraIterator.next();
}
return true;
}
// We dont need to reset the calculation, so we just override this.
@Override
public void setEndNode( Node endNode )
{
this.endNode = endNode;
}
/**
* @see Dijkstra
*/
public CostType getCost( Node targetNode )
{
if ( targetNode == null )
{
throw new RuntimeException( "No end node defined" );
}
calculate( targetNode );
return distances.get( targetNode );
}
public List<List<PropertyContainer>> getPaths( Node targetNode )
{
if ( targetNode == null )
{
throw new RuntimeException( "No end node defined" );
}
calculateMultiple( targetNode );
if ( !distances.containsKey( targetNode ) )
{
return null;
}
return new LinkedList<List<PropertyContainer>>( Util
.constructAllPathsToNode( targetNode, predecessors1, true, false ) );
}
public List<List<Node>> getPathsAsNodes( Node targetNode )
{
if ( targetNode == null )
{
throw new RuntimeException( "No end node defined" );
}
calculateMultiple( targetNode );
if ( !distances.containsKey( targetNode ) )
{
return null;
}
return new LinkedList<List<Node>>( Util.constructAllPathsToNodeAsNodes(
targetNode, predecessors1, true, false ) );
}
public List<List<Relationship>> getPathsAsRelationships( Node targetNode )
{
if ( targetNode == null )
{
throw new RuntimeException( "No end node defined" );
}
calculateMultiple( targetNode );
if ( !distances.containsKey( targetNode ) )
{
return null;
}
return new LinkedList<List<Relationship>>( Util
.constructAllPathsToNodeAsRelationships( targetNode, predecessors1,
false ) );
}
public List<PropertyContainer> getPath( Node targetNode )
{
if ( targetNode == null )
{
throw new RuntimeException( "No end node defined" );
}
calculate( targetNode );
if ( !distances.containsKey( targetNode ) )
{
return null;
}
return Util.constructSinglePathToNode( targetNode, predecessors1, true,
false );
}
public List<Node> getPathAsNodes( Node targetNode )
{
if ( targetNode == null )
{
throw new RuntimeException( "No end node defined" );
}
calculate( targetNode );
if ( !distances.containsKey( targetNode ) )
{
return null;
}
return Util.constructSinglePathToNodeAsNodes( targetNode,
predecessors1, true, false );
}
public List<Relationship> getPathAsRelationships( Node targetNode )
{
if ( targetNode == null )
{
throw new RuntimeException( "No end node defined" );
}
calculate( targetNode );
if ( !distances.containsKey( targetNode ) )
{
return null;
}
return Util.constructSinglePathToNodeAsRelationships( targetNode,
predecessors1, false );
}
// Override all the result-getters
@Override
public CostType getCost()
{
return getCost( endNode );
}
@Override
public List<PropertyContainer> getPath()
{
return getPath( endNode );
}
@Override
public List<Node> getPathAsNodes()
{
return getPathAsNodes( endNode );
}
@Override
public List<Relationship> getPathAsRelationships()
{
return getPathAsRelationships( endNode );
}
@Override
public List<List<PropertyContainer>> getPaths()
{
return getPaths( endNode );
}
@Override
public List<List<Node>> getPathsAsNodes()
{
return getPathsAsNodes( endNode );
}
@Override
public List<List<Relationship>> getPathsAsRelationships()
{
return getPathsAsRelationships( endNode );
}
/**
* @see SingleSourceShortestPath
*/
public List<Node> getPredecessorNodes( Node node )
{
List<Node> result = new LinkedList<Node>();
List<Relationship> predecessorRelationShips = predecessors1.get( node );
if ( predecessorRelationShips == null
|| predecessorRelationShips.size() == 0 )
{
return null;
}
for ( Relationship relationship : predecessorRelationShips )
{
result.add( relationship.getOtherNode( node ) );
}
return result;
}
/**
* @see SingleSourceShortestPath
*/
public Map<Node,List<Relationship>> getPredecessors()
{
calculateMultiple();
return predecessors1;
}
/**
* @see SingleSourceShortestPath
*/
public Direction getDirection()
{
return relationDirection;
}
/**
* @see SingleSourceShortestPath
*/
public RelationshipType[] getRelationshipTypes()
{
return costRelationTypes;
}
}
| false
|
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_shortestpath_SingleSourceShortestPathDijkstra.java
|
3,582
|
public class SingleSourceShortestPathBFS implements
SingleSourceShortestPath<Integer>
{
protected Node startNode;
protected Direction relationShipDirection;
protected RelationshipType[] relationShipTypes;
protected HashMap<Node,Integer> distances = new HashMap<Node,Integer>();;
protected HashMap<Node,List<Relationship>> predecessors = new HashMap<Node,List<Relationship>>();
// Limits
protected long maxDepth = Long.MAX_VALUE;
protected long depth = 0;
LinkedList<Node> currentLayer = new LinkedList<Node>();;
LinkedList<Node> nextLayer = new LinkedList<Node>();
public SingleSourceShortestPathBFS( Node startNode,
Direction relationShipDirection, RelationshipType... relationShipTypes )
{
super();
this.startNode = startNode;
this.relationShipDirection = relationShipDirection;
this.relationShipTypes = relationShipTypes;
reset();
}
/**
* This sets the maximum depth to scan.
*/
public void limitDepth( long maxDepth )
{
this.maxDepth = maxDepth;
}
/**
* @see SingleSourceShortestPath
*/
public void setStartNode( Node node )
{
startNode = node;
reset();
}
/**
* @see SingleSourceShortestPath
*/
public void reset()
{
distances = new HashMap<Node,Integer>();
predecessors = new HashMap<Node,List<Relationship>>();
currentLayer = new LinkedList<Node>();;
nextLayer = new LinkedList<Node>();
currentLayer.add( startNode );
depth = 0;
}
/**
* @see SingleSourceShortestPath
*/
public Integer getCost( Node targetNode )
{
calculate( targetNode );
return distances.get( targetNode );
}
/**
* @see SingleSourceShortestPath
*/
public List<PropertyContainer> getPath( Node targetNode )
{
if ( targetNode == null )
{
throw new RuntimeException( "No end node defined" );
}
calculate( targetNode );
if ( !distances.containsKey( targetNode ) )
{
return null;
}
return Util.constructSinglePathToNode( targetNode, predecessors, true,
false );
}
/**
* @see SingleSourceShortestPath
*/
public List<Node> getPathAsNodes( Node targetNode )
{
if ( targetNode == null )
{
throw new RuntimeException( "No end node defined" );
}
calculate( targetNode );
if ( !distances.containsKey( targetNode ) )
{
return null;
}
return Util.constructSinglePathToNodeAsNodes( targetNode, predecessors,
true, false );
}
/**
* @see SingleSourceShortestPath
*/
public List<Relationship> getPathAsRelationships( Node targetNode )
{
if ( targetNode == null )
{
throw new RuntimeException( "No end node defined" );
}
calculate( targetNode );
if ( !distances.containsKey( targetNode ) )
{
return null;
}
return Util.constructSinglePathToNodeAsRelationships( targetNode,
predecessors, false );
}
/**
* @see SingleSourceShortestPath
*/
public List<List<PropertyContainer>> getPaths( Node targetNode )
{
if ( targetNode == null )
{
throw new RuntimeException( "No end node defined" );
}
calculate( targetNode );
if ( !distances.containsKey( targetNode ) )
{
return null;
}
return Util.constructAllPathsToNode( targetNode, predecessors, true,
false );
}
/**
* @see SingleSourceShortestPath
*/
public List<List<Node>> getPathsAsNodes( Node targetNode )
{
if ( targetNode == null )
{
throw new RuntimeException( "No end node defined" );
}
calculate( targetNode );
if ( !distances.containsKey( targetNode ) )
{
return null;
}
return Util.constructAllPathsToNodeAsNodes( targetNode, predecessors,
true, false );
}
/**
* @see SingleSourceShortestPath
*/
public List<List<Relationship>> getPathsAsRelationships( Node targetNode )
{
if ( targetNode == null )
{
throw new RuntimeException( "No end node defined" );
}
calculate( targetNode );
if ( !distances.containsKey( targetNode ) )
{
return null;
}
return Util.constructAllPathsToNodeAsRelationships( targetNode,
predecessors, false );
}
/**
* Iterator-style "next" method.
* @return True if evaluate was made. False if no more computation could be
* done.
*/
public boolean processNextNode()
{
// finished with current layer? increase depth
if ( currentLayer.isEmpty() )
{
if ( nextLayer.isEmpty() )
{
return false;
}
currentLayer = nextLayer;
nextLayer = new LinkedList<Node>();
++depth;
}
Node node = currentLayer.poll();
// Multiple paths to a certain node might make it appear several
// times, just process it once
if ( distances.containsKey( node ) )
{
return true;
}
// Put it in distances
distances.put( node, (int) depth );
// Follow all edges
for ( RelationshipType relationshipType : relationShipTypes )
{
for ( Relationship relationship : node.getRelationships(
relationshipType, relationShipDirection ) )
{
Node targetNode = relationship.getOtherNode( node );
// Are we going back into the already finished area?
// That would be more expensive.
if ( !distances.containsKey( targetNode ) )
{
// Put this into the next layer and the predecessors
nextLayer.add( targetNode );
List<Relationship> targetPreds = predecessors
.get( targetNode );
if ( targetPreds == null )
{
targetPreds = new LinkedList<Relationship>();
predecessors.put( targetNode, targetPreds );
}
targetPreds.add( relationship );
}
}
}
return true;
}
/**
* Internal calculate method that will do the calculation. This can however
* be called externally to manually trigger the calculation.
*/
public boolean calculate()
{
return calculate( null );
}
/**
* Internal calculate method that will run the calculation until either the
* limit is reached or a result has been generated for a given node.
*/
public boolean calculate( Node targetNode )
{
while ( depth <= maxDepth
&& (targetNode == null || !distances.containsKey( targetNode )) )
{
if ( !processNextNode() )
{
return false;
}
}
return true;
}
/**
* @see SingleSourceShortestPath
*/
public List<Node> getPredecessorNodes( Node node )
{
List<Node> result = new LinkedList<Node>();
List<Relationship> predecessorRelationShips = predecessors.get( node );
if ( predecessorRelationShips == null
|| predecessorRelationShips.size() == 0 )
{
return null;
}
for ( Relationship relationship : predecessorRelationShips )
{
result.add( relationship.getOtherNode( node ) );
}
return result;
}
/**
* @see SingleSourceShortestPath
*/
public Map<Node,List<Relationship>> getPredecessors()
{
calculate();
return predecessors;
}
/**
* @see SingleSourceShortestPath
*/
public Direction getDirection()
{
return relationShipDirection;
}
/**
* @see SingleSourceShortestPath
*/
public RelationshipType[] getRelationshipTypes()
{
return relationShipTypes;
}
}
| false
|
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_shortestpath_SingleSourceShortestPathBFS.java
|
3,583
|
public class FloydWarshall<CostType>
{
protected CostType startCost; // starting cost for all nodes
protected CostType infinitelyBad; // starting value for calculation
protected Direction relationDirection;
protected CostEvaluator<CostType> costEvaluator = null;
protected CostAccumulator<CostType> costAccumulator = null;
protected Comparator<CostType> costComparator = null;
protected Set<Node> nodeSet;
protected Set<Relationship> relationshipSet;
CostType[][] costMatrix;
Integer[][] predecessors;
Map<Node,Integer> nodeIndexes; // node ->index
Node[] IndexedNodes; // index -> node
protected boolean doneCalculation = false;
/**
* @param startCost
* The cost for just starting (or ending) a path in a node.
* @param infinitelyBad
* A cost worse than all others. This is used to initialize the
* distance matrix.
* @param costRelationType
* The relationship type to traverse.
* @param relationDirection
* The direction in which the paths should follow the
* relationships.
* @param costEvaluator
* @see {@link CostEvaluator}
* @param costAccumulator
* @see {@link CostAccumulator}
* @param costComparator
* @see {@link CostAccumulator} or {@link CostEvaluator}
* @param nodeSet
* The set of nodes the calculation should be run on.
* @param relationshipSet
* The set of relationships that should be processed.
*/
public FloydWarshall( CostType startCost, CostType infinitelyBad,
Direction relationDirection, CostEvaluator<CostType> costEvaluator,
CostAccumulator<CostType> costAccumulator,
Comparator<CostType> costComparator, Set<Node> nodeSet,
Set<Relationship> relationshipSet )
{
super();
this.startCost = startCost;
this.infinitelyBad = infinitelyBad;
this.relationDirection = relationDirection;
this.costEvaluator = costEvaluator;
this.costAccumulator = costAccumulator;
this.costComparator = costComparator;
this.nodeSet = nodeSet;
this.relationshipSet = relationshipSet;
}
/**
* This resets the calculation if we for some reason would like to redo it.
*/
public void reset()
{
doneCalculation = false;
}
/**
* Internal calculate method that will do the calculation. This can however
* be called externally to manually trigger the calculation.
*/
@SuppressWarnings( "unchecked" )
public void calculate()
{
// Don't do it more than once
if ( doneCalculation )
{
return;
}
doneCalculation = true;
// Build initial matrix
int n = nodeSet.size();
costMatrix = (CostType[][]) new Object[n][n];
predecessors = new Integer[n][n];
IndexedNodes = new Node[n];
nodeIndexes = new HashMap<Node,Integer>();
for ( int i = 0; i < n; ++i )
{
for ( int j = 0; j < n; ++j )
{
costMatrix[i][j] = infinitelyBad;
}
costMatrix[i][i] = startCost;
}
int nodeIndex = 0;
for ( Node node : nodeSet )
{
nodeIndexes.put( node, nodeIndex );
IndexedNodes[nodeIndex] = node;
++nodeIndex;
}
// Put the relationships in there
for ( Relationship relationship : relationshipSet )
{
Integer i1 = nodeIndexes.get( relationship.getStartNode() );
Integer i2 = nodeIndexes.get( relationship.getEndNode() );
if ( i1 == null || i2 == null )
{
// TODO: what to do here? pretend nothing happened? cast
// exception?
continue;
}
if ( relationDirection.equals( Direction.BOTH )
|| relationDirection.equals( Direction.OUTGOING ) )
{
costMatrix[i1][i2] = costEvaluator
.getCost( relationship,
Direction.OUTGOING );
predecessors[i1][i2] = i1;
}
if ( relationDirection.equals( Direction.BOTH )
|| relationDirection.equals( Direction.INCOMING ) )
{
costMatrix[i2][i1] = costEvaluator.getCost( relationship,
Direction.INCOMING );
predecessors[i2][i1] = i2;
}
}
// Do it!
for ( int v = 0; v < n; ++v )
{
for ( int i = 0; i < n; ++i )
{
for ( int j = 0; j < n; ++j )
{
CostType alternative = costAccumulator.addCosts(
costMatrix[i][v], costMatrix[v][j] );
if ( costComparator.compare( costMatrix[i][j], alternative ) > 0 )
{
costMatrix[i][j] = alternative;
predecessors[i][j] = predecessors[v][j];
}
}
}
}
// TODO: detect negative cycles?
}
/**
* This returns the cost for the shortest path between two nodes.
* @param node1
* The start node.
* @param node2
* The end node.
* @return The cost for the shortest path.
*/
public CostType getCost( Node node1, Node node2 )
{
calculate();
return costMatrix[nodeIndexes.get( node1 )][nodeIndexes.get( node2 )];
}
/**
* This returns the shortest path between two nodes as list of nodes.
* @param startNode
* The start node.
* @param targetNode
* The end node.
* @return The shortest path as a list of nodes.
*/
public List<Node> getPath( Node startNode, Node targetNode )
{
calculate();
LinkedList<Node> path = new LinkedList<Node>();
int index = nodeIndexes.get( targetNode );
int startIndex = nodeIndexes.get( startNode );
Node n = targetNode;
while ( !n.equals( startNode ) )
{
path.addFirst( n );
index = predecessors[startIndex][index];
n = IndexedNodes[index];
}
path.addFirst( n );
return path;
}
}
| false
|
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_shortestpath_FloydWarshall.java
|
3,584
|
protected class pathObject
{
private Node node;
private CostType cost;
public pathObject( Node node, CostType cost )
{
this.node = node;
this.cost = cost;
}
public CostType getCost()
{
return cost;
}
public Node getNode()
{
return node;
}
/*
* Equals is only defined from the stored node, so we can use it to find
* entries in the queue
*/
@Override
public boolean equals( Object obj )
{
if ( this == obj ) return true;
if ( obj == null ) return false;
if ( getClass() != obj.getClass() ) return false;
final pathObject other = (pathObject) obj;
if ( node == null )
{
if ( other.node != null ) return false;
}
else if ( !node.equals( other.node ) ) return false;
return true;
}
@Override
public int hashCode()
{
int result = node != null ? node.hashCode() : 0;
result = 31 * result + (cost != null ? cost.hashCode() : 0);
return result;
}
}
| false
|
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_shortestpath_DijkstraPriorityQueueImpl.java
|
3,585
|
{
public int compare( pathObject o1, pathObject o2 )
{
return costComparator.compare( o1.getCost(), o2.getCost() );
}
} );
| false
|
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_shortestpath_DijkstraPriorityQueueImpl.java
|
3,586
|
public class DijkstraPriorityQueueImpl<CostType> implements
DijkstraPriorityQueue<CostType>
{
/**
* Data structure used for the internal priority queue
*/
protected class pathObject
{
private Node node;
private CostType cost;
public pathObject( Node node, CostType cost )
{
this.node = node;
this.cost = cost;
}
public CostType getCost()
{
return cost;
}
public Node getNode()
{
return node;
}
/*
* Equals is only defined from the stored node, so we can use it to find
* entries in the queue
*/
@Override
public boolean equals( Object obj )
{
if ( this == obj ) return true;
if ( obj == null ) return false;
if ( getClass() != obj.getClass() ) return false;
final pathObject other = (pathObject) obj;
if ( node == null )
{
if ( other.node != null ) return false;
}
else if ( !node.equals( other.node ) ) return false;
return true;
}
@Override
public int hashCode()
{
int result = node != null ? node.hashCode() : 0;
result = 31 * result + (cost != null ? cost.hashCode() : 0);
return result;
}
}
Comparator<CostType> costComparator;
PriorityQueue<pathObject> queue;
public DijkstraPriorityQueueImpl( final Comparator<CostType> costComparator )
{
super();
this.costComparator = costComparator;
queue = new PriorityQueue<pathObject>( 11, new Comparator<pathObject>()
{
public int compare( pathObject o1, pathObject o2 )
{
return costComparator.compare( o1.getCost(), o2.getCost() );
}
} );
}
public void insertValue( Node node, CostType value )
{
queue.add( new pathObject( node, value ) );
}
public void decreaseValue( Node node, CostType newValue )
{
pathObject po = new pathObject( node, newValue );
// Shake the queue
// remove() will remove the old pathObject
// BUT IT TAKES A LOT OF TIME FOR SOME REASON
// queue.remove( po );
queue.add( po );
}
/**
* Retrieve and remove
*/
public Node extractMin()
{
pathObject po = queue.poll();
if ( po == null )
{
return null;
}
return po.getNode();
}
/**
* Retrieve without removing
*/
public Node peek()
{
pathObject po = queue.peek();
if ( po == null )
{
return null;
}
return po.getNode();
}
public boolean isEmpty()
{
return queue.isEmpty();
}
}
| false
|
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_shortestpath_DijkstraPriorityQueueImpl.java
|
3,587
|
protected class HeapObject
{
private Node node;
private CostType cost;
public HeapObject( Node node, CostType cost )
{
this.node = node;
this.cost = cost;
}
public CostType getCost()
{
return cost;
}
public Node getNode()
{
return node;
}
/*
* Equals is only defined from the stored node, so we can use it to find
* entries in the queue
*/
@Override
public boolean equals( Object obj )
{
if ( this == obj ) return true;
if ( obj == null ) return false;
if ( getClass() != obj.getClass() ) return false;
final HeapObject other = (HeapObject) obj;
if ( node == null )
{
if ( other.node != null ) return false;
}
else if ( !node.equals( other.node ) ) return false;
return true;
}
@Override
public int hashCode()
{
return node == null ? 23 : 14 ^ node.hashCode();
}
}
| false
|
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_shortestpath_DijkstraPriorityQueueFibonacciImpl.java
|
3,588
|
public class FibonacciHeap<KeyType>
{
/**
* One entry in the fibonacci heap is stored as an instance of this class.
* References to such entries are required for some operations, like
* decreaseKey().
*/
public class FibonacciHeapNode
{
FibonacciHeapNode left, right, parent, child;
boolean marked = false;
KeyType key;
int degree = 0;
public FibonacciHeapNode( KeyType key )
{
super();
this.key = key;
left = this;
right = this;
}
/**
* @return the key
*/
public KeyType getKey()
{
return key;
}
}
Comparator<KeyType> keyComparator;
FibonacciHeapNode minimum;
int nrNodes = 0;
public FibonacciHeap( Comparator<KeyType> keyComparator )
{
super();
this.keyComparator = keyComparator;
}
/**
* @return True if the heap is empty.
*/
public boolean isEmpty()
{
return minimum == null;
}
/**
* @return The number of entries in this heap.
*/
public int size()
{
return nrNodes;
}
/**
* @return The entry with the highest priority or null if the heap is empty.
*/
public FibonacciHeapNode getMinimum()
{
return minimum;
}
/**
* Internal helper function for moving nodes into the root list
*/
protected void insertInRootList( FibonacciHeapNode fNode )
{
fNode.parent = null;
fNode.marked = false;
if ( minimum == null )
{
minimum = fNode;
minimum.right = minimum;
minimum.left = minimum;
}
else
{
// insert in root list
fNode.left = minimum.left;
fNode.right = minimum;
fNode.left.right = fNode;
fNode.right.left = fNode;
if ( keyComparator.compare( fNode.key, minimum.key ) < 0 )
{
minimum = fNode;
}
}
}
/**
* Inserts a new value into the heap.
* @param key
* the value to be inserted.
* @return The entry made into the heap.
*/
public FibonacciHeapNode insert( KeyType key )
{
FibonacciHeapNode node = new FibonacciHeapNode( key );
insertInRootList( node );
++nrNodes;
return node;
}
/**
* Creates the union of two heaps by absorbing the other into this one.
* Note: Destroys other
*/
public void union( FibonacciHeap<KeyType> other )
{
nrNodes += other.nrNodes;
if ( other.minimum == null )
{
return;
}
if ( minimum == null )
{
minimum = other.minimum;
return;
}
// swap left nodes
FibonacciHeapNode otherLeft = other.minimum.left;
other.minimum.left = minimum.left;
minimum.left = otherLeft;
// update their right pointers
minimum.left.right = minimum;
other.minimum.left.right = other.minimum;
// get min
if ( keyComparator.compare( other.minimum.key, minimum.key ) < 0 )
{
minimum = other.minimum;
}
}
/**
* This removes and returns the entry with the highest priority.
* @return The value with the highest priority.
*/
public KeyType extractMin()
{
if ( minimum == null )
{
return null;
}
FibonacciHeapNode minNode = minimum;
// move all children to root list
if ( minNode.child != null )
{
FibonacciHeapNode child = minNode.child;
while ( minNode.equals( child.parent ) )
{
FibonacciHeapNode nextChild = child.right;
insertInRootList( child );
child = nextChild;
}
}
// remove minNode from root list
minNode.left.right = minNode.right;
minNode.right.left = minNode.left;
// update minimum
if ( minNode.right.equals( minNode ) )
{
minimum = null;
}
else
{
minimum = minimum.right;
consolidate();
}
--nrNodes;
return minNode.key;
}
/**
* Internal helper function.
*/
protected void consolidate()
{
// TODO: lower the size of this (log(n))
int arraySize = nrNodes + 1;
// arraySize = 2;
// for ( int a = nrNodes + 1; a < 0; a /= 2 )
// {
// arraySize++;
// }
// arraySize = (int) Math.log( (double) nrNodes )+1;
// FibonacciHeapNode[] A = (FibonacciHeapNode[]) new Object[arraySize];
// FibonacciHeapNode[] A = new FibonacciHeapNode[arraySize];
ArrayList<FibonacciHeapNode> A = new ArrayList<FibonacciHeapNode>(
arraySize );
for ( int i = 0; i < arraySize; ++i )
{
A.add( null );
}
List<FibonacciHeapNode> rootNodes = new LinkedList<FibonacciHeapNode>();
rootNodes.add( minimum );
for ( FibonacciHeapNode n = minimum.right; !n.equals( minimum ); n = n.right )
{
rootNodes.add( n );
}
for ( FibonacciHeapNode node : rootNodes )
{
// no longer a root node?
if ( node.parent != null )
{
continue;
}
int d = node.degree;
while ( A.get( d ) != null )
{
FibonacciHeapNode y = A.get( d );
// swap?
if ( keyComparator.compare( node.key, y.key ) > 0 )
{
FibonacciHeapNode tmp = node;
node = y;
y = tmp;
}
link( y, node );
A.set( d, null );
++d;
}
A.set( d, node );
}
// throw away the root list
minimum = null;
// and rebuild it from A
for ( FibonacciHeapNode node : A )
{
if ( node != null )
{
insertInRootList( node );
}
}
}
/**
* Internal helper function. Makes root node y a child of root node x.
*/
protected void link( FibonacciHeapNode y, FibonacciHeapNode x )
{
// remove y from root list
y.left.right = y.right;
y.right.left = y.left;
// make y a child of x
if ( x.child == null ) // no previous children?
{
y.right = y;
y.left = y;
}
else
{
y.left = x.child.left;
y.right = x.child;
y.right.left = y;
y.left.right = y;
}
x.child = y;
y.parent = x;
// adjust degree and mark
x.degree++;
y.marked = false;
}
/**
* Raises the priority for an entry.
* @param node
* The entry to recieve a higher priority.
* @param newKey
* The new value.
*/
public void decreaseKey( FibonacciHeapNode node, KeyType newKey )
{
if ( keyComparator.compare( newKey, node.key ) > 0 )
{
throw new RuntimeException( "Trying to decrease to a greater key" );
}
node.key = newKey;
FibonacciHeapNode parent = node.parent;
if ( parent != null
&& keyComparator.compare( node.key, parent.key ) < 0 )
{
cut( node, parent );
cascadingCut( parent );
}
if ( keyComparator.compare( node.key, minimum.key ) < 0 )
{
minimum = node;
}
}
/**
* Internal helper function. This removes y's child x and moves x to the
* root list.
*/
protected void cut( FibonacciHeapNode x, FibonacciHeapNode y )
{
// remove x from child list of y
x.left.right = x.right;
x.right.left = x.left;
if ( x.right.equals( x ) )
{
y.child = null;
}
else
{
y.child = x.right;
}
y.degree--;
// add x to root list
insertInRootList( x );
}
/**
* Internal helper function.
*/
protected void cascadingCut( FibonacciHeapNode y )
{
FibonacciHeapNode parent = y.parent;
if ( parent != null )
{
if ( !parent.marked )
{
parent.marked = true;
}
else
{
cut( y, parent );
cascadingCut( parent );
}
}
}
}
| false
|
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_util_FibonacciHeap.java
|
3,589
|
public class GeoEstimateEvaluator implements EstimateEvaluator<Double>
{
private static final double EARTH_RADIUS = 6371*1000; // Meters
private Node cachedGoal;
private double[] cachedGoalCoordinates;
private final String latitudePropertyKey;
private final String longitudePropertyKey;
public GeoEstimateEvaluator( String latitudePropertyKey, String longitudePropertyKey )
{
this.latitudePropertyKey = latitudePropertyKey;
this.longitudePropertyKey = longitudePropertyKey;
}
public Double getCost( Node node, Node goal )
{
double[] nodeCoordinates = getCoordinates( node );
if ( cachedGoal == null || !cachedGoal.equals( goal ) )
{
cachedGoalCoordinates = getCoordinates( goal );
cachedGoal = goal;
}
return distance( nodeCoordinates[0], nodeCoordinates[1],
cachedGoalCoordinates[0], cachedGoalCoordinates[1] );
}
private double[] getCoordinates( Node node )
{
return new double[] {
((Number) node.getProperty( latitudePropertyKey )).doubleValue(),
((Number) node.getProperty( longitudePropertyKey )).doubleValue()
};
}
private double distance( double latitude1, double longitude1,
double latitude2, double longitude2 )
{
latitude1 = Math.toRadians( latitude1 );
longitude1 = Math.toRadians( longitude1 );
latitude2 = Math.toRadians( latitude2 );
longitude2 = Math.toRadians( longitude2 );
double cLa1 = Math.cos( latitude1 );
double x_A = EARTH_RADIUS * cLa1 * Math.cos( longitude1 );
double y_A = EARTH_RADIUS * cLa1 * Math.sin( longitude1 );
double z_A = EARTH_RADIUS * Math.sin( latitude1 );
double cLa2 = Math.cos( latitude2 );
double x_B = EARTH_RADIUS * cLa2 * Math.cos( longitude2 );
double y_B = EARTH_RADIUS * cLa2 * Math.sin( longitude2 );
double z_B = EARTH_RADIUS * Math.sin( latitude2 );
return Math.sqrt( ( x_A - x_B ) * ( x_A - x_B ) + ( y_A - y_B )
* ( y_A - y_B ) + ( z_A - z_B ) * ( z_A - z_B ) );
}
}
| false
|
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_util_GeoEstimateEvaluator.java
|
3,590
|
{
@Override
public int compare( Node<E, P> o1, Node<E, P> o2 )
{
return order.compare( o1.priority, o2.priority );
}
} );
| false
|
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_util_PriorityMap.java
|
3,591
|
public class IntegerAdder implements CostAccumulator<Integer>
{
public Integer addCosts(Integer c1, Integer c2) {
return c1 + c2;
}
}
| false
|
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_util_IntegerAdder.java
|
3,592
|
{
@Override
public Object convert( Object source )
{
return source;
}
};
| false
|
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_util_PriorityMap.java
|
3,593
|
public class PriorityMap<E, K, P>
{
public interface Converter<T, S>
{
T convert( S source );
}
public static final class Entry<E, P>
{
private final E entity;
private final P priority;
private Entry( E entity, P priority )
{
this.entity = entity;
this.priority = priority;
}
Entry( Node<E, P> node )
{
this( node.head.entity, node.priority );
}
public E getEntity()
{
return entity;
}
public P getPriority()
{
return priority;
}
}
@SuppressWarnings( "unchecked" )
private static final Converter SELF_KEY = new Converter()
{
@Override
public Object convert( Object source )
{
return source;
}
};
@SuppressWarnings( "unchecked" )
public static <K, P> PriorityMap<K, K, P> withSelfKey(
Comparator<P> priority )
{
return new PriorityMap<K, K, P>( SELF_KEY, priority );
}
private static class NaturalPriority<P extends Comparable<P>> implements
Comparator<P>
{
private final boolean reversed;
NaturalPriority( boolean reversed )
{
this.reversed = reversed;
}
@Override
public int compare( P o1, P o2 )
{
if ( reversed )
{
return o2.compareTo( o1 );
}
else
{
return o1.compareTo( o2 );
}
}
}
public static <E, K, P extends Comparable<P>> PriorityMap<E, K, P> withNaturalOrder(
Converter<K, E> key )
{
return PriorityMap.<E, K, P>withNaturalOrder( key, false );
}
public static <E, K, P extends Comparable<P>> PriorityMap<E, K, P> withNaturalOrder(
Converter<K, E> key, boolean reversed )
{
Comparator<P> priority = new NaturalPriority<P>( reversed );
return new PriorityMap<E, K, P>( key, priority );
}
public static <K, P extends Comparable<P>> PriorityMap<K, K, P> withSelfKeyNaturalOrder()
{
return PriorityMap.<K, P>withSelfKeyNaturalOrder( false );
}
@SuppressWarnings( "unchecked" )
public static <K, P extends Comparable<P>> PriorityMap<K, K, P> withSelfKeyNaturalOrder(
boolean reversed )
{
Comparator<P> priority = new NaturalPriority<P>( reversed );
return new PriorityMap<K, K, P>( SELF_KEY, priority );
}
private final Converter<K, E> keyFunction;
private final Comparator<P> order;
private PriorityMap( Converter<K, E> key, Comparator<P> priority )
{
this.keyFunction = key;
this.order = priority;
}
/**
* Add an entity to the priority map. If the key for the {@code entity}
* was already found in the priority map and the priority is the same
* the entity will be added. If the priority is lower the existing entities
* for that key will be discarded.
*
* @param entity the entity to add.
* @param priority the priority of the entity.
* @return whether or not the entity (with its priority) was added to the
* priority map. Will return {@code false} iff the key for the entity
* already exist and its priority is better than the given
* {@code priority}.
*/
public boolean put( E entity, P priority )
{
K key = keyFunction.convert( entity );
Node<E, P> node = map.get( key );
boolean result = false;
if ( node != null )
{
if ( priority.equals( node.priority ) )
{
node.head = new Link<E>( entity, node.head );
result = true;
}
else if ( order.compare( priority, node.priority ) < 0 )
{
queue.remove( node );
put( entity, priority, key );
result = true;
}
}
else
{
put( entity, priority, key );
result = true;
}
return result;
}
private void put( E entity, P priority, K key )
{
Node<E, P> node = new Node<E, P>( entity, priority );
map.put( key, node );
queue.add( node );
}
/**
* Get the priority for the entity with the specified key.
*
* @param key the key.
* @return the priority for the the entity with the specified key.
*/
public P get( K key )
{
Node<E, P> node = map.get( key );
if ( node == null )
{
return null;
}
return node.priority;
}
/**
* Remove and return the entry with the highest priority.
*
* @return the entry with the highest priority.
*/
public Entry<E, P> pop()
{
Node<E, P> node = queue.peek();
Entry<E, P> result = null;
if ( node == null )
{
return null;
}
else if ( node.head.next == null )
{
node = queue.poll();
map.remove( keyFunction.convert( node.head.entity ) );
result = new Entry<E, P>( node );
}
else
{
result = new Entry<E, P>( node );
node.head = node.head.next;
}
return result;
}
public Entry<E, P> peek()
{
Node<E, P> node = queue.peek();
if ( node == null )
{
return null;
}
return new Entry<E, P>( node );
}
// Naive implementation
private final Map<K, Node<E, P>> map = new HashMap<K, Node<E, P>>();
private final PriorityQueue<Node<E, P>> queue = new PriorityQueue<Node<E, P>>(
11, new Comparator<Node<E, P>>()
{
@Override
public int compare( Node<E, P> o1, Node<E, P> o2 )
{
return order.compare( o1.priority, o2.priority );
}
} );
private static class Node<E, P>
{
Link<E> head;
final P priority;
Node( E entity, P priority )
{
this.head = new Link<E>( entity, null );
this.priority = priority;
}
}
private static class Link<E>
{
final E entity;
final Link<E> next;
Link( E entity, Link<E> next )
{
this.entity = entity;
this.next = next;
}
}
}
| false
|
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_util_PriorityMap.java
|
3,594
|
class MockRelationship extends MockPropertyContainer implements Relationship
{
private final long fromNode;
private final long toNode;
public MockRelationship( long fromNode, long toNode )
{
this.fromNode = fromNode;
this.toNode = toNode;
}
@Override
public long getId()
{
return fromNode ^ toNode;
}
@Override
public boolean equals( Object other )
{
return other instanceof Relationship && ((Relationship) other).getId() == getId();
}
@Override
public Node getOtherNode( Node node )
{
return node.getId() == fromNode ? new MockNode( toNode ) : new MockNode( fromNode );
}
@Override
public Node getStartNode()
{
return new MockNode( fromNode );
}
@Override
public RelationshipType getType()
{
return DynamicRelationshipType.withName( "Banana" );
}
@Override
public void delete()
{
}
@Override
public Node getEndNode()
{
return null;
}
@Override
public Node[] getNodes()
{
return new Node[0];
}
@Override
public boolean isType( RelationshipType type )
{
return false;
}
}
| false
|
community_graph-algo_src_test_java_org_neo4j_graphalgo_impl_util_PathImplTest.java
|
3,595
|
class MockPropertyContainer implements PropertyContainer
{
@Override
public GraphDatabaseService getGraphDatabase()
{
return null;
}
@Override
public boolean hasProperty( String key )
{
return false;
}
@Override
public Object getProperty( String key )
{
return null;
}
@Override
public Object getProperty( String key, Object defaultValue )
{
return null;
}
@Override
public void setProperty( String key, Object value )
{
}
@Override
public Object removeProperty( String key )
{
return null;
}
@Override
public Iterable<String> getPropertyKeys()
{
return null;
}
}
| false
|
community_graph-algo_src_test_java_org_neo4j_graphalgo_impl_util_PathImplTest.java
|
3,596
|
@SuppressWarnings("deprecation")
class MockNode extends MockPropertyContainer implements Node
{
private final long id;
public MockNode( long id )
{
this.id = id;
}
@Override
public long getId()
{
return id;
}
@Override
public boolean equals( Object other )
{
return other instanceof Node && ((Node) other).getId() == id;
}
// Unimplemented
@Override
public void delete()
{
}
@Override
public Iterable<Relationship> getRelationships()
{
return null;
}
@Override
public boolean hasRelationship()
{
return false;
}
@Override
public Iterable<Relationship> getRelationships( RelationshipType... types )
{
return null;
}
@Override
public Iterable<Relationship> getRelationships( Direction direction, RelationshipType... types )
{
return null;
}
@Override
public boolean hasRelationship( RelationshipType... types )
{
return false;
}
@Override
public boolean hasRelationship( Direction direction, RelationshipType... types )
{
return false;
}
@Override
public Iterable<Relationship> getRelationships( Direction dir )
{
return null;
}
@Override
public boolean hasRelationship( Direction dir )
{
return false;
}
@Override
public Iterable<Relationship> getRelationships( RelationshipType type, Direction dir )
{
return null;
}
@Override
public boolean hasRelationship( RelationshipType type, Direction dir )
{
return false;
}
@Override
public Relationship getSingleRelationship( RelationshipType type, Direction dir )
{
return null;
}
@Override
public Relationship createRelationshipTo( Node otherNode, RelationshipType type )
{
return null;
}
@Override
public Traverser traverse( Traverser.Order traversalOrder, StopEvaluator stopEvaluator, ReturnableEvaluator returnableEvaluator, RelationshipType relationshipType, Direction direction )
{
return null;
}
@Override
public Traverser traverse( Traverser.Order traversalOrder, StopEvaluator stopEvaluator, ReturnableEvaluator returnableEvaluator, RelationshipType firstRelationshipType, Direction firstDirection, RelationshipType secondRelationshipType, Direction secondDirection )
{
return null;
}
@Override
public Traverser traverse( Traverser.Order traversalOrder, StopEvaluator stopEvaluator, ReturnableEvaluator returnableEvaluator, Object... relationshipTypesAndDirections )
{
return null;
}
@Override
public void addLabel( Label label )
{
}
@Override
public void removeLabel( Label label )
{
}
@Override
public boolean hasLabel( Label label )
{
return false;
}
@Override
public ResourceIterable<Label> getLabels()
{
return null;
}
}
| false
|
community_graph-algo_src_test_java_org_neo4j_graphalgo_impl_util_PathImplTest.java
|
3,597
|
public class PathImplTest
{
@Test
public void pathsWithTheSameContentsShouldBeEqual() throws Exception
{
// Given
Path firstPath = new PathImpl.Builder( node( 1337l ) ).push( rel( 1337l, 7331l ) ).build();
Path secondPath = new PathImpl.Builder( node( 1337l ) ).push( rel( 1337l, 7331l ) ).build();
// When Then
assertEquals( firstPath, secondPath );
assertEquals( secondPath, firstPath );
}
@Test
public void pathsWithDifferentLengthAreNotEqual() throws Exception
{
// Given
Path firstPath = new PathImpl.Builder( node( 1337l ) ).push( rel( 1337l, 7331l ) ).build();
Path secondPath = new PathImpl.Builder( node( 1337l ) ).push( rel( 1337l, 7331l ) ).push( rel( 7331l, 13l ) ).build();
// When Then
assertThat( firstPath, not( equalTo( secondPath ) ) );
assertThat( secondPath, not( equalTo( firstPath ) ) );
}
private Node node( final long id )
{
return new MockNode( id );
}
private Relationship rel( final long fromId, final long toId )
{
return new MockRelationship( fromId, toId );
}
class MockPropertyContainer implements PropertyContainer
{
@Override
public GraphDatabaseService getGraphDatabase()
{
return null;
}
@Override
public boolean hasProperty( String key )
{
return false;
}
@Override
public Object getProperty( String key )
{
return null;
}
@Override
public Object getProperty( String key, Object defaultValue )
{
return null;
}
@Override
public void setProperty( String key, Object value )
{
}
@Override
public Object removeProperty( String key )
{
return null;
}
@Override
public Iterable<String> getPropertyKeys()
{
return null;
}
}
@SuppressWarnings("deprecation")
class MockNode extends MockPropertyContainer implements Node
{
private final long id;
public MockNode( long id )
{
this.id = id;
}
@Override
public long getId()
{
return id;
}
@Override
public boolean equals( Object other )
{
return other instanceof Node && ((Node) other).getId() == id;
}
// Unimplemented
@Override
public void delete()
{
}
@Override
public Iterable<Relationship> getRelationships()
{
return null;
}
@Override
public boolean hasRelationship()
{
return false;
}
@Override
public Iterable<Relationship> getRelationships( RelationshipType... types )
{
return null;
}
@Override
public Iterable<Relationship> getRelationships( Direction direction, RelationshipType... types )
{
return null;
}
@Override
public boolean hasRelationship( RelationshipType... types )
{
return false;
}
@Override
public boolean hasRelationship( Direction direction, RelationshipType... types )
{
return false;
}
@Override
public Iterable<Relationship> getRelationships( Direction dir )
{
return null;
}
@Override
public boolean hasRelationship( Direction dir )
{
return false;
}
@Override
public Iterable<Relationship> getRelationships( RelationshipType type, Direction dir )
{
return null;
}
@Override
public boolean hasRelationship( RelationshipType type, Direction dir )
{
return false;
}
@Override
public Relationship getSingleRelationship( RelationshipType type, Direction dir )
{
return null;
}
@Override
public Relationship createRelationshipTo( Node otherNode, RelationshipType type )
{
return null;
}
@Override
public Traverser traverse( Traverser.Order traversalOrder, StopEvaluator stopEvaluator, ReturnableEvaluator returnableEvaluator, RelationshipType relationshipType, Direction direction )
{
return null;
}
@Override
public Traverser traverse( Traverser.Order traversalOrder, StopEvaluator stopEvaluator, ReturnableEvaluator returnableEvaluator, RelationshipType firstRelationshipType, Direction firstDirection, RelationshipType secondRelationshipType, Direction secondDirection )
{
return null;
}
@Override
public Traverser traverse( Traverser.Order traversalOrder, StopEvaluator stopEvaluator, ReturnableEvaluator returnableEvaluator, Object... relationshipTypesAndDirections )
{
return null;
}
@Override
public void addLabel( Label label )
{
}
@Override
public void removeLabel( Label label )
{
}
@Override
public boolean hasLabel( Label label )
{
return false;
}
@Override
public ResourceIterable<Label> getLabels()
{
return null;
}
}
class MockRelationship extends MockPropertyContainer implements Relationship
{
private final long fromNode;
private final long toNode;
public MockRelationship( long fromNode, long toNode )
{
this.fromNode = fromNode;
this.toNode = toNode;
}
@Override
public long getId()
{
return fromNode ^ toNode;
}
@Override
public boolean equals( Object other )
{
return other instanceof Relationship && ((Relationship) other).getId() == getId();
}
@Override
public Node getOtherNode( Node node )
{
return node.getId() == fromNode ? new MockNode( toNode ) : new MockNode( fromNode );
}
@Override
public Node getStartNode()
{
return new MockNode( fromNode );
}
@Override
public RelationshipType getType()
{
return DynamicRelationshipType.withName( "Banana" );
}
@Override
public void delete()
{
}
@Override
public Node getEndNode()
{
return null;
}
@Override
public Node[] getNodes()
{
return new Node[0];
}
@Override
public boolean isType( RelationshipType type )
{
return false;
}
}
}
| false
|
community_graph-algo_src_test_java_org_neo4j_graphalgo_impl_util_PathImplTest.java
|
3,598
|
public static final class Builder
{
private final Builder previous;
private final Node start;
private final Relationship relationship;
private final int size;
public Builder( Node start )
{
if ( start == null )
{
throw new NullPointerException();
}
this.start = start;
this.previous = null;
this.relationship = null;
this.size = 0;
}
private Builder( Builder prev, Relationship rel )
{
this.start = prev.start;
this.previous = prev;
this.relationship = rel;
this.size = prev.size + 1;
}
public Node getStartNode()
{
return start;
}
public Path build()
{
return new PathImpl( this, null );
}
public Builder push( Relationship relationship )
{
if ( relationship == null )
{
throw new NullPointerException();
}
return new Builder( this, relationship );
}
public Path build( Builder other )
{
return new PathImpl( this, other );
}
@Override
public String toString()
{
if ( previous == null )
{
return start.toString();
}
else
{
return relToString( relationship ) + ":" + previous.toString();
}
}
}
| false
|
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_util_PathImpl.java
|
3,599
|
{
Iterator<? extends PropertyContainer> current = nodes().iterator();
Iterator<? extends PropertyContainer> next = relationships().iterator();
public boolean hasNext()
{
return current.hasNext();
}
public PropertyContainer next()
{
try
{
return current.next();
}
finally
{
Iterator<? extends PropertyContainer> temp = current;
current = next;
next = temp;
}
}
public void remove()
{
next.remove();
}
};
| false
|
community_graph-algo_src_main_java_org_neo4j_graphalgo_impl_util_PathImpl.java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.