List of usage examples for com.mongodb BasicDBObject getDouble
public double getDouble(final String key)
From source file:com.streamreduce.core.transformer.message.AgentMessageTransformer.java
License:Apache License
/** * {@inheritDoc}//from ww w . j a v a 2 s. c om */ @Override public String doTransform(Event event) { EventId eventId = event.getEventId(); Map<String, Object> eventMetadata = event.getMetadata(); String msg = ""; switch (eventId) { case ACTIVITY: BasicDBObject payload = (BasicDBObject) eventMetadata.get("payload"); StringBuilder sb = new StringBuilder(); sb.append("Current system overview at ").append(eventMetadata.get("activityGenerated")) // Should we format this? .append("\n\n"); sb.append("Uptime: ").append(payload.getString("uptime")).append("s\n").append("Disk usage:\n"); BasicDBObject partitionsObj = (BasicDBObject) payload.get("partitions"); Set<String> partitions = new TreeSet<>(partitionsObj.keySet()); for (String key : partitions) { BasicDBObject partition = (BasicDBObject) partitionsObj.get(key); double totalAsKb = partition.getDouble("total"); // Certain devices show as 0.00GB and should be pruned if (totalAsKb == 0) { continue; } double totalAsGB = MessageUtils.kbToGB(totalAsKb); double usedAsGB = MessageUtils.kbToGB(partition.getDouble("used")); double freeAsGB = MessageUtils.kbToGB(partition.getDouble("free")); sb.append(" ").append(key).append(": Total ").append(MessageUtils.roundAndTruncate(totalAsGB, 2)) .append("GB, Used ").append(MessageUtils.roundAndTruncate(usedAsGB, 2)).append("GB, Free ") .append(MessageUtils.roundAndTruncate(freeAsGB, 2)).append("GB\n"); } sb.append("Disk I/O:\n"); BasicDBObject diskIO = (BasicDBObject) payload.get("disk_io"); Set<String> disks = new TreeSet<>(diskIO.keySet()); if (disks.size() == 0) { sb.append(" Unavailable\n"); } else { for (String key : disks) { BasicDBObject disk = (BasicDBObject) diskIO.get(key); long reads = disk.getLong("read_count"); long writes = disk.getLong("write_count"); double gbRead = MessageUtils.kbToGB(disk.getLong("read_kbytes")); double gbWrite = MessageUtils.kbToGB(disk.getLong("write_kbytes")); long readSecs = disk.getLong("read_time"); long writeSecs = disk.getLong("write_time"); sb.append(" ").append(key).append(": Reads ").append(reads).append(", Writes ").append(writes) .append(", GB Read ").append(MessageUtils.roundAndTruncate(gbRead, 2)) .append(", GB Written ").append(MessageUtils.roundAndTruncate(gbWrite, 2)) .append(", Read Time ").append(readSecs).append("s, Write Time ").append(writeSecs) .append("s\n"); } } sb.append("Network I/O:\n"); BasicDBObject netIO = (BasicDBObject) payload.get("network_io"); Set<String> nics = new TreeSet<>(netIO.keySet()); int nicsDisplayed = 0; for (String key : nics) { BasicDBObject nic = (BasicDBObject) netIO.get(key); long packetsIn = nic.getInt("packets_in"); long packetsOut = nic.getInt("packets_out"); // Certain devices show 0 packets in/out and should be pruned if (packetsIn == 0 && packetsOut == 0) { continue; } double gbIn = MessageUtils.kbToGB(nic.getLong("kbytes_in")); double gbOut = MessageUtils.kbToGB(nic.getLong("kbytes_out")); sb.append(" ").append(key).append(": Packets In ").append(packetsIn).append(", Packets Out ") .append(packetsOut).append(", GB In ").append(MessageUtils.roundAndTruncate(gbIn, 2)) .append(", GB Out ").append(MessageUtils.roundAndTruncate(gbOut, 2)).append("\n"); nicsDisplayed++; } if (nicsDisplayed == 0) { sb.append(" Unavailable\n"); } sb.append("Load: 1m ").append(MessageUtils.roundAndTruncate(payload.getDouble("load_avg_0"), 2)) .append(", ").append("5m ") .append(MessageUtils.roundAndTruncate(payload.getDouble("load_avg_1"), 2)).append(", ") .append("15m ").append(MessageUtils.roundAndTruncate(payload.getDouble("load_avg_2"), 2)) .append("\n"); float gbTotalRAM = (float) MessageUtils.kbToGB(payload.getLong("phy_ram_total")); float gbUsedRAM = (float) MessageUtils.kbToGB(payload.getLong("phy_ram_used")); float gbFreeRAM = (float) MessageUtils.kbToGB(payload.getLong("phy_ram_free")); sb.append("Real Mem: Total ").append(MessageUtils.roundAndTruncate(gbTotalRAM, 2)).append("GB, Used ") .append(MessageUtils.roundAndTruncate(gbUsedRAM, 2)).append("GB, Free ") .append(MessageUtils.roundAndTruncate(gbFreeRAM, 2)).append("GB\n"); double gbTotalVRAM = MessageUtils.kbToGB(payload.getLong("vir_ram_total")); double gbUsedVRAM = MessageUtils.kbToGB(payload.getLong("vir_ram_used")); double gbFreeVRAM = MessageUtils.kbToGB(payload.getLong("vir_ram_free")); sb.append("Virt Mem: Total ").append(MessageUtils.roundAndTruncate(gbTotalVRAM, 2)).append("GB, Used ") .append(MessageUtils.roundAndTruncate(gbUsedVRAM, 2)).append("GB, Free ") .append(MessageUtils.roundAndTruncate(gbFreeVRAM, 2)).append("GB\n"); sb.append("Processes: ").append(payload.getInt("processes")).append("\n"); sb.append("Users: Total ").append(payload.getInt("users_total")).append(", Unique ") .append(payload.getInt("users_unique")).append("\n"); msg = sb.toString(); break; default: super.doTransform(event); break; } return msg; }
From source file:controllers.FilterController.java
License:Apache License
public static Statistics getStatisticsFromResult(BasicDBObject aggregation) { if (aggregation == null) return null; final DecimalFormat df = new DecimalFormat("#.##"); Statistics stats = new Statistics(); stats.setCount(aggregation.getInt("count") + " objects"); stats.setSize(df.format(aggregation.getLong("sum") / 1024D / 1024) + " MB"); stats.setAvg(df.format(aggregation.getDouble("avg") / 1024 / 1024) + " MB"); stats.setMin(aggregation.getLong("min") + " B"); stats.setMax(df.format(aggregation.getLong("max") / 1024D / 1024) + " MB"); stats.setSd(df.format(aggregation.getDouble("stddev") / 1024 / 1024) + " MB"); stats.setVar(df.format(aggregation.getDouble("variance") / 1024 / 1024 / 1024 / 1024) + " MB"); // because of sd^2 return stats; }
From source file:GeoHazardServices.Inst.java
License:Apache License
private String _computeById(User user, String evtid, Integer dur, Integer accel, Integer gridres, String algo) { DBObject eq = db.getCollection("eqs").findOne(new BasicDBObject("_id", evtid)); if (eq == null) return null; BasicDBObject process = new BasicDBObject("process", new BasicDBList()); BasicDBObject set = new BasicDBObject("$set", process); db.getCollection("eqs").update(eq, set); /* extract properties to pass them to the request method */ BasicDBObject prop = (BasicDBObject) eq.get("prop"); double lat = prop.getDouble("latitude"); double lon = prop.getDouble("longitude"); double dip = prop.getDouble("dip"); double strike = prop.getDouble("strike"); double rake = prop.getDouble("rake"); double depth = prop.getDouble("depth"); Date date = prop.getDate("date"); EQParameter eqp;/* w w w . j a v a 2 s . c o m*/ double mag = 0.0; double slip = 0.0; double length = 0.0; double width = 0.0; if (prop.get("magnitude") == null) { slip = prop.getDouble("slip"); length = prop.getDouble("length"); width = prop.getDouble("width"); eqp = new EQParameter(lon, lat, slip, length, width, depth, dip, strike, rake, date); } else { mag = prop.getDouble("magnitude"); eqp = new EQParameter(lon, lat, mag, depth, dip, strike, rake, date); } if (accel == null) accel = 1; /* start request */ EQTask task = new EQTask(eqp, evtid, user, dur, accel, gridres); task.algo = algo; task.setSlots(IScheduler.SLOT_NORMAL, IScheduler.SLOT_EXCLUSIVE); return request(evtid, task); }
From source file:GeoHazardServices.Inst.java
License:Apache License
@POST @Path("/computeById") @Produces(MediaType.APPLICATION_JSON)/*from ww w. j av a2s. c om*/ public String computeById(@Context HttpServletRequest request, @FormParam("inst") String inst, @FormParam("secret") String secret, @FormParam("id") String id, @FormParam("refineId") Long refineId, @FormParam("dur") Integer dur, @FormParam("accel") Integer accel, @FormParam("apikey") String apikey, @FormParam("evtid") String evtid, @FormParam("raw") @DefaultValue("0") Integer raw, @FormParam("gridres") Integer gridres, @FormParam("dt_out") @DefaultValue("10") Integer dt_out, @FormParam("algo") @DefaultValue("easywave") String algo) { /* Check for invalid parameter configurations. */ if ((inst != null || secret != null) && apikey != null) return jsfailure("Don't mix 'apikey' and 'secret'."); /* Support 'inst' and 'secret' for compatibility reasons. */ if (inst != null && secret != null) { /* Obtain the 'apikey' and pretend a call to the new api. */ DBObject query = new BasicDBObject("name", inst).append("secret", secret); DBObject tmp_inst = db.getCollection("institutions").findOne(query); if (tmp_inst == null) return jsdenied(); apikey = (String) ((DBObject) tmp_inst.get("api")).get("key"); if (apikey == null) return jsfailure("No 'apikey' set for this institution!"); } /* Authenticate user. */ DBObject db_user = auth_api(apikey, "user"); DBObject db_inst = auth_api(apikey, "inst"); User user; if (db_user != null) { user = new User(db_user, getInst(db_user)); } else if (db_inst != null) { user = new Inst(db_inst); } else { return jsdenied(); } /* Check for invalid parameter configurations. */ if ((id != null || refineId != null) && evtid != null) return jsfailure("Don't mix 'id' and 'evtid'."); if (evtid == null) evtid = new CompId(inst, id, refineId).toString(); /* Check for missing parameters */ if (evtid == null) return jsfailure("Missing parameter."); /* search for given id */ BasicDBObject query = new BasicDBObject("_id", evtid).append("user", user.objId); DBObject entry = db.getCollection("eqs").findOne(query); /* return if id not found */ if (entry == null) return jsfailure("Event ID not found."); /* check if already computed */ Integer progress = _status(evtid, raw); if (progress != STATUS_NO_COMP) { if (raw == 0) return jsfailure("Re-computation not allowed."); if (progress != 100) return jsfailure("A computation is currently running."); } /* Use same duration as in original simulation if available. */ if (dur == null) { Number n = (Number) getField(entry, "process.0.simTime"); /* Duration could not be determined. */ if (n == null) return jsfailure("Missing parameter."); dur = n.intValue(); } /* Use grid resolution of original computation or default to 120 seconds. */ if (gridres == null) { Number res = (Number) getField(entry, "process.0.resolution"); gridres = res == null ? 120 : (int) (res.doubleValue() * 60); } /* get properties of returned entry */ BasicDBObject prop = (BasicDBObject) entry.get("prop"); BasicDBObject process = new BasicDBObject("raw_progress", 0); if (raw == 0) { process.append("process", new BasicDBList()); } BasicDBObject set = new BasicDBObject("$set", process); db.getCollection("eqs").update(entry, set); /* extract properties to pass them to the request method */ double lat = prop.getDouble("latitude"); double lon = prop.getDouble("longitude"); double mag = prop.getDouble("magnitude"); double dip = prop.getDouble("dip"); double strike = prop.getDouble("strike"); double rake = prop.getDouble("rake"); double depth = prop.getDouble("depth"); Date date = prop.getDate("date"); if (accel == null) accel = 1; /* prepare the simulation for execution */ EQParameter eqp = new EQParameter(lon, lat, mag, depth, dip, strike, rake, date); EQTask task = new EQTask(eqp, evtid, user, dur, accel, gridres); task.raw = raw; task.dt_out = dt_out; task.algo = algo; String ret_id = request(evtid, task); return jssuccess(new BasicDBObject("_id", ret_id)); }
From source file:org.apache.gora.mongodb.utils.BSONDecorator.java
License:Apache License
/** * Access field as a double./*from www. j a v a 2s . c o m*/ * * @param fieldName * fully qualified name of the field to be accessed * @return value of the field as a double */ public Double getDouble(String fieldName) { BasicDBObject parent = getFieldParent(fieldName); return parent.getDouble(getLeafName(fieldName)); }
From source file:org.knowrob.knowrob_robcog.MongoRobcogQueries.java
License:Open Source License
/** * Query the Traj of the actor between the given timepoints *//*from w ww . ja v a 2 s.c om*/ public double[][] GetActorTraj(String actorName, String start, String end, double deltaT) { // transform the knowrob time to double with 3 decimal precision final double start_ts = (double) Math.round(parseTime_d(start) * 1000) / 1000; final double end_ts = (double) Math.round(parseTime_d(end) * 1000) / 1000; // create the pipeline operations, first with the $match check the times DBObject match_time = new BasicDBObject("$match", new BasicDBObject("timestamp", new BasicDBObject("$gte", start_ts).append("$lte", end_ts))); // $unwind the actors DBObject unwind_actors = new BasicDBObject("$unwind", "$actors"); // $match for the given actor name from the unwinded actors DBObject match_actor = new BasicDBObject("$match", new BasicDBObject("actors.name", actorName)); // build the $projection operation DBObject proj_fields = new BasicDBObject("_id", 0); proj_fields.put("timestamp", 1); proj_fields.put("pos", "$actors.pos"); proj_fields.put("rot", "$actors.rot"); DBObject project = new BasicDBObject("$project", proj_fields); // run aggregation List<DBObject> pipeline = Arrays.asList(match_time, unwind_actors, match_actor, project); AggregationOptions aggregationOptions = AggregationOptions.builder().batchSize(100) .outputMode(AggregationOptions.OutputMode.CURSOR).allowDiskUse(true).build(); // get results Cursor cursor = this.MongoRobcogConn.coll.aggregate(pipeline, aggregationOptions); // Traj as dynamic array ArrayList<double[]> traj_list = new ArrayList<double[]>(); // if the query returned nothing, get the most recent pose if (!cursor.hasNext()) { System.out.println("Java - GetActorTraj - No results found, returning most recent pose.."); // get the most recent pose traj_list.add(this.GetActorPoseAt(actorName, start)); // cast from dynamic array to standard array return traj_list.toArray(new double[traj_list.size()][7]); } // timestamp used for deltaT double prev_ts = 0; // while query has a response, return the pose while (cursor.hasNext()) { // get the first document as the next cursor and append the metadata to it BasicDBObject curr_doc = (BasicDBObject) cursor.next(); // get the curr timestamp double curr_ts = curr_doc.getDouble("timestamp"); // if time diff > then deltaT add position to trajectory if (curr_ts - prev_ts > deltaT) { // get the current pose traj_list.add(new double[] { ((BasicDBObject) curr_doc.get("pos")).getDouble("x"), ((BasicDBObject) curr_doc.get("pos")).getDouble("y"), ((BasicDBObject) curr_doc.get("pos")).getDouble("z"), ((BasicDBObject) curr_doc.get("rot")).getDouble("w"), ((BasicDBObject) curr_doc.get("rot")).getDouble("x"), ((BasicDBObject) curr_doc.get("rot")).getDouble("y"), ((BasicDBObject) curr_doc.get("rot")).getDouble("z") }); prev_ts = curr_ts; //System.out.println(curr_doc.toString()); } } // close cursor cursor.close(); // cast from dynamic array to standard array return traj_list.toArray(new double[traj_list.size()][7]); }
From source file:org.knowrob.knowrob_robcog.MongoRobcogQueries.java
License:Open Source License
/** * Query the Traj of the actors bone between the given timepoints *///from w w w . j a v a 2 s .co m public double[][] GetBoneTraj(String actorName, String boneName, String start, String end, double deltaT) { // transform the knowrob time to double with 3 decimal precision final double start_ts = (double) Math.round(parseTime_d(start) * 1000) / 1000; final double end_ts = (double) Math.round(parseTime_d(end) * 1000) / 1000; // create the pipeline operations, first with the $match check the times DBObject match_time = new BasicDBObject("$match", new BasicDBObject("timestamp", new BasicDBObject("$gte", start_ts).append("$lte", end_ts))); // $unwind the actors DBObject unwind_actors = new BasicDBObject("$unwind", "$actors"); // $match for the given actor name from the unwinded actors DBObject match_actor = new BasicDBObject("$match", new BasicDBObject("actors.name", actorName)); // build the $projection operation DBObject proj_fields = new BasicDBObject("_id", 0); proj_fields.put("timestamp", 1); proj_fields.put("pos", "$actors.pos"); proj_fields.put("rot", "$actors.rot"); DBObject project = new BasicDBObject("$project", proj_fields); // run aggregation List<DBObject> pipeline = Arrays.asList(match_time, unwind_actors, match_actor, project); AggregationOptions aggregationOptions = AggregationOptions.builder().batchSize(100) .outputMode(AggregationOptions.OutputMode.CURSOR).allowDiskUse(true).build(); // get results Cursor cursor = this.MongoRobcogConn.coll.aggregate(pipeline, aggregationOptions); // Traj as dynamic array ArrayList<double[]> traj_list = new ArrayList<double[]>(); // if the query returned nothing, get the most recent pose if (!cursor.hasNext()) { System.out.println("Java - GetBoneTraj - No results found, returning most recent pose.."); // get the most recent pose traj_list.add(this.GetBonePoseAt(actorName, boneName, start)); // cast from dynamic array to standard array return traj_list.toArray(new double[traj_list.size()][7]); } // timestamp used for deltaT double prev_ts = 0; // if query has a response, return the pose while (cursor.hasNext()) { // get the first document as the next cursor and append the metadata to it BasicDBObject curr_doc = (BasicDBObject) cursor.next(); // get the curr timestamp double curr_ts = curr_doc.getDouble("timestamp"); // if time diff > then deltaT add position to trajectory if (curr_ts - prev_ts > deltaT) { // get the current pose traj_list.add(new double[] { ((BasicDBObject) curr_doc.get("pos")).getDouble("x"), ((BasicDBObject) curr_doc.get("pos")).getDouble("y"), ((BasicDBObject) curr_doc.get("pos")).getDouble("z"), ((BasicDBObject) curr_doc.get("rot")).getDouble("w"), ((BasicDBObject) curr_doc.get("rot")).getDouble("x"), ((BasicDBObject) curr_doc.get("rot")).getDouble("y"), ((BasicDBObject) curr_doc.get("rot")).getDouble("z") }); prev_ts = curr_ts; //System.out.println(curr_doc.toString()); } } // close cursor cursor.close(); // cast from dynamic array to standard array return traj_list.toArray(new double[traj_list.size()][7]); }
From source file:org.knowrob.knowrob_robcog.MongoRobcogQueries.java
License:Open Source License
/** * Query the Trajectories of the actor bones at the given timepoint (or the most recent one) *//*from w w w . j ava 2s . co m*/ public double[][][] GetBonesTrajs(String actorName, String start, String end, double deltaT) { // transform the knowrob time to double with 3 decimal precision final double start_ts = (double) Math.round(parseTime_d(start) * 1000) / 1000; final double end_ts = (double) Math.round(parseTime_d(end) * 1000) / 1000; // create the pipeline operations, first with the $match check the times DBObject match_time = new BasicDBObject("$match", new BasicDBObject("timestamp", new BasicDBObject("$gte", start_ts).append("$lte", end_ts))); // $unwind actors in order to output only the queried actor DBObject unwind_actors = new BasicDBObject("$unwind", "$actors"); // $match for the given actor name from the unwinded actors DBObject match_actor = new BasicDBObject("$match", new BasicDBObject("actors.name", actorName)); // build the $projection operation DBObject proj_fields = new BasicDBObject("_id", 0); proj_fields.put("timestamp", 1); proj_fields.put("bones_pos", "$actors.bones.pos"); proj_fields.put("bones_rot", "$actors.bones.rot"); DBObject project = new BasicDBObject("$project", proj_fields); // run aggregation List<DBObject> pipeline = Arrays.asList(match_time, unwind_actors, match_actor, project); AggregationOptions aggregationOptions = AggregationOptions.builder().batchSize(100) .outputMode(AggregationOptions.OutputMode.CURSOR).allowDiskUse(true).build(); // get results Cursor cursor = this.MongoRobcogConn.coll.aggregate(pipeline, aggregationOptions); // Trajectories as dynamic array (dynamic on the time part) ArrayList<double[][]> bone_trajs = new ArrayList<double[][]>(); // the number of bones int nr_bones = 0; // if the query returned nothing, get the most recent pose if (!cursor.hasNext()) { System.out.println("Java - GetBonesTrajs - No results found, returning most recent poses.."); // get the most recent pose bone_trajs.add(this.GetBonesPosesAt(actorName, start)); // set the nr of bones nr_bones = bone_trajs.get(0).length; // cast from dynamic array to standard array return bone_trajs.toArray(new double[bone_trajs.size()][nr_bones][7]); } // timestamp used for deltaT double prev_ts = 0; // if query has a response, return the pose while (cursor.hasNext()) { // get the first document as the next cursor and append the metadata to it BasicDBObject curr_doc = (BasicDBObject) cursor.next(); // get the curr timestamp double curr_ts = curr_doc.getDouble("timestamp"); // if time diff > then deltaT add position to trajectory if (curr_ts - prev_ts > deltaT) { // get the list of bones pos and rot BasicDBList pos_list = (BasicDBList) curr_doc.get("bones_pos"); BasicDBList rot_list = (BasicDBList) curr_doc.get("bones_rot"); // set the nr of bones nr_bones = pos_list.size(); // Poses as dynamic array (dynamic on the nr of bones part) ArrayList<double[]> pose_list = new ArrayList<double[]>(); // pos_list and rot_list length should be always the same for (int i = 0; i < nr_bones; ++i) { pose_list.add(new double[] { ((BasicDBObject) pos_list.get(i)).getDouble("x"), ((BasicDBObject) pos_list.get(i)).getDouble("y"), ((BasicDBObject) pos_list.get(i)).getDouble("z"), ((BasicDBObject) rot_list.get(i)).getDouble("w"), ((BasicDBObject) rot_list.get(i)).getDouble("x"), ((BasicDBObject) rot_list.get(i)).getDouble("y"), ((BasicDBObject) rot_list.get(i)).getDouble("z") }); } // cast from dynamic array to standard array bone_trajs.add(pose_list.toArray(new double[nr_bones][7])); prev_ts = curr_ts; } } // close cursor cursor.close(); // return the actor bones trajectories as float[][][] return bone_trajs.toArray(new double[bone_trajs.size()][nr_bones][7]); }
From source file:org.knowrob.knowrob_sim_games.MongoSimGames.java
License:Open Source License
/** * Query the trajectory of the given model with double timestamps * view as rviz markers/*from w w w . j ava 2 s . co m*/ */ public void ViewModelTrajectory(double start_ts, double end_ts, String model_name, String markerID, String markerType, String color, float scale, double deltaT) { // create the pipeline operations, first with the $match check the times DBObject match_time = new BasicDBObject("$match", new BasicDBObject("timestamp", new BasicDBObject("$gte", start_ts).append("$lte", end_ts))); // $unwind the models DBObject unwind_models = new BasicDBObject("$unwind", "$models"); // $match for the given model name from the unwinded models DBObject match_model = new BasicDBObject("$match", new BasicDBObject("models.name", model_name)); // build the $projection operation DBObject proj_fields = new BasicDBObject("_id", 0); proj_fields.put("timestamp", 1); proj_fields.put("pos", "$models.pos"); proj_fields.put("rot", "$models.rot"); DBObject project = new BasicDBObject("$project", proj_fields); // run aggregation List<DBObject> pipeline = Arrays.asList(match_time, unwind_models, match_model, project); AggregationOptions aggregationOptions = AggregationOptions.builder().batchSize(100) .outputMode(AggregationOptions.OutputMode.CURSOR).allowDiskUse(true).build(); Cursor cursor = this.coll.aggregate(pipeline, aggregationOptions); // Traj as dynamic array ArrayList<Vector3d> traj = new ArrayList<Vector3d>(); // timestamp used for deltaT double prev_ts = 0; // if cursor not empty, append matadata to the first doc if (cursor.hasNext()) { // get the first document as the next cursor BasicDBObject first_doc = (BasicDBObject) cursor.next(); traj.add(new Vector3d(((BasicDBObject) first_doc.get("pos")).getDouble("x"), ((BasicDBObject) first_doc.get("pos")).getDouble("y"), ((BasicDBObject) first_doc.get("pos")).getDouble("z"))); // set the timestamp prev_ts = first_doc.getDouble("timestamp"); } // if query returned no values for these timestamps, get the pose at the nearest timestamp else { // write the pose to the given db and coll this.ViewModelPoseAt(start_ts, model_name, markerID, markerType, color, scale); } // insert rest of trajectory while (cursor.hasNext()) { // get the current document BasicDBObject curr_doc = (BasicDBObject) cursor.next(); double curr_ts = curr_doc.getDouble("timestamp"); // if time diff > then deltaT add position to trajectory if (curr_ts - prev_ts > deltaT) { traj.add(new Vector3d(((BasicDBObject) curr_doc.get("pos")).getDouble("x"), ((BasicDBObject) curr_doc.get("pos")).getDouble("y"), ((BasicDBObject) curr_doc.get("pos")).getDouble("z"))); prev_ts = curr_ts; } } // create the markers this.CreateMarkers(traj, markerID, markerType, color, scale); }
From source file:org.knowrob.knowrob_sim_games.MongoSimGames.java
License:Open Source License
/** * Query the trajectory of the given model with double timestamps * view as rviz markers//from w w w. j a v a 2s .c o m */ public void ViewModelMeshTrajectory(double start_ts, double end_ts, String model_name, String meshPath, String markerID, double deltaT) { // create the pipeline operations, first with the $match check the times DBObject match_time = new BasicDBObject("$match", new BasicDBObject("timestamp", new BasicDBObject("$gte", start_ts).append("$lte", end_ts))); // $unwind the models DBObject unwind_models = new BasicDBObject("$unwind", "$models"); // $match for the given model name from the unwinded models DBObject match_model = new BasicDBObject("$match", new BasicDBObject("models.name", model_name)); // build the $projection operation DBObject proj_fields = new BasicDBObject("_id", 0); proj_fields.put("timestamp", 1); proj_fields.put("pos", "$models.pos"); proj_fields.put("rot", "$models.rot"); DBObject project = new BasicDBObject("$project", proj_fields); // run aggregation List<DBObject> pipeline = Arrays.asList(match_time, unwind_models, match_model, project); AggregationOptions aggregationOptions = AggregationOptions.builder().batchSize(100) .outputMode(AggregationOptions.OutputMode.CURSOR).allowDiskUse(true).build(); Cursor cursor = this.coll.aggregate(pipeline, aggregationOptions); // timestamp used for deltaT double prev_ts = 0; // marker ID suffix int marker_suff = 0; // if cursor not empty, append matadata to the first doc if (cursor.hasNext()) { // get the first document as the next cursor BasicDBObject first_doc = (BasicDBObject) cursor.next(); double[] translation = new double[] { ((BasicDBObject) first_doc.get("pos")).getDouble("x"), ((BasicDBObject) first_doc.get("pos")).getDouble("y"), ((BasicDBObject) first_doc.get("pos")).getDouble("z") }; double[] orientation = this.quatFromEulerRad(((BasicDBObject) first_doc.get("rot")).getDouble("x"), ((BasicDBObject) first_doc.get("rot")).getDouble("y"), ((BasicDBObject) first_doc.get("rot")).getDouble("z")); // create the markers this.CreateMeshMarker(translation, orientation, meshPath, markerID); // set the timestamp prev_ts = first_doc.getDouble("timestamp"); } // if query returned no values for these timestamps, get the pose at the nearest timestamp else { // write the pose to the given db and coll this.ViewModelMeshAt(start_ts, model_name, markerID, meshPath); } // insert rest of trajectory while (cursor.hasNext()) { // get the current document BasicDBObject curr_doc = (BasicDBObject) cursor.next(); double curr_ts = curr_doc.getDouble("timestamp"); // if time diff > then deltaT add position to trajectory if (curr_ts - prev_ts > deltaT) { double[] translation = new double[] { ((BasicDBObject) curr_doc.get("pos")).getDouble("x"), ((BasicDBObject) curr_doc.get("pos")).getDouble("y"), ((BasicDBObject) curr_doc.get("pos")).getDouble("z") }; double[] orientation = this.quatFromEulerRad(((BasicDBObject) curr_doc.get("rot")).getDouble("x"), ((BasicDBObject) curr_doc.get("rot")).getDouble("y"), ((BasicDBObject) curr_doc.get("rot")).getDouble("z")); // create the markers this.CreateMeshMarker(translation, orientation, meshPath, markerID + marker_suff); // update current ts prev_ts = curr_ts; // append to marker suffix marker_suff++; } } }