Giraph测试用例之Parallel BFS

该用例源自:

 https://github.com/MarcoLotz/GiraphBFSSO/blob/master/src/uk/co/qmul/giraph/structurebfs/SimpleBFSStructureComputation.java

本人对其做了轻度修改和注释,想将消息修改为出发点ID的,但是发现作者原版能看出BFS的深度和解决环的问题就不改了。

关于结果正确性的问题,只要该点的值有值说明被遍历过就可以了。

package org.apache.giraph.examples;

import java.io.IOException;
import org.apache.giraph.conf.LongConfOption;
import org.apache.giraph.edge.Edge;
import org.apache.giraph.graph.BasicComputation;
import org.apache.giraph.graph.Vertex;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.log4j.Logger;

public class SimpleBFSStructureComputation extends
BasicComputation<IntWritable, IntWritable, NullWritable, IntWritable>  {
	/**
	 * 定义最大超步数
	 */
	public final int MAX_SUPERSTEPS = 9999;
	/**
	 * 单源遍历出发点
	 */
	public static final LongConfOption START_ID = new LongConfOption("SimpleBFSComputation.START_ID", 1,"the first vertex to be computed");

	/**BFS类日志 */
	private static final Logger LOG = Logger.getLogger(SimpleBFSStructureComputation.class);

	/**
	 * 判断是否为起始点
	 */
	private boolean isStart(Vertex<IntWritable, ?, ?> vertex) {
		return vertex.getId().get() == START_ID.get(getConf());
	}

	@Override
	public void compute(
			Vertex<IntWritable, IntWritable, NullWritable> vertex,
			Iterable<IntWritable> messages) throws IOException {
		if (!(getSuperstep() == MAX_SUPERSTEPS)) { //首轮超步仅起始点发送消息 
			if (getSuperstep() == 0) {
				if (isStart(vertex)) {
					vertex.setValue(new IntWritable(0));
					for (Edge<IntWritable, NullWritable> edge : vertex.getEdges()) {
						sendMessage(edge.getTargetVertexId(), new IntWritable(1));
			 		}
					if (LOG.isInfoEnabled()) {
						LOG.info("[Start Vertex] Vertex ID: " + vertex.getId());
					}
				} else {  //其它点不动
					vertex.setValue(new IntWritable(Integer.MAX_VALUE));
				}
			} else {
				if (vertex.getValue().get() == Integer.MAX_VALUE) { //如果当前点已经被遍历则转为halt以避免回环,否则遍历发送
					vertex.setValue(new IntWritable((int) getSuperstep()));
					for (Edge<IntWritable, NullWritable> edge : vertex.getEdges()) {
						sendMessage(edge.getTargetVertexId(), new IntWritable(1));
			 		} 
				}
  			}
			vertex.voteToHalt();
		}
	}
}

 

测试数据(起始点为1):

1. bfs_loop_sample_1.txt 有环

1       2       3
2       3       4
3       5
4       6
5       1       6
6       7
7       7

结果:

1       0
2       1
3       1
4       2
5       2
6       3
7       4

2.bfs_noloop_sample_2.txt
1       2       3
2       3       4
3       5
4       6
5       6
6       7
7       7

结果:

1       0
2       1
3       1
4       2
5       2
6       3
7       4

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值