miguelriemoliveira / simpleBot

BSD 3-Clause "New" or "Revised" License
1 stars 0 forks source link

Problem using functions #3

Open Analtino2021 opened 2 years ago

Analtino2021 commented 2 years ago

good afternoon teacher I'm trying to use a function that can choose the sensor to use from the dataset but it always gives me an error, the function is called by an argparser that I can't understand what it does. here is the argparser

 ap.add_argument("--ssf", "--sensor_selection_function" default=None, type=lambda s: eval(s, globals()),
                    help='A string to be evaluated into a lambda function that receives a collection name as input and '
                         'returns True or False to indicate if the collection should be loaded (and used in the '
                         'optimization). The Syntax is lambda name: f(x), where f(x) is the function in python '
                         'language. Example: lambda name: int(name) > 5 , to load only collections 6, 7, and onward.')

and here is the function thath i'm traing to call


  def filterSensorsFromDataset(dataset, args):
      """
      Filters some sensors from the dataset, using a couple of arguments in arg
      :param dataset:
      :param args: Makes use of 'sensor_selection_function'
      """

      if not args['sensor_selection_function'] is None:
          deleted = []
          for sensor_key in dataset['sensors']:
              if not args['sensor_selection_function'](sensor_key):  # use the lambda expression ssf
                  deleted.append(sensor_key)

          for sensor_key in deleted:
              del dataset['sensors'][sensor_key]

          print("Deleted sensors: " + str(deleted))

      if not dataset['sensors'].keys():
          raise ValueError('No sensors were selected. Cannot optimize without sensors. Please revise your '
                           'dataset and your sensor selection function.')

      return dataset

in this my code:

#!/usr/bin/env python3
import argparse
from json_reader import *
import os, math, signal, sys
import cv2
import numpy as np

# 3rd-party
import rospy, tf
from colorama import Fore, Style, Back
from urdf_parser_py.urdf import URDF

from atom_core.dataset_io import loadResultsJSON, saveResultsJSON, \
    getPointCloudMessageFromDictionary, filterCollectionsFromDataset, filterSensorsFromDataset, \
    addNoiseToInitialGuess

# -------------------------------------------------------------------------------
# --- MAIN
# -------------------------------------------------------------------------------
def main():
    ap = argparse.ArgumentParser()
    # ap = OptimizationUtils.addArguments(ap)  # OptimizationUtils arguments
    ap.add_argument("-json", "--json_file", help="Json file containing input dataset.", type=str, required=True)
    ap.add_argument("-csf", "--collection_selection_function", default=None, type=lambda s: eval(s, globals()),
                    help='A string to be evaluated into a lambda function that receives a collection name as input and '
                         'returns True or False to indicate if the collection should be loaded (and used in the '
                         'optimization). The Syntax is lambda name: f(x), where f(x) is the function in python '
                         'language. Example: lambda name: int(name) > 5 , to load only collections 6, 7, and onward.')
    ap.add_argument("--ssf", "--sensor_selection_function",  default=None, type=lambda s: eval(s, globals()), help='A')

    # Roslaunch adds two arguments (__name and __log) that break our parser. Lets remove those.
    arglist = [x for x in sys.argv[1:] if not x.startswith('__')]
    args = vars(ap.parse_args(args=arglist))

    # ---------------------------------------
    # --- INITIALIZATION Read data from file
    # ---------------------------------------
    # Loads a json file containing the detections. Returned json_file has path resolved by urireader.

    dataset, json_file = loadResultsJSON(args['json_file'], args['collection_selection_function'])
    print(dataset)
    print(dataset['sensors'].keys())
    # ---------------------------------------
    # --- Filter some collections and / or sensors from the dataset
    # ---------------------------------------
    filterSensorsFromDataset(dataset, args) # filter sensors

    print('')
    print(dataset)
    print('')
    print(dataset["collections"].keys())
    print('')
    print(dataset['sensors'].keys())
    print('')
    print(args['sensor_selection_function'])

    # models = dataset
    # args = models['args']
    # collections = models['dataset']['collections']

if __name__ == "__main__":
    main()

but it keeps giving me the folowing error: novo

and i already verifid that the kee exists manking:

    print(dataset['sensors'].keys())

and the result was:

dict_keys(['left_camera', 'lidar3d'])
miguelriemoliveira commented 2 years ago

Hi,

This is a better way to write an issue:

The problem is here:

https://github.com/miguelriemoliveira/simpleBot/blob/16de3010a43101dbcb0d02ccd2ca9c62012f4c7c/simplebot_bringup/launch/bringup.launch#L9-L22

This is my code:

  # ---------------------------------------
    # --- INITIALIZATION Read data from file
    # ---------------------------------------
    # Loads a json file containing the detections. Returned json_file has path resolved by urireader.
    dataset, json_file = loadResultsJSON(args['json_file'], args['collection_selection_function'])

    # ---------------------------------------
    # --- Filter some collections and / or sensors from the dataset
    # ---------------------------------------
    dataset = filterCollectionsFromDataset(dataset, args)  # filter collections

When I run the code with:

roslaunch mmtbot_calibration playbag.launch

The result is:

... logging to /home/mike/.ros/log/10c50ae0-5a92-11ec-97fb-1bc17e6b9bb3/roslaunch-ZB-33309.log
Checking log directory for disk usage. This may take a while.
Press Ctrl-C to interrupt
WARNING: disk usage in log directory [/home/mike/.ros/log] is over 1GB.
It's recommended that you use the 'rosclean' command.

Using load_yaml() directly is deprecated. Use xacro.load_yaml() instead.
Using load_yaml() directly is deprecated. Use xacro.load_yaml() instead.
Using load_yaml() directly is deprecated. Use xacro.load_yaml() instead.
Using load_yaml() directly is deprecated. Use xacro.load_yaml() instead.
started roslaunch server http://ZB:42353/

SUMMARY
========

PARAMETERS
 * /robot_description: <?xml version="1....
 * /rosdistro: noetic
 * /rosversion: 1.15.13
 * /use_sim_time: True

NODES
  /
    robot_state_publisher (robot_state_publisher/robot_state_publisher)
    rosbag_play (rosbag/play)
    rviz (rviz/rviz)

auto-starting new master
process[master]: started with pid [33387]
ROS_MASTER_URI=http://localhost:11311

setting /run_id to 10c50ae0-5a92-11ec-97fb-1bc17e6b9bb3
process[rosout-1]: started with pid [33431]
started core service [/rosout]
process[robot_state_publisher-2]: started with pid [33434]
process[rosbag_play-3]: started with pid [33438]
process[rviz-4]: started with pid [33440]
[ INFO] [1639234394.697254763]: Opening /home/mike/bagfiles/mmtbot/test_rgbd.bag

Waiting 2 seconds after advertising topics...qt5ct: using qt5ct plugin
qt5ct: D-Bus global menu: no
 done.

Hit space to toggle paused, or 's' to step.
[rviz-4] killing on exit 744.147861   Duration: 2.369861 / 11.654000               
[rosbag_play-3] killing on exit
[robot_state_publisher-2] killing on exit
 [RUNNING]  Bag Time:    744.433077   Duration: 2.655077 / 11.654000               
[rosout-1] killing on exit
[master] killing on exit
shutting down processing monitor...
... shutting down processing monitor complete