Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(api): support adamic-adar & resource-allocation algorithms #1763

Merged
merged 3 commits into from
Mar 18, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@

public class API {

private static final Logger LOG = Log.logger(RestServer.class);
protected static final Logger LOG = Log.logger(RestServer.class);

public static final String CHARSET = "UTF-8";

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/*
* Copyright 2022 HugeGraph Authors
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with this
* work for additional information regarding copyright ownership. The ASF
* licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/

package com.baidu.hugegraph.api.traversers;

import static com.baidu.hugegraph.traversal.algorithm.HugeTraverser.DEFAULT_ELEMENTS_LIMIT;
import static com.baidu.hugegraph.traversal.algorithm.HugeTraverser.DEFAULT_MAX_DEGREE;

import javax.inject.Singleton;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;

import com.baidu.hugegraph.HugeGraph;
import com.baidu.hugegraph.api.API;
import com.baidu.hugegraph.api.graph.EdgeAPI;
import com.baidu.hugegraph.api.graph.VertexAPI;
import com.baidu.hugegraph.backend.id.Id;
import com.baidu.hugegraph.core.GraphManager;
import com.baidu.hugegraph.traversal.algorithm.PredictionTraverser;
import com.baidu.hugegraph.type.define.Directions;
import com.baidu.hugegraph.util.E;
import com.baidu.hugegraph.util.JsonUtil;
import com.codahale.metrics.annotation.Timed;
import com.google.common.collect.ImmutableMap;

/**
* This API include similar prediction algorithms, now include:
* - Adamic Adar
* - Resource Allocation
imbajin marked this conversation as resolved.
Show resolved Hide resolved
*
* Could add more prediction algorithms in future
*/
@Path("graphs/{graph}/traversers/adamicadar")
@Singleton
public class AdamicAdarAPI extends API {

@GET
@Timed
@Produces(APPLICATION_JSON_WITH_CHARSET)
public String get(@Context GraphManager manager,
@PathParam("graph") String graph,
@QueryParam("vertex") String current,
@QueryParam("other") String other,
@QueryParam("direction") String direction,
@QueryParam("label") String edgeLabel,
@QueryParam("max_degree")
@DefaultValue(DEFAULT_MAX_DEGREE) long maxDegree,
@QueryParam("limit")
@DefaultValue(DEFAULT_ELEMENTS_LIMIT) long limit) {
LOG.debug("Graph [{}] get adamic adar between '{}' and '{}' with " +
"direction {}, edge label {}, max degree '{}' and limit '{}'",
graph, current, other, direction, edgeLabel, maxDegree,
limit);

Id sourceId = VertexAPI.checkAndParseVertexId(current);
Id targetId = VertexAPI.checkAndParseVertexId(other);
E.checkArgument(!current.equals(other),
"The source and target vertex id can't be same");
Directions dir = Directions.convert(EdgeAPI.parseDirection(direction));

HugeGraph g = graph(manager, graph);
PredictionTraverser traverser = new PredictionTraverser(g);
double score = traverser.adamicAdar(sourceId, targetId, dir,
edgeLabel, maxDegree, limit);
return JsonUtil.toJson(ImmutableMap.of("adamic_adar", score));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/*
* Copyright 2022 HugeGraph Authors
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with this
* work for additional information regarding copyright ownership. The ASF
* licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/

package com.baidu.hugegraph.api.traversers;

import static com.baidu.hugegraph.traversal.algorithm.HugeTraverser.DEFAULT_ELEMENTS_LIMIT;
import static com.baidu.hugegraph.traversal.algorithm.HugeTraverser.DEFAULT_MAX_DEGREE;

import javax.inject.Singleton;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;

import com.baidu.hugegraph.HugeGraph;
import com.baidu.hugegraph.api.API;
import com.baidu.hugegraph.api.graph.EdgeAPI;
import com.baidu.hugegraph.api.graph.VertexAPI;
import com.baidu.hugegraph.backend.id.Id;
import com.baidu.hugegraph.core.GraphManager;
import com.baidu.hugegraph.traversal.algorithm.PredictionTraverser;
import com.baidu.hugegraph.type.define.Directions;
import com.baidu.hugegraph.util.E;
import com.baidu.hugegraph.util.JsonUtil;
import com.codahale.metrics.annotation.Timed;
import com.google.common.collect.ImmutableMap;

/**
* This API include similar prediction algorithms, now include:
* - Adamic Adar
imbajin marked this conversation as resolved.
Show resolved Hide resolved
* - Resource Allocation
*
* Could add more prediction algorithms in future
*/
@Path("graphs/{graph}/traversers/resourceallocation")
@Singleton
public class ResourceAllocationAPI extends API {

@GET
@Timed
@Produces(APPLICATION_JSON_WITH_CHARSET)
public String create(@Context GraphManager manager,
@PathParam("graph") String graph,
@QueryParam("vertex") String current,
@QueryParam("other") String other,
@QueryParam("direction") String direction,
@QueryParam("label") String edgeLabel,
@QueryParam("max_degree")
@DefaultValue(DEFAULT_MAX_DEGREE) long maxDegree,
@QueryParam("limit")
@DefaultValue(DEFAULT_ELEMENTS_LIMIT) long limit) {
LOG.debug("Graph [{}] get resource allocation between '{}' and '{}' " +
"with direction {}, edge label {}, max degree '{}' and " +
"limit '{}'", graph, current, other, direction, edgeLabel,
maxDegree, limit);

Id sourceId = VertexAPI.checkAndParseVertexId(current);
Id targetId = VertexAPI.checkAndParseVertexId(other);
E.checkArgument(!current.equals(other),
"The source and target vertex id can't be same");
Directions dir = Directions.convert(EdgeAPI.parseDirection(direction));

HugeGraph g = graph(manager, graph);
PredictionTraverser traverser = new PredictionTraverser(g);
double score = traverser.resourceAllocation(sourceId, targetId, dir,
edgeLabel, maxDegree,
limit);
return JsonUtil.toJson(ImmutableMap.of("resource_allocation", score));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -117,12 +117,13 @@ public final class ApiVersion {
* [0.65] Issue-1506: Support olap property key
* [0.66] Issue-1567: Support get schema RESTful API
* [0.67] Issue-1065: Support dynamically add/remove graph
* [0.68] Issue-1763: Support adamic-adar & resource-allocation API
*/

// The second parameter of Version.of() is for IDE running without JAR
public static final Version VERSION = Version.of(ApiVersion.class, "0.67");
public static final Version VERSION = Version.of(ApiVersion.class, "0.68");

public static final void check() {
public static void check() {
// Check version of hugegraph-core. Firstly do check from version 0.3
VersionUtil.check(CoreVersion.VERSION, "0.12", "0.13", CoreVersion.NAME);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/*
* Copyright 2017 HugeGraph Authors
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with this
* work for additional information regarding copyright ownership. The ASF
* licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/

package com.baidu.hugegraph.traversal.algorithm;

import java.util.Set;

import com.baidu.hugegraph.HugeGraph;
import com.baidu.hugegraph.backend.id.Id;
import com.baidu.hugegraph.traversal.algorithm.steps.EdgeStep;
import com.baidu.hugegraph.type.define.Directions;
import com.baidu.hugegraph.util.E;
import com.google.common.collect.ImmutableList;

public class PredictionTraverser extends OltpTraverser {

public PredictionTraverser(HugeGraph graph) {
super(graph);
}

public double adamicAdar(Id source, Id target, Directions dir,
String label, long degree, long limit) {
Set<Id> neighbors = checkAndGetCommonNeighbors(source, target, dir,
label, degree, limit);
EdgeStep step = label == null ? new EdgeStep(graph(), dir) :
new EdgeStep(graph(), dir, ImmutableList.of(label));

double sum = 0.0;
for (Id vid : neighbors) {
sum += 1.0 / Math.log(this.edgesCount(vid, step));
}
return sum;
}

public double resourceAllocation(Id source, Id target, Directions dir,
String label, long degree, long limit) {
Set<Id> neighbors = checkAndGetCommonNeighbors(source, target, dir,
label, degree, limit);
EdgeStep step = label == null ? new EdgeStep(graph(), dir) :
new EdgeStep(graph(), dir, ImmutableList.of(label));

double sum = 0.0;
for (Id vid : neighbors) {
sum += 1.0 / this.edgesCount(vid, step);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

may this.edgesCount() return 0

Copy link
Member Author

@imbajin imbajin Feb 22, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why common neighbor vertex's degree could be zero? seems at least is 2?

}
return sum;
}

private Set<Id> checkAndGetCommonNeighbors(Id source, Id target,
Directions dir, String label,
long degree, long limit) {
E.checkNotNull(source, "source id");
E.checkNotNull(target, "the target id");
this.checkVertexExist(source, "source");
this.checkVertexExist(target, "target");
E.checkNotNull(dir, "direction");
checkDegree(degree);
SameNeighborTraverser traverser = new SameNeighborTraverser(graph());
return traverser.sameNeighbors(source, target, dir, label, degree, limit);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/*
* Copyright 2022 HugeGraph Authors
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with this
* work for additional information regarding copyright ownership. The ASF
* licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/

package com.baidu.hugegraph.api.traversers;

import java.util.Map;

import javax.ws.rs.core.Response;

import org.junit.Before;
import org.junit.Test;

import com.baidu.hugegraph.api.BaseApiTest;
import com.google.common.collect.ImmutableMap;

public class AdamicAdarAPITest extends BaseApiTest {

private final static String PATH = TRAVERSERS_API + "/adamicadar";

@Before
public void prepareSchema() {
BaseApiTest.initPropertyKey();
BaseApiTest.initVertexLabel();
BaseApiTest.initEdgeLabel();
BaseApiTest.initVertex();
BaseApiTest.initEdge();
}

@Test
public void testGet() {
Map<String, String> name2Ids = listAllVertexName2Ids();

String markoId = name2Ids.get("marko");
String joshId = name2Ids.get("josh");
String peterId = name2Ids.get("peter");
Response r = client().get(PATH, ImmutableMap.of("vertex",
id2Json(markoId),
"other",
id2Json(joshId)));
String content = assertResponseStatus(200, r);
assertJsonContains(content, "adamic_adar");
}
}
Loading