Is there a way using the Java API to access an edge index in OrientDB to determine whether a edge with a given label exists in between two known vertices?
Afaik tinkergraph is not exposing any methods for this?
I believe that Neo4j is providing an API like this:
graphDatabaseService.index().forRelationships("HAS_USER").get(key, valueOrNull, startNodeOrNull, endNodeOrNull)
You can call getEdges() from your vertex. Example:
v1.getEdges(v2, Direction.BOTH, "HAS_USER");
This is the JavaDoc:
/**
* (Blueprints Extension) Returns all the edges from the current Vertex to another one.
*
* #param iDestination
* The target vertex
* #param iDirection
* The direction between OUT, IN or BOTH
* #param iLabels
* Optional labels as Strings to consider
* #return
*/
public Iterable<Edge> getEdges(final OrientVertex iDestination, final Direction iDirection, final String... iLabels)
Another way is to use OrientGraph.getEdges()
It is important to create an index first via:
cmd.setText("create index edge.HAS_ITEM on E (out,in) unique");
g.command(cmd).execute();
or via pure Java:
OrientEdgeType e = g.getEdgeType("E");
e.createProperty("in", OType.LINK);
e.createProperty("out", OType.LINK);
e.createIndex("edge.has_item", OClass.INDEX_TYPE.UNIQUE_HASH_INDEX, "out", "in");
After this the index can be queried using:
Iterable<Edge> edges = g.getEdges("edge.has_item", new OCompositeKey(root.getId(), randomDocument.getId()));
Small pittfall: It is important to lowercase the index type when referencing it in the getEdges method. Otherwise orientdb will not be able to retrieve it.
A complete example which shows four ways of finding a specific edge in between two vertices is listed below.
In the example 14k vertices (items) are created which are connected to a single root node.
Creating {14000} items.
[graph.getEdges] Duration: 38
[graph.getEdges] Duration per lookup: 0.0095
[root.getEdges] Duration: 59439
[root.getEdges] Duration per lookup: 14.85975
[root.getEdges - iterating] Duration: 56710
[root.getEdges - iterating] Duration per lookup: 14.1775
[query] Duration: 817
[query] Duration per lookup: 0.20425
Example:
package de.jotschi.orientdb;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import com.orientechnologies.orient.core.index.OCompositeKey;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.sql.OCommandSQL;
import com.tinkerpop.blueprints.Direction;
import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.impls.orient.OrientEdgeType;
import com.tinkerpop.blueprints.impls.orient.OrientGraphFactory;
import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx;
import com.tinkerpop.blueprints.impls.orient.OrientVertex;
import com.tinkerpop.blueprints.impls.orient.OrientVertexType;
public class EdgeIndexPerformanceTest {
private static OrientGraphFactory factory = new OrientGraphFactory("memory:tinkerpop");
private final static int nDocuments = 14000;
private final static int nChecks = 4000;
private static List<OrientVertex> items;
private static OrientVertex root;
#BeforeClass
public static void setupDatabase() {
setupTypesAndIndices(factory);
root = createRoot(factory);
items = createData(root, factory, nDocuments);
}
private static void setupTypesAndIndices(OrientGraphFactory factory2) {
OrientGraphNoTx g = factory.getNoTx();
try {
OCommandSQL cmd = new OCommandSQL();
cmd.setText("alter database custom useLightweightEdges=false");
g.command(cmd).execute();
cmd.setText("alter database custom useVertexFieldsForEdgeLabels=false");
g.command(cmd).execute();
OrientEdgeType e = g.getEdgeType("E");
e.createProperty("in", OType.LINK);
e.createProperty("out", OType.LINK);
OrientVertexType v = g.createVertexType("root", "V");
v.createProperty("name", OType.STRING);
v = g.createVertexType("item", "V");
v.createProperty("name", OType.STRING);
cmd.setText("create index edge.HAS_ITEM on E (out,in) unique");
g.command(cmd).execute();
} finally {
g.shutdown();
}
}
private static List<OrientVertex> createData(OrientVertex root, OrientGraphFactory factory, int count) {
OrientGraphNoTx g = factory.getNoTx();
try {
System.out.println("Creating {" + count + "} items.");
List<OrientVertex> items = new ArrayList<>();
for (int i = 0; i < count; i++) {
OrientVertex item = g.addVertex("class:item");
item.setProperty("name", "item_" + i);
items.add(item);
root.addEdge("HAS_ITEM", item, "class:E");
}
return items;
} finally {
g.shutdown();
}
}
private static OrientVertex createRoot(OrientGraphFactory factory) {
OrientGraphNoTx g = factory.getNoTx();
try {
OrientVertex root = g.addVertex("class:root");
root.setProperty("name", "root vertex");
return root;
} finally {
g.shutdown();
}
}
#Test
public void testEdgeIndexViaRootGetEdgesWithoutTarget() throws Exception {
OrientGraphNoTx g = factory.getNoTx();
try {
long start = System.currentTimeMillis();
for (int i = 0; i < nChecks; i++) {
OrientVertex randomDocument = items.get((int) (Math.random() * items.size()));
Iterable<Edge> edges = root.getEdges(Direction.OUT, "HAS_ITEM");
boolean found = false;
for (Edge edge : edges) {
if (edge.getVertex(Direction.IN).equals(randomDocument)) {
found = true;
break;
}
}
assertTrue(found);
}
long dur = System.currentTimeMillis() - start;
System.out.println("[root.getEdges - iterating] Duration: " + dur);
System.out.println("[root.getEdges - iterating] Duration per lookup: " + ((double) dur / (double) nChecks));
} finally {
g.shutdown();
}
}
#Test
public void testEdgeIndexViaRootGetEdges() throws Exception {
OrientGraphNoTx g = factory.getNoTx();
try {
long start = System.currentTimeMillis();
for (int i = 0; i < nChecks; i++) {
OrientVertex randomDocument = items.get((int) (Math.random() * items.size()));
Iterable<Edge> edges = root.getEdges(randomDocument, Direction.OUT, "HAS_ITEM");
assertTrue(edges.iterator().hasNext());
}
long dur = System.currentTimeMillis() - start;
System.out.println("[root.getEdges] Duration: " + dur);
System.out.println("[root.getEdges] Duration per lookup: " + ((double) dur / (double) nChecks));
} finally {
g.shutdown();
}
}
#Test
public void testEdgeIndexViaGraphGetEdges() throws Exception {
OrientGraphNoTx g = factory.getNoTx();
try {
long start = System.currentTimeMillis();
for (int i = 0; i < nChecks; i++) {
OrientVertex randomDocument = items.get((int) (Math.random() * items.size()));
Iterable<Edge> edges = g.getEdges("edge.has_item", new OCompositeKey(root.getId(), randomDocument.getId()));
assertTrue(edges.iterator().hasNext());
}
long dur = System.currentTimeMillis() - start;
System.out.println("[graph.getEdges] Duration: " + dur);
System.out.println("[graph.getEdges] Duration per lookup: " + ((double) dur / (double) nChecks));
} finally {
g.shutdown();
}
}
#Test
public void testEdgeIndexViaQuery() throws Exception {
OrientGraphNoTx g = factory.getNoTx();
try {
System.out.println("Checking edge");
long start = System.currentTimeMillis();
for (int i = 0; i < nChecks; i++) {
OrientVertex randomDocument = items.get((int) (Math.random() * items.size()));
OCommandSQL cmd = new OCommandSQL("select from index:edge.has_item where key=?");
OCompositeKey key = new OCompositeKey(root.getId(), randomDocument.getId());
assertTrue(((Iterable<Vertex>) g.command(cmd).execute(key)).iterator().hasNext());
}
long dur = System.currentTimeMillis() - start;
System.out.println("[query] Duration: " + dur);
System.out.println("[query] Duration per lookup: " + ((double) dur / (double) nChecks));
} finally {
g.shutdown();
}
}
}
Related
I inherited by my ex collegue a Unity game. Now I need to implement this behaviour. The game consist in a car drive by user using Logitech steering.
Now I need to show a Text every X minute in a part of the screen like "What level of anxiety do you have ? " Ad the user should to set a value from 0 to 9 using the Logitech steering but I really don't know where to start.
This is my manager class:
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
namespace DrivingTest
{
// Braking test Manager
public class BtManager : BaseTestManger
{
// Public variables
public BreakCar breakCar;
public float minBrakeThreshold = 0.2f;
internal int vehicalSpeed;
internal int noOfEvents;
internal float durationOfTest;
// Private variables
private IRDSPlayerControls playerControlCar;
protected int xSpeed;
protected int ySpeed;
private float brakeEventStartTime;
private float brakeEventDifferenceTime;
private SafetyDistanceCheck safetyDistanceCheck;
protected float totalSafetyDistance;
protected int totalSafetyDistanceCount;
private List<float> averageEventReactionTime = new List<float>();
#region Init
// Use this for initialization
public override void Start()
{
base.Start();
playerControlCar = car.GetComponent<IRDSPlayerControls>();
safetyDistanceCheck = car.GetComponent<SafetyDistanceCheck>();
}
public override void OnEnable()
{
base.OnEnable();
BreakCar.BrakeStart += BrakeCarEvent;
BreakCar.BrakeEventEnd += CallTestOver;
}
public override void OnDisable()
{
base.OnDisable();
BreakCar.BrakeStart -= BrakeCarEvent;
BreakCar.BrakeEventEnd -= CallTestOver;
}
protected override void SetUpCar()
{
car.AddComponent<SelfDriving>();
}
#endregion
/// <summary>
/// Calls the main Test over method.
/// </summary>
private void CallTestOver()
{
GameManager.Instance.Testover();
}
protected override void OnSceneLoaded(eTESTS test)
{
UiManager.Instance.UpdateInstructions(Constants.BT_INSTRUCTION);
}
protected override void GetApiParams()
{
NextTestOutput nextTestOutput = GameManager.Instance.currentTest;
if (nextTestOutput.content != null && nextTestOutput.content.Count > 0)
{
foreach (var item in nextTestOutput.content[0].listInputParameter)
{
switch ((ePARAMETERS)item.id)
{
case ePARAMETERS.X_SPEED:
xSpeed = System.Convert.ToInt32(item.Value);
break;
case ePARAMETERS.Y_SPEED:
ySpeed = System.Convert.ToInt32(item.Value);
break;
case ePARAMETERS.SPEED_OF_VEHICLE:
vehicalSpeed = System.Convert.ToInt32(item.Value);
break;
case ePARAMETERS.NUMBER_OF_EVENTS:
noOfEvents = System.Convert.ToInt32(item.Value);
break;
case ePARAMETERS.DURATION_OF_TEST:
durationOfTest = float.Parse(item.Value) * 60; //converting minutes into seconds
break;
}
}
SetupBrakeCar();
}
}
protected virtual void SetupBrakeCar()
{
DOTween.Clear();
durationOfTest = noOfEvents * Random.Range(10,20); // The random value is the time between two consecutive tests.
breakCar.SetInitalParams(new BrakeCarInit
{
carMaxSpeed = vehicalSpeed * 0.95f,
durationOfTest = durationOfTest,
noOfEvents = noOfEvents,
xSpeed = xSpeed,
ySpeed = ySpeed
});
breakCar.distanceCheck = true;
}
protected override void SubmitRestultToServer()
{
SubmitTest submitTest = new SubmitTest
{
outputParameters = new List<SaveOutputParameter>
{
new SaveOutputParameter
{
id = (int)ePARAMETERS.OUT_REACTION_TIME,
value = ((int)(GetEventReactionTimeAvg () * Constants.FLOAT_TO_INT_MULTIPLAYER)).ToString()
},
new SaveOutputParameter
{
id = (int)ePARAMETERS.OUT_AVG_RT,
value = GetReactionResult().ToString()
}
}
};
WebService.Instance.SendRequest(Constants.API_URL_FIRST_SAVE_TEST_RESULT, JsonUtility.ToJson(submitTest), SubmitedResultCallback);
}
protected override void ShowResult()
{
UiManager.Instance.UpdateStats(
(
"1. " + Constants.EVENT_REACTION + (GetEventReactionTimeAvg() * Constants.FLOAT_TO_INT_MULTIPLAYER).ToString("0.00") + "\n" +
"2. " + Constants.REACTION_TIME + reactionTest.GetReactionTimeAvg().ToString("0.00")
));
}
public void LateUpdate()
{
//Debug.Log("TH " + .Car.ThrottleInput1 + " TH " + playerControlCar.Car.ThrottleInput + " brake " + playerControlCar.Car.Brake + " brake IP " + playerControlCar.Car.BrakeInput);
//Debug.Log("BrakeCarEvent "+ brakeEventStartTime + " Player car " + playerControlCar.ThrottleInput1 + " minBrakeThreshold " + minBrakeThreshold);
if (brakeEventStartTime > 0 && playerControlCar.Car.ThrottleInput1 > minBrakeThreshold)
{
brakeEventDifferenceTime = Time.time - brakeEventStartTime;
Debug.Log("Brake event diff " + brakeEventDifferenceTime);
Debug.Log("Throttle " + playerControlCar.Car.ThrottleInput1);
averageEventReactionTime.Add(brakeEventDifferenceTime);
brakeEventStartTime = 0;
safetyDistanceCheck.GetSafetyDistance(SafetyDistance);
}
}
private void SafetyDistance(float obj)
{
totalSafetyDistance += obj;
++totalSafetyDistanceCount;
}
/// <summary>
/// Records the time when the car ahead starts braking
/// </summary>
protected void BrakeCarEvent()
{
brakeEventStartTime = Time.time;
Debug.Log("BrakeCarEvent ");
}
/// <summary>
/// calculates the average time taken to react
/// </summary>
public float GetEventReactionTimeAvg()
{
float avg = 0;
foreach (var item in averageEventReactionTime)
{
avg += item;
}//noofevents
return avg / (float)averageEventReactionTime.Count;
}
}
}
EDIT
I create new class FearTest:
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace DrivingTest
{
public class FearTest : MonoBehaviour
{
//public GameObject redDot;
public TextMeshPro textAnsia2;
public TextMesh textAnsia3;
public int shouldEvaluateTest = 0; // 0 - false, 1 - true
public int secondsInterval;
public int secondsToDisaply;
public int radiusR1;
public int radiusR2;
public int reactionTestDuration;
public int maxDots;
public float dotRadius = 1;
private float endTime;
private float dotDisaplyAtTime;
private List<float> dotDisplayReactTime = new List<float>();
private int missedSignals;
private int currentDotsCount;
private bool isReactionAlreadyGiven;
public bool ShouldEvaluateTest
{
get
{
return shouldEvaluateTest != 0;
}
}
void OnEnable()
{
GameManager.TestSceneLoaded += OnSceneLoaded;
}
private void OnDisable()
{
GameManager.TestSceneLoaded -= OnSceneLoaded;
}
#region Scene Loaded
private void OnSceneLoaded(eTESTS test)
{
if (SceneManager.GetActiveScene().name != test.ToString())
return;
Reset();
GetApiParams();
}
#endregion
private void GetApiParams()
{
#if UNITY_EDITOR
if (!GameManager.Instance)
{
Init();
return;
}
#endif
Debug.Log("called rt");
NextTestOutput nextTestOutput = GameManager.Instance.currentTest;
if (nextTestOutput.content != null && nextTestOutput.content.Count > 0)
{
foreach (var item in nextTestOutput.content[0].listInputParameter)
{
switch ((ePARAMETERS)item.id)
{
case ePARAMETERS.RT_ENABLE:
shouldEvaluateTest = System.Convert.ToInt32(item.Value);
break;
case ePARAMETERS.RT_DURATION:
reactionTestDuration = System.Convert.ToInt32(item.Value);
break;
case ePARAMETERS.RED_DOT_FREQ:
secondsInterval = System.Convert.ToInt32(item.Value);
break;
case ePARAMETERS.RED_DOT_MAX_COUNT:
maxDots = System.Convert.ToInt32(item.Value);
break;
case ePARAMETERS.RED_DOT_RADIUS_R1:
radiusR1 = System.Convert.ToInt32(item.Value);
break;
case ePARAMETERS.RED_DOT_RADIUS_R2:
radiusR2 = System.Convert.ToInt32(item.Value);
break;
case ePARAMETERS.RED_DOT_SIZE:
dotRadius = float.Parse(item.Value)/10f;
break;
case ePARAMETERS.RED_DOT_TIME:
secondsToDisaply = System.Convert.ToInt32(item.Value);
break;
}
}
Debug.Log("called rt "+ shouldEvaluateTest);
/*if (ShouldEvaluateTest)
{
Init();
}*/
Init();//dopo bisogna sistemare il shoudl evaluatetest
}
}
Coroutine displayCoroutine;
public void Init()
{
endTime = Time.time + reactionTestDuration + 10;
SetRedDotSize();
displayCoroutine = StartCoroutine(RedDotDisplay());
}
private IEnumerator RedDotDisplay()
{
yield return new WaitForSeconds(2);
while (true)
{
SetRandomDotPosition();
RedDot(true);
isReactionAlreadyGiven = false;
dotDisaplyAtTime = Time.time;
currentDotsCount++;
yield return new WaitForSeconds(secondsToDisaply);
if(!isReactionAlreadyGiven)
{
missedSignals++;
}
RedDot(false);
if ((reactionTestDuration > 0 && endTime <= Time.time) || (maxDots > 0 && currentDotsCount >= maxDots))
break;
float waitTime = secondsInterval - secondsToDisaply;
yield return new WaitForSeconds(waitTime);
}
}
private void Update()
{
if (!ShouldEvaluateTest)
return;
if (!isReactionAlreadyGiven && /*redDot.activeSelf &&*/ (LogitechGSDK.LogiIsConnected(0) && LogitechGSDK.LogiButtonIsPressed(0, 23)))
{
isReactionAlreadyGiven = true;
float reactionTime = Time.time - dotDisaplyAtTime;
Debug.Log("Reaction Time RT : " + reactionTime);
RedDot(false);
dotDisplayReactTime.Add(reactionTime);
}
}
public double GetReactionTimeAvg()
{
double avg = 0;
foreach (var item in dotDisplayReactTime)
{
avg += item;
}
//avg / currentDotsCount
return avg / (float)dotDisplayReactTime.Count;
}
public double GetMissedSignals()
{
return ((float) missedSignals / (float) currentDotsCount) * 100;
}
private void RedDot(bool state)
{
//redDot.SetActive(state);
textAnsia2.SetText("Pippo 2");
}
private void SetRedDotSize()
{
//redDot.transform.localScale *= dotRadius;
textAnsia2.transform.localScale *= dotRadius;
textAnsia3.transform.localScale *= dotRadius;
}
private void SetRandomDotPosition()
{
//redDot.GetComponent<RectTransform>().anchoredPosition = GetRandomPointBetweenTwoCircles(radiusR1, radiusR2)*scale;
float scale = ((Screen.height*0.9f) / radiusR2) * 0.9f;
Vector3 pos = GetRandomPointBetweenTwoCircles(radiusR1, radiusR2) * scale;
Debug.Log("RT temp pos : " + pos);
pos = new Vector3(500, 500, 0);
Debug.Log("RT pos : " + pos);
// redDot.transform.position = pos;
Vector3 pos2 = new Vector3(20, 20, 0);
Debug.Log("text ansia 2 : " + pos2);
textAnsia2.transform.position = pos2;
textAnsia3.transform.position = pos;
}
#region Getting Red Dot b/w 2 cricles
/*
Code from : https://gist.github.com/Ashwinning/89fa09b3aa3de4fd72c946a874b77658
*/
/// <summary>
/// Returns a random point in the space between two concentric circles.
/// </summary>
/// <param name="minRadius"></param>
/// <param name="maxRadius"></param>
/// <returns></returns>
Vector3 GetRandomPointBetweenTwoCircles(float minRadius, float maxRadius)
{
//Get a point on a unit circle (radius = 1) by normalizing a random point inside unit circle.
Vector3 randomUnitPoint = Random.insideUnitCircle.normalized;
//Now get a random point between the corresponding points on both the circles
return GetRandomVector3Between(randomUnitPoint * minRadius, randomUnitPoint * maxRadius);
}
/// <summary>
/// Returns a random vector3 between min and max. (Inclusive)
/// </summary>
/// <returns>The <see cref="UnityEngine.Vector3"/>.</returns>
/// <param name="min">Minimum.</param>
/// <param name="max">Max.</param>
Vector3 GetRandomVector3Between(Vector3 min, Vector3 max)
{
return min + Random.Range(0, 1) * (max - min);
}
#endregion
#region Reset
private void Reset()
{
if (displayCoroutine != null)
StopCoroutine(displayCoroutine);
RedDot(false);
shouldEvaluateTest = 0;
reactionTestDuration = 0;
secondsInterval = 0;
missedSignals = 0;
maxDots = 0;
radiusR1 = 0;
radiusR2 = 0;
dotRadius = 1;
secondsToDisaply = 0;
endTime = 0;
dotDisaplyAtTime = 0;
dotDisplayReactTime.Clear();
//redDot.transform.localScale = Vector3.one;
textAnsia2.transform.localScale = Vector3.one;
textAnsia3.transform.localScale = Vector3.one;
currentDotsCount = 0;
isReactionAlreadyGiven = true;
}
#endregion
}
}
When "SetRandomDotPosition" method is called, in my scene I can display in a random position of the screen the RedDot (that is a simple image with a red dot), but I m not able to display my textAnsia2. How can I fixed it ?
I hope this will help you to get started :
https://vimeo.com/709527359
the scripts:
https://imgur.com/a/csNKwEh
I hope that in the video i covered every step that i've made.
Edit: The only thing is for you to do is to make the input of the Wheel to work on the slider. Try to make a simple script: when the text is enabled then the input from a joystick to work on that . When is disabled switch it back for his purpose .
Process:*****.googlemapapp, PID: 2402
java.lang.UnsatisfiedLinkError: Couldn't load rocket from loader bvt[DexPathList[[zip file "/data/data/com.google.android.gms/app_chimera/m/00000003/DynamiteModulesB_GmsCore_prod_alldpi_release.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]]: findLibrary returned null
at java.lang.Runtime.loadLibrary(Runtime.java:358)
at java.lang.System.loadLibrary(System.java:526)
at com.google.maps.api.android.lib6.rocket.a.onSurfaceCreated(:com.google.android.gms.DynamiteModulesB:119)
at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1501)
at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1240)
i m Getting an error when i run my mapFragment.getMapAsync(this)
i works very well for first time ...when i start again its giving error like above ...everything works well for first time ....it is like for odd it works for even application crashesh.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = MapsActivity.this;
setContentView(R.layout.activity_maps);
MarkerPoints = new ArrayList<>();
nextBtn = (Button) findViewById(R.id.nextBtn);
txtDistance = (TextView) findViewById(R.id.txtDistance);
txtCheckpoint = (TextView) findViewById(R.id.txtCheckpoint);
txtDistance.setText("Distance Travel : 0 Mtr");
distance = new ArrayList<Float>();
waypoints = new ArrayList<LatLng>();
Intent i = getIntent();
Places place = (Places) i.getParcelableExtra("data");
Log.d("data", place.toString());
startPoint = place.startPoint;
endPoint = place.endPoint;
waypoints=place.waypoints;
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if(resultCode == ConnectionResult.SUCCESS)
{
if(mapFragment != null) {
mapFragment.getMapAsync(this);
}
}else
Toast.makeText(context, "UnAvailable", Toast.LENGTH_SHORT).show();
}
//here application crashes on alternative run on mapFragment.getMapAsync(this) ,
all code works fine for first time on second time it says
java.lang.UnsatisfiedLinkError: Couldn't load rocket from loader bvt[DexPathList[[zip file "/data/data/com.google.android.gms/app_chimera/m/00000003/DynamiteModulesB_GmsCore_prod_alldpi_release.apk"],
nativeLibraryDirectories=[/vendor/lib, /system/lib]]]:
findLibrary returned null
at java.lang.Runtime.loadLibrary(Runtime.java:358)
//i initialize maps and then according to location i change panoroma image, here Fetchurl will save the path data in routes which is List<List<HashMap<String, String>>> it is Asynchronous call
#Override
public void onMapReady(GoogleMap googleMap) {
try {
mMap = googleMap;
MarkerPoints.add(startPoint);
startMarker.position(startPoint);
startMarker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
m = mMap.addMarker(startMarker);
m.setTitle("You");
m.showInfoWindow();
MarkerPoints.add(endPoint);
endMarker.position(endPoint);
endMarker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
Marker e = mMap.addMarker(endMarker);
e.setTitle("Goal");
LatLng origin = MarkerPoints.get(0);
LatLng dest = MarkerPoints.get(1);
String url = getUrl(origin, dest);
FetchUrl FetchUrl = new FetchUrl();
FetchUrl.execute(url);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(startPoint));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
initializeSteatView();
} catch (Exception e) {
}
}`
///here i initialize streatview
` public void initializeSteatView() {
SupportStreetViewPanoramaFragment streetViewPanoramaFragment =
(SupportStreetViewPanoramaFragment)
getSupportFragmentManager().findFragmentById(R.id.mapPanaroma);
streetViewPanoramaFragment.getStreetViewPanoramaAsync(
new OnStreetViewPanoramaReadyCallback() {
#Override
public void onStreetViewPanoramaReady(final StreetViewPanorama panorama) {
panorama.setUserNavigationEnabled(false);
panorama.setPosition(startPoint);
nextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!isRouteLoaded)return;
if (currentPosition == routes.get(0).size() - 1) return;
if (currentPosition == 0) {
String s1 = routes.get(0).get(currentPosition).get("lat");
String s2 = routes.get(0).get(currentPosition).get("lng");
double d1 = Double.parseDouble(s1);
double d2 = Double.parseDouble(s2);
LatLng newPosition = new LatLng(d1, d2);
mMap.moveCamera(CameraUpdateFactory.newLatLng(newPosition));
mMap.animateCamera(CameraUpdateFactory.zoomTo(17));
panorama.setPosition(newPosition);
m.setPosition(newPosition);
distance.add(totalDistance);
for (int i = 1; i < routes.get(0).size(); i++) {
d1 = Double.parseDouble(routes.get(0).get(i - 1).get("lat"));
d2 = Double.parseDouble(routes.get(0).get(i - 1).get("lng"));
LatLng start = new LatLng(d1, d2);
d1 = Double.parseDouble(routes.get(0).get(i).get("lat"));
d2 = Double.parseDouble(routes.get(0).get(i).get("lng"));
LatLng end = new LatLng(d1, d2);
totalDistance += calculateDistance(start, end);
distance.add(totalDistance);
Log.d("distance", distance.toString());
}
final Handler handler = new Handler();
final TimerTask timertask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
distanceTravel++;
txtDistance.setText("Distance Travel : " + distanceTravel + " Mtr");
checkDistance();
}
});
}
};
Timer timer = new Timer();
timer.schedule(timertask, 0, 500);
}
}
public void checkDistance() {
if (currentPosition == routes.get(0).size() - 1) return;
checkPoint = distance.get(currentPosition + 1);
txtCheckpoint.setText("Checkpoint : " + checkPoint);
if (checkPoint < Float.parseFloat(distanceTravel + "")) {
currentPosition++;
} else {
return;
}
String s1 = routes.get(0).get(currentPosition).get("lat");
String s2 = routes.get(0).get(currentPosition).get("lng");
double d1 = Double.parseDouble(s1);
double d2 = Double.parseDouble(s2);
LatLng newPosition = new LatLng(d1, d2);
mMap.moveCamera(CameraUpdateFactory.newLatLng(newPosition));
mMap.animateCamera(CameraUpdateFactory.zoomTo(17));
panorama.setPosition(newPosition);
m.setPosition(newPosition);
}
});
panorama.setOnStreetViewPanoramaChangeListener(new StreetViewPanorama.OnStreetViewPanoramaChangeListener() {
#Override
public void onStreetViewPanoramaChange(StreetViewPanoramaLocation streetViewPanoramaLocation) {
if(!isRouteLoaded)return;
if (routes.size() > 0) {
double lat1 = Double.parseDouble(routes.get(0).get(currentPosition).get("lat"));
double lng1 = Double.parseDouble(routes.get(0).get(currentPosition).get("lng"));
double lat2 = Double.parseDouble(routes.get(0).get
(currentPosition + 1).get("lat"));
double lng2 = Double.parseDouble(routes.get(0).get
(currentPosition + 1).get("lng"));
double dLon = (lng2 - lng1);
double y = Math.sin(dLon) * Math.cos(lat2);
double x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLon);
double brng = Math.toDegrees((Math.atan2(y, x)));
// brng = (360 - ((brng + 360) % 360));
long duration = 1000;
StreetViewPanoramaCamera camera =
new StreetViewPanoramaCamera.Builder()
.zoom(panorama.getPanoramaCamera().zoom)
.tilt(panorama.getPanoramaCamera().tilt)
.bearing(Float.parseFloat(brng + ""))
.build();
panorama.animateTo(camera, duration);
}
}
});
}
});
}
`
Are there any examples of pedestrian modelling in repast simphony? I am novice in repast and was trying to model a simple pedestrian movement simulation. Any pointers to useful resources/ examples?
Andrew Crook's blog GIS and Agent-Based Modeling (http://www.gisagents.org/) has lots of interesting links to pedestrian models. I think there are even some specific to Repast.
Repast isn't the best for open libraries, but I've had some luck searching GitHub. Here's a basic ped agent I built once, you'll have to build a context with a scheduler class to call the pedestrians:
context:
public class RoadBuilder extends DefaultContext<Object> implements ContextBuilder<Object> {
context.setId("driving1");
ContinuousSpaceFactory spaceFactory =
ContinuousSpaceFactoryFinder.createContinuousSpaceFactory(null);
ContinuousSpace<Object> space =
spaceFactory.createContinuousSpace("space",context, new SimpleCartesianAdder<Object>(),
new StrictBorders(), roadL, worldW);
clock = RunEnvironment.getInstance().getCurrentSchedule();
flowSource = new Scheduler();
context.add(flowSource);
return context;
}
the scheduler:
public class Scheduler {
static ArrayList<Ped> allPeds;
#ScheduledMethod(start = 1, interval = 1, priority = 1)
public void doStuff() {
Ped addedPed = addPed(1);
allPeds.add(addedPed);
for (Ped a : allPeds) {
a.calc();}
for (Ped b : allPeds) {
b.walk();}
public Ped addPed(int direction) {
Context<Object> context = ContextUtils.getContext(this);
ContinuousSpace<Object> space = (ContinuousSpace<Object>) context.getProjection("space");
Ped newPed = new Ped(space,direction);
context.add(newPed);
space.moveTo(newPed,xPlacement,yPlacement);
newPed.myLoc = space.getLocation(newPed);
return(newPed);
}
The pedestrians - This is based on a "generalized force model" (source: Simulating Dynamical Features of Escape Panic - Helbing, Farkas, and Vicsek - https://arxiv.org/pdf/cond-mat/0009448.pdf)
and here's the pedestrian class
public class Ped {
private ContinuousSpace<Object> space;
private List<Double> forcesX, forcesY;
private NdPoint endPt;
private Random rnd = new Random();
private int age;
private double endPtDist, endPtTheta, critGap;
private double side = RoadBuilder.sidewalk;
private double wS, etaS, wV, etaV, sigR; //errors
private double m, horiz, A, B, k, r; //interactive force constants (accT is also)
public NdPoint myLoc, destination;
public double[] v, dv, newV;
public double xTime, accT, maxV, xLoc, yLoc;
public int dir; // dir = 1 walks up, -1 walks down
public void calc() {
myLoc = space.getLocation(this);
dv = accel(myLoc,dir,destination);
newV = sumV(v,dv);
newV = limitV(newV);
}
public void walk() {
v = newV;
move(myLoc,v);
}
public double[] accel(NdPoint location, int direct, NdPoint endPt) {
forcesX = new ArrayList<Double>();
forcesY = new ArrayList<Double>();
double xF, yF;
double[] acc;
xF = yF = 0;
//calculate heading to endpoint
endPtDist = space.getDistance(location, endPt);
double endPtDelX = endPt.getX()-location.getX();
endPtTheta = FastMath.asin((double)direct*endPtDelX/endPtDist);
if (direct == -1) {
endPtTheta += Math.PI;}
//calculate motive force
Double motFx = (maxV*Math.sin(endPtTheta) - v[0])/accT;
Double motFy = (maxV*Math.cos(endPtTheta) - v[1])/accT;
forcesX.add(motFx);
forcesY.add(motFy);
//calculate interactive forces
//TODO: write code to make a threshold for interaction instead of the arbitrary horizon
for (Ped a : Scheduler.allPeds) {
if (a != this) {
NdPoint otherLoc = space.getLocation(a);
double otherY = otherLoc.getY();
double visible = Math.signum((double)dir*(otherY-yLoc));
if (visible == 1) { //peds only affected by those in front of them
double absDist = space.getDistance(location, otherLoc);
if (absDist < horiz) {
double delX = location.getX()-otherLoc.getX();
double delY = location.getY()-otherLoc.getY();
double delXabs = Math.abs(delX);
double signFx = Math.signum(delX);
double signFy = Math.signum(delY);
double theta = FastMath.asin(delXabs/absDist);
double rij = r + a.r;
Double interFx = signFx*A*Math.exp((rij-absDist)/B)*Math.sin(theta)/m;
Double interFy = signFy*A*Math.exp((rij-absDist)/B)*Math.cos(theta)/m;
forcesX.add(interFx);
forcesY.add(interFy);}}}}
//sum all forces
for (Double b : forcesX) {
xF += b;}
for (Double c : forcesY) {
yF += c;}
acc = new double[] {xF, yF};
return acc;
}
public void move(NdPoint loc, double[] displacement) {
double[] zero = new double[] {0,0};
double yl = loc.getY();
if (displacement != zero) {
space.moveByDisplacement(this,displacement);
myLoc = space.getLocation(this);}
}
public double[] limitV(double[] input) {
double totalV, norm;
if (this.dir == 1) {
if (input[1] < 0) {
input[1] = 0;}}
else {
if (input[1] > 0) {
input[1] = 0;}}
totalV = Math.sqrt(input[0]*input[0] + input[1]*input[1]);
if (totalV > maxV) {
norm = maxV/totalV;
input[0] = input[0]*norm;
input[1] = input[1]*norm;}
return input;
}
public double[] sumV(double[] a, double[] b) {
double[] c = new double[2];
for (int i = 0; i < 2; i++) {
c[i] = a[i] + b[i];}
return c;
}
public Ped(ContinuousSpace<Object> contextSpace, int direction) {
space = contextSpace;
maxV = rnd.nextGaussian() * UserPanel.pedVsd + UserPanel.pedVavg;
dir = direction; // 1 moves up, -1 moves down
v = new double[] {0,(double)dir*.5*maxV};
age = 0;
//3-circle variables - from Helbing, et al (2000) [r from Rouphail et al 1998]
accT = 0.5/UserPanel.tStep; //acceleration time
m = 80; //avg ped mass in kg
horiz = 5/RoadBuilder.spaceScale; //distance at which peds affect each other
A = 2000*UserPanel.tStep*UserPanel.tStep/RoadBuilder.spaceScale; //ped interaction constant (kg*space units/time units^2)
B = 0.08/RoadBuilder.spaceScale; //ped distance interaction constant (space units)
k = 120000*UserPanel.tStep*UserPanel.tStep; //wall force constant
r = 0.275/RoadBuilder.spaceScale; //ped radius (space units)
}
}
I'm testing the OrientDB and unfamiliar with the OrientDB-Graph API. And now I copied the code on the net, it rises the Exception.
Next is my code:
import com.tinkerpop.blueprints.impls.orient.*;
import com.tinkerpop.blueprints.Element.*;
import java.util.*;
class OrientInsert {
public static void testInsertion(OrientGraphNoTx graph) {
System.out.println(new Date());
int count = 1000;
for (int i = 0; i < count; ++i) {
OrientVertex vertex1 = graph.addVertex("class:CLASS1", "prop1", Integer.toString(i), "prop2", "22", "prop3", "3333");
for (int j = 0; j < count; ++j) {
OrientVertex vertex2 = graph.addVertex("class:CLASS2", "prop1", Integer.toString(i + j / 1000), "prop2", "22", "prop3", "3333");
graph.addEdge(null, vertex1, vertex2, "v1v2");
}
}
graph.commit();
System.out.println(new Date());
}
public static void main(String[] args) {
OrientGraphFactory factory = new OrientGraphFactory("remote:10.240.137.12/test", "admin", "admin");
OrientGraphNoTx graph = factory.getNoTx();
OrientInsert.testInsertion(graph);
}
} `
And the output is:
Mar 29, 2016 11:45:19 AM com.orientechnologies.common.log.OLogManager log
INFO: OrientDB auto-config DISKCACHE=3,725MB (heap=14,288MB os=64,292MB disk=7,451MB)
Tue Mar 29 11:45:19 CST 2016
Exception in thread "main" com.orientechnologies.orient.server.distributed.ODistributedException: Error on execution distributed COMMAND
at com.orientechnologies.orient.server.distributed.ODistributedStorage.command(ODistributedStorage.java:346)
at com.orientechnologies.orient.core.command.OCommandRequestTextAbstract.execute(OCommandRequestTextAbstract.java:67)
at com.orientechnologies.orient.server.network.protocol.binary.ONetworkProtocolBinary.command(ONetworkProtocolBinary.java:1323)
at com.orientechnologies.orient.server.network.protocol.binary.ONetworkProtocolBinary.executeRequest(ONetworkProtocolBinary.java:400)
at com.orientechnologies.orient.server.network.protocol.binary.OBinaryNetworkProtocolAbstract.execute(OBinaryNetworkProtocolAbstract.java:223)
at com.orientechnologies.common.thread.OSoftThread.run(OSoftThread.java:77)
Caused by: com.orientechnologies.orient.core.exception.OSchemaException: Class CLASS1 already exists in current database
at com.orientechnologies.orient.core.metadata.schema.OSchemaShared.doCreateClass(OSchemaShared.java:983)
at com.orientechnologies.orient.core.metadata.schema.OSchemaShared.createClass(OSchemaShared.java:415)
at com.orientechnologies.orient.core.metadata.schema.OSchemaProxy.createClass(OSchemaProxy.java:127)
at com.orientechnologies.orient.core.sql.OCommandExecutorSQLCreateClass.execute(OCommandExecutorSQLCreateClass.java:179)
at com.orientechnologies.orient.core.sql.OCommandExecutorSQLDelegate.execute(OCommandExecutorSQLDelegate.java:90)
at com.orientechnologies.orient.server.distributed.task.OSQLCommandTask.execute(OSQLCommandTask.java:116)
at com.orientechnologies.orient.server.hazelcast.OHazelcastPlugin.executeOnLocalNode(OHazelcastPlugin.java:810)
at com.orientechnologies.orient.server.hazelcast.ODistributedWorker.onMessage(ODistributedWorker.java:279)
at com.orientechnologies.orient.server.hazelcast.ODistributedWorker.run(ODistributedWorker.java:103)
Apparently, it first inserts the vertex1 and vertex2 into the graphDatabase, and creates class1 and class2. But when it comes to the second insertion, it still wants to create the class1 and class2. Why? how can i control the creation of class. But, so many users use this api for testing.
Try this code:
public static void main(String[] args) {
OrientGraphFactory factory = new OrientGraphFactory("remote:localhost/test", "admin", "admin");
OrientGraphNoTx graph = factory.getNoTx();
OrientInsert.testInsertion(graph);
graph.shutdown();
System.out.println("");
System.out.println("End main");
}
public static class OrientInsert {
public static void testInsertion(OrientGraphNoTx graph) {
System.out.println(new Date());
int count = 1000;
//create class 1
OClass clVertice1;
OrientVertex vVertice1;
clVertice1 = graph.createVertexType("CLASS1", "V");
clVertice1.createProperty("prop1", OType.STRING);
clVertice1.createProperty("prop2", OType.STRING);
clVertice1.createProperty("prop3", OType.STRING);
//create class 2
OClass clVertice2;
OrientVertex vVertice2;
clVertice2 = graph.createVertexType("CLASS2", "V");
clVertice2.createProperty("prop1", OType.STRING);
clVertice2.createProperty("prop2", OType.STRING);
clVertice2.createProperty("prop3", OType.STRING);
for (int i = 0; i < count; ++i) {
System.out.println("");
System.out.println("i :"+i+" -------------------" );
//....class 1
vVertice1 = graph.addVertex("class:CLASS1");
vVertice1.setProperties("prop1", Integer.toString(i));
vVertice1.setProperties("prop2", "22");
vVertice1.setProperties("prop3", "3333");
for (int j = 0; j < count; ++j) {
System.out.print("");
System.out.print(j+" ");
//...class 2
vVertice2 = graph.addVertex("class:CLASS2");
vVertice2.setProperties("prop1", Integer.toString(i + j / 1000));
vVertice2.setProperties("prop2", "22");
vVertice2.setProperties("prop3", "3333");
//edge
graph.addEdge(null, vVertice1, vVertice2, "v1v2");
}
}
}
}
The result is this (i selected only 2 vertex with limit 100 E)
I'm planning to use (Handwritten Number Recognition by Yan Cheng, Cheok) for a project I'm working on it,I should use their database for number recognition but the files are not on their website, I should use a file called "LRTBHVtrainingdata.txtI=96H=200LR=0.9M=0.1C=2000.snet" as they say in their tutorial,But what I found on their website (http://yann.lecun.com/exdb/mnist/) is four files and I don't know how to use them ? so any help on where to get their database or where or the files to use them ?
The files you're looking at are the correct files. They are normalized grey-scale images (0-white, 255-black) centered in a 20x20 box. The page explains the structure of the files (just scroll down towards the bottom).
Here's some code I wrote a while back in Java, that reads in the MNIST image and label files:
import net.vivin.digit.DigitImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Created by IntelliJ IDEA.
* User: vivin
* Date: 11/11/11
* Time: 10:07 AM
*/
public class DigitImageLoadingService {
private String labelFileName;
private String imageFileName;
/** the following constants are defined as per the values described at http://yann.lecun.com/exdb/mnist/ **/
private static final int MAGIC_OFFSET = 0;
private static final int OFFSET_SIZE = 4; //in bytes
private static final int LABEL_MAGIC = 2049;
private static final int IMAGE_MAGIC = 2051;
private static final int NUMBER_ITEMS_OFFSET = 4;
private static final int ITEMS_SIZE = 4;
private static final int NUMBER_OF_ROWS_OFFSET = 8;
private static final int ROWS_SIZE = 4;
public static final int ROWS = 28;
private static final int NUMBER_OF_COLUMNS_OFFSET = 12;
private static final int COLUMNS_SIZE = 4;
public static final int COLUMNS = 28;
private static final int IMAGE_OFFSET = 16;
private static final int IMAGE_SIZE = ROWS * COLUMNS;
public DigitImageLoadingService(String labelFileName, String imageFileName) {
this.labelFileName = labelFileName;
this.imageFileName = imageFileName;
}
public List<DigitImage> loadDigitImages() throws IOException {
List<DigitImage> images = new ArrayList<DigitImage>();
ByteArrayOutputStream labelBuffer = new ByteArrayOutputStream();
ByteArrayOutputStream imageBuffer = new ByteArrayOutputStream();
InputStream labelInputStream = this.getClass().getResourceAsStream(labelFileName);
InputStream imageInputStream = this.getClass().getResourceAsStream(imageFileName);
int read;
byte[] buffer = new byte[16384];
while((read = labelInputStream.read(buffer, 0, buffer.length)) != -1) {
labelBuffer.write(buffer, 0, read);
}
labelBuffer.flush();
while((read = imageInputStream.read(buffer, 0, buffer.length)) != -1) {
imageBuffer.write(buffer, 0, read);
}
imageBuffer.flush();
byte[] labelBytes = labelBuffer.toByteArray();
byte[] imageBytes = imageBuffer.toByteArray();
byte[] labelMagic = Arrays.copyOfRange(labelBytes, 0, OFFSET_SIZE);
byte[] imageMagic = Arrays.copyOfRange(imageBytes, 0, OFFSET_SIZE);
if(ByteBuffer.wrap(labelMagic).getInt() != LABEL_MAGIC) {
throw new IOException("Bad magic number in label file!");
}
if(ByteBuffer.wrap(imageMagic).getInt() != IMAGE_MAGIC) {
throw new IOException("Bad magic number in image file!");
}
int numberOfLabels = ByteBuffer.wrap(Arrays.copyOfRange(labelBytes, NUMBER_ITEMS_OFFSET, NUMBER_ITEMS_OFFSET + ITEMS_SIZE)).getInt();
int numberOfImages = ByteBuffer.wrap(Arrays.copyOfRange(imageBytes, NUMBER_ITEMS_OFFSET, NUMBER_ITEMS_OFFSET + ITEMS_SIZE)).getInt();
if(numberOfImages != numberOfLabels) {
throw new IOException("The number of labels and images do not match!");
}
int numRows = ByteBuffer.wrap(Arrays.copyOfRange(imageBytes, NUMBER_OF_ROWS_OFFSET, NUMBER_OF_ROWS_OFFSET + ROWS_SIZE)).getInt();
int numCols = ByteBuffer.wrap(Arrays.copyOfRange(imageBytes, NUMBER_OF_COLUMNS_OFFSET, NUMBER_OF_COLUMNS_OFFSET + COLUMNS_SIZE)).getInt();
if(numRows != ROWS && numRows != COLUMNS) {
throw new IOException("Bad image. Rows and columns do not equal " + ROWS + "x" + COLUMNS);
}
for(int i = 0; i < numberOfLabels; i++) {
int label = labelBytes[OFFSET_SIZE + ITEMS_SIZE + i];
byte[] imageData = Arrays.copyOfRange(imageBytes, (i * IMAGE_SIZE) + IMAGE_OFFSET, (i * IMAGE_SIZE) + IMAGE_OFFSET + IMAGE_SIZE);
images.add(new DigitImage(label, imageData));
}
return images;
}
}