repo_id
stringlengths 19
138
| file_path
stringlengths 32
200
| content
stringlengths 1
12.9M
| __index_level_0__
int64 0
0
|
|---|---|---|---|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/rosbag/dump_gpsbin.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2018 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
"""
This program can extract raw gpsbin from rosbag directory into /tmp/gpsimu.bin.
dump_gpsbin.py rosbag_input_directory output_file
"""
import argparse
import glob
import os
import shutil
from cyber.python.cyber_py3 import cyber
from cyber.python.cyber_py3.record import RecordReader
from modules.common_msgs.sensor_msgs import gnss_pb2
g_args = None
kRawDataTopic = '/apollo/sensor/gnss/raw_data'
def dump_bag(in_dir, out_file):
"""
out_bag = in_bag
"""
print('Begin')
gnss = gnss_pb2.RawData()
global g_args
bag_files = glob.glob(in_dir + "/*.record.*")
with open(out_file, 'w') as fp:
for bag_file in sorted(bag_files):
print('Processing bag_file: %s' % bag_file)
reader = RecordReader(bag_file)
for msg in reader.read_messages():
if msg.topic == kRawDataTopic:
gnss.ParseFromString(msg.message)
f.write(str(gnss))
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description="A tool to dump gpsimu raw data")
parser.add_argument(
"in_dir", action="store", type=str, help="the input bag directory")
parser.add_argument(
"out_file", action="store", type=str, help="the output file")
g_args = parser.parse_args()
dump_bag(g_args.in_dir, g_args.out_file)
print("{} is generated".format(g_args.out_file))
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/rosbag/body_sensation_evaluation.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2018 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
"""
Usage:
python body_sensation_evalution.py bag1 bag2 ...
"""
import argparse
import collections
import math
import sys
import time
from cyber.python.cyber_py3 import cyber
from cyber.python.cyber_py3.record import RecordReader
from modules.common_msgs.chassis_msgs import chassis_pb2
from modules.common_msgs.chassis_msgs.chassis_pb2 import Chassis
from modules.common_msgs.localization_msgs import localization_pb2
BUMP_TIME_THRESHOLD = 3
ACCELERATE_TIME_THRESHOLD = 1
SPEED_UP_THRESHOLD_2 = 2
SPEED_UP_THRESHOLD_4 = 4
SPEED_DOWN_THRESHOLD_2 = -2
SPEED_DOWN_THRESHOLD_4 = -4
kChassisTopic = '/apollo/canbus/chassis'
kLocalizationTopic = '/apollo/localization/pose'
class BodySensationCalculator(object):
"""The class to dispose body sensation from rosbag"""
def __init__(self):
self.driving_mode = []
self._timestamp = 0.0
self._last_bump_time = 0.0
self._last_speed_down_2_time = 0.0
self._last_speed_down_4_time = 0.0
self._last_speed_up_2_time = 0.0
self._last_speed_up_4_time = 0.0
self._last_turning_time = 0.0
self._speed_down_2_flag = 0
self._speed_down_4_flag = 0
self._speed_up_2_flag = 0
self._speed_up_4_flag = 0
self._turning_flag = 0
self.auto_counts = {}
self.auto_counts["speed_down_2"] = 0
self.auto_counts["speed_down_4"] = 0
self.auto_counts["speed_up_2"] = 0
self.auto_counts["speed_up_4"] = 0
self.auto_counts["turning"] = 0
self.auto_counts["bumps"] = 0
self.manual_counts = {}
self.manual_counts["speed_down_2"] = 0
self.manual_counts["speed_down_4"] = 0
self.manual_counts["speed_up_2"] = 0
self.manual_counts["speed_up_4"] = 0
self.manual_counts["turning"] = 0
self.manual_counts["bumps"] = 0
def get_driving_mode(self, bag_file):
"""get driving mode, which is stored in a dict"""
mode = {}
mode["status"] = 'UNKNOW'
mode["start_time"] = 0.0
mode["end_time"] = 0.0
chassis = chassis_pb2.Chassis()
reader = RecordReader(bag_file)
for msg in reader.read_messages():
if msg.topic == kChassisTopic:
chassis.ParseFromString(msg.message)
_t = msg.timestamp
t = int(str(_t)) * pow(10, -9)
cur_status = chassis.driving_mode
if mode["status"] != cur_status:
if mode["status"] != 'UNKNOW':
self.driving_mode.append(mode)
mode["status"] = cur_status
mode["start_time"] = t
mode["end_time"] = t
self.driving_mode.append(mode)
def _check_status(self, timestamp):
"""check driving mode according to timestamp"""
for mode in self.driving_mode:
if timestamp >= mode["start_time"] and timestamp <= mode["end_time"]:
if mode["status"] == Chassis.COMPLETE_AUTO_DRIVE:
return True
else:
return False
return False
def _bumps_rollback(self, bump_time):
"""rollback 1 second when passing bumps"""
if bump_time - self._last_speed_down_2_time <= ACCELERATE_TIME_THRESHOLD:
if self._check_status(self._last_speed_down_2_time):
self.auto_counts["speed_down_2"] -= 1
else:
self.manual_counts["speed_down_2"] -= 1
if bump_time - self._last_speed_up_2_time <= ACCELERATE_TIME_THRESHOLD:
if self._check_status(self._last_speed_up_2_time):
self.auto_counts["speed_up_2"] -= 1
else:
self.manual_counts["speed_up_2"] -= 1
if bump_time - self._last_speed_down_4_time <= ACCELERATE_TIME_THRESHOLD:
if self._check_status(self._last_speed_down_4_time):
self.auto_counts["speed_down_4"] -= 1
else:
self.manual_counts["speed_down_4"] -= 1
if bump_time - self._last_speed_up_4_time <= ACCELERATE_TIME_THRESHOLD:
if self._check_status(self._last_speed_up_4_time):
self.auto_counts["speed_up_4"] -= 1
else:
self.manual_counts["speed_up_4"] -= 1
if bump_time - self._last_turning_time <= ACCELERATE_TIME_THRESHOLD:
if self._check_status(self._last_turning_time):
self.auto_counts["turning"] -= 1
else:
self.manual_counts["turning"] -= 1
def calculate(self, bag_file):
"""calculate body sensation, it should be after get driving mode"""
localization = localization_pb2.LocalizationEstimate()
reader = RecordReader(bag_file)
for msg in reader.read_messages():
if msg.topic == kLocalizationTopic:
localization.ParseFromString(msg.message)
_t = msg.timestamp
t = int(str(_t)) * pow(10, -9)
self.timestamp = t
diff_bump_time = t - self._last_bump_time
if diff_bump_time <= BUMP_TIME_THRESHOLD:
continue
acc_x = localization.pose.linear_acceleration.x
acc_y = localization.pose.linear_acceleration.y
acc_z = localization.pose.linear_acceleration.z
if abs(acc_z) >= SPEED_UP_THRESHOLD_2 and diff_bump_time >= BUMP_TIME_THRESHOLD:
self._bumps_rollback(t)
self._last_bump_time = t
if self._check_status(t):
self.auto_counts["bumps"] += 1
else:
self.manual_counts["bumps"] += 1
else:
if self._speed_down_2_flag:
if acc_y <= SPEED_DOWN_THRESHOLD_4:
self._speed_down_4_flag = 1
continue
if acc_y <= SPEED_DOWN_THRESHOLD_2:
continue
if self._speed_down_4_flag == 1 \
and t - self._last_speed_down_4_time >= ACCELERATE_TIME_THRESHOLD:
self._last_speed_down_4_time = t
if self._check_status(t):
self.auto_counts["speed_down_4"] += 1
else:
self.manual_counts["speed_down_4"] += 1
elif t - self._last_speed_down_2_time >= ACCELERATE_TIME_THRESHOLD:
self._last_speed_down_2_time = t
if self._check_status(t):
self.auto_counts["speed_down_2"] += 1
else:
self.manual_counts["speed_down_2"] += 1
self._speed_down_2_flag = 0
self._speed_down_4_flag = 0
elif acc_y <= SPEED_DOWN_THRESHOLD_2:
self._speed_down_2_flag = 1
if self._speed_up_2_flag:
if acc_y >= SPEED_UP_THRESHOLD_4:
self._speed_up_4_flag = 1
continue
if acc_y >= SPEED_UP_THRESHOLD_2:
continue
if self._speed_up_4_flag == 1 \
and t - self._last_speed_up_4_time >= ACCELERATE_TIME_THRESHOLD:
self._last_speed_up_4_time = t
if self._check_status(t):
self.auto_counts["speed_up_4"] += 1
else:
self.manual_counts["speed_up_4"] += 1
elif t - self._last_speed_up_2_time >= ACCELERATE_TIME_THRESHOLD:
self._last_speed_up_2_time = t
if self._check_status(t):
self.auto_counts["speed_up_2"] += 1
else:
self.manual_counts["speed_up_2"] += 1
self._speed_up_2_flag = 0
self._speed_up_4_flag = 0
elif acc_y >= SPEED_UP_THRESHOLD_2:
self._speed_up_2_flag = 1
if self._turning_flag:
if abs(acc_x) >= SPEED_UP_THRESHOLD_2:
continue
if t - self._last_turning_time >= ACCELERATE_TIME_THRESHOLD:
self._last_turning_time = t
if self._check_status(t):
self.auto_counts["turning"] += 1
else:
self.manual_counts["turning"] += 1
self._turning_flag = 0
elif abs(acc_x) >= SPEED_UP_THRESHOLD_2:
self._turning_flag = 1
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description="A tool to evaluate the body sensation. \
It should be used like 'python body_sensation_evalution.py bag1 bag2 ...' ")
parser.add_argument(
"in_rosbag", action="store", nargs='+', type=str, help="the input rosbag")
args = parser.parse_args()
bsc = BodySensationCalculator()
for bag_file in args.in_rosbag:
bsc.get_driving_mode(bag_file)
for bag_file in args.in_rosbag:
bsc.calculate(bag_file)
counts = {}
counts["auto"] = sorted(bsc.auto_counts.items())
counts["manual"] = sorted(bsc.manual_counts.items())
print(counts)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/rosbag/BUILD
|
load("@rules_python//python:defs.bzl", "py_binary")
load("//tools/install:install.bzl", "install")
package(default_visibility = ["//visibility:public"])
install(
name = "install",
py_dest = "tools/rosbag",
targets = [
":audio_event_record",
":body_sensation_evaluation",
":channel_size_stats",
":drive_event",
":dump_gpsbin",
":dump_planning",
":dump_record",
":dump_road_test_log",
":extract_trajectory",
":sample_pnc_topics",
":stat_mileage",
":stat_static_info",
":tf_stats",
":transcribe",
],
)
py_binary(
name = "audio_event_record",
srcs = ["audio_event_record.py"],
deps = [
"//cyber/python/cyber_py3:cyber",
"//cyber/python/cyber_py3:cyber_time",
"//modules/tools/common:message_manager",
"//modules/tools/common:proto_utils",
],
)
py_binary(
name = "body_sensation_evaluation",
srcs = ["body_sensation_evaluation.py"],
deps = [
"//cyber/python/cyber_py3:cyber",
"//cyber/python/cyber_py3:record",
"//modules/common_msgs/chassis_msgs:chassis_py_pb2",
"//modules/common_msgs/localization_msgs:localization_py_pb2",
],
)
py_binary(
name = "channel_size_stats",
srcs = ["channel_size_stats.py"],
deps = [
"//cyber/python/cyber_py3:cyber",
"//cyber/python/cyber_py3:record",
"//modules/common_msgs/planning_msgs:planning_py_pb2",
],
)
py_binary(
name = "drive_event",
srcs = ["drive_event.py"],
deps = [
"//cyber/python/cyber_py3:cyber",
"//cyber/python/cyber_py3:cyber_time",
"//modules/tools/common:message_manager",
"//modules/tools/common:proto_utils",
],
)
py_binary(
name = "dump_gpsbin",
srcs = ["dump_gpsbin.py"],
deps = [
"//cyber/python/cyber_py3:cyber",
"//cyber/python/cyber_py3:record",
"//modules/common_msgs/sensor_msgs:gnss_py_pb2",
],
)
py_binary(
name = "dump_planning",
srcs = ["dump_planning.py"],
deps = [
"//cyber/python/cyber_py3:record",
],
)
py_binary(
name = "dump_record",
srcs = ["dump_record.py"],
deps = [
"//cyber/python/cyber_py3:cyber",
"//cyber/python/cyber_py3:record",
"//modules/tools/common:message_manager",
],
)
py_binary(
name = "dump_road_test_log",
srcs = ["dump_road_test_log.py"],
deps = [
"//cyber/python/cyber_py3:cyber",
"//cyber/python/cyber_py3:record",
"//modules/common_msgs/basic_msgs:drive_event_py_pb2",
],
)
py_binary(
name = "extract_trajectory",
srcs = ["extract_trajectory.py"],
deps = [
"//cyber/python/cyber_py3:cyber",
"//cyber/python/cyber_py3:record",
"//modules/tools/common:message_manager",
],
)
py_binary(
name = "sample_pnc_topics",
srcs = ["sample_pnc_topics.py"],
deps = [
"//cyber/python/cyber_py3:cyber",
"//cyber/python/cyber_py3:record",
"//modules/common_msgs/chassis_msgs:chassis_py_pb2",
"//modules/common_msgs/localization_msgs:localization_py_pb2",
],
)
py_binary(
name = "stat_mileage",
srcs = ["stat_mileage.py"],
deps = [
"//cyber/python/cyber_py3:cyber",
"//cyber/python/cyber_py3:record",
"//modules/common_msgs/chassis_msgs:chassis_py_pb2",
"//modules/common_msgs/localization_msgs:localization_py_pb2",
],
)
py_binary(
name = "stat_static_info",
srcs = ["stat_static_info.py"],
deps = [
"//cyber/python/cyber_py3:cyber",
"//cyber/python/cyber_py3:record",
"//modules/common_msgs/chassis_msgs:chassis_py_pb2",
"//modules/common_msgs/dreamview_msgs:hmi_status_py_pb2",
],
)
py_binary(
name = "tf_stats",
srcs = ["tf_stats.py"],
deps = [
"//cyber/python/cyber_py3:record",
"//modules/common_msgs/transform_msgs:transform_py_pb2",
],
)
py_binary(
name = "transcribe",
srcs = ["transcribe.py"],
deps = [
"//cyber/python/cyber_py3:cyber",
"//modules/tools/common:message_manager",
"//modules/tools/common:proto_utils",
],
)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/rosbag/stat_mileage.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
"""
Stat disengagements and auto/manual driving mileage.
Usage:
./stat_mileage.py bag1 bag2 ...
"""
import collections
import math
import sys
from cyber.python.cyber_py3 import cyber
from cyber.python.cyber_py3.record import RecordReader
from modules.common_msgs.chassis_msgs import chassis_pb2
from modules.common_msgs.chassis_msgs.chassis_pb2 import Chassis
from modules.common_msgs.localization_msgs import localization_pb2
kChassisTopic = '/apollo/canbus/chassis'
kLocalizationTopic = '/apollo/localization/pose'
class MileageCalculator(object):
"""
Calculate mileage
"""
def __init__(self):
"""Init."""
self.auto_mileage = 0.0
self.manual_mileage = 0.0
self.disengagements = 0
def calculate(self, bag_file):
"""
Calculate mileage
"""
last_pos = None
last_mode = 'Unknown'
mileage = collections.defaultdict(lambda: 0.0)
chassis = chassis_pb2.Chassis()
localization = localization_pb2.LocalizationEstimate()
reader = RecordReader(bag_file)
for msg in reader.read_messages():
if msg.topic == kChassisTopic:
chassis.ParseFromString(msg.message)
# Mode changed
if last_mode != chassis.driving_mode:
if (last_mode == Chassis.COMPLETE_AUTO_DRIVE and
chassis.driving_mode == Chassis.EMERGENCY_MODE):
self.disengagements += 1
last_mode = chassis.driving_mode
# Reset start position.
last_pos = None
elif msg.topic == kLocalizationTopic:
localization.ParseFromString(msg.message)
cur_pos = localization.pose.position
if last_pos:
# Accumulate mileage, from xyz-distance to miles.
mileage[last_mode] += 0.000621371 * math.sqrt(
(cur_pos.x - last_pos.x) ** 2 +
(cur_pos.y - last_pos.y) ** 2 +
(cur_pos.z - last_pos.z) ** 2)
last_pos = cur_pos
self.auto_mileage += mileage[Chassis.COMPLETE_AUTO_DRIVE]
self.manual_mileage += (mileage[Chassis.COMPLETE_MANUAL] +
mileage[Chassis.EMERGENCY_MODE])
def main():
if len(sys.argv) < 2:
print('Usage: %s [Bag_file1] [Bag_file2] ...' % sys.argv[0])
sys.exit(0)
mc = MileageCalculator()
for bag_file in sys.argv[1:]:
mc.calculate(bag_file)
print('Disengagements: %d' % mc.disengagements)
print('Auto mileage: %.3f km / %.3f miles' %
(mc.auto_mileage * 1.60934, mc.auto_mileage))
print('Manual mileage: %.3f km / %.3f miles' %
(mc.manual_mileage * 1.60934, mc.manual_mileage))
if __name__ == '__main__':
main()
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/rosbag/tf_stats.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2019 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
"""
This program can dump tf2 stats
usage:
tf_stats -f record_file
"""
import argparse
from cyber.python.cyber_py3.record import RecordReader
from modules.common_msgs.transform_msgs import transform_pb2
g_args = None
def tf_stats(in_bag):
"""
"""
reader = RecordReader(in_bag)
global g_args
stats = {}
for channel, message, _type, _timestamp in reader.read_messages():
if channel != '/tf':
continue
tf_pb = transform_pb2.TransformStampeds()
tf_pb.ParseFromString(message)
for transform in tf_pb.transforms:
key = transform.header.frame_id + "=>" + transform.child_frame_id
if key in stats.keys():
stats[key] += 1
else:
stats[key] = 1
print('tf stats: {}'.format(stats))
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description="A tool to print tf stats")
parser.add_argument(
"-f", action="store", type=str, help="the input data file")
g_args = parser.parse_args()
tf_stats(g_args.f)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/rosbag/stat_static_info.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
"""
Stat static info.
Usage:
./stat_static_info.py <record_file>
./stat_static_info.py <task_dir> # <task_dir> contains a list of records.
"""
import os
import sys
from cyber.python.cyber_py3 import cyber
from cyber.python.cyber_py3.record import RecordReader
from modules.common_msgs.chassis_msgs import chassis_pb2
from modules.common_msgs.dreamview_msgs import hmi_status_pb2
kChassisInfoTopic = '/apollo/canbus/chassis'
kHMIInfoTopic = '/apollo/hmi/status'
class StaticInfoCalculator(object):
"""
Stat static information
"""
def __init__(self):
self.vehicle_name = None
self.vehicle_vin = None
def process_file(self, record_file):
"""
Extract information from record file.
Return True if we are done collecting all information.
"""
try:
reader = RecordReader(record_file)
print("Begin to process record file {}".format(record_file))
for msg in reader.read_messages():
print(msg.topic)
if msg.topic == kChassisInfoTopic and self.vehicle_vin is None:
chassis = chassis_pb2.Chassis()
chassis.ParseFromString(msg.message)
if chassis.license.vin:
self.vehicle_vin = chassis.license.vin
elif msg.topic == kHMIInfoTopic and self.vehicle_name is None:
hmistatus = hmi_status_pb2.HMIStatus()
hmistatus.ParseFromString(msg.message)
if hmistatus.current_map:
self.vehicle_name = hmistatus.current_map
print(self.vehicle_name)
if self.done():
return True
except:
return False
print("Finished processing record file {}".format(record_file))
return self.done()
def process_dir(self, record_dir):
"""
Process a directory
"""
files = []
dirs = []
for f in os.listdir(record_dir):
f_path = os.path.join(record_dir, f)
if os.path.isfile(f_path):
files.append(f_path)
elif os.path.isdir(f_path):
dirs.append(f_path)
# Ignore links.
# Reverse sort the records or dirs, trying to get info from the latest.
for record in sorted(files, reverse=True):
if self.process_file(record):
return True
for subdir in sorted(dirs, reverse=True):
if self.process_dir(subdir):
return True
return False
def done(self):
"""
Check if all info are collected
"""
# Currently we only care about vehicle name.
return bool(self.vehicle_name)
def main():
"""
Process a path
"""
if len(sys.argv) < 2:
print("Usage: %s <record_file|task_dir>" % sys.argv[0])
sys.exit(0)
path = sys.argv[1]
calc = StaticInfoCalculator()
if os.path.isfile(path):
calc.process_file(path)
else:
calc.process_dir(path)
# Output result, which might be None
print('vehicle_name: %s' % calc.vehicle_name)
print('vehicle_vin: %s' % calc.vehicle_vin)
if __name__ == '__main__':
main()
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/rosbag/extract_trajectory.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2018 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
"""
This program can extract driving trajectory from a record
"""
import argparse
import os
import shutil
import sys
import time
from cyber.python.cyber_py3 import cyber
from cyber.python.cyber_py3 import record
from modules.tools.common.message_manager import PbMessageManager
g_message_manager = PbMessageManager()
def write_to_file(file_path, topic_pb):
"""
write pb message to file
"""
with open(file_path, 'w') as fp:
fp.write(str(topic_pb))
def extract_record(in_record, output):
freader = record.RecordReader(in_record)
print("begin to extract from record {}".format(in_record))
time.sleep(1)
seq = 0
localization_topic = '/apollo/localization/pose'
meta_msg = g_message_manager.get_msg_meta_by_topic(localization_topic)
localization_type = meta_msg.msg_type
for channelname, msg_data, datatype, timestamp in freader.read_messages():
topic = channelname
if topic != localization_topic:
continue
msg = localization_type()
msg.ParseFromString(msg_data)
pose = msg.pose
output.write("%s %s %s %s %s %s %s %s\n" %
(msg.measurement_time, pose.position.x, pose.position.y,
pose.position.z, pose.orientation.qx,
pose.orientation.qy, pose.orientation.qz,
pose.orientation.qw))
print("Finished extracting from record {}".format(in_record))
def main(args):
out = open(args.output, 'w') if args.output or sys.stdout
for record_file in args.in_record:
extract_record(record_file, out)
out.close()
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description="A tool to dump the localization messages for map team"
"Usage: python extract_trajectory.py bag1 bag2 --output output.txt")
parser.add_argument(
"in_record",
action="store",
nargs='+',
type=str,
help="the input cyber record(s)")
parser.add_argument(
"--output",
action="store",
type=str,
help="the output file, default is stdout")
args = parser.parse_args()
main(args)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/plot_control/realtime_test.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
"""Real Time ACC Calculate Test Tool Based on Speed"""
import argparse
import datetime
import os
import sys
from cyber.python.cyber_py3 import cyber
from modules.common_msgs.chassis_msgs import chassis_pb2
from modules.common_msgs.localization_msgs import localization_pb2
SmoothParam = 9
class RealTimeTest(object):
def __init__(self):
self.last_t = None
self.last_speed = None
self.last_acc = None
self.acc = None
self.accs = []
self.buff = []
self.count = 0
self.acclimit = 0
def chassis_callback(self, chassis_pb2):
"""Calculate ACC from Chassis Speed"""
speedmps = chassis_pb2.speed_mps
t = chassis_pb2.header.timestamp_sec
#speedkmh = speedmps * 3.6
self.buff.append(speedmps)
if len(self.buff) < SmoothParam:
return
if self.last_t is not None:
self.count += 1
deltt = t - self.last_t
deltv = sum(self.buff) / len(self.buff) - self.last_speed
if deltt <= 1e-10:
deltt = 0.000000000001
print("delt=0 ", t, ",", self.last_t)
self.acc = deltv / deltt
self.accs.append(self.acc)
if abs(self.acc) > self.acclimit:
print(t, "\t", (sum(self.buff) / len(self.buff)) * 3.6, "\t",
self.acc, "\t", self.count, "\t", self.acclimit)
self.last_acc = self.acc
self.last_t = t
self.last_speed = sum(self.buff) / len(self.buff)
self.buff = []
if __name__ == '__main__':
"""Main function"""
parser = argparse.ArgumentParser(
description="Test car realtime status.",
prog="RealTimeTest.py",
usage="python realtime_test.py")
parser.add_argument(
"--acc",
type=int,
required=False,
default=2,
help="Acc limit default must > 0")
args = parser.parse_args()
if args.acc < 0:
print("acc must larger than 0")
cyber.init()
rttest = RealTimeTest()
rttest.acclimit = args.acc
cyber_node = cyber.Node("RealTimeTest")
cyber_node.create_reader("/apollo/canbus/chassis",
chassis_pb2.Chassis, rttest.chassis_callback)
cyber_node.spin()
cyber.shutdown()
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/plot_control/run.sh
|
#!/usr/bin/env bash
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
TOP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd -P)"
source "${TOP_DIR}/scripts/apollo_base.sh"
eval "${TOP_DIR}/bazel-bin/modules/tools/plot_control/plot_control $1"
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/plot_control/plot_control.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
import sys
import gflags
from cyber.python.cyber_py3 import cyber
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from modules.common_msgs.control_msgs import control_cmd_pb2
BRAKE_LINE_DATA = []
TROTTLE_LINE_DATA = []
STEERING_LINE_DATA = []
FLAGS = gflags.FLAGS
gflags.DEFINE_integer("data_length", 500, "Control plot data length")
def callback(control_cmd_pb):
global STEERING_LINE_DATA
global TROTTLE_LINE_DATA, BRAKE_LINE_DATA
STEERING_LINE_DATA.append(control_cmd_pb.steering_target)
if len(STEERING_LINE_DATA) > FLAGS.data_length:
STEERING_LINE_DATA = STEERING_LINE_DATA[-FLAGS.data_length:]
BRAKE_LINE_DATA.append(control_cmd_pb.brake)
if len(BRAKE_LINE_DATA) > FLAGS.data_length:
BRAKE_LINE_DATA = BRAKE_LINE_DATA[-FLAGS.data_length:]
TROTTLE_LINE_DATA.append(control_cmd_pb.throttle)
if len(TROTTLE_LINE_DATA) > FLAGS.data_length:
TROTTLE_LINE_DATA = TROTTLE_LINE_DATA[-FLAGS.data_length:]
def listener():
cyber.init()
test_node = cyber.Node("control_listener")
test_node.create_reader("/apollo/control",
control_cmd_pb2.ControlCommand, callback)
test_node.spin()
cyber.shutdown()
def compensate(data_list):
comp_data = [0] * FLAGS.data_length
comp_data.extend(data_list)
if len(comp_data) > FLAGS.data_length:
comp_data = comp_data[-FLAGS.data_length:]
return comp_data
def update(frame_number):
brake_data = compensate(BRAKE_LINE_DATA)
brake_line.set_ydata(brake_data)
throttle_data = compensate(TROTTLE_LINE_DATA)
throttle_line.set_ydata(throttle_data)
steering_data = compensate(STEERING_LINE_DATA)
steering_line.set_ydata(steering_data)
brake_text.set_text('brake = %.1f' % brake_data[-1])
throttle_text.set_text('throttle = %.1f' % throttle_data[-1])
steering_text.set_text('steering = %.1f' % steering_data[-1])
if __name__ == '__main__':
argv = FLAGS(sys.argv)
listener()
fig, ax = plt.subplots()
X = range(FLAGS.data_length)
Xs = [i * -1 for i in X]
Xs.sort()
steering_line, = ax.plot(
Xs, [0] * FLAGS.data_length, 'b', lw=3, alpha=0.5, label='steering')
throttle_line, = ax.plot(
Xs, [0] * FLAGS.data_length, 'g', lw=3, alpha=0.5, label='throttle')
brake_line, = ax.plot(
Xs, [0] * FLAGS.data_length, 'r', lw=3, alpha=0.5, label='brake')
brake_text = ax.text(0.75, 0.85, '', transform=ax.transAxes)
throttle_text = ax.text(0.75, 0.90, '', transform=ax.transAxes)
steering_text = ax.text(0.75, 0.95, '', transform=ax.transAxes)
ani = animation.FuncAnimation(fig, update, interval=100)
ax.set_ylim(-100, 120)
ax.set_xlim(-1 * FLAGS.data_length, 10)
ax.legend(loc="upper left")
plt.show()
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/plot_control/BUILD
|
load("@rules_python//python:defs.bzl", "py_binary")
load("//tools/install:install.bzl", "install")
package(default_visibility = ["//visibility:public"])
py_binary(
name = "plot_control",
srcs = ["plot_control.py"],
deps = [
"//cyber/python/cyber_py3:cyber",
"//modules/common_msgs/control_msgs:control_cmd_py_pb2",
],
)
py_binary(
name = "realtime_test",
srcs = ["realtime_test.py"],
deps = [
"//cyber/python/cyber_py3:cyber",
"//modules/common_msgs/chassis_msgs:chassis_py_pb2",
"//modules/common_msgs/localization_msgs:localization_py_pb2",
],
)
install(
name = "install",
py_dest = "tools/plot_control",
targets = [
":plot_control",
":realtime_test"
]
)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/mobileye_viewer/view_subplot.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
import math
class ViewSubplot:
def __init__(self, ax):
# self.ax = ax
self.right_lane, = ax.plot(
[-10, 10, -10, 10], [-10, 150, 150, -10],
'bo', lw=3, alpha=0.4)
self.left_lane, = ax.plot(
[0], [0], 'go', lw=3, alpha=0.5)
self.obstacles, = ax.plot(
[0], [0], 'r.', ms=20, alpha=0.5)
self.ref_lane, = ax.plot(
[0], [0], 'k--', lw=3, alpha=0.8)
self.vehicle = ax.plot(
[-1.055, 1.055, 1.055, -1.055, -1.055], [0, 0, -4.933, -4.933, 0],
'r-', lw=1)
self.routing, = ax.plot(
[0], [0], 'r--', lw=3, alpha=0.8)
self.speed_line, = ax.plot([0], [0], 'r-', lw=3, alpha=0.4)
self.acc_line, = ax.plot([0], [0], 'y-', lw=3, alpha=1)
ax.set_xlim([-10, 10])
ax.set_ylim([-10, 100])
ax.relim()
ax.set_xlabel("lat(m)")
self.next_lanes = []
for i in range(8):
lane, = ax.plot([0], [0], 'b-', lw=3, alpha=0.4)
self.next_lanes.append(lane)
self.left_lane.set_visible(False)
self.right_lane.set_visible(False)
self.ref_lane.set_visible(False)
def show(self, mobileye_data, localization_data, planning_data,
chassis_data, routing_data):
self.left_lane.set_visible(True)
self.right_lane.set_visible(True)
self.ref_lane.set_visible(True)
mobileye_data.lane_data_lock.acquire()
self.right_lane.set_xdata(mobileye_data.right_lane_x)
self.right_lane.set_ydata(mobileye_data.right_lane_y)
self.left_lane.set_xdata(mobileye_data.left_lane_x)
self.left_lane.set_ydata(mobileye_data.left_lane_y)
mobileye_data.lane_data_lock.release()
planning_data.path_lock.acquire()
self.ref_lane.set_xdata(planning_data.path_x)
self.ref_lane.set_ydata(planning_data.path_y)
planning_data.path_lock.release()
if chassis_data.is_auto():
self.ref_lane.set_color('r')
else:
self.ref_lane.set_color('k')
mobileye_data.obstacle_data_lock.acquire()
self.obstacles.set_ydata(mobileye_data.obstacle_x)
self.obstacles.set_xdata(mobileye_data.obstacle_y)
mobileye_data.obstacle_data_lock.release()
mobileye_data.next_lane_data_lock.acquire()
for i in range(len(mobileye_data.next_lanes_x)):
if i >= len(self.next_lanes):
mobileye_data.next_lane_data_lock.release()
break
self.next_lanes[i].set_xdata(mobileye_data.next_lanes_x[i])
self.next_lanes[i].set_ydata(mobileye_data.next_lanes_y[i])
mobileye_data.next_lane_data_lock.release()
if localization_data.localization_pb is None:
return
vx = localization_data.localization_pb.pose.position.x
vy = localization_data.localization_pb.pose.position.y
routing_data.routing_data_lock.acquire()
path_x = [x - vx for x in routing_data.routing_x]
path_y = [y - vy for y in routing_data.routing_y]
routing_data.routing_data_lock.release()
heading = localization_data.localization_pb.pose.heading
npath_x = []
npath_y = []
for i in range(len(path_x)):
x = path_x[i]
y = path_y[i]
# newx = x * math.cos(heading) - y * math.sin(heading)
# newy = y * math.cos(heading) + x * math.sin(heading)
newx = x * math.cos(- heading + 1.570796) - y * math.sin(
-heading + 1.570796)
newy = y * math.cos(- heading + 1.570796) + x * math.sin(
-heading + 1.570796)
npath_x.append(newx)
npath_y.append(newy)
self.routing.set_xdata(npath_x)
self.routing.set_ydata(npath_y)
speed_x = localization_data.localization_pb.pose.linear_velocity.x
speed_y = localization_data.localization_pb.pose.linear_velocity.y
acc_x = localization_data.localization_pb.pose.linear_acceleration.x
acc_y = localization_data.localization_pb.pose.linear_acceleration.y
heading = localization_data.localization_pb.pose.heading
new_speed_x = math.cos(-heading + math.pi / 2) * speed_x - math.sin(
-heading + math.pi / 2) * speed_y
new_speed_y = math.sin(-heading + math.pi / 2) * speed_x + math.cos(
-heading + math.pi / 2) * speed_y
new_acc_x = math.cos(-heading + math.pi / 2) * acc_x - math.sin(
-heading + math.pi / 2) * acc_y
new_acc_y = math.sin(-heading + math.pi / 2) * acc_x + math.cos(
-heading + math.pi / 2) * acc_y
# self.speed_line.set_xdata([0, new_speed_x])
# self.speed_line.set_ydata([0, new_speed_y])
# self.acc_line.set_xdata([0, new_acc_x])
# self.acc_line.set_ydata([0, new_acc_y])
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/mobileye_viewer/subplot_routing.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
import math
class SubplotRouting:
def __init__(self, ax):
self.ax = ax
self.routing_dot, = ax.plot([0], [0], 'ro', lw=3, alpha=0.4)
self.routing_line, = ax.plot([0], [0], 'b-', lw=1, alpha=1)
self.segment_line, = ax.plot([0], [0], 'bo', lw=1, alpha=1)
def show(self, routing_data):
routing_data.routing_data_lock.acquire()
self.routing_dot.set_xdata(routing_data.routing_x)
self.routing_dot.set_ydata(routing_data.routing_y)
self.routing_line.set_xdata(routing_data.routing_x)
self.routing_line.set_ydata(routing_data.routing_y)
self.segment_line.set_xdata(routing_data.segment_x)
self.segment_line.set_ydata(routing_data.segment_y)
routing_data.routing_data_lock.release()
self.ax.autoscale_view()
self.ax.relim()
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/mobileye_viewer/localization_data.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
import threading
class LocalizationData:
def __init__(self, localization_pb=None):
self.localization_pb = localization_pb
def update(self, localization_pb):
self.localization_pb = localization_pb
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/mobileye_viewer/planning_data.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
import threading
class PlanningData:
def __init__(self, planning_pb=None):
self.path_lock = threading.Lock()
self.path_param_lock = threading.Lock()
self.planning_pb = planning_pb
self.path_x = []
self.path_y = []
self.relative_time = []
self.speed = []
self.s = []
self.theta = []
def update(self, planning_pb):
self.planning_pb = planning_pb
def compute_path(self):
if self.planning_pb is None:
return
path_x = []
path_y = []
for point in self.planning_pb.trajectory_point:
path_x.append(-1 * point.path_point.y)
path_y.append(point.path_point.x)
self.path_lock.acquire()
self.path_x = path_x
self.path_y = path_y
self.path_lock.release()
def compute_path_param(self):
if self.planning_pb is None:
return
relative_time = []
speed = []
s = []
theta = []
for point in self.planning_pb.trajectory_point:
relative_time.append(point.relative_time)
speed.append(point.v)
s.append(point.path_point.s)
theta.append(point.path_point.theta)
self.path_param_lock.acquire()
self.relative_time = relative_time
self.speed = speed
self.s = s
self.theta = theta
self.path_param_lock.release()
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/mobileye_viewer/mobileye_data.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
import threading
class MobileyeData:
def __init__(self, mobileye_pb=None):
self.mobileye_pb = mobileye_pb
self.lane_data_lock = threading.Lock()
self.next_lane_data_lock = threading.Lock()
self.obstacle_data_lock = threading.Lock()
self.left_lane_x = []
self.left_lane_y = []
self.right_lane_x = []
self.right_lane_y = []
self.obstacle_x = []
self.obstacle_y = []
self.ref_lane_x = []
self.ref_lane_y = []
self.next_lanes_x = []
self.next_lanes_y = []
def update(self, mobileye_pb):
self.mobileye_pb = mobileye_pb
def compute_next_lanes(self):
if self.mobileye_pb is None:
return
self.next_lane_data_lock.acquire()
self.next_lanes_x = []
self.next_lanes_y = []
if len(self.mobileye_pb.next_76c) != len(self.mobileye_pb.next_76d):
print("next lanes output is incomplete!")
self.next_lane_data_lock.release()
return
for i in range(len(self.mobileye_pb.next_76c)):
lane_x = []
lane_y = []
c0 = self.mobileye_pb.next_76c[i].position
c1 = self.mobileye_pb.next_76d[i].heading_angle
c2 = self.mobileye_pb.next_76c[i].curvature
c3 = self.mobileye_pb.next_76c[i].curvature_derivative
rangex = self.mobileye_pb.next_76d[i].view_range
for y in range(int(rangex)):
lane_y.append(y)
x = c3*(y*y*y) + c2*(y*y) + c1*y + c0
lane_x.append(x)
# print rangex
self.next_lanes_x.append(lane_x)
self.next_lanes_y.append(lane_y)
self.next_lane_data_lock.release()
def compute_lanes(self):
if self.mobileye_pb is None:
return
self.left_lane_x = []
self.left_lane_y = []
self.right_lane_x = []
self.right_lane_y = []
self.ref_lane_x = []
self.ref_lane_y = []
rc0 = self.mobileye_pb.lka_768.position
rc1 = self.mobileye_pb.lka_769.heading_angle
rc2 = self.mobileye_pb.lka_768.curvature
rc3 = self.mobileye_pb.lka_768.curvature_derivative
rrangex = self.mobileye_pb.lka_769.view_range + 1
self.lane_data_lock.acquire()
for y in range(int(rrangex)):
self.right_lane_y.append(y)
x = rc3*(y*y*y) + rc2*(y*y) + rc1*y + rc0
self.right_lane_x.append(x)
self.lane_data_lock.release()
lc0 = self.mobileye_pb.lka_766.position
lc1 = self.mobileye_pb.lka_767.heading_angle
lc2 = self.mobileye_pb.lka_766.curvature
lc3 = self.mobileye_pb.lka_766.curvature_derivative
lrangex = self.mobileye_pb.lka_767.view_range + 1
self.lane_data_lock.acquire()
for y in range(int(lrangex)):
self.left_lane_y.append(y)
x = lc3*(y * y * y) + lc2 * (y * y) + lc1 * y + lc0
self.left_lane_x.append(x)
self.lane_data_lock.release()
c0 = (rc0 + lc0) // 2
c1 = (rc1 + lc1) // 2
c2 = (rc2 + lc2) // 2
c3 = (rc3 + lc3) // 2
rangex = (lrangex + rrangex) // 2
self.lane_data_lock.acquire()
for y in range(int(rangex)):
self.ref_lane_y.append(y)
x = c3 * (y * y * y) + c2 * (y * y) + c1 * y + c0
self.ref_lane_x.append(x)
self.lane_data_lock.release()
def compute_obstacles(self):
if self.mobileye_pb is None:
return
self.obstacle_x = []
self.obstacle_y = []
self.obstacle_data_lock.acquire()
for i in range(len(self.mobileye_pb.details_739)):
x = self.mobileye_pb.details_739[i].obstacle_pos_x
y = self.mobileye_pb.details_739[i].obstacle_pos_y
self.obstacle_x.append(x)
self.obstacle_y.append(y * -1)
self.obstacle_data_lock.release()
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/mobileye_viewer/subplot_s_speed.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
import math
class SubplotSSpeed:
def __init__(self, ax):
self.s_speed_line, = ax.plot([0], [0], 'r-', lw=3, alpha=0.4)
ax.set_xlim([-2, 100])
ax.set_ylim([-1, 40])
ax.set_xlabel("s (m)")
ax.set_ylabel("speed (m/s)")
def show(self, planning_data):
planning_data.path_param_lock.acquire()
self.s_speed_line.set_xdata(planning_data.s)
self.s_speed_line.set_ydata(planning_data.speed)
planning_data.path_param_lock.release()
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/mobileye_viewer/location_monitor.html
|
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps - pygmaps </title>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
var symbolCar = {
path: 'M -1,0 A 1,1 0 0 0 -3,0 1,1 0 0 0 -1,0M 1,0 A 1,1 0 0 0 3,0 1,1 0 0 0 1,0M -3,3 Q 0,5 3,3',
strokeColor: '#00F',
rotation: 180,
scale: 2
};
var vehicleMarker;
var map;
var interval;
var routingPath = false;
var rightLaneMarker = false;
var leftLaneMarker = false;
var centerVehicle = true;
var destinationMarker = false;
style.webkitTransform = 'translateZ(0px)';
function Initialize() {
LoadGoogleMap();
interval = setInterval(function () {
GetMapData();
}, 100);
var centerControlDiv = document.createElement('div');
var centerControl = new CenterControl(centerControlDiv, map);
centerControlDiv.index = 1;
map.controls[google.maps.ControlPosition.TOP_CENTER].push(centerControlDiv);
var centerControlDiv2 = document.createElement('div');
var routingControl = new RoutingControl(centerControlDiv2, map);
centerControlDiv2.index = 1;
map.controls[google.maps.ControlPosition.TOP_CENTER].push(centerControlDiv2);
google.maps.event.addListener(map, 'click', function (event) {
var clickedLocation = event.latLng;
if (destinationMarker === false) {
destinationMarker = new google.maps.Marker({
position: clickedLocation,
map: map,
label: 'D',
draggable: true //make it draggable
});
//Listen for drag events!
google.maps.event.addListener(vehicleMarker, 'dragend', function (event) {
markerLocation();
});
} else {
//Marker has already been added, so just change its location.
destinationMarker.setPosition(clickedLocation);
}
//Get the marker's location.
//markerLocation();
});
}
function LoadGoogleMap() {
var latlng = new google.maps.LatLng(37.415885, -122.014487);
var mapOptions = {
center: latlng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
vehicleMarker = new google.maps.Marker({
position: latlng
});
vehicleMarker.setMap(map);
}
function GetMapData() {
var json = '';
$.ajax({
type: "POST",
url: "http://localhost:5001/",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (resp) {
var LatLng = new google.maps.LatLng(resp[0].lat, resp[0].lon);
if (centerVehicle) {
map.setCenter(LatLng);
}
vehicleMarker.setPosition(LatLng);
if (rightLaneMarker !== false) {
rightLaneMarker.setMap(null);
}
rightLaneMarker = new google.maps.Polyline({
path: resp[1],
geodesic: true,
strokeColor: '#0000FF',
strokeOpacity: 1.0,
strokeWeight: 2
});
rightLaneMarker.setMap(map);
if (leftLaneMarker !== false) {
leftLaneMarker.setMap(null);
}
leftLaneMarker = new google.maps.Polyline({
path: resp[2],
geodesic: true,
strokeColor: '#0000FF',
strokeOpacity: 1.0,
strokeWeight: 2
});
leftLaneMarker.setMap(map);
},
error: function () {
debugger;
}
});
}
function CenterControl(controlDiv, map) {
// Set CSS for the control border.
var controlUI = document.createElement('div');
controlUI.style.backgroundColor = '#fff';
controlUI.style.border = '2px solid #fff';
controlUI.style.borderRadius = '3px';
controlUI.style.boxShadow = '0 2px 6px rgba(0,0,0,.3)';
controlUI.style.cursor = 'pointer';
controlUI.style.marginBottom = '22px';
controlUI.style.textAlign = 'center';
controlUI.title = 'Click to recenter the vehicle';
controlDiv.appendChild(controlUI);
// Set CSS for the control interior.
var controlText = document.createElement('div');
controlText.style.color = 'rgb(25,25,25)';
controlText.style.fontFamily = 'Roboto,Arial,sans-serif';
controlText.style.fontSize = '16px';
controlText.style.lineHeight = '38px';
controlText.style.paddingLeft = '5px';
controlText.style.paddingRight = '5px';
controlText.innerHTML = 'Center Vehicle is ON';
controlUI.appendChild(controlText);
// Setup the click event listeners: simply set the map to Chicago.
controlUI.addEventListener('click', function () {
if (centerVehicle) {
centerVehicle = false;
controlText.innerHTML = 'Center Vehicle is OFF';
}
else {
centerVehicle = true;
controlText.innerHTML = 'Center Vehicle is ON';
}
});
}
function RoutingControl(controlDiv, map) {
// Set CSS for the control border.
var controlUI = document.createElement('div');
controlUI.style.backgroundColor = '#f00';
controlUI.style.border = '2px solid #fff';
controlUI.style.borderRadius = '3px';
controlUI.style.boxShadow = '0 2px 6px rgba(0,0,0,.3)';
controlUI.style.cursor = 'pointer';
controlUI.style.marginBottom = '22px';
controlUI.style.textAlign = 'center';
controlUI.title = 'Click to send routing request';
controlDiv.appendChild(controlUI);
// Set CSS for the control interior.
var controlText = document.createElement('div');
controlText.style.color = 'rgb(25,25,25)';
controlText.style.fontFamily = 'Roboto,Arial,sans-serif';
controlText.style.fontSize = '16px';
controlText.style.lineHeight = '38px';
controlText.style.paddingLeft = '5px';
controlText.style.paddingRight = '5px';
controlText.innerHTML = 'routing request';
controlUI.appendChild(controlText);
// Setup the click event listeners: simply set the map to Chicago.
controlUI.addEventListener('click', function () {
var data = {
"start_lat": vehicleMarker.getPosition().lat(),
"start_lon": vehicleMarker.getPosition().lng(),
"end_lat": destinationMarker.getPosition().lat(),
"end_lon": destinationMarker.getPosition().lng()
};
$.ajax({
type: "POST",
url: "http://localhost:5001/routing",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (resp) {
if (routingPath !== false) {
routingPath.setMap(null);
}
routingPath = new google.maps.Polyline({
path: resp,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
routingPath.setMap(map);
},
error: function () {
debugger;
}
});
});
}
function markerLocation() {
//Get location.
var currentLocation = destinationMarker.getPosition();
//Add lat and lng values to a field that we can save.
document.getElementById('lat').value = currentLocation.lat(); //latitude
document.getElementById('lng').value = currentLocation.lng(); //longitude
}
</script>
</head>
<body style="margin:0px; padding:0px;" onload="Initialize()">
<div id="map_canvas" style="width: 100%; height: 100%;"></div>
</body>
</html>
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/mobileye_viewer/subplot_s_time.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
import math
class SubplotSTime:
def __init__(self, ax):
self.s_speed_line, = ax.plot([0], [0], 'r-', lw=3, alpha=0.4)
ax.set_xlim([-2, 100])
ax.set_ylim([-0.5, 10])
ax.set_xlabel("s (m)")
ax.set_ylabel("time (sec)")
def show(self, planning_data):
planning_data.path_param_lock.acquire()
self.s_speed_line.set_xdata(planning_data.s)
self.s_speed_line.set_ydata(planning_data.relative_time)
planning_data.path_param_lock.release()
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/mobileye_viewer/chassis_data.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
import threading
class ChassisData:
def __init__(self, chassis_pb=None):
self.chassis_pb = chassis_pb
def update(self, chassis_pb):
self.chassis_pb = chassis_pb
def is_auto(self):
if self.chassis_pb is None:
return False
if self.chassis_pb.driving_mode is None:
return False
if self.chassis_pb.driving_mode == \
self.chassis_pb.COMPLETE_AUTO_DRIVE:
return True
return False
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/mobileye_viewer/routing_data.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
import threading
import json
class RoutingData:
def __init__(self, routing_str=None):
self.routing_str = routing_str
self.routing_debug_str = None
self.routing_data_lock = threading.Lock()
self.routing_x = []
self.routing_y = []
self.segment_x = []
self.segment_y = []
def update_navigation(self, navigation_info_pb):
routing_x = []
routing_y = []
for navi_path in navigation_info_pb.navigation_path:
for path_point in navi_path.path.path_point:
routing_x.append(path_point.x)
routing_y.append(path_point.y)
self.routing_data_lock.acquire()
self.routing_x = routing_x
self.routing_y = routing_y
self.routing_data_lock.release()
def update(self, routing_str):
self.routing_str = routing_str
routing_json = json.loads(routing_str.data)
routing_x = []
routing_y = []
for step in routing_json:
points = step['polyline']['points']
for point in points:
routing_x.append(point[0])
routing_y.append(point[1])
self.routing_data_lock.acquire()
self.routing_x = routing_x
self.routing_y = routing_y
self.routing_data_lock.release()
def update_debug(self, routing_debug_str):
self.routing_debug_str = routing_debug_str
segment_json = json.loads(routing_debug_str.data)
if segment_json is None:
return
segment_x = []
segment_y = []
for point in segment_json:
segment_x.append(point[0])
segment_y.append(point[1])
self.routing_data_lock.acquire()
self.segment_x = segment_x
self.segment_y = segment_y
self.routing_data_lock.release()
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/mobileye_viewer/BUILD
|
load("@rules_python//python:defs.bzl", "py_library")
package(default_visibility = ["//visibility:public"])
py_library(
name = "chassis_data",
srcs = ["chassis_data.py"],
)
py_library(
name = "localization_data",
srcs = ["localization_data.py"],
)
py_library(
name = "mobileye_data",
srcs = ["mobileye_data.py"],
)
py_library(
name = "planning_data",
srcs = ["planning_data.py"],
)
py_library(
name = "routing_data",
srcs = ["routing_data.py"],
)
py_library(
name = "subplot_routing",
srcs = ["subplot_routing.py"],
)
py_library(
name = "subplot_s_speed",
srcs = ["subplot_s_speed.py"],
)
py_library(
name = "subplot_s_theta",
srcs = ["subplot_s_theta.py"],
)
py_library(
name = "subplot_s_time",
srcs = ["subplot_s_time.py"],
)
py_library(
name = "view_subplot",
srcs = ["view_subplot.py"],
)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/mobileye_viewer/subplot_s_theta.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
import math
class SubplotSTheta:
def __init__(self, ax):
self.s_speed_line, = ax.plot([0], [0], 'r-', lw=3, alpha=0.4)
ax.set_xlim([-2, 100])
ax.set_ylim([-0.5, 0.5])
ax.set_xlabel("s (m)")
ax.set_ylabel("theta (r)")
def show(self, planning_data):
planning_data.path_param_lock.acquire()
self.s_speed_line.set_xdata(planning_data.s)
self.s_speed_line.set_ydata(planning_data.theta)
planning_data.path_param_lock.release()
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/record_analyzer/lidar_endtoend_analyzer.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2018 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
from modules.tools.record_analyzer.common.statistical_analyzer import PrintColors
from modules.tools.record_analyzer.common.statistical_analyzer import StatisticalAnalyzer
class LidarEndToEndAnalyzer(object):
"""
Control analyzer
"""
def __init__(self):
"""
Init
"""
self.modules = ['control', 'planning', 'prediction', 'perception']
self.endtoend_latency = {}
self.unprocessed_lidar_timestamps = {}
for m in self.modules:
self.endtoend_latency[m] = []
self.unprocessed_lidar_timestamps[m] = []
def put_pb(self, module_name, pb_msg):
"""
Put data
"""
if module_name not in self.unprocessed_lidar_timestamps:
print(module_name, " is not supported")
return
if pb_msg.header.lidar_timestamp in \
self.unprocessed_lidar_timestamps[module_name]:
ind = self.unprocessed_lidar_timestamps[module_name].index(
pb_msg.header.lidar_timestamp)
del (self.unprocessed_lidar_timestamps[module_name][ind])
self.endtoend_latency[module_name].append(
(pb_msg.header.timestamp_sec -
pb_msg.header.lidar_timestamp * 1.0e-9) * 1000.0)
def put_lidar(self, point_cloud):
"""
Put lidar data
"""
for m in self.modules:
self.unprocessed_lidar_timestamps[m].append(
point_cloud.header.lidar_timestamp)
def print_endtoend_latency(self):
"""
Print end to end latency
"""
print("\n\n")
for m in self.modules:
print(PrintColors.HEADER + "* End to End (" + m
+ ") Latency (ms)" + PrintColors.ENDC)
analyzer = StatisticalAnalyzer()
analyzer.print_statistical_results(self.endtoend_latency[m])
print(PrintColors.FAIL + " - MISS # OF LIDAR: " +
str(len(self.unprocessed_lidar_timestamps[m])) +
PrintColors.ENDC)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/record_analyzer/module_planning_analyzer.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2018 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
import json
import sys
import numpy as np
from modules.tools.record_analyzer.common.distribution_analyzer import DistributionAnalyzer
from modules.tools.record_analyzer.common.error_code_analyzer import ErrorCodeAnalyzer
from modules.tools.record_analyzer.common.error_msg_analyzer import ErrorMsgAnalyzer
from modules.tools.record_analyzer.common.frechet_distance import frechet_distance
from modules.tools.record_analyzer.common.statistical_analyzer import PrintColors
from modules.tools.record_analyzer.common.statistical_analyzer import StatisticalAnalyzer
from modules.tools.record_analyzer.metrics.curvature import Curvature
from modules.tools.record_analyzer.metrics.frame_count import FrameCount
from modules.tools.record_analyzer.metrics.latency import Latency
from modules.tools.record_analyzer.metrics.lat_acceleration import LatAcceleration
from modules.tools.record_analyzer.metrics.lon_acceleration import LonAcceleration
from modules.tools.record_analyzer.metrics.reference_line import ReferenceLine
from modules.common_msgs.planning_msgs import planning_pb2
from shapely.geometry import LineString, Point
class PlannigAnalyzer:
"""planning analyzer"""
def __init__(self, arguments):
"""init"""
self.module_latency = []
self.trajectory_type_dist = {}
self.estop_reason_dist = {}
self.error_code_analyzer = ErrorCodeAnalyzer()
self.error_msg_analyzer = ErrorMsgAnalyzer()
self.last_adc_trajectory = None
self.frechet_distance_list = []
self.is_sim = arguments.simulation
self.hard_break_list = []
self.total_cycle_num = 0
self.curvature_analyzer = Curvature()
self.frame_count_analyzer = FrameCount()
self.lat_acceleration_analyzer = LatAcceleration()
self.lon_acceleration_analyzer = LonAcceleration()
self.latency_analyzer = Latency()
self.reference_line = ReferenceLine()
self.bag_start_time_t = None
self.print_acc = arguments.showacc
def put(self, adc_trajectory):
self.total_cycle_num += 1
if not self.is_sim:
latency = adc_trajectory.latency_stats.total_time_ms
self.module_latency.append(latency)
self.error_code_analyzer.put(
adc_trajectory.header.status.error_code)
self.error_msg_analyzer.put(adc_trajectory.header.status.msg)
traj_type = planning_pb2.ADCTrajectory.TrajectoryType.Name(
adc_trajectory.trajectory_type)
self.trajectory_type_dist[traj_type] = \
self.trajectory_type_dist.get(traj_type, 0) + 1
if adc_trajectory.estop.is_estop:
self.estop_reason_dist[adc_trajectory.estop.reason] = \
self.estop_reason_dist.get(
adc_trajectory.estop.reason, 0) + 1
else:
self.curvature_analyzer.put(adc_trajectory)
self.frame_count_analyzer.put(adc_trajectory)
self.lat_acceleration_analyzer.put(adc_trajectory)
self.lon_acceleration_analyzer.put(adc_trajectory)
self.latency_analyzer.put(adc_trajectory)
self.reference_line.put(adc_trajectory)
def find_common_path(self, current_adc_trajectory, last_adc_trajectory):
current_path_points = current_adc_trajectory.trajectory_point
last_path_points = last_adc_trajectory.trajectory_point
current_path = []
for point in current_path_points:
current_path.append([point.path_point.x, point.path_point.y])
if point.path_point.s > 5.0:
break
last_path = []
for point in last_path_points:
last_path.append([point.path_point.x, point.path_point.y])
if point.path_point.s > 5.0:
break
if len(current_path) == 0 or len(last_path) == 0:
return [], []
current_ls = LineString(current_path)
last_ls = LineString(last_path)
current_start_point = Point(current_path[0])
dist = last_ls.project(current_start_point)
cut_lines = self.cut(last_ls, dist)
if len(cut_lines) == 1:
return [], []
last_ls = cut_lines[1]
dist = current_ls.project(Point(last_path[-1]))
if dist <= current_ls.length:
current_ls = self.cut(current_ls, dist)[0]
else:
dist = last_ls.project(Point(current_path[-1]))
last_ls = self.cut(last_ls, dist)[0]
return current_ls.coords, last_ls.coords
def cut(self, line, distance):
if distance <= 0.0 or distance >= line.length:
return [LineString(line)]
coords = list(line.coords)
for i, p in enumerate(coords):
pd = line.project(Point(p))
if pd == distance:
return [
LineString(coords[:i+1]),
LineString(coords[i:])]
if pd > distance:
cp = line.interpolate(distance)
return [
LineString(coords[:i] + [(cp.x, cp.y)]),
LineString([(cp.x, cp.y)] + coords[i:])]
def print_latency_statistics(self):
"""print_latency_statistics"""
print("\n\n")
print(PrintColors.HEADER + "--- Planning Latency (ms) ---" +
PrintColors.ENDC)
StatisticalAnalyzer().print_statistical_results(self.module_latency)
print(PrintColors.HEADER + "--- Planning Trajectroy Type Distribution"
" ---" + PrintColors.ENDC)
DistributionAnalyzer().print_distribution_results(
self.trajectory_type_dist)
print(PrintColors.HEADER + "--- Planning Estop Distribution"
" ---" + PrintColors.ENDC)
DistributionAnalyzer().print_distribution_results(
self.estop_reason_dist)
print(PrintColors.HEADER + "--- Planning Error Code Distribution---" +
PrintColors.ENDC)
self.error_code_analyzer.print_results()
print(PrintColors.HEADER + "--- Planning Error Msg Distribution ---" +
PrintColors.ENDC)
self.error_msg_analyzer.print_results()
print(PrintColors.HEADER + "--- Planning Trajectory Frechet Distance (m) ---" +
PrintColors.ENDC)
StatisticalAnalyzer().print_statistical_results(self.frechet_distance_list)
def print_sim_results(self):
"""
dreamland metrics for planning v2
"""
v2_results = {}
# acceleration
v2_results["accel"] = self.lon_acceleration_analyzer.get_acceleration()
# deceleration
v2_results["decel"] = self.lon_acceleration_analyzer.get_deceleration()
# jerk
v2_results["acc_jerk"] = self.lon_acceleration_analyzer.get_acc_jerk()
v2_results["dec_jerk"] = self.lon_acceleration_analyzer.get_dec_jerk()
# centripetal_jerk
v2_results["lat_jerk"] = self.lat_acceleration_analyzer.get_jerk()
# centripetal_accel
v2_results["lat_accel"] = self.lat_acceleration_analyzer.get_acceleration()
# frame_count
v2_results["frame_count"] = self.frame_count_analyzer.get()
# latency
v2_results["planning_latency"] = self.latency_analyzer.get()
# reference line
v2_results["reference_line"] = self.reference_line.get()
# output final reuslts
print(json.dumps(v2_results))
def plot_path(self, plt, adc_trajectory):
path_coords = self.trim_path_by_distance(adc_trajectory, 5.0)
x = []
y = []
for point in path_coords:
x.append(point[0])
y.append(point[1])
plt.plot(x, y, 'r-', alpha=0.5)
def plot_refpath(self, plt, adc_trajectory):
for path in adc_trajectory.debug.planning_data.path:
if path.name != 'planning_reference_line':
continue
path_coords = self.trim_path_by_distance(adc_trajectory, 5.0)
ref_path_coord = []
for point in path.path_point:
ref_path_coord.append([point.x, point.y])
ref_path = LineString(ref_path_coord)
start_point = Point(path_coords[0])
dist = ref_path.project(start_point)
ref_path = self.cut(ref_path, dist)[1]
end_point = Point(path_coords[-1])
dist = ref_path.project(end_point)
ref_path = self.cut(ref_path, dist)[0]
x = []
y = []
for point in ref_path.coords:
x.append(point[0])
y.append(point[1])
plt.plot(x, y, 'b--', alpha=0.5)
def trim_path_by_distance(self, adc_trajectory, s):
path_coords = []
path_points = adc_trajectory.trajectory_point
for point in path_points:
if point.path_point.s <= s:
path_coords.append([point.path_point.x, point.path_point.y])
return path_coords
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/record_analyzer/module_control_analyzer.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2018 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
from modules.tools.record_analyzer.common.error_code_analyzer import ErrorCodeAnalyzer
from modules.tools.record_analyzer.common.error_msg_analyzer import ErrorMsgAnalyzer
from modules.tools.record_analyzer.common.statistical_analyzer import PrintColors
from modules.tools.record_analyzer.common.statistical_analyzer import StatisticalAnalyzer
class ControlAnalyzer:
"""control analyzer"""
def __init__(self):
"""init"""
self.module_latency = []
self.error_code_analyzer = ErrorCodeAnalyzer()
self.error_msg_analyzer = ErrorMsgAnalyzer()
self.lon_station_error = []
self.lon_speed_error = []
self.lat_lateral_error = []
self.lat_heading_error = []
def put(self, control_cmd):
"""put data"""
latency = control_cmd.latency_stats.total_time_ms
self.module_latency.append(latency)
self.error_code_analyzer.put(control_cmd.header.status.error_code)
self.error_msg_analyzer.put(control_cmd.header.status.msg)
lon_debug = control_cmd.debug.simple_lon_debug
self.lon_station_error.append(lon_debug.station_error)
self.lon_speed_error.append(lon_debug.speed_error)
lat_debug = control_cmd.debug.simple_lat_debug
self.lat_lateral_error.append(lat_debug.lateral_error)
self.lat_heading_error.append(lat_debug.heading_error)
def print_latency_statistics(self):
"""print_latency_statistics"""
print("\n\n")
print(PrintColors.HEADER + "--- Control Latency (ms) ---" +
PrintColors.ENDC)
analyzer = StatisticalAnalyzer()
analyzer.print_statistical_results(self.module_latency)
print(PrintColors.HEADER + "--- station error ---" +
PrintColors.ENDC)
analyzer.print_statistical_results(self.lon_station_error)
print(PrintColors.HEADER + "--- speed error ---" +
PrintColors.ENDC)
analyzer.print_statistical_results(self.lon_speed_error)
print(PrintColors.HEADER + "--- lateral error ---" +
PrintColors.ENDC)
analyzer.print_statistical_results(self.lat_lateral_error)
print(PrintColors.HEADER + "--- heading error ---" +
PrintColors.ENDC)
analyzer.print_statistical_results(self.lat_heading_error)
print(PrintColors.HEADER + "--- Control Error Code Distribution ---" +
PrintColors.ENDC)
self.error_code_analyzer.print_results()
print(PrintColors.HEADER + "--- Control Error Msg Distribution ---" +
PrintColors.ENDC)
self.error_msg_analyzer.print_results()
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/record_analyzer/README.md
|
# Record Analyzer Tool
## Offline Record files analysis
### Functions
Record analyzer is a tool for analyzing the .record file created by cyber_recorder tool.
It currently supports statistical analysis for
* Control module latency
* Planning module latency
* End to end system latency
And distribution analysis for
* Control error code
* Control error message
* Planning trajectory type
* Planning estop
* Planning error code
* Planning error message
### Usage
```bash
python main.py -f record_file
```
## Simulation Score API
### Functions
This API is used for simulation to grade planning trajectories.
It currently supports following scores:
* frechet_dist: calculate the frechet_dist for two consecutive planning trajectories
* hard_brake_cycle_num: number of planning cycles that acceleration is less than -2.0 m/s^2
* overall_score: aggregated score for above metrics
### Usage
```bash
python main.py -f record_file -s
```
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/record_analyzer/BUILD
|
load("@rules_python//python:defs.bzl", "py_binary", "py_library")
load("//tools/install:install.bzl", "install")
package(default_visibility = ["//visibility:public"])
filegroup(
name = "readme",
srcs = [
"README.md",
],
)
py_library(
name = "lidar_endtoend_analyzer",
srcs = ["lidar_endtoend_analyzer.py"],
deps = [
"//modules/tools/record_analyzer/common:statistical_analyzer",
],
)
py_binary(
name = "main",
srcs = ["main.py"],
deps = [
":lidar_endtoend_analyzer",
":module_control_analyzer",
":module_planning_analyzer",
"//cyber/python/cyber_py3:record",
"//modules/common_msgs/chassis_msgs:chassis_py_pb2",
"//modules/common_msgs/control_msgs:control_cmd_py_pb2",
"//modules/common_msgs/sensor_msgs:pointcloud_py_pb2",
"//modules/common_msgs/perception_msgs:perception_obstacle_py_pb2",
"//modules/common_msgs/planning_msgs:planning_py_pb2",
"//modules/common_msgs/prediction_msgs:prediction_obstacle_py_pb2",
],
)
py_library(
name = "module_control_analyzer",
srcs = ["module_control_analyzer.py"],
deps = [
"//modules/tools/record_analyzer/common:error_code_analyzer",
"//modules/tools/record_analyzer/common:error_msg_analyzer",
"//modules/tools/record_analyzer/common:statistical_analyzer",
],
)
py_library(
name = "module_planning_analyzer",
srcs = ["module_planning_analyzer.py"],
deps = [
"//modules/common_msgs/planning_msgs:planning_py_pb2",
"//modules/tools/record_analyzer/common:distribution_analyzer",
"//modules/tools/record_analyzer/common:error_code_analyzer",
"//modules/tools/record_analyzer/common:error_msg_analyzer",
"//modules/tools/record_analyzer/common:frechet_distance",
"//modules/tools/record_analyzer/common:statistical_analyzer",
"//modules/tools/record_analyzer/metrics:curvature",
"//modules/tools/record_analyzer/metrics:frame_count",
"//modules/tools/record_analyzer/metrics:lat_acceleration",
"//modules/tools/record_analyzer/metrics:latency",
"//modules/tools/record_analyzer/metrics:lon_acceleration",
"//modules/tools/record_analyzer/metrics:reference_line",
],
)
install(
name = "install",
data = [":readme"],
data_dest = "tools/record_analyzer",
py_dest = "tools/record_analyzer",
targets = [
":main",
],
deps = [
"//modules/tools/record_analyzer/tools:install",
"//modules/tools/record_analyzer/common:install",
]
)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/record_analyzer/main.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2018 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
import argparse
import sys
import matplotlib.pyplot as plt
from cyber.python.cyber_py3.record import RecordReader
from modules.tools.record_analyzer.lidar_endtoend_analyzer import LidarEndToEndAnalyzer
from modules.common_msgs.chassis_msgs import chassis_pb2
from modules.common_msgs.control_msgs import control_cmd_pb2
from modules.common_msgs.sensor_msgs import pointcloud_pb2
from modules.common_msgs.perception_msgs import perception_obstacle_pb2
from modules.common_msgs.planning_msgs import planning_pb2
from modules.common_msgs.prediction_msgs import prediction_obstacle_pb2
from modules.tools.record_analyzer.module_control_analyzer import ControlAnalyzer
from modules.tools.record_analyzer.module_planning_analyzer import PlannigAnalyzer
def process(control_analyzer, planning_analyzer, lidar_endtoend_analyzer,
is_simulation, plot_planning_path, plot_planning_refpath, all_data):
is_auto_drive = False
for msg in reader.read_messages():
if msg.topic == "/apollo/canbus/chassis":
chassis = chassis_pb2.Chassis()
chassis.ParseFromString(msg.message)
if chassis.driving_mode == \
chassis_pb2.Chassis.COMPLETE_AUTO_DRIVE:
is_auto_drive = True
else:
is_auto_drive = False
if msg.topic == "/apollo/control":
if (not is_auto_drive and not all_data) or \
is_simulation or plot_planning_path or plot_planning_refpath:
continue
control_cmd = control_cmd_pb2.ControlCommand()
control_cmd.ParseFromString(msg.message)
control_analyzer.put(control_cmd)
lidar_endtoend_analyzer.put_pb('control', control_cmd)
if msg.topic == "/apollo/planning":
if (not is_auto_drive) and (not all_data):
continue
adc_trajectory = planning_pb2.ADCTrajectory()
adc_trajectory.ParseFromString(msg.message)
planning_analyzer.put(adc_trajectory)
lidar_endtoend_analyzer.put_pb('planning', adc_trajectory)
if plot_planning_path:
planning_analyzer.plot_path(plt, adc_trajectory)
if plot_planning_refpath:
planning_analyzer.plot_refpath(plt, adc_trajectory)
if msg.topic == "/apollo/sensor/velodyne64/compensator/PointCloud2" or \
msg.topic == "/apollo/sensor/lidar128/compensator/PointCloud2":
if ((not is_auto_drive) and (not all_data)) or is_simulation or \
plot_planning_path or plot_planning_refpath:
continue
point_cloud = pointcloud_pb2.PointCloud()
point_cloud.ParseFromString(msg.message)
lidar_endtoend_analyzer.put_lidar(point_cloud)
if msg.topic == "/apollo/perception/obstacles":
if ((not is_auto_drive) and (not all_data)) or is_simulation or \
plot_planning_path or plot_planning_refpath:
continue
perception = perception_obstacle_pb2.PerceptionObstacles()
perception.ParseFromString(msg.message)
lidar_endtoend_analyzer.put_pb('perception', perception)
if msg.topic == "/apollo/prediction":
if ((not is_auto_drive) and (not all_data)) or is_simulation or \
plot_planning_path or plot_planning_refpath:
continue
prediction = prediction_obstacle_pb2.PredictionObstacles()
prediction.ParseFromString(msg.message)
lidar_endtoend_analyzer.put_pb('prediction', prediction)
if __name__ == "__main__":
if len(sys.argv) < 2:
print("usage: python main.py record_file")
parser = argparse.ArgumentParser(
description="Recode Analyzer is a tool to analyze record files.",
prog="main.py")
parser.add_argument(
"-f", "--file", action="store", type=str, required=True,
help="Specify the record file for analysis.")
parser.add_argument(
"-sim", "--simulation", action="store_const", const=True,
help="For dreamland API call")
parser.add_argument(
"-path", "--planningpath", action="store_const", const=True,
help="plot planing paths in cartesian coordinate.")
parser.add_argument(
"-refpath", "--planningrefpath", action="store_const", const=True,
help="plot planing reference paths in cartesian coordinate.")
parser.add_argument(
"-a", "--alldata", action="store_const", const=True,
help="Analyze all data (both auto and manual), otherwise auto data only without this option.")
parser.add_argument(
"-acc", "--showacc", action="store_const", const=True,
help="Analyze all data (both auto and manual), otherwise auto data only without this option.")
args = parser.parse_args()
record_file = args.file
reader = RecordReader(record_file)
control_analyzer = ControlAnalyzer()
planning_analyzer = PlannigAnalyzer(args)
lidar_endtoend_analyzer = LidarEndToEndAnalyzer()
process(control_analyzer, planning_analyzer,
lidar_endtoend_analyzer, args.simulation, args.planningpath,
args.planningrefpath, args.alldata)
if args.simulation:
planning_analyzer.print_sim_results()
elif args.planningpath or args.planningrefpath:
plt.axis('equal')
plt.show()
else:
control_analyzer.print_latency_statistics()
planning_analyzer.print_latency_statistics()
lidar_endtoend_analyzer.print_endtoend_latency()
| 0
|
apollo_public_repos/apollo/modules/tools/record_analyzer
|
apollo_public_repos/apollo/modules/tools/record_analyzer/metrics/latency.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2019 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
import numpy as np
class Latency:
def __init__(self):
self.latency_list = []
def put(self, adc_trajectory):
self.latency_list.append(adc_trajectory.latency_stats.total_time_ms)
def get(self):
if len(self.latency_list) > 0:
planning_latency = {
"max": max(self.latency_list),
"min": min(self.latency_list),
"avg": np.average(self.latency_list)
}
else:
planning_latency = {
"max": 0.0,
"min": 0.0,
"avg": 0.0
}
return planning_latency
| 0
|
apollo_public_repos/apollo/modules/tools/record_analyzer
|
apollo_public_repos/apollo/modules/tools/record_analyzer/metrics/lon_acceleration.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2019 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
import math
import numpy as np
class LonAcceleration:
def __init__(self):
self.last_velocity = None
self.last_velocity_timestamp = None
self.last_acceleration = None
self.last_acceleration_timestamp = None
self.acceleration_list = []
self.deceleration_list = []
self.acc_jerk_list = []
self.dec_jerk_list = []
def put(self, adc_trajectory):
init_point = adc_trajectory.debug.planning_data.init_point
current_velocity_timestamp = adc_trajectory.header.timestamp_sec + \
init_point.relative_time
current_velocity = init_point.v
if self.last_velocity_timestamp is not None and self.last_velocity is not None:
# acceleration
duration = current_velocity_timestamp - self.last_velocity_timestamp
if duration > 0.03:
current_acceleration = (
current_velocity - self.last_velocity) / duration
if current_acceleration > 0 and not math.isnan(current_acceleration):
self.acceleration_list.append(current_acceleration)
elif current_acceleration < 0 and not math.isnan(current_acceleration):
self.deceleration_list.append(current_acceleration)
if self.last_acceleration is not None and self.last_acceleration_timestamp is not None:
# jerk
acc_duration = current_velocity_timestamp - self.last_acceleration_timestamp
if acc_duration > 0.03:
current_jerk = (current_acceleration -
self.last_acceleration) / acc_duration
if current_acceleration > 0 and not math.isnan(current_jerk):
self.acc_jerk_list.append(current_jerk)
elif current_acceleration < 0 and not math.isnan(current_jerk):
self.dec_jerk_list.append(current_jerk)
self.last_acceleration = current_acceleration
self.last_acceleration_timestamp = current_velocity_timestamp
self.last_velocity_timestamp = current_velocity_timestamp
self.last_velocity = current_velocity
def get_acceleration(self):
# [2, 4) unit m/s^2
ACCEL_M_LB = 2
ACCEL_M_UB = 4
accel_medium_cnt = 0
# [4, ) unit m/s^2
ACCEL_H_LB = 4
accel_high_cnt = 0
lon_acceleration = {}
for accel in self.acceleration_list:
if ACCEL_M_LB <= accel < ACCEL_M_UB:
accel_medium_cnt += 1
if ACCEL_H_LB <= accel:
accel_high_cnt += 1
if len(self.acceleration_list) > 0:
lon_acceleration["max"] = max(self.acceleration_list)
lon_acceleration["avg"] = np.average(self.acceleration_list)
else:
lon_acceleration["max"] = 0.0
lon_acceleration["avg"] = 0.0
lon_acceleration["medium_cnt"] = accel_medium_cnt
lon_acceleration["high_cnt"] = accel_high_cnt
return lon_acceleration
def get_deceleration(self):
# [-4, -2)
DECEL_M_LB = -4
DECEL_M_UB = -2
decel_medium_cnt = 0
# [-4, )
DECEL_H_UB = -4
decel_high_cnt = 0
for accel in self.deceleration_list:
if DECEL_M_LB < accel <= DECEL_M_UB:
decel_medium_cnt += 1
if accel <= DECEL_H_UB:
decel_high_cnt += 1
lon_deceleration = {}
if len(self.deceleration_list) > 0:
lon_deceleration["max"] = abs(max(self.deceleration_list, key=abs))
lon_deceleration["avg"] = np.average(
np.absolute(self.deceleration_list))
else:
lon_deceleration["max"] = 0.0
lon_deceleration["avg"] = 0.0
lon_deceleration["medium_cnt"] = decel_medium_cnt
lon_deceleration["high_cnt"] = decel_high_cnt
return lon_deceleration
def get_acc_jerk(self):
# [1,2) (-2, -1]
JERK_M_LB_P = 1
JERK_M_UB_P = 2
JERK_M_LB_N = -2
JERK_M_UB_N = -1
jerk_medium_cnt = 0
# [2, inf) (-inf, -2]
JERK_H_LB_P = 2
JERK_H_UB_N = -2
jerk_high_cnt = 0
for jerk in self.acc_jerk_list:
if JERK_M_LB_P <= jerk < JERK_M_UB_P or \
JERK_M_LB_N < jerk <= JERK_M_UB_N:
jerk_medium_cnt += 1
if jerk >= JERK_H_LB_P or jerk <= JERK_H_UB_N:
jerk_high_cnt += 1
lon_acc_jerk = {}
if len(self.acc_jerk_list) > 0:
lon_acc_jerk["max"] = abs(max(self.acc_jerk_list, key=abs))
jerk_avg = np.average(np.absolute(self.acc_jerk_list))
lon_acc_jerk["avg"] = jerk_avg
else:
lon_acc_jerk["max"] = 0
lon_acc_jerk["avg"] = 0
lon_acc_jerk["medium_cnt"] = jerk_medium_cnt
lon_acc_jerk["high_cnt"] = jerk_high_cnt
return lon_acc_jerk
def get_dec_jerk(self):
# [1,2) (-2, -1]
JERK_M_LB_P = 1
JERK_M_UB_P = 2
JERK_M_LB_N = -2
JERK_M_UB_N = -1
jerk_medium_cnt = 0
# [2, inf) (-inf, -2]
JERK_H_LB_P = 2
JERK_H_UB_N = -2
jerk_high_cnt = 0
for jerk in self.dec_jerk_list:
if JERK_M_LB_P <= jerk < JERK_M_UB_P or \
JERK_M_LB_N < jerk <= JERK_M_UB_N:
jerk_medium_cnt += 1
if jerk >= JERK_H_LB_P or jerk <= JERK_H_UB_N:
jerk_high_cnt += 1
lon_dec_jerk = {}
if len(self.dec_jerk_list) > 0:
lon_dec_jerk["max"] = abs(max(self.dec_jerk_list, key=abs))
jerk_avg = np.average(np.absolute(self.dec_jerk_list))
lon_dec_jerk["avg"] = jerk_avg
else:
lon_dec_jerk["max"] = 0
lon_dec_jerk["avg"] = 0
lon_dec_jerk["medium_cnt"] = jerk_medium_cnt
lon_dec_jerk["high_cnt"] = jerk_high_cnt
return lon_dec_jerk
| 0
|
apollo_public_repos/apollo/modules/tools/record_analyzer
|
apollo_public_repos/apollo/modules/tools/record_analyzer/metrics/reference_line.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2019 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
import sys
import numpy as np
class ReferenceLine:
def __init__(self):
self.rl_is_offroad_cnt = 0
self.rl_minimum_boundary = sys.float_info.max
self.rl_kappa_rms_list = []
self.rl_dkappa_rms_list = []
self.rl_kappa_max_abs_list = []
self.rl_dkappa_max_abs_list = []
def put(self, adc_trajectory):
for ref_line_debug in adc_trajectory.debug.planning_data.reference_line:
if ref_line_debug.HasField("is_offroad") and ref_line_debug.is_offroad:
self.rl_is_offroad_cnt += 1
if ref_line_debug.HasField("minimum_boundary") and \
ref_line_debug.minimum_boundary < self.rl_minimum_boundary:
self.rl_minimum_boundary = ref_line_debug.minimum_boundary
if ref_line_debug.HasField("kappa_rms"):
self.rl_kappa_rms_list.append(ref_line_debug.kappa_rms)
if ref_line_debug.HasField("dkappa_rms"):
self.rl_dkappa_rms_list.append(ref_line_debug.dkappa_rms)
if ref_line_debug.HasField("kappa_max_abs"):
self.rl_kappa_max_abs_list.append(ref_line_debug.kappa_max_abs)
if ref_line_debug.HasField("dkappa_max_abs"):
self.rl_dkappa_max_abs_list.append(ref_line_debug.dkappa_max_abs)
def get(self):
kappa_rms = 0
if len(self.rl_kappa_rms_list) > 0:
kappa_rms = np.average(self.rl_kappa_rms_list)
dkappa_rms = 0
if len(self.rl_dkappa_rms_list) > 0:
dkappa_rms = np.average(self.rl_dkappa_rms_list)
if self.rl_minimum_boundary > 999:
self.rl_minimum_boundary = 0
kappa_max_abs = 0
if len(self.rl_kappa_max_abs_list) > 0:
kappa_max_abs = max(self.rl_kappa_max_abs_list)
dkappa_max_abs = 0
if len(self.rl_dkappa_max_abs_list) > 0:
dkappa_max_abs = max(self.rl_dkappa_max_abs_list)
reference_line = {
"is_offroad": self.rl_is_offroad_cnt,
"minimum_boundary": self.rl_minimum_boundary,
"kappa_rms": kappa_rms,
"dkappa_rms": dkappa_rms,
"kappa_max_abs": kappa_max_abs,
"dkappa_max_abs": dkappa_max_abs
}
return reference_line
| 0
|
apollo_public_repos/apollo/modules/tools/record_analyzer
|
apollo_public_repos/apollo/modules/tools/record_analyzer/metrics/lat_acceleration.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2019 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
import math
import numpy as np
class LatAcceleration:
def __init__(self):
self.centripetal_accel_list = []
self.centripetal_jerk_list = []
def put(self, adc_trajectory):
init_point = adc_trajectory.debug.planning_data.init_point
# centripetal_jerk
centripetal_jerk = 2 * init_point.v * init_point.a \
* init_point.path_point.kappa + init_point.v \
* init_point.v * init_point.path_point.dkappa
if not math.isnan(centripetal_jerk):
self.centripetal_jerk_list.append(centripetal_jerk)
# centripetal_accel
centripetal_accel = init_point.v * init_point.v \
* init_point.path_point.kappa
if not math.isnan(centripetal_accel):
self.centripetal_accel_list.append(centripetal_accel)
def get_acceleration(self):
# [1, 2) [-2, -1)
LAT_ACCEL_M_LB_P = 1
LAT_ACCEL_M_UB_P = 2
LAT_ACCEL_M_LB_N = -2
LAT_ACCEL_M_UB_N = -1
lat_accel_medium_cnt = 0
# [2, inf) [-inf,-2)
LAT_ACCEL_H_LB_P = 2
LAT_ACCEL_H_UB_N = -2
lat_accel_high_cnt = 0
for centripetal_accel in self.centripetal_accel_list:
if LAT_ACCEL_M_LB_P <= centripetal_accel < LAT_ACCEL_M_UB_P \
or LAT_ACCEL_M_LB_N < centripetal_accel <= LAT_ACCEL_M_UB_N:
lat_accel_medium_cnt += 1
if centripetal_accel >= LAT_ACCEL_H_LB_P \
or centripetal_accel <= LAT_ACCEL_H_UB_N:
lat_accel_high_cnt += 1
# centripetal_accel
lat_accel = {}
if len(self.centripetal_accel_list) > 0:
lat_accel["max"] = abs(max(self.centripetal_accel_list, key=abs))
accel_avg = np.average(np.absolute(self.centripetal_accel_list))
lat_accel["avg"] = accel_avg
else:
lat_accel["max"] = 0
lat_accel["avg"] = 0
lat_accel["medium_cnt"] = lat_accel_medium_cnt
lat_accel["high_cnt"] = lat_accel_high_cnt
return lat_accel
def get_jerk(self):
# [0.5,1) [-1, -0.5)
LAT_JERK_M_LB_P = 0.5
LAT_JERK_M_UB_P = 1
LAT_JERK_M_LB_N = -1
LAT_JERK_M_UB_N = -0.5
lat_jerk_medium_cnt = 0
# [1, inf) [-inf,-1)
LAT_JERK_H_LB_P = 1
LAT_JERK_H_UB_N = -1
lat_jerk_high_cnt = 0
for centripetal_jerk in self.centripetal_jerk_list:
if LAT_JERK_M_LB_P <= centripetal_jerk < LAT_JERK_M_UB_P \
or LAT_JERK_M_LB_N < centripetal_jerk <= LAT_JERK_M_UB_N:
lat_jerk_medium_cnt += 1
if centripetal_jerk >= LAT_JERK_H_LB_P \
or centripetal_jerk <= LAT_JERK_H_UB_N:
lat_jerk_high_cnt += 1
# centripetal_jerk
lat_jerk = {}
if len(self.centripetal_jerk_list) > 0:
lat_jerk["max"] = abs(max(self.centripetal_jerk_list, key=abs))
jerk_avg = np.average(np.absolute(self.centripetal_jerk_list))
lat_jerk["avg"] = jerk_avg
else:
lat_jerk["max"] = 0
lat_jerk["avg"] = 0
lat_jerk["medium_cnt"] = lat_jerk_medium_cnt
lat_jerk["high_cnt"] = lat_jerk_high_cnt
return lat_jerk
| 0
|
apollo_public_repos/apollo/modules/tools/record_analyzer
|
apollo_public_repos/apollo/modules/tools/record_analyzer/metrics/curvature.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2019 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
import numpy as np
class Curvature:
def __init__(self):
self.curvature_list = []
self.curvature_derivative_list = []
def put(self, adc_trajectory):
init_point = adc_trajectory.debug.planning_data.init_point
self.curvature_list.append(abs(init_point.path_point.kappa))
self.curvature_derivative_list.append(abs(init_point.path_point.dkappa))
def get_curvature(self):
curvature = {}
if len(self.curvature_list) == 0:
curvature["max"] = 0
curvature["avg"] = 0
return curvature
curvature["max"] = max(self.curvature_list, key=abs)
curvature["avg"] = np.average(np.absolute(self.curvature_list))
return curvature
def get_curvature_derivative(self):
curvature_derivative = {}
if len(self.curvature_derivative_list) == 0:
curvature_derivative["max"] = 0
curvature_derivative["avg"] = 0
curvature_derivative["max"] = max(self.curvature_derivative_list, key=abs)
curvature_derivative["avg"] = np.average(np.absolute(self.curvature_derivative_list))
return curvature_derivative
| 0
|
apollo_public_repos/apollo/modules/tools/record_analyzer
|
apollo_public_repos/apollo/modules/tools/record_analyzer/metrics/frame_count.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2019 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
class FrameCount:
def __init__(self):
self.count = 0
def put(self, adc_trajectory):
self.count += 1
def get(self):
frame_count = {}
frame_count["total"] = self.count
return frame_count
| 0
|
apollo_public_repos/apollo/modules/tools/record_analyzer
|
apollo_public_repos/apollo/modules/tools/record_analyzer/metrics/BUILD
|
load("@rules_python//python:defs.bzl", "py_library")
package(default_visibility = ["//visibility:public"])
py_library(
name = "curvature",
srcs = ["curvature.py"],
)
py_library(
name = "frame_count",
srcs = ["frame_count.py"],
)
py_library(
name = "lat_acceleration",
srcs = ["lat_acceleration.py"],
)
py_library(
name = "latency",
srcs = ["latency.py"],
)
py_library(
name = "lon_acceleration",
srcs = ["lon_acceleration.py"],
)
py_library(
name = "reference_line",
srcs = ["reference_line.py"],
)
| 0
|
apollo_public_repos/apollo/modules/tools/record_analyzer
|
apollo_public_repos/apollo/modules/tools/record_analyzer/tools/perception_obstacle_sender.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2018 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
import time
import argparse
import google.protobuf.text_format as text_format
from cyber.python.cyber_py3 import cyber
from cyber.python.cyber_py3 import cyber_time
from modules.common_msgs.perception_msgs import perception_obstacle_pb2
def update(perception_obstacles):
"""update perception obstacles timestamp"""
now = cyber_time.Time.now().to_sec()
perception_obstacles.header.timestamp_sec = now
perception_obstacles.header.lidar_timestamp = \
(int(now) - int(0.5)) * int(1e9)
for perception_obstacle in perception_obstacles.perception_obstacle:
perception_obstacle.timestamp = now - 0.5
for measure in perception_obstacle.measurements:
measure.timestamp = now - 0.5
return perception_obstacles
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Recode Analyzer is a tool to analyze record files.",
prog="main.py")
parser.add_argument(
"-f", "--file", action="store", type=str, required=True,
help="Specify the message file for sending.")
args = parser.parse_args()
cyber.init()
node = cyber.Node("perception_obstacle_sender")
perception_pub = node.create_writer(
"/apollo/perception/obstacles",
perception_obstacle_pb2.PerceptionObstacles)
perception_obstacles = perception_obstacle_pb2.PerceptionObstacles()
with open(args.file, 'r') as f:
text_format.Merge(f.read(), perception_obstacles)
while not cyber.is_shutdown():
now = cyber_time.Time.now().to_sec()
perception_obstacles = update(perception_obstacles)
perception_pub.write(perception_obstacles)
sleep_time = 0.1 - (cyber_time.Time.now().to_sec() - now)
if sleep_time > 0:
time.sleep(sleep_time)
cyber.shutdown()
| 0
|
apollo_public_repos/apollo/modules/tools/record_analyzer
|
apollo_public_repos/apollo/modules/tools/record_analyzer/tools/dump_message.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2018 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
import argparse
import sys
from cyber.python.cyber_py3.record import RecordReader
from modules.common_msgs.chassis_msgs import chassis_pb2
from modules.common_msgs.control_msgs import control_cmd_pb2
from modules.common_msgs.sensor_msgs import pointcloud_pb2
from modules.common_msgs.perception_msgs import perception_obstacle_pb2
from modules.common_msgs.planning_msgs import planning_pb2
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Recode Analyzer is a tool to analyze record files.",
prog="main.py")
parser.add_argument(
"-f", "--file", action="store", type=str, required=True,
help="Specify the record file for message dumping.")
parser.add_argument(
"-m", "--message", action="store", type=str, required=True,
help="Specify the message topic for dumping.")
parser.add_argument(
"-t", "--timestamp", action="store", type=float, required=True,
help="Specify the timestamp for dumping.")
args = parser.parse_args()
record_file = args.file
reader = RecordReader(record_file)
for msg in reader.read_messages():
timestamp = msg.timestamp / float(1e9)
if msg.topic == args.message and abs(timestamp - args.timestamp) <= 1:
if msg.topic == "/apollo/perception/obstacles":
perception_obstacles = \
perception_obstacle_pb2.PerceptionObstacles()
perception_obstacles.ParseFromString(msg.message)
with open('perception_obstacles.txt', 'w') as f:
f.write(str(perception_obstacles))
print(str(perception_obstacles))
break
| 0
|
apollo_public_repos/apollo/modules/tools/record_analyzer
|
apollo_public_repos/apollo/modules/tools/record_analyzer/tools/BUILD
|
load("@rules_python//python:defs.bzl", "py_binary", "py_library")
load("//tools/install:install.bzl", "install")
package(default_visibility = ["//visibility:public"])
py_binary(
name = "dump_message",
srcs = ["dump_message.py"],
deps = [
"//cyber/python/cyber_py3:record",
"//modules/common_msgs/chassis_msgs:chassis_py_pb2",
"//modules/common_msgs/control_msgs:control_cmd_py_pb2",
"//modules/common_msgs/sensor_msgs:pointcloud_py_pb2",
"//modules/common_msgs/perception_msgs:perception_obstacle_py_pb2",
"//modules/common_msgs/planning_msgs:planning_py_pb2",
],
)
py_binary(
name = "perception_obstacle_sender",
srcs = ["perception_obstacle_sender.py"],
deps = [
"//cyber/python/cyber_py3:cyber",
"//cyber/python/cyber_py3:cyber_time",
"//modules/common_msgs/perception_msgs:perception_obstacle_py_pb2",
],
)
install(
name = "install",
py_dest = "tools/record_analyzer/tools",
targets = [
":perception_obstacle_sender",
":dump_message",
]
)
| 0
|
apollo_public_repos/apollo/modules/tools/record_analyzer
|
apollo_public_repos/apollo/modules/tools/record_analyzer/common/frechet_distance.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2018 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
import math
import numpy as np
def euclidean_distance(pt1, pt2):
return math.sqrt((pt2[0] - pt1[0]) * (pt2[0]-pt1[0]) +
(pt2[1] - pt1[1]) * (pt2[1] - pt1[1]))
def _c(ca, i, j, P, Q):
if ca[i, j] > -1:
return ca[i, j]
elif i == 0 and j == 0:
ca[i, j] = euclidean_distance(P[0], Q[0])
elif i > 0 and j == 0:
ca[i, j] = max(_c(ca, i-1, 0, P, Q), euclidean_distance(P[i], Q[0]))
elif i == 0 and j > 0:
ca[i, j] = max(_c(ca, 0, j-1, P, Q), euclidean_distance(P[0], Q[j]))
elif i > 0 and j > 0:
ca[i, j] = max(min(_c(ca, i-1, j, P, Q),
_c(ca, i-1, j-1, P, Q),
_c(ca, i, j-1, P, Q)),
euclidean_distance(P[i], Q[j]))
else:
ca[i, j] = float("inf")
return ca[i, j]
def frechet_distance(P, Q):
ca = np.ones((len(P), len(Q)))
ca = np.multiply(ca, -1)
dist = None
try:
dist = _c(ca, len(P)-1, len(Q)-1, P, Q)
except:
print("calculate frechet_distance exception.")
return dist
if __name__ == "__main__":
"""test"""
P = [[1, 1], [2, 1], [2, 2]]
Q = [[2, 2], [0, 1], [2, 4]]
print(frechet_distance(P, Q)) # 2
P = [[1, 1], [2, 1], [2, 2]]
Q = [[1, 1], [2, 1], [2, 2]]
print(frechet_distance(P, Q)) # 0
| 0
|
apollo_public_repos/apollo/modules/tools/record_analyzer
|
apollo_public_repos/apollo/modules/tools/record_analyzer/common/error_msg_analyzer.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2018 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
from modules.common_msgs.basic_msgs import error_code_pb2
from modules.tools.record_analyzer.common.statistical_analyzer import PrintColors
from modules.tools.record_analyzer.common.distribution_analyzer import DistributionAnalyzer
class ErrorMsgAnalyzer:
"""class"""
def __init__(self):
"""init"""
self.error_msg_count = {}
def put(self, error_msg):
"""put"""
if len(error_msg) == 0:
return
if error_msg not in self.error_msg_count:
self.error_msg_count[error_msg] = 1
else:
self.error_msg_count[error_msg] += 1
def print_results(self):
"""print"""
DistributionAnalyzer().print_distribution_results(self.error_msg_count)
| 0
|
apollo_public_repos/apollo/modules/tools/record_analyzer
|
apollo_public_repos/apollo/modules/tools/record_analyzer/common/error_code_analyzer.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2018 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
from modules.common_msgs.basic_msgs import error_code_pb2
from modules.tools.record_analyzer.common.statistical_analyzer import PrintColors
from modules.tools.record_analyzer.common.distribution_analyzer import DistributionAnalyzer
class ErrorCodeAnalyzer:
"""class"""
def __init__(self):
"""init"""
self.error_code_count = {}
def put(self, error_code):
"""put"""
error_code_name = \
error_code_pb2.ErrorCode.Name(error_code)
if error_code_name not in self.error_code_count:
self.error_code_count[error_code_name] = 1
else:
self.error_code_count[error_code_name] += 1
def print_results(self):
"""print"""
DistributionAnalyzer().print_distribution_results(self.error_code_count)
| 0
|
apollo_public_repos/apollo/modules/tools/record_analyzer
|
apollo_public_repos/apollo/modules/tools/record_analyzer/common/BUILD
|
load("@rules_python//python:defs.bzl", "py_binary", "py_library")
load("//tools/install:install.bzl", "install")
package(default_visibility = ["//visibility:public"])
py_library(
name = "distribution_analyzer",
srcs = ["distribution_analyzer.py"],
deps = [
":statistical_analyzer",
],
)
py_library(
name = "error_code_analyzer",
srcs = ["error_code_analyzer.py"],
deps = [
":distribution_analyzer",
":statistical_analyzer",
"//modules/common_msgs/basic_msgs:error_code_py_pb2",
],
)
py_library(
name = "error_msg_analyzer",
srcs = ["error_msg_analyzer.py"],
deps = [
":distribution_analyzer",
":statistical_analyzer",
"//modules/common_msgs/basic_msgs:error_code_py_pb2",
],
)
py_binary(
name = "frechet_distance",
srcs = ["frechet_distance.py"],
)
py_library(
name = "statistical_analyzer",
srcs = ["statistical_analyzer.py"],
)
install(
name = "install",
py_dest = "tools/record_analyzer/common",
targets = [
":frechet_distance",
]
)
| 0
|
apollo_public_repos/apollo/modules/tools/record_analyzer
|
apollo_public_repos/apollo/modules/tools/record_analyzer/common/statistical_analyzer.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2018 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
import numpy as np
class PrintColors:
""" output color schema"""
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
class StatisticalAnalyzer:
"""statistical analzer class"""
def print_statistical_results(self, data):
""" statistical analyzer"""
if len(data) == 0:
print(PrintColors.FAIL + "No Data Generated!" + PrintColors.ENDC)
return
arr = np.array(data)
v = np.average(arr)
print(PrintColors.OKBLUE + "Average: \t" + PrintColors.ENDC,
"{0:.2f}".format(v))
std = np.std(arr)
print(PrintColors.OKBLUE + "STD: \t\t" + PrintColors.ENDC,
"{0:.2f}".format(std))
p = np.percentile(arr, 10)
print(PrintColors.OKBLUE + "10 Percentile: \t" + PrintColors.ENDC,
"{0:.2f}".format(p))
p = np.percentile(arr, 50)
print(PrintColors.OKBLUE + "50 Percentile: \t" + PrintColors.ENDC,
"{0:.2f}".format(p))
p = np.percentile(arr, 90)
print(PrintColors.OKBLUE + "90 Percentile: \t" + PrintColors.ENDC,
"{0:.2f}".format(p))
p = np.percentile(arr, 99)
print(PrintColors.OKBLUE + "99 Percentile: \t" + PrintColors.ENDC,
"{0:.2f}".format(p))
p = np.min(arr)
print(PrintColors.OKBLUE + "min: \t" + PrintColors.ENDC,
"{0:.2f}".format(p))
p = np.max(arr)
print(PrintColors.OKBLUE + "max: \t" + PrintColors.ENDC,
"{0:.2f}".format(p))
| 0
|
apollo_public_repos/apollo/modules/tools/record_analyzer
|
apollo_public_repos/apollo/modules/tools/record_analyzer/common/distribution_analyzer.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2018 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
from modules.tools.record_analyzer.common.statistical_analyzer import PrintColors
class DistributionAnalyzer:
"""statistical analzer class"""
def print_distribution_results(self, data):
"""distribution analyzer"""
if len(data) == 0:
print(PrintColors.FAIL + "No Data Generated!" + PrintColors.ENDC)
return
total = 0
for k, v in data.items():
total += v
for k, v in data.items():
percentage = "{0:.2f}".format((float(v) / total) * 100)
print(PrintColors.OKBLUE + k + " = " + str(v) +
"(" + percentage + "%)" + PrintColors.ENDC)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/mapviewers/hdmapviewer.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2018 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
import argparse
from bokeh.plotting import figure, output_file, show
from modules.common_msgs.map_msgs import map_pb2
import modules.tools.common.proto_utils as proto_utils
def draw(map_pb, plot):
for lane in map_pb.lane:
for curve in lane.left_boundary.curve.segment:
if curve.HasField('line_segment'):
x = []
y = []
for p in curve.line_segment.point:
x.append(p.x)
y.append(p.y)
plot.line(x, y, line_width=2)
for curve in lane.right_boundary.curve.segment:
if curve.HasField('line_segment'):
x = []
y = []
for p in curve.line_segment.point:
x.append(p.x)
y.append(p.y)
plot.line(x, y, line_width=2)
def load_map_data(map_file):
map_pb = map_pb2.Map()
proto_utils.get_pb_from_file(map_file, map_pb)
return map_pb
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="HDMapViewer is a tool to display hdmap.",
prog="hdmapviewer.py")
parser.add_argument(
"-m", "--map", action="store", type=str, required=True,
help="Specify the HDMap file in txt or binary format")
args = parser.parse_args()
map_pb = load_map_data(args.map)
output_file("hdmap.html")
plot = figure(sizing_mode='scale_both', match_aspect=True)
draw(map_pb, plot)
show(plot)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/mapviewers/gmapviewer.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2018 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
import json
import pyproj
import argparse
from yattag import Doc
import modules.tools.common.proto_utils as proto_utils
from modules.common_msgs.map_msgs import map_pb2
def generate(api_key, left_boundaries, right_boundaries, center_lat,
center_lon):
"""
function to generate html code.
"""
doc, tag, text, line = Doc().ttl()
doc.asis('<!DOCTYPE html>')
api_url = 'https://maps.googleapis.com/maps/api/js?key=' + \
api_key + '&callback=initMap'
with tag('html'):
with tag('head'):
with tag('title'):
text('Gmap Viewer')
doc.asis('<meta name="viewport" content="initial-scale=1.0">')
doc.asis('<meta charset="utf-8">')
with tag('style'):
doc.asis('#map { height: 100%; }')
doc.asis('html, body { height: 100%; margin: 0; padding: 0; }')
with tag('body'):
with tag('div', id='map'):
pass
with tag('script'):
doc.asis('\nvar map;\n')
doc.asis("\nvar colors = ['#e6194b', '#3cb44b', '#ffe119', \
'#0082c8', '#f58231', '#911eb4', '#46f0f0', '#f032e6', \
'#d2f53c', '#fabebe', '#008080', '#e6beff', '#aa6e28', \
'#fffac8', '#800000', '#aaffc3', '#808000', '#ffd8b1', \
'#000080', '#808080', '#000000']\n")
doc.asis('function initMap() {\n')
doc.asis("map = new google.maps.Map(\
document.getElementById('map'), {\n")
doc.asis('center: {lat: ' + str(center_lat) +
', lng: ' + str(center_lon) + '},\n')
doc.asis('zoom: 16\n')
doc.asis('});\n')
doc.asis('var left_boundaries = ' +
json.dumps(left_boundaries) + ';\n')
doc.asis("""
for (var i = 0; i < left_boundaries.length; i++) {
var boundary = new google.maps.Polyline({
path: left_boundaries[i],
geodesic: true,
strokeColor: colors[i % colors.length],
strokeOpacity: 1.0,
strokeWeight: 3
});
boundary.setMap(map);
}
""")
doc.asis('var right_boundaries = ' +
json.dumps(right_boundaries) + ';\n')
doc.asis("""
for (var i = 0; i < right_boundaries.length; i++) {
var boundary = new google.maps.Polyline({
path: right_boundaries[i],
geodesic: true,
strokeColor: colors[i % colors.length],
strokeOpacity: 1.0,
strokeWeight: 3
});
boundary.setMap(map);
}
""")
doc.asis('}\n')
doc.asis('<script src="' + api_url + '"></script>')
html = doc.getvalue()
return html
def utm2latlon(x, y, pzone=10):
"""
convert the utm x y to lat and lon
"""
projector2 = pyproj.Proj(proj='utm', zone=pzone, ellps='WGS84')
lon, lat = projector2(x, y, inverse=True)
return lat, lon
def run(gmap_key, map_file, utm_zone):
"""
read and process map file
"""
map_pb = map_pb2.Map()
proto_utils.get_pb_from_file(map_file, map_pb)
left_boundaries = []
right_boundaries = []
center_lat = None
center_lon = None
for lane in map_pb.lane:
for curve in lane.left_boundary.curve.segment:
if curve.HasField('line_segment'):
left_boundary = []
for p in curve.line_segment.point:
point = {}
lat, lng = utm2latlon(p.x, p.y, utm_zone)
if center_lat is None:
center_lat = lat
if center_lon is None:
center_lon = lng
point['lat'] = lat
point['lng'] = lng
left_boundary.append(point)
left_boundaries.append(left_boundary)
for curve in lane.right_boundary.curve.segment:
if curve.HasField('line_segment'):
right_boundary = []
for p in curve.line_segment.point:
point = {}
lat, lng = utm2latlon(p.x, p.y, utm_zone)
point['lat'] = lat
point['lng'] = lng
right_boundary.append(point)
right_boundaries.append(right_boundary)
html = generate(gmap_key, left_boundaries, right_boundaries, center_lat,
center_lon)
with open('gmap.html', 'w') as file:
file.write(html)
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Mapshow is a tool to display hdmap info on a map.",
prog="mapshow.py")
parser.add_argument(
"-m", "--map", action="store", type=str, required=True,
help="Specify the HDMap file in txt or binary format")
parser.add_argument(
"-k", "--key", action="store", type=str, required=True,
help="Specify your google map api key")
parser.add_argument(
"-z", "--zone", action="store", type=int, required=True,
help="Specify utm zone id. e.g, -z 10")
args = parser.parse_args()
run(args.key, args.map, args.zone)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/mapviewers/README.md
|
# MapViewers
MapViewers folder contains a set of tools for plotting map related data.
### gmapviewer.py
Gmapviewer is a tool to display HDMap on Google map through Google map javascript API. It generates a html file (gmap.html) with HDMap data. You could view the data by opening the html file in a web browser.
You need to install yattag before running the script
```
pip install yattag
```
Inside docker, run the following command from your Apollo root dir:
```
python modules/tools/mapviewer/gmap_viwer.py -m map_path_and_file
```
An output file
```
gmap.html
```
can be found in your Apollo root dir.
The default utm zone is set to ***10*** in this tool. if the HDMap is located in a differet utm zone, run following command with a specified zone id:
```
python modules/tools/mapviewer/gmap_viwer.py map_path_and_file utm_zone_id
```
### hdmapviewer.py
Activate environments:
```
conda create --name py27bokeh python=2.7.15 numpy scipy bokeh protobuf
conda activate py27bokeh
```
Inside docker, run the following command from Apollo root dir:
```
python modules/tools/mapviewer/hdmapviwer.py -m map_path_and_file
```
An output file
```
hdmap.html
```
can be found in your Apollo root dir.
Deactivate environments:
```
conda deactivate
```
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/mapviewers/BUILD
|
load("@rules_python//python:defs.bzl", "py_binary")
load("//tools/install:install.bzl", "install")
package(default_visibility = ["//visibility:public"])
filegroup(
name = "readme",
srcs = [
"README.md",
],
)
py_binary(
name = "gmapviewer",
srcs = ["gmapviewer.py"],
deps = [
"//modules/common_msgs/map_msgs:map_py_pb2",
"//modules/tools/common:proto_utils",
],
)
py_binary(
name = "hdmapviewer",
srcs = ["hdmapviewer.py"],
deps = [
"//modules/common_msgs/map_msgs:map_py_pb2",
"//modules/tools/common:proto_utils",
],
)
install(
name = "install",
data = [":readme"],
data_dest = "tools/mapviewers",
py_dest = "tools/mapviewers",
targets = [
"gmapviewer",
"hdmapviewer",
]
)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/common/logger.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
"""
This module provides the logging function.
"""
import logging
import logging.handlers
import os
import sys
class Logger(object):
"""The logger factory class. It is a template to help quickly create a log utility.
Attributes:
set_conf(log_file, use_stdout, log_level): this is a static method that returns a configured logger.
get_logger(tag): this is a static method that returns a configured logger.
"""
__loggers = {}
__use_stdout = True
__log_file = ""
__log_level = logging.DEBUG
@staticmethod
def config(log_file, use_stdout, log_level):
"""set the config, where config is a ConfigParser object
"""
Logger.__use_stdout = use_stdout
Logger.__log_level = log_level
dirname = os.path.dirname(log_file)
if (not os.path.isfile(log_file)) and (not os.path.isdir(dirname)):
try:
os.makedirs(dirname)
except OSError as e:
print("create path '%s' for logging failed: %s" % (dirname, e))
sys.exit()
Logger.__log_file = log_file
@staticmethod
def get_logger(tag):
"""return the configured logger object
"""
if tag not in Logger.__loggers:
Logger.__loggers[tag] = logging.getLogger(tag)
Logger.__loggers[tag].setLevel(Logger.__log_level)
formatter = logging.Formatter(
"[%(name)s][%(levelname)s] %(asctime)s "
"%(filename)s:%(lineno)s %(message)s")
file_handler = logging.handlers.TimedRotatingFileHandler(
Logger.__log_file, when='H', interval=1, backupCount=0)
file_handler.setLevel(Logger.__log_level)
file_handler.setFormatter(formatter)
file_handler.suffix = "%Y%m%d%H%M.log"
Logger.__loggers[tag].addHandler(file_handler)
if Logger.__use_stdout:
stream_headler = logging.StreamHandler()
stream_headler.setLevel(Logger.__log_level)
stream_headler.setFormatter(formatter)
Logger.__loggers[tag].addHandler(stream_headler)
return Logger.__loggers[tag]
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/common/file_utils.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2020 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
"""File utils."""
import os
def list_files(dir_path):
"""List all sub-files in given dir_path."""
return [
os.path.join(root, f) for root, _, files in os.walk(dir_path)
for f in files
]
def getInputDirDataSize(path):
sumsize = 0
filelist = list_files(path)
for file in filelist:
size = os.path.getsize(file)
sumsize += size
return int(sumsize)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/common/message_manager.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
from modules.common_msgs.audio_msgs import audio_event_pb2
from modules.common_msgs.localization_msgs import localization_pb2
from modules.common_msgs.perception_msgs import perception_obstacle_pb2
from modules.common_msgs.perception_msgs import traffic_light_detection_pb2
from modules.common_msgs.planning_msgs import planning_internal_pb2
from modules.common_msgs.planning_msgs import planning_pb2
from modules.common_msgs.prediction_msgs import prediction_obstacle_pb2
from modules.common_msgs.routing_msgs import routing_pb2
from modules.common_msgs.control_msgs import control_cmd_pb2
from modules.common_msgs.chassis_msgs import chassis_pb2
from modules.common_msgs.basic_msgs import drive_event_pb2
from modules.common_msgs.planning_msgs import navigation_pb2
from modules.common_msgs.guardian_msgs import guardian_pb2
from modules.tools.common import proto_utils
class MessageType:
def __init__(self, name, topic, msg_type):
self.name = name
self.topic = topic
self.msg_type = msg_type
def instance(self):
return self.__msg_type()
def parse_file(self, filename):
value = self.instance()
if not proto_utils.get_pb_from_file(filename, value):
print("Failed to parse file %s" % filename)
return None
else:
return value
topic_pb_list = [
MessageType("audio_event", "/apollo/audio_event",
audio_event_pb2.AudioEvent),
MessageType("planning", "/apollo/planning", planning_pb2.ADCTrajectory),
MessageType("control", "/apollo/control", control_cmd_pb2.ControlCommand),
MessageType("chassis", "/apollo/canbus/chassis", chassis_pb2.Chassis),
MessageType("prediction", "/apollo/prediction",
prediction_obstacle_pb2.PredictionObstacles),
MessageType("perception", "/apollo/perception/obstacles",
perception_obstacle_pb2.PerceptionObstacles),
MessageType("routing_response", "/apollo/routing_response",
routing_pb2.RoutingResponse),
MessageType("routing_request", "/apollo/routing_request",
routing_pb2.RoutingRequest),
MessageType("localization", "/apollo/localization/pose",
localization_pb2.LocalizationEstimate),
MessageType("traffic_light", "/apollo/perception/traffic_light",
traffic_light_detection_pb2.TrafficLightDetection),
MessageType("drive_event", "/apollo/drive_event",
drive_event_pb2.DriveEvent),
MessageType("relative_map", "/apollo/relative_map", navigation_pb2.MapMsg),
MessageType("navigation", "/apollo/navigation",
navigation_pb2.NavigationInfo),
MessageType("guardian", "/apollo/guardian", guardian_pb2.GuardianCommand),
]
class PbMessageManager:
def __init__(self):
self.__topic_dict = {}
self.__name_dict = {}
for msg in topic_pb_list:
self.__topic_dict[msg.topic] = msg
self.__name_dict[msg.name] = msg
def topic_dict(self):
return self.__topic_dict
def get_msg_meta_by_topic(self, topic):
if topic in self.__topic_dict:
return self.__topic_dict[topic]
else:
return None
def get_msg_meta_by_name(self, name):
if name in self.__name_dict:
return self.__name_dict[name]
else:
return None
def name_dict(self):
return self.__name_dict
def parse_topic_file(self, topic, filename):
if topic not in self.__topic_dict:
print("topic %s is not registered in topic_pb_list" % topic)
return None
meta_msg = self.__topic_dict[topic]
return meta_msg.parse_file(filename)
def parse_file(self, filename):
"""parse a file by guessing topic type"""
for topic, meta_msg in self.__topic_dict.items():
try:
message = meta_msg.parse_file(filename)
if message:
print("identified topic %s" % topic)
return (meta_msg, message)
except text_format.ParseError as e:
print("Tried %s, failed" % (topic))
continue
return (None, None)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/common/BUILD
|
load("@rules_python//python:defs.bzl", "py_library")
package(default_visibility = ["//visibility:public"])
filegroup(
name = "py_files",
srcs = glob([
"*.py",
]),
)
py_library(
name = "logger",
srcs = ["logger.py"],
)
py_library(
name = "message_manager",
srcs = ["message_manager.py"],
deps = [
":proto_utils",
"//modules/common_msgs/audio_msgs:audio_event_py_pb2",
"//modules/common_msgs/chassis_msgs:chassis_py_pb2",
"//modules/common_msgs/basic_msgs:drive_event_py_pb2",
"//modules/common_msgs/control_msgs:control_cmd_py_pb2",
"//modules/common_msgs/guardian_msgs:guardian_py_pb2",
"//modules/common_msgs/localization_msgs:localization_py_pb2",
"//modules/common_msgs/planning_msgs:navigation_py_pb2",
"//modules/common_msgs/perception_msgs:perception_obstacle_py_pb2",
"//modules/common_msgs/perception_msgs:traffic_light_detection_py_pb2",
"//modules/common_msgs/planning_msgs:planning_internal_py_pb2",
"//modules/common_msgs/planning_msgs:planning_py_pb2",
"//modules/common_msgs/prediction_msgs:prediction_obstacle_py_pb2",
"//modules/common_msgs/routing_msgs:routing_py_pb2",
],
)
py_library(
name = "proto_utils",
srcs = ["proto_utils.py"],
)
py_library(
name = "file_utils",
srcs = ["file_utils.py"],
)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/common/proto_utils.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
"""Protobuf utils."""
import google.protobuf.text_format as text_format
def write_pb_to_text_file(topic_pb, file_path):
"""write pb message to file"""
with open(file_path, 'w') as f:
f.write(str(topic_pb))
def get_pb_from_text_file(filename, pb_value):
"""Get a proto from given text file."""
with open(filename, 'r') as file_in:
return text_format.Merge(file_in.read(), pb_value)
def get_pb_from_bin_file(filename, pb_value):
"""Get a proto from given binary file."""
with open(filename, 'rb') as file_in:
pb_value.ParseFromString(file_in.read())
return pb_value
def get_pb_from_file(filename, pb_value):
"""Get a proto from given file by trying binary mode and text mode."""
try:
return get_pb_from_bin_file(filename, pb_value)
except:
try:
return get_pb_from_text_file(filename, pb_value)
except:
print('Error: Cannot parse %s as binary or text proto' % filename)
return None
def flatten(pb_value, selectors):
"""
Get a flattened tuple from pb_value. Selectors is a list of sub-fields.
Usage:
For a pb_value of:
total_pb = {
me: { name: 'myself' }
children: [{ name: 'child0' }, { name: 'child1' }]
}
my_name, child0_name = flatten(total_pb, ['me.name', 'children[0].name'])
# You get (my_name='myself', child0_name='child0')
children_names = flatten(total_pb, 'children.name')
# You get (children_names=['child0', 'child1'])
"""
def __select_field(val, field):
if hasattr(val, '__len__'):
# Flatten repeated field.
return [__select_field(elem, field) for elem in val]
if not field.endswith(']'):
# Simple field.
return val.__getattribute__(field)
# field contains index: "field[index]".
field, index = field.split('[')
val = val.__getattribute__(field)
index = int(index[:-1])
return val[index] if index < len(val) else None
def __select(val, selector):
for field in selector.split('.'):
val = __select_field(val, field)
if val is None:
return None
return val
# Return the single result for single selector.
if isinstance(selectors, str):
return __select(pb_value, selectors)
# Return tuple result for multiple selectors.
return tuple((__select(pb_value, selector) for selector in selectors))
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/plot_trace/plot_trace.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
import sys
import matplotlib.animation as animation
import matplotlib.pyplot as plt
import numpy as np
from cyber.python.cyber_py3 import cyber
from modules.common_msgs.chassis_msgs import chassis_pb2
from modules.common_msgs.localization_msgs import localization_pb2
GPS_X = list()
GPS_Y = list()
GPS_LINE = None
DRIVING_MODE_TEXT = ""
CHASSIS_TOPIC = "/apollo/canbus/chassis"
LOCALIZATION_TOPIC = "/apollo/localization/pose"
IS_AUTO_MODE = False
def chassis_callback(chassis_data):
global IS_AUTO_MODE
if chassis_data.driving_mode == chassis_pb2.Chassis.COMPLETE_AUTO_DRIVE:
IS_AUTO_MODE = True
else:
IS_AUTO_MODE = False
DRIVING_MODE_TEXT = str(chassis_data.driving_mode)
def localization_callback(localization_data):
global GPS_X
global GPS_Y
global IS_AUTO_MODE
if IS_AUTO_MODE:
GPS_X.append(localization_data.pose.position.x)
GPS_Y.append(localization_data.pose.position.y)
def setup_listener(node):
node.create_reader(CHASSIS_TOPIC, chassis_pb2.Chassis, chassis_callback)
node.create_reader(LOCALIZATION_TOPIC,
localization_pb2.LocalizationEstimate,
localization_callback)
while not cyber.is_shutdown():
time.sleep(0.002)
def update(frame_number):
global GPS_X
global GPS_Y
if IS_AUTO_MODE and len(GPS_X) > 1:
min_len = min(len(GPS_X), len(GPS_Y)) - 1
GPS_LINE.set_data(GPS_X[-min_len:], GPS_Y[-min_len:])
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(
description="""A visualization tool that can plot a manual driving trace produced by the rtk_player tool,
and plot the autonomous driving trace in real time.
The manual driving trace is the blue lines, and the autonomous driving trace is the red lines.
It is visualization a way to verify the precision of the autonomous driving trace.
If you have a cyber record file, you can play the record and the tool will plot the received localization
message in realtime. To do that, start this tool first with a manual driving trace, and then
play record use another terminal with the following command [replace your_file.record to your
own record file]: cyber_record play -f your_file.record
""")
parser.add_argument(
"trace",
action='store',
type=str,
help='the manual driving trace produced by rtk_player')
args = parser.parse_args()
fig, ax = plt.subplots()
with open(args.trace, 'r') as fp:
trace_data = np.genfromtxt(handle, delimiter=',', names=True)
ax.plot(trace_data['x'], trace_data['y'], 'b-', alpha=0.5, linewidth=1)
cyber.init()
node = cyber.Node("plot_trace")
setup_listener(node)
x_min = min(trace_data['x'])
x_max = max(trace_data['x'])
y_min = min(trace_data['y'])
y_max = max(trace_data['y'])
GPS_LINE, = ax.plot(GPS_X, GPS_Y, 'r', linewidth=3, label="gps")
ani = animation.FuncAnimation(fig, update, interval=100)
plt.show()
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/plot_trace/BUILD
|
load("@rules_python//python:defs.bzl", "py_binary")
load("//tools/install:install.bzl", "install")
package(default_visibility = ["//visibility:public"])
py_binary(
name = "plot_planning_result",
srcs = ["plot_planning_result.py"],
deps = [
"//modules/common_msgs/chassis_msgs:chassis_py_pb2",
"//modules/common_msgs/localization_msgs:localization_py_pb2",
"//modules/common_msgs/planning_msgs:planning_py_pb2",
],
)
py_binary(
name = "plot_trace",
srcs = ["plot_trace.py"],
deps = [
"//cyber/python/cyber_py3:cyber",
"//modules/common_msgs/chassis_msgs:chassis_py_pb2",
"//modules/common_msgs/localization_msgs:localization_py_pb2",
],
)
install(
name = "install",
py_dest = "tools/plot_trace",
targets = [
":plot_trace",
":plot_planning_result",
]
)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/plot_trace/plot_planning_result.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
from subprocess import call
import sys
from google.protobuf import text_format
from mpl_toolkits.mplot3d import Axes3D
import matplotlib
import matplotlib.animation as animation
import matplotlib.pyplot as plt
import numpy as np
from modules.common_msgs.chassis_msgs import chassis_pb2
from modules.common_msgs.localization_msgs import localization_pb2
from modules.common_msgs.planning_msgs import planning_pb2
g_args = None
def get_3d_trajectory(planning_pb):
x = [p.path_point.x for p in planning_pb.trajectory_point]
y = [p.path_point.y for p in planning_pb.trajectory_point]
z = [p.v for p in planning_pb.trajectory_point]
return (x, y, z)
def get_debug_paths(planning_pb):
if not planning_pb.HasField("debug"):
return None
if not planning_pb.debug.HasField("planning_data"):
return None
results = []
for path in planning_pb.debug.planning_data.path:
x = [p.x for p in path.path_point]
y = [p.y for p in path.path_point]
results.append((path.name, (x, y)))
return results
def plot_planning(ax, planning_file):
with open(planning_file, 'r') as fp:
planning_pb = planning_pb2.ADCTrajectory()
text_format.Merge(fp.read(), planning_pb)
trajectory = get_3d_trajectory(planning_pb)
ax.plot(trajectory[0], trajectory[1], trajectory[2],
label="Trajectory:%s" % planning_file)
paths = get_debug_paths(planning_pb)
if paths:
for name, path in paths:
ax.plot(path[0], path[1], label="%s:%s" % (name, planning_file))
ax.legend()
def press_key(event):
if event.key == 'c':
files = g_args.planning_files
if len(files) != 2:
print('Need more than two files.')
return
command = ["cp"]
for f in files:
command.append(f)
if call(command) == 0:
print('command success: %s' % " ".join(command))
sys.exit(0)
else:
print('Failed to run command: %s ' % " ".join(command))
sys.exit(1)
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(
description="""A visualization tool that can plot one or multiple planning "
results, so that we can compare the differences.
Example: plot_planning_result.py result_file1.pb.txt result_file2.pb.txt"""
)
parser.add_argument(
"planning_files",
action='store',
nargs="+",
help="The planning results")
parser.add_argument(
"--figure",
action='store',
type=str,
help="Save the planning results to picture, if not set, show on screen"
)
g_args = parser.parse_args()
matplotlib.rcParams['legend.fontsize'] = 10
fig = plt.figure()
fig.canvas.mpl_connect('key_press_event', press_key)
ax = fig.gca(projection='3d')
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("speed")
for planning_file in g_args.planning_files:
plot_planning(ax, planning_file)
if g_args.figure:
plt.savefig(g_args.figure)
print('picture saved to %s' % g_args.figure)
else:
plt.show()
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/record_parse_save/parse_camera.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2018 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
"""
function to parse camera images from *.record files, created using Apollo-Auto
parsed data is saved to *.jpeg file, for each capture
"""
import os
import sys
from cyber.python.cyber_py3 import cyber
from cyber.python.cyber_py3 import record
from modules.common_msgs.sensor_msgs.sensor_image_pb2 import CompressedImage
def parse_data(channelname, msg, out_folder):
"""
parser images from Apollo record file
"""
msg_camera = CompressedImage()
msg_camera.ParseFromString(msg)
tstamp = msg_camera.measurement_time
temp_time = str(tstamp).split('.')
if len(temp_time[1]) == 1:
temp_time1_adj = temp_time[1] + '0'
else:
temp_time1_adj = temp_time[1]
image_time = temp_time[0] + '_' + temp_time1_adj
image_filename = "image_" + image_time + ".jpeg"
f = open(out_folder + image_filename, 'w+b')
f.write(msg_camera.data)
f.close()
return tstamp
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/record_parse_save/parse_lidar.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2018 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
"""
function to parse lidar data from *.record files, created using Apollo-Auto
parsed data is saved to *.txt file, for each scan
current implementation for:
* Velodyne VLS-128 lidar
"""
import os
import sys
from cyber.python.cyber_py3 import cyber
from cyber.python.cyber_py3 import record
from modules.common_msgs.sensor_msgs.pointcloud_pb2 import PointCloud
def parse_data(channelname, msg, out_folder):
"""
"""
msg_lidar = PointCloud()
msg_lidar.ParseFromString(msg)
nPts = len(msg_lidar.point)
pcd = []
for j in range(nPts):
p = msg_lidar.point[j]
pcd.append([p.x, p.y, p.z, p.intensity])
tstamp = msg_lidar.measurement_time
temp_time = str(tstamp).split('.')
if len(temp_time[1]) == 1:
temp_time1_adj = temp_time[1] + '0'
else:
temp_time1_adj = temp_time[1]
pcd_time = temp_time[0] + '_' + temp_time1_adj
pcd_filename = "pcd_" + pcd_time + ".txt"
with open(out_folder + pcd_filename, 'w') as outfile:
for item in pcd:
data = str(item)[1:-1]
outfile.write("%s\n" % data)
return tstamp
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/record_parse_save/record_parse_save.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2018 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
"""
function to parse data from *.record files, created using Apollo-Auto
current implementation illustrates sample record file parsing for
* radar (Continental ars-408)
* camera (Leopard Imaging 6mm)
* lidar (Velodyne vls-128)
* saves extracted images in separate folder using *.jpg format
* saves radar and lidar data in respective folders in *.txt format for each scan
* also saves timestamp in separate text files
"""
import os
import sys
import time
from importlib import import_module
import yaml
from cyber.python.cyber_py3 import cyber
from cyber.python.cyber_py3 import record
os.system('clear')
def read_parameters(yaml_file):
"""
function to read YAML parameter file and define output destinations
"""
with open(yaml_file, 'r') as f:
params = yaml.safe_load(f)
# record file params
RECORD_FOLDER = params['records']['filepath']
parse_type = params['parse']
# define destinations
dest_path = os.path.split(RECORD_FOLDER)
if not dest_path[-1]:
dest_path = os.path.split(dest_path[0])
OUT_FOLDER = dest_path[0] + '/'
temp_path = os.path.split(dest_path[0])
FOLDER_PREFIX = temp_path[1].replace("-", "")
parse_dict = {"params": params,
"parse_type": parse_type,
"out_folder": OUT_FOLDER,
"prefix": FOLDER_PREFIX,
"record_folder": RECORD_FOLDER}
return parse_dict
def define_destinations(parse_dict):
"""
define destination for extracted files
"""
dest_dict = {
"channel_name": "",
"timestamp_file": "",
"destination_folder": ""
}
parse_type = parse_dict["parse_type"]
params = parse_dict["params"]
dest_folder = parse_dict["out_folder"]
prefix = parse_dict["prefix"]
parser_func = 'parse_' + parse_type
dest_dict['channel_name'] = params[parse_type]['channel_name']
dest_dict['timestamp_file'] = dest_folder + prefix + params[parse_type]['timestamp_file_extn']
dest_dict['destination_folder'] = dest_folder + \
prefix + params[parse_type]['out_folder_extn'] + '/'
if not os.path.exists(dest_dict["destination_folder"]):
os.makedirs(dest_dict["destination_folder"])
return dest_dict, parser_func
def parse_apollo_record(parse_dict, dest_dict, parser_func):
"""
"""
record_folder_path = parse_dict["record_folder"]
parse_type = parse_dict["parse_type"]
record_files = sorted(os.listdir(parse_dict["record_folder"]))
parse_timestamp = []
parse_mod = import_module(parser_func)
print("=" * 60)
print('--------- Parsing data for: ' + parse_type + ' ---------')
for rfile in record_files:
print("=" * 60)
print("parsing record file: %s" % rfile)
freader = record.RecordReader(record_folder_path + rfile)
time.sleep(.025)
for channelname, msg, datatype, timestamp in freader.read_messages():
if channelname == dest_dict["channel_name"]:
tstamp = parse_mod.parse_data(channelname, msg, dest_dict['destination_folder'])
parse_timestamp.append(tstamp)
# write radar-timestamp files
with open(dest_dict["timestamp_file"], 'w+') as f:
for item in parse_timestamp:
f.write("%s\n" % item)
print("=" * 60)
print('DONE: records parsed and data saved to: \n ' + dest_dict['destination_folder'])
print("=" * 60)
if __name__ == '__main__':
cyber.init()
parse_dict = read_parameters('./parser_params.yaml')
dest_dict, parser_func = define_destinations(parse_dict)
parse_apollo_record(parse_dict, dest_dict, parser_func)
cyber.shutdown()
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/record_parse_save/parser_params.yaml
|
records:
filepath: /apollo/data/record_files/2019-04-22-14-27-05/2019-04-22-14-27-05_records/
parse: radar
# use one of the following options or add more:
# lidar
# radar
# camera
lidar: # for velodyne vls-128 lidar
channel_name: /apollo/sensor/lidar128/PointCloud2
out_folder_extn: _lidar_vls128
timestamp_file_extn: _lidar_vls128_timestamp.txt
radar: # for ARS-408 radar mounted in front
channel_name: /apollo/sensor/radar/front
out_folder_extn: _radar_conti408_front
timestamp_file_extn: _radar_conti408_front_timestamp.txt
camera: # for 6mm camera mounted in front
channel_name: /apollo/sensor/camera/front_6mm/image/compressed
out_folder_extn: _camera_6mm_front
timestamp_file_extn: _camera_6mm_front_timestamp.txt
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/record_parse_save/README.md
|
## Apollo cyber-record file parser (Python based)
#### Introduction
This tool presents multiple examples of how to parse data from a record file and
save using predefined format. The tool has been built on example provided within
Apollo (`/apollo/cyber/python/examples/`).
The samples provided here illustrate cases for, parsing data from:
- lidar: based on
[Velodyne VLS-128](../../../docs/specs/Lidar/VLS_128_Installation_Guide.md)
- radar: based on
[Continental ARS-408-21](../../../docs/specs/Radar/Continental_ARS408-21_Radar_Installation_Guide.md)
- camera: based on
[Leopard Imaging Inc's Camera - LI-USB30-AZ023WDRB](../../../docs/specs/Camera/Leopard_Camera_LI-USB30-AZ023WDR__Installation_Guide.md)
#### Files and functions:
The files/functions provided are as follows:
- [`record_parse_save.py`](./record_parse_save.py): main function that parses
record files from and saves extracted data to specified location
- [`parse_lidar.py`](./parse_lidar.py): function to parse lidar data
- [`parse_radar.py`](./parse_radar.py): function to parse radar data
- [`parse_camera.py`](./parse_camera.py): function to parse camera data
- [`parser_params.yaml`](./parser_params.yaml): YAML file with details of
record-file location, where the output files should be saved and what sensor
data should be parsed along with specific channel-names associated with
particular sensor, it's configuration and it's location.
- list of channels in a record-file can be obtained using
`cyber_recorder info`. For example, to get details on a sample record file
`20190422142705.record.00000` saved at:
`/apollo/data/record_files/2019-04-22-14-27-05/2019-04-22-14-27-05_records/`
enter following at command prompt:
- `cyber_recorder info /apollo/data/record_files/2019-04-22-14-27-05/2019-04-22-14-27-05_records/20190422142705.record.00000`
- The output on screen will look like that presented in the image below:

#### Dependency
> sudo pip install pyyaml
#### How-to-use:
- It is assumed that the user is within Apollo docker environment and has
successfully built it. Please check documentation on
[Build Apollo](../../../docs/howto/how_to_launch_and_run_apollo.md) if
required.
- Modify parameters specified within `parser_params.yaml` to serve your purpose.
- After correct parameters are specified in the YAML file, run parser function
in `/apollo` using:
`./bazel-bin/modules/tools/record_parse_save/record_parse_save`
- parsed sensor data will be saved in new folder along with associated capture
or scan timestamps in a text file.
#### NOTES
- In the example setup here, parsed data is saved within the parent folder
containing the records-file's folder. Every saved file has associated
timestamp with it.
- All record-files within the folder are parsed. If any record file is corrupt,
the parser will display error message and continue to next record file.
- `radar` data is saved in text files in JSON format for each scan
- `lidar` point-cloud data is saved in text files for each scan
- `camera` images are saved in jpeg file for each capture
- All timestamps are saved in a separate file with `timestamp` suffix, in the
same order in which the parsed files are saved in corresponding folder.
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/record_parse_save/parse_radar.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2018 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
"""
function to parse radar data from *.record files, created using Apollo-Auto
parsed data is saved to *.txt file, for each scan
currently implementation for:
* Continental ARS-408 radar
"""
import json
import os
import sys
from cyber.python.cyber_py3 import cyber
from cyber.python.cyber_py3 import record
from modules.common_msgs.sensor_msgs.conti_radar_pb2 import ContiRadar
class RadarMessageConti408(object):
def __init__(self):
self.radarDetectionList = []
self.timestamp_sec = None
self.num_of_detections = None
self.radar_module = None
self.sequence_num = None
self.radar_channel = None
self.additional_notes = None
def toJSON(self):
return json.dumps(self, default=lambda o: o.__dict__,
sort_keys=True, indent=4)
class ContiRadarARS408Detection(object):
def __init__(self):
self.clusterortrack = None
self.obstacle_id = None
self.longitude_dist = None
self.lateral_dist = None
self.longitude_vel = None
self.lateral_vel = None
self.rcs = None
self.dynprop = None
self.longitude_dist_rms = None
self.lateral_dist_rms = None
self.longitude_vel_rms = None
self.lateral_vel_rms = None
self.probexist = None
self.meas_state = None
self.longitude_accel = None
self.lateral_accel = None
self.oritation_angle = None
self.longitude_accel_rms = None
self.lateral_accel_rms = None
self.oritation_angle_rms = None
self.length = None
self.width = None
self.obstacle_class = None
def pull_conti_radar_detections(obs):
"""
file to convert structure from c++ to python format
"""
dets = ContiRadarARS408Detection()
dets.clusterortrack = obs.clusterortrack
dets.obstacle_id = obs.obstacle_id
dets.longitude_dist = obs.longitude_dist
dets.lateral_dist = obs.lateral_dist
dets.longitude_vel = obs.longitude_vel
dets.lateral_vel = obs.lateral_vel
dets.rcs = obs.rcs
dets.dynprop = obs.dynprop
dets.longitude_dist_rms = obs.longitude_dist_rms
dets.lateral_dist_rms = obs.lateral_dist_rms
dets.longitude_vel_rms = obs.longitude_vel_rms
dets.lateral_vel_rms = obs.lateral_vel_rms
dets.probexist = obs.probexist
dets.meas_state = obs.meas_state
dets.longitude_accel = obs.longitude_accel
dets.lateral_accel = obs.lateral_accel
dets.oritation_angle = obs.oritation_angle
dets.longitude_accel_rms = obs.longitude_accel_rms
dets.lateral_accel_rms = obs.lateral_accel_rms
dets.oritation_angle_rms = obs.oritation_angle_rms
dets.length = obs.length
dets.width = obs.width
dets.obstacle_class = obs.obstacle_class
return dets
def parse_data(channelname, msg, out_folder):
"""
parser for record-file data from continental ars-408 radar
"""
msg_contiradar = ContiRadar()
msg_contiradar.ParseFromString(msg)
n = len(msg_contiradar.contiobs)
detections = []
radar_msg = RadarMessageConti408()
head_msg = msg_contiradar.contiobs[0].header
radar_msg.timestamp_sec = head_msg.timestamp_sec
radar_msg.num_of_detections = n
radar_msg.radar_module = head_msg.module_name
radar_msg.sequence_num = head_msg.sequence_num
radar_msg.radar_channel = channelname
for i in range(len(msg_contiradar.contiobs)):
detections.append(pull_conti_radar_detections(msg_contiradar.contiobs[i]))
radar_msg.radarDetectionList = detections
json_data = radar_msg.toJSON()
tstamp = json_data.split()[-2].ljust(20, '0')
# write this scan to file
scan_filename = "radar_scan_" + tstamp.replace('.', '_') + ".txt"
with open(out_folder + scan_filename, 'w') as outfile:
outfile.write(json_data)
return tstamp
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/record_parse_save/BUILD
|
load("@rules_python//python:defs.bzl", "py_binary", "py_library")
load("//tools/install:install.bzl", "install")
package(default_visibility = ["//visibility:public"])
filegroup(
name = "config",
srcs = glob(["*.yaml"]) + ["README.md"],
)
py_library(
name = "parse_camera",
srcs = ["parse_camera.py"],
deps = [
"//cyber/python/cyber_py3:cyber",
"//cyber/python/cyber_py3:record",
"//modules/common_msgs/sensor_msgs:sensor_image_py_pb2",
],
)
py_library(
name = "parse_lidar",
srcs = ["parse_lidar.py"],
deps = [
"//cyber/python/cyber_py3:cyber",
"//cyber/python/cyber_py3:record",
"//modules/common_msgs/sensor_msgs:pointcloud_py_pb2",
],
)
py_library(
name = "parse_radar",
srcs = ["parse_radar.py"],
deps = [
"//cyber/python/cyber_py3:cyber",
"//cyber/python/cyber_py3:record",
"//modules/common_msgs/sensor_msgs:conti_radar_py_pb2",
],
)
py_binary(
name = "record_parse_save",
srcs = ["record_parse_save.py"],
data = [":config"],
deps = [
":parse_camera",
":parse_lidar",
":parse_radar",
"//cyber/python/cyber_py3:cyber",
"//cyber/python/cyber_py3:record",
],
)
install(
name = "install",
data = [":config"],
data_dest = "tools/record_parse_save",
py_dest = "tools/record_parse_save",
targets = [
":record_parse_save",
],
)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/navigator/viewer_smooth.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
import sys
import json
import matplotlib.pyplot as plt
import numpy
from scipy.signal import butter, lfilter, freqz
def get_s_xy_kappa(fn, ax, ax2):
f = open(fn, 'r')
xs = []
ys = []
ks = []
theta = []
s = []
cnt = 0
for line in f:
cnt += 1
if cnt < 3:
continue
line = line.replace("\n", '')
data = json.loads(line)
ks.append(data['kappa'])
s.append(data['s'])
xs.append(data['x'])
ys.append(data['y'])
theta.append(data['theta'])
f.close()
return s, xs, ys, theta, ks
def plot_raw_path(fn, ax):
f = open(fn, 'r')
xs = []
ys = []
for line in f:
line = line.replace("\n", '')
data = line.split(',')
x = float(data[0])
y = float(data[1])
xs.append(x)
ys.append(y)
f.close()
ax.plot(xs, ys, "r-", lw=3, alpha=0.8)
if __name__ == "__main__":
fig = plt.figure()
ax = plt.subplot2grid((2, 2), (0, 0))
ax2 = plt.subplot2grid((2, 2), (0, 1))
ax3 = plt.subplot2grid((2, 2), (1, 0))
ax4 = plt.subplot2grid((2, 2), (1, 1))
styles = ["bo", "ro", "yo"]
i = 0
fn = sys.argv[1]
plot_raw_path(fn, ax)
fn = sys.argv[2]
s, xs, ys, theta, ks = get_s_xy_kappa(fn, ax, ax2)
ax.plot(xs, ys, "b-", lw=8, alpha=0.5)
ax.set_title("x-y")
ax2.plot(s, ks, 'k-')
ax2.set_title("s-kappa")
ax2.axhline(y=0.0, color='b', linestyle='-')
ax3.plot(s, theta, 'k-')
ax3.set_title("s-theta")
ax4.plot(s, s, 'k-')
ax4.set_title("s-s")
if len(sys.argv) >= 4:
fn = sys.argv[3]
s, xs, ys, theta, ks = get_s_xy_kappa(fn, ax, ax2)
ax.plot(xs, ys, "r-", lw=8, alpha=0.5)
ax.set_title("x-y")
ax2.plot(s, ks, 'r-')
ax2.set_title("s-kappa")
ax2.axhline(y=0.0, color='b', linestyle='-')
ax3.plot(s, theta, 'r-')
ax3.set_title("s-theta")
ax4.plot(s, s, 'r-')
ax4.set_title("s-s")
ax.axis('equal')
plt.show()
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/navigator/smooth.sh
|
#!/usr/bin/env bash
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
# Get the absolute path.
dir=$(cd "$(dirname "$1" )" && pwd)
filename=$(basename $1)
pathname="${dir}/${filename}"
#echo ${pathname}
cd /apollo
./bazel-bin/modules/planning/reference_line/spiral_smoother_util --input_file ${pathname} --smooth_length $2
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/navigator/viewer_raw.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
import sys
import matplotlib.pyplot as plt
fig = plt.figure()
ax = plt.subplot2grid((1, 1), (0, 0))
styles = ["b-", "r-", "y-"]
i = 0
for fn in sys.argv[1:]:
f = open(fn, 'r')
xs = []
ys = []
for line in f:
line = line.replace("\n", '')
data = line.split(',')
x = float(data[0])
y = float(data[1])
xs.append(x)
ys.append(y)
f.close()
si = i % len(styles)
ax.plot(xs, ys, styles[si], lw=3, alpha=0.8)
i += 1
ax.axis('equal')
plt.show()
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/navigator/README.md
|
# Steps for
- Generating navigation data from bag and
- Manually sending the data to /apollo/navigation topic
### Step 1: In dev docker, extract path data from bags
```
dev_docker:/apollo$cd /modules/tools/navigator
dev_docker:/apollo/modules/tools/navigator$python extractor.py path-to-bags/*.bag
```
A path file will be generated in
```
dev_docker:/apollo/modules/tools/navigator$
```
With format of
```
path_[first_bag_name].bag.txt
```
### Step2: (Optional) Verify the extracted path is correct
dev_docker:/apollo/modules/tools/navigator$python viewer_raw.py path_[bag_name].bag.txt
### Step3: Smooth the path
```
dev_docker:/apollo/modules/tools/navigator$./smooth.sh /apollo/modules/tools/navigator/path_[first_bag_name].bag.txt 200
```
200 is the parameter for smooth length. If the smooth is failed, try to change this parameter to make the smooth pass. The preferred number is between 150 and 200.
A smoothed data file, path_[first_bag_name].bag.txt.smoothed, is generated under folder
```
dev_docker:/apollo/modules/tools/navigator$
```
### Step4: (Optional) Verify the smoothed data
```
dev_docker:/apollo/modules/tools/navigator$ python viewer_smooth.py path[first_bag_name].bag.txt path[first_bag_name].bag.txt.smoothed
```
### Step5: Send /apollo/navigation topic
Run follow command to send /apollo/navigation data
```
dev_docker:/apollo/modules/tools/navigator$python navigator.py path_[first_bag_name].bag.txt.smoothed
```
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/navigator/record_extractor.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2018 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
import sys
from datetime import datetime
from cyber.python.cyber_py3.record import RecordReader
from modules.common_msgs.localization_msgs import localization_pb2
if __name__ == '__main__':
if len(sys.argv) < 2:
print("usage: python record_extractor.py record_file1 record_file2 ...")
frecords = sys.argv[1:]
now = datetime.now().strftime("%Y-%m-%d_%H.%M.%S")
with open("path_" + frecords[0].split('/')[-1] + ".txt", 'w') as f:
for frecord in frecords:
print("processing " + frecord)
reader = RecordReader(frecord)
for msg in reader.read_messages():
if msg.topic == "/apollo/localization/pose":
localization = localization_pb2.LocalizationEstimate()
localization.ParseFromString(msg.message)
x = localization.pose.position.x
y = localization.pose.position.y
f.write(str(x) + "," + str(y) + "\n")
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/navigator/BUILD
|
load("@rules_python//python:defs.bzl", "py_binary")
package(default_visibility = ["//visibility:public"])
py_binary(
name = "viewer_raw",
srcs = ["viewer_raw.py"],
)
py_binary(
name = "viewer_smooth",
srcs = ["viewer_smooth.py"],
)
py_binary(
name = "record_extractor",
srcs = ["record_extractor.py"],
deps = [
"//cyber/python/cyber_py3:record",
"//modules/common_msgs/localization_msgs:localization_py_pb2",
],
)
| 0
|
apollo_public_repos/apollo/modules/tools/navigator
|
apollo_public_repos/apollo/modules/tools/navigator/dbmap/setup.sh
|
SRC_DIR=./proto
DST_DIR=./proto
protoc -I=$SRC_DIR --python_out=$DST_DIR $SRC_DIR/*.proto
| 0
|
apollo_public_repos/apollo/modules/tools/navigator
|
apollo_public_repos/apollo/modules/tools/navigator/dbmap/viewer.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2018 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
import json
import sys
from yattag import Doc
import pyproj
from modules.common_msgs.planning_msgs import navigation_pb2
import modules.tool.common.proto_utils as proto_utils
class DBMapViewer:
def __init__(self, utm_zone):
"""
init function
"""
self.utm_zone = utm_zone
self.projector = pyproj.Proj(
proj='utm', zone=self.utm_zone, ellps='WGS84')
self.navigation_lines = []
self.center_lat = None
self.center_lon = None
self.html = ""
def utm2latlon(self, x, y):
"""
convert the utm x y to lat and lon
"""
lon, lat = self.projector(x, y, inverse=True)
return lat, lon
def add(self, dbmap):
for navigation_path in dbmap.navigation_path:
navigation_line = []
for p in navigation_path.path.path_point:
point = {}
lat, lng = self.utm2latlon(p.x, p.y)
if self.center_lat is None:
self.center_lat = lat
if self.center_lon is None:
self.center_lon = lng
point['lat'] = lat
point['lng'] = lng
navigation_line.append(point)
self.navigation_lines.append(navigation_line)
def generate(self):
"""
function to generate html code.
"""
doc, tag, text, line = Doc().ttl()
doc.asis('<!DOCTYPE html>')
api_url = 'http://maps.google.com/maps/api/js?sensor=' \
'false&callback=initMap'
with tag('html'):
with tag('head'):
with tag('title'):
text('Gmap Viewer')
doc.asis('<meta name="viewport" content="initial-scale=1.0">')
doc.asis('<meta charset="utf-8">')
with tag('style'):
doc.asis('#map { height: 100%; }')
doc.asis(
'html, body { height: 100%; margin: 0; padding: 0; }')
with tag('body'):
with tag('div', id='map'):
pass
with tag('script'):
doc.asis('\nvar map;\n')
doc.asis("\nvar colors = ['#e6194b', '#3cb44b', '#ffe119', "
"'#0082c8', '#f58231', '#911eb4', '#46f0f0', "
"'#f032e6', '#d2f53c', '#fabebe', '#008080', "
"'#e6beff', '#aa6e28', '#fffac8', '#800000', "
"'#aaffc3', '#808000', '#ffd8b1', '#000080', "
"'#808080', '#000000']\n")
doc.asis('function initMap() {\n')
doc.asis("map = new google.maps.Map("
"document.getElementById('map'), {\n")
doc.asis('center: {lat: ' + str(self.center_lat) +
', lng: ' + str(self.center_lon) + '},\n')
doc.asis('zoom: 16\n')
doc.asis('});\n')
doc.asis('var navi_lines = ' +
json.dumps(self.navigation_lines) + ';\n')
doc.asis("""
for (var i = 0; i < navi_lines.length; i++) {
var boundary = new google.maps.Polyline({
path: navi_lines[i],
geodesic: true,
strokeColor: colors[i % colors.length],
strokeOpacity: 1.0,
strokeWeight: 3
});
boundary.setMap(map);
}
""")
doc.asis('}\n')
doc.asis('<script src="' + api_url + '"></script>')
self.html = doc.getvalue()
return self.html
if __name__ == "__main__":
import google.protobuf.text_format as text_format
if len(sys.argv) < 2:
print("usage: python map_viewer.py dbmap_file [utm_zone=10]")
sys.exit(0)
map_file = sys.argv[1]
utm_zone = 10
if len(sys.argv) >= 3:
utm_zone = int(sys.argv[2])
dbmap = navigation_pb2.NavigationInfo()
proto_utils.get_pb_from_file(map_file, dbmap)
with open(map_file, 'r') as file_in:
text_format.Merge(file_in.read(), dbmap)
viewer = DBMapViewer(utm_zone)
viewer.add(dbmap)
html = viewer.generate()
with open('dbmap.html', 'w') as f:
f.write(html)
| 0
|
apollo_public_repos/apollo/modules/tools/navigator
|
apollo_public_repos/apollo/modules/tools/navigator/dbmap/README.md
|
# Driving Behavior Map (DBMap)
DBMap is learned and generated based on human driving behaviors.
| 0
|
apollo_public_repos/apollo/modules/tools/navigator
|
apollo_public_repos/apollo/modules/tools/navigator/dbmap/generator.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2018 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
from datetime import datetime
import json
import sys
from modules.common_msgs.planning_msgs import navigation_pb2
if __name__ == '__main__':
if len(sys.argv) < 2:
print("usage: python generator.py "
"navi_line1.smoothed navi_line2.smoothed ...")
sys.exit(0)
navi_files = sys.argv[1:]
# generate navigation info
navigation_info = navigation_pb2.NavigationInfo()
priority = 0
for fdata in navi_files:
print("processing " + fdata)
navigation_path = navigation_info.navigation_path.add()
navigation_path.path_priority = priority
priority += 1
navigation_path.path.name = "navigation"
with open(fdata, 'r') as f:
cnt = 0
for line in f:
cnt += 1
if cnt < 3:
continue
json_point = json.loads(line)
point = navigation_path.path.path_point.add()
point.x = json_point['x']
point.y = json_point['y']
point.s = json_point['s']
point.theta = json_point['theta']
point.kappa = json_point['kappa']
point.dkappa = json_point['dkappa']
datetime_str = datetime.now().strftime("%Y%m%d_%H%M%S")
with open(datetime_str + ".dbmap", 'w') as f:
f.write(str(navigation_info))
| 0
|
apollo_public_repos/apollo/modules/tools/navigator
|
apollo_public_repos/apollo/modules/tools/navigator/dbmap/BUILD
|
load("@rules_python//python:defs.bzl", "py_binary", "py_library")
package(default_visibility = ["//visibility:public"])
py_library(
name = "generator",
srcs = ["generator.py"],
deps = [
"//modules/common_msgs/planning_msgs:navigation_py_pb2",
],
)
py_binary(
name = "viewer",
srcs = ["viewer.py"],
deps = [
"//modules/common_msgs/planning_msgs:navigation_py_pb2",
],
)
| 0
|
apollo_public_repos/apollo/modules/tools/navigator/dbmap
|
apollo_public_repos/apollo/modules/tools/navigator/dbmap/proto/dbmap.proto
|
syntax = "proto2";
package apollo.dbmap;
message DBPoint {
optional double x = 1;
optional double y = 2;
optional double z = 3;
optional double s = 4;
optional double heading = 5;
}
message DBLine {
repeated DBPoint point = 1;
}
message DBNeighbourSegment {
optional double start_s = 1;
optional double end_s = 2;
optional string path_id = 3;
optional double path_start_s = 4;
optional double path_end_s = 5;
}
message DBNeighbourPath {
repeated DBNeighbourSegment segment = 1;
}
message DBPath {
optional string id = 1;
repeated DBLine path = 2;
repeated DBLine left_bounday = 3;
repeated DBLine right_bounday = 4;
repeated DBNeighbourPath left_path = 5;
repeated DBNeighbourPath right_path = 6;
repeated DBNeighbourPath duplicate_path = 7;
}
message DBMap {
repeated DBPath paths = 1;
}
| 0
|
apollo_public_repos/apollo/modules/tools/navigator/dbmap
|
apollo_public_repos/apollo/modules/tools/navigator/dbmap/proto/BUILD
|
## Auto generated by `proto_build_generator.py`
load("@rules_proto//proto:defs.bzl", "proto_library")
load("@rules_cc//cc:defs.bzl", "cc_proto_library")
load("//tools:python_rules.bzl", "py_proto_library")
package(default_visibility = ["//visibility:public"])
cc_proto_library(
name = "dbmap_cc_proto",
deps = [
":dbmap_proto",
],
)
proto_library(
name = "dbmap_proto",
srcs = ["dbmap.proto"],
)
py_proto_library(
name = "dbmap_py_pb2",
deps = [
":dbmap_proto",
],
)
| 0
|
apollo_public_repos/apollo/modules/tools/navigator/dbmap
|
apollo_public_repos/apollo/modules/tools/navigator/dbmap/libs/point.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2018 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
import pyproj
import math
class PointUtils:
"""point utils"""
@staticmethod
def utm2latlon(x, y, zone):
"""utm to latlon"""
proj = pyproj.Proj(proj='utm', zone=zone, ellps='WGS84')
lon, lat = proj(x, y, inverse=True)
return lat, lon
@staticmethod
def latlon2utm(lat, lon):
"""latlon to utm"""
zone = PointUtils.latlon2utmzone(lat, lon)
projector2 = pyproj.Proj(proj='utm', zone=zone, ellps='WGS84')
x, y = projector2(lon, lat)
return x, y, zone
@staticmethod
def latlon2utmzone(lat, lon):
"""latlon to utm zone"""
zone_num = math.floor((lon + 180) / 6) + 1
if 56.0 <= lat < 64.0 and 3.0 <= lon < 12.0:
zone_num = 32
if 72.0 <= lat < 84.0:
if 0.0 <= lon < 9.0:
zone_num = 31
elif 9.0 <= lon < 21.0:
zone_num = 33
elif 21.0 <= lon < 33.0:
zone_num = 35
elif 33.0 <= lon < 42.0:
zone_num = 37
return zone_num
@staticmethod
def latlon2latlondict(lat, lon):
"""latlon to latlon dictionary"""
return {'lat': lat, 'lng': lon}
@staticmethod
def utm2grididx(x, y, resolution_mm):
"""utm to grid index"""
index_str = str(int(round(x / resolution_mm)) * resolution_mm)
index_str += ","
index_str += str(int(round(y / resolution_mm)) * resolution_mm)
return index_str
| 0
|
apollo_public_repos/apollo/modules/tools/navigator/dbmap
|
apollo_public_repos/apollo/modules/tools/navigator/dbmap/libs/BUILD
|
load("@rules_python//python:defs.bzl", "py_library")
package(default_visibility = ["//visibility:public"])
py_library(
name = "point",
srcs = ["point.py"],
)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/control_info/BUILD
|
load("@rules_python//python:defs.bzl", "py_binary")
load("//tools/install:install.bzl", "install")
package(default_visibility = ["//visibility:public"])
py_binary(
name = "control_info",
srcs = ["control_info.py"],
deps = [
"//cyber/python/cyber_py3:cyber",
"//cyber/python/cyber_py3:record",
"//modules/common_msgs/chassis_msgs:chassis_py_pb2",
"//modules/common_msgs/control_msgs:control_cmd_py_pb2",
"//modules/common_msgs/localization_msgs:localization_py_pb2",
"//modules/common_msgs/planning_msgs:planning_py_pb2",
],
)
install(
name = "install",
py_dest = "tools/control_info",
targets = [":control_info"]
)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/control_info/control_info.py
|
#!/usr/bin/env python
###############################################################################
# Copyright 2022 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
"""
Control Planning Analyzer
"""
import argparse
import math
import sys
import threading
import time
import os
import shutil
import xlsxwriter
import fnmatch
import matplotlib.pyplot as plt
import numpy
import tkinter.filedialog
from matplotlib import patches
from matplotlib import lines
from cyber.python.cyber_py3 import cyber
from cyber.python.cyber_py3.record import RecordReader
from modules.common_msgs.localization_msgs import localization_pb2
from modules.common_msgs.chassis_msgs import chassis_pb2
from modules.common_msgs.planning_msgs import planning_pb2
from modules.common_msgs.control_msgs import control_cmd_pb2
class ControlInfo(object):
"""
ControlInfo Class
"""
def __init__(self, axarr):
self.imuright = []
self.imuforward = []
self.imuup = []
self.heading = []
self.controltime = []
self.planningtime = []
self.trajectory_type = []
self.trajectory_gear = []
self.localizationtime = []
self.canbustime = []
#station information
self.station_reference = []
self.current_station = []
self.station_error = []
self.station_error_limited = []
#speed information
self.speed_reference = []
self.preview_speed_reference = []
self.current_speed = []
self.speed_error = []
self.speed_offset = []
self.speed_controller_input_limited = []
#acceleration information
self.acc_open = []
self.acc_close = []
self.slope_offset_compensation = []
self.acceleration_lookup = []
self.speed_lookup = []
self.calibration_value = []
self.acc_lon = []
self.throttlecmd = []
self.canbus_throttlefbk = []
self.brakecmd = []
self.canbus_brakefbk = []
self.gear_location = []
self.is_full_stop = []
self.path_remain = []
self.pid_saturation_status = []
self.heading_error = []
self.lateral_error = []
self.heading_error_rate = []
self.lateral_error_rate = []
self.heading_error_feedback = []
self.lateral_error_feedback = []
self.steercmd = []
self.canbus_steerfbk = []
self.canbus_speed = []
self.curvature = []
#debug
self.steer_angle = []
self.steer_angle_feedback = []
self.steer_angle_feedforward = []
self.steer_angle_feedback_augment = []
self.steer_angle_lateral_contribution = []
self.steer_angle_lateral_rate_contribution = []
self.steer_angle_heading_contribution = []
self.steer_angle_heading_rate_contribution = []
self.target_speed = []
self.target_curvature = []
self.target_acceleration = []
self.target_heading = []
self.target_time = []
self.driving_mode = 0
self.canbus_Driving_mode = []
self.mode_time = []
self.gear_mode_time = []
self.planningavailable = False
self.carx = []
self.cary = []
self.cartime = []
self.planning_pathx = []
self.planning_pathy = []
self.planning_paths = []
self.planning_patha = []
self.planning_pathv = []
self.planningx = []
self.planningy = []
self.i = 0
self.drivingAction = []
self.numpoints_sum = []
self.planning_sum = []
self.show_planning_flag = True
self.count = 1
self.axarr = axarr
self.lock = threading.Lock()
def __callback_planning(self, entity):
"""
New Planning Trajectory
"""
self.planning_pathx = [p.path_point.x for p in entity.trajectory_point]
self.planning_pathy = [p.path_point.y for p in entity.trajectory_point]
self.planning_paths = [p.path_point.s for p in entity.trajectory_point]
self.planning_pathv = [p.v for p in entity.trajectory_point]
self.planning_patha = [p.a for p in entity.trajectory_point]
if self.i < 1:
self.planningx = self.planning_pathx
self.planningy = self.planning_pathy
self.i += 1
self.planningtime.append(entity.header.timestamp_sec)
self.trajectory_type.append(entity.trajectory_type)
self.trajectory_gear.append(entity.gear)
numpoints = len(entity.trajectory_point)
self.numpoints_sum.append(numpoints)
if self.show_planning_flag:
self.add_planning_sheet(entity)
self.count = self.count + 1
if numpoints == 0:
self.planningavailable = False
else:
self.planningavailable = True
if self.show_planning_flag:
self.axarr.plot(self.planning_pathx,
self.planning_pathy,
linestyle='--')
plt.draw()
def __callback_canbus(self, entity):
"""
New Canbus
"""
self.canbus_throttlefbk.append(entity.throttle_percentage)
self.canbus_brakefbk.append(entity.brake_percentage)
self.canbus_steerfbk.append(entity.steering_percentage)
self.canbus_speed.append(entity.speed_mps)
self.canbustime.append(entity.header.timestamp_sec)
self.gear_location.append(entity.gear_location)
if entity.gear_location == 1:
self.gear_mode_time.append(entity.header.timestamp_sec)
if entity.driving_mode == chassis_pb2.Chassis.COMPLETE_AUTO_DRIVE:
if self.driving_mode == 0:
self.mode_time.append(entity.header.timestamp_sec)
self.driving_mode = 1
elif self.driving_mode == 1:
self.mode_time.append(entity.header.timestamp_sec)
self.driving_mode = 0
self.canbus_Driving_mode.append(self.driving_mode)
def __callback_localization(self, entity):
"""
New Localization
"""
self.imuright.append(entity.pose.linear_acceleration_vrf.x)
self.imuforward.append(entity.pose.linear_acceleration_vrf.y)
self.imuup.append(entity.pose.linear_acceleration_vrf.z)
self.heading.append(entity.pose.heading)
self.localizationtime.append(entity.header.timestamp_sec)
heading_angle = entity.pose.heading
acc_x = entity.pose.linear_acceleration.x
acc_y = entity.pose.linear_acceleration.y
acc = acc_x * math.cos(heading_angle) + acc_y * math.sin(heading_angle)
self.acc_lon.append(acc)
self.carx.append(entity.pose.position.x)
self.cary.append(entity.pose.position.y)
self.cartime.append(entity.header.timestamp_sec)
def __callback_control(self, entity):
"""
New Control Command
"""
self.throttlecmd.append(entity.throttle)
self.brakecmd.append(entity.brake)
self.steercmd.append(entity.steering_target)
self.controltime.append(entity.header.timestamp_sec)
self.acceleration_lookup.append(
entity.debug.simple_lon_debug.acceleration_lookup)
self.slope_offset_compensation.append(
entity.debug.simple_lon_debug.slope_offset_compensation)
self.speed_lookup.append(entity.debug.simple_lon_debug.speed_lookup)
self.calibration_value.append(
entity.debug.simple_lon_debug.calibration_value)
self.is_full_stop.append(entity.debug.simple_lon_debug.is_full_stop)
self.path_remain.append(entity.debug.simple_lon_debug.path_remain)
self.pid_saturation_status.append(
entity.debug.simple_lon_debug.pid_saturation_status)
self.acc_open.append(
entity.debug.simple_lon_debug.preview_acceleration_reference)
self.preview_speed_reference.append(
entity.debug.simple_lon_debug.preview_speed_reference)
self.acc_close.append(
entity.debug.simple_lon_debug.acceleration_cmd_closeloop)
self.station_reference.append(
entity.debug.simple_lon_debug.station_reference)
self.current_station.append(
entity.debug.simple_lon_debug.current_station)
self.station_error.append(entity.debug.simple_lon_debug.station_error)
self.station_error_limited.append(
entity.debug.simple_lon_debug.station_error_limited)
self.speed_error.append(entity.debug.simple_lon_debug.speed_error)
self.speed_offset.append(entity.debug.simple_lon_debug.speed_offset)
self.speed_controller_input_limited.append(
entity.debug.simple_lon_debug.speed_controller_input_limited)
self.speed_reference.append(
entity.debug.simple_lon_debug.speed_reference)
self.current_speed.append(
entity.debug.simple_lon_debug.speed_reference -
entity.debug.simple_lon_debug.speed_error)
self.drivingAction.append(entity.pad_msg.action)
self.curvature.append(entity.debug.simple_lat_debug.curvature * 100.0)
self.heading_error.append(entity.debug.simple_lat_debug.heading_error)
self.heading_error_feedback.append(
entity.debug.simple_lat_debug.heading_error_feedback)
self.lateral_error.append(entity.debug.simple_lat_debug.lateral_error)
self.lateral_error_feedback.append(
entity.debug.simple_lat_debug.lateral_error_feedback)
self.heading_error_rate.append(
entity.debug.simple_lat_debug.heading_error_rate)
self.lateral_error_rate.append(
entity.debug.simple_lat_debug.lateral_error_rate)
self.steer_angle.append(entity.debug.simple_lat_debug.steer_angle)
self.steer_angle_feedback.append(
entity.debug.simple_lat_debug.steer_angle_feedback)
self.steer_angle_feedforward.append(
entity.debug.simple_lat_debug.steer_angle_feedforward)
self.steer_angle_feedback_augment.append(
entity.debug.simple_lat_debug.steer_angle_feedback_augment)
self.steer_angle_lateral_contribution.append(
entity.debug.simple_lat_debug.steer_angle_lateral_contribution)
self.steer_angle_lateral_rate_contribution.append(
entity.debug.simple_lat_debug.steer_angle_lateral_rate_contribution)
self.steer_angle_heading_contribution.append(
entity.debug.simple_lat_debug.steer_angle_heading_contribution)
self.steer_angle_heading_rate_contribution.append(
entity.debug.simple_lat_debug.steer_angle_heading_rate_contribution)
def read_bag(self, bag_file):
file_path = bag_file
#bag = rosbag.Bag(file_path)
reader = RecordReader(file_path)
print("Begin reading the file: ", file_path)
for msg in reader.read_messages():
#print msg.timestamp,msg.topic
if msg.topic == "/apollo/localization/pose":
localization = localization_pb2.LocalizationEstimate()
localization.ParseFromString(msg.message)
self.__callback_localization(localization)
elif msg.topic == "/apollo/planning":
adc_trajectory = planning_pb2.ADCTrajectory()
adc_trajectory.ParseFromString(msg.message)
self.__callback_planning(adc_trajectory)
elif msg.topic == "/apollo/control":
control_cmd = control_cmd_pb2.ControlCommand()
control_cmd.ParseFromString(msg.message)
self.__callback_control(control_cmd)
elif msg.topic == "/apollo/canbus/chassis":
chassis = chassis_pb2.Chassis()
chassis.ParseFromString(msg.message)
self.__callback_canbus(chassis)
print("Done reading the file: ", file_path)
def plot_station_speed(self):
fig, ax = plt.subplots(2, 1)
ax[0].get_shared_x_axes().join(ax[0], ax[1])
ax[0].plot(self.controltime,
self.station_reference,
label='station_reference')
ax[0].plot(self.controltime,
self.current_station,
label='current_station')
ax[0].plot(self.controltime, self.station_error, label='station_error')
ax[0].plot(self.controltime,
self.station_error_limited,
label='station_error_limited')
ax[0].plot(self.controltime, self.speed_offset, label='speed_offset')
ax[0].legend(fontsize='medium')
ax[0].grid(True)
ax[0].set_title('Station information')
ax[0].set_xlabel('Time-s')
ax[0].set_ylabel('Station-m')
ax[1].plot(self.controltime, self.speed_error, label='speed_error')
ax[1].plot(self.controltime,
self.speed_controller_input_limited,
label='speed_controller_input_limited')
ax[1].plot(self.controltime, self.speed_offset, label='speed_offset')
ax[1].plot(self.controltime, self.current_speed, label='current_speed')
ax[1].plot(self.controltime,
self.speed_reference,
label='speed_reference')
ax[1].legend(fontsize='medium')
ax[1].grid(True)
ax[1].set_title('Speed Info')
ax[1].set_xlabel('Time-s')
ax[1].set_ylabel('Speed-m/s')
if len(self.mode_time) % 2 == 1:
self.mode_time.append(self.controltime[-1])
for i in range(0, len(self.mode_time), 2):
ax[0].axvspan(self.mode_time[i],
self.mode_time[i + 1],
fc='0.1',
alpha=0.1)
ax[1].axvspan(self.mode_time[i],
self.mode_time[i + 1],
fc='0.1',
alpha=0.1)
def plot_speed_pid(self):
fig, ax = plt.subplots(2, 1)
ax[0].get_shared_x_axes().join(ax[0], ax[1])
ax[0].plot(self.controltime, self.speed_error, label='speed_error')
ax[0].plot(self.controltime,
self.speed_controller_input_limited,
label='speed_controller_input_limited')
ax[0].plot(self.controltime, self.speed_offset, label='speed_offset')
ax[0].legend(fontsize='medium')
ax[0].grid(True)
ax[0].set_title('Speed Info')
ax[0].set_xlabel('Time-s')
ax[0].set_ylabel('Speed-m/s')
ax[1].plot(self.controltime, self.acc_open, label='Acc Open')
ax[1].plot(self.controltime,
self.acceleration_lookup,
label='Lookup Acc')
ax[1].plot(self.controltime, self.acc_close, label='Acc Close')
ax[1].legend(fontsize='medium')
ax[1].grid(True)
ax[1].set_title('Acc Info')
ax[1].set_xlabel('Time-s')
if len(self.mode_time) % 2 == 1:
self.mode_time.append(self.controltime[-1])
for i in range(0, len(self.mode_time), 2):
ax[0].axvspan(self.mode_time[i],
self.mode_time[i + 1],
fc='0.1',
alpha=0.1)
ax[1].axvspan(self.mode_time[i],
self.mode_time[i + 1],
fc='0.1',
alpha=0.1)
def plot_chassis(self):
fig, ax = plt.subplots(2, 1)
ax[0].get_shared_x_axes().join(ax[0], ax[1])
ax[0].plot(self.canbustime,
self.canbus_throttlefbk,
label='Throttle Feedback')
ax[0].plot(self.controltime, self.throttlecmd, label='Throttle Command')
ax[0].plot(self.canbustime,
self.canbus_brakefbk,
label='Brake Feedback')
ax[0].plot(self.controltime, self.brakecmd, label='Brake Command')
ax[0].legend(fontsize='medium')
ax[0].grid(True)
ax[0].set_title('Throttle Brake Info')
ax[0].set_xlabel('Time-s')
ax[1].plot(self.controltime, self.is_full_stop, label='is_full_stop')
ax[1].plot(self.controltime,
self.pid_saturation_status,
label='pid_saturation_status')
ax[1].plot(self.canbustime,
self.canbus_Driving_mode,
label='Driving_mode')
ax[1].plot(self.controltime, self.drivingAction, label='drivingAction')
ax[1].plot(self.controltime, self.path_remain, label='path_remain')
# ax[1].plot(self.planningtime, self.numpoints_sum, label='numpoints')
ax[1].legend(fontsize='medium')
ax[1].grid(True)
ax[1].set_title('Mode Info')
ax[1].set_xlabel('Time-s')
if len(self.mode_time) % 2 == 1:
self.mode_time.append(self.controltime[-1])
for i in range(0, len(self.mode_time), 2):
ax[0].axvspan(self.mode_time[i],
self.mode_time[i + 1],
fc='0.1',
alpha=0.1)
ax[1].axvspan(self.mode_time[i],
self.mode_time[i + 1],
fc='0.1',
alpha=0.1)
def show_longitudinal_all(self):
"""
Showing Longitudinal
"""
fig, ax = plt.subplots(2, 3)
ax[0, 0].get_shared_x_axes().join(ax[0, 0], ax[0, 0])
ax[0, 0].get_shared_x_axes().join(ax[0, 0], ax[0, 1])
ax[0, 0].get_shared_x_axes().join(ax[0, 0], ax[0, 2])
ax[0, 0].get_shared_x_axes().join(ax[0, 0], ax[1, 0])
ax[0, 0].get_shared_x_axes().join(ax[0, 0], ax[1, 1])
ax[0, 0].get_shared_x_axes().join(ax[0, 0], ax[1, 2])
ax[0, 0].plot(self.controltime,
self.current_speed,
label='current_speed')
ax[0, 0].plot(self.controltime,
self.preview_speed_reference,
label='preview_speed_reference')
ax[0, 0].plot(self.controltime,
self.speed_reference,
label='speed_reference')
ax[0, 0].legend(fontsize='medium')
ax[0, 0].grid(True)
ax[0, 0].set_title('Speed Info')
ax[0, 0].set_xlabel('Time-s')
ax[0, 1].plot(self.controltime,
self.station_reference,
label='station_reference')
ax[0, 1].plot(self.controltime,
self.current_station,
label='current_station')
ax[0, 1].plot(self.controltime,
self.station_error,
label='station_error')
ax[0, 1].plot(self.controltime,
self.station_error_limited,
label='station_error_limited')
ax[0, 1].legend(fontsize='medium')
ax[0, 1].grid(True)
ax[0, 1].set_title('Station information')
ax[0, 1].set_xlabel('Time-s')
ax[0, 1].set_ylabel('Station-m')
ax[0, 2].plot(self.canbustime,
self.canbus_throttlefbk,
label='Throttle Feedback')
ax[0, 2].plot(self.controltime,
self.throttlecmd,
label='Throttle Command')
ax[0, 2].plot(self.canbustime,
self.canbus_brakefbk,
label='Brake Feedback')
ax[0, 2].plot(self.controltime, self.brakecmd, label='Brake Command')
ax[0, 2].legend(fontsize='medium')
ax[0, 2].grid(True)
ax[0, 2].set_title('Throttle Brake Info')
ax[0, 2].set_xlabel('Time-s')
ax[1, 0].plot(self.controltime, self.speed_error, label='speed_error')
ax[1, 0].plot(self.controltime,
self.speed_controller_input_limited,
label='speed_controller_input_limited')
ax[1, 0].plot(self.controltime, self.speed_offset, label='speed_offset')
ax[1, 0].legend(fontsize='medium')
ax[1, 0].grid(True)
ax[1, 0].set_title('Speed Info')
ax[1, 0].set_xlabel('Time-s')
ax[1, 0].set_ylabel('Speed-m/s')
ax[1, 1].plot(self.controltime, self.acc_open, label='Acc Open')
ax[1, 1].plot(self.controltime,
self.acceleration_lookup,
label='Lookup Acc')
ax[1, 1].plot(self.controltime, self.acc_close, label='Acc Close')
# ax[1, 1].plot(self.controltime,
# self.slope_offset_compensation,
# label='slope_offset_compensation')
# ax[1, 1].plot(self.controltime,
# self.calibration_value,
# label='calibration_value')
# ax[1, 1].plot(self.controltime,
# self.station_error,
# label='station_error')
ax[1, 1].plot(self.controltime, self.speed_error, label='speed_error')
ax[1, 1].legend(fontsize='medium')
ax[1, 1].grid(True)
ax[1, 1].set_title('Acc Info')
ax[1, 1].set_xlabel('Time-s')
ax[1, 2].plot(self.controltime, self.is_full_stop, label='is_full_stop')
ax[1, 2].plot(self.canbustime,
self.gear_location,
label='gear_location')
ax[1, 2].plot(self.planningtime,
self.trajectory_gear,
label='trajectory_gear')
# ax[1, 2].plot(self.controltime, self.path_remain, label='path_remain')
# ax[1, 2].plot(self.controltime, self.Driving_mode, label='Driving_mode')
# ax[1, 2].plot(self.controltime,
# self.drivingAction,
# label='drivingAction')
# ax[1, 2].plot(self.planningtime, self.numpoints_sum, label='numpoints')
# ax[1, 2].plot(self.controltime, self.path_remain, label='path_remain')
# ax[1, 2].plot(self.planningtime,
# self.trajectory_type,
# label='trajectory_type')
ax[1, 2].legend(fontsize='medium')
ax[1, 2].grid(True)
ax[1, 2].set_title('Mode Info')
ax[1, 2].set_xlabel('Time-s')
if len(self.mode_time) % 2 == 1:
self.mode_time.append(self.controltime[-1])
for i in range(0, len(self.mode_time), 2):
ax[0, 0].axvspan(self.mode_time[i],
self.mode_time[i + 1],
fc='0.1',
alpha=0.1)
ax[0, 1].axvspan(self.mode_time[i],
self.mode_time[i + 1],
fc='0.1',
alpha=0.1)
ax[0, 2].axvspan(self.mode_time[i],
self.mode_time[i + 1],
fc='0.1',
alpha=0.1)
ax[1, 0].axvspan(self.mode_time[i],
self.mode_time[i + 1],
fc='0.1',
alpha=0.1)
ax[1, 1].axvspan(self.mode_time[i],
self.mode_time[i + 1],
fc='0.1',
alpha=0.1)
ax[1, 2].axvspan(self.mode_time[i],
self.mode_time[i + 1],
fc='0.1',
alpha=0.1)
plt.draw()
def plot_heading(self):
"""
Plot plot_lateral_error
"""
print("ploting Lateral Error")
fig, ax = plt.subplots(3, 1)
ax[0].get_shared_x_axes().join(ax[0], ax[1])
ax[0].get_shared_x_axes().join(ax[0], ax[2])
ax[0].plot(self.controltime, self.heading_error, label='heading_error')
ax[0].plot(self.controltime, self.lateral_error, label='lateral_error')
ax[0].legend(fontsize='medium')
ax[0].grid(True)
ax[0].set_title('Error Info')
ax[0].set_xlabel('Time')
ax[1].plot(self.controltime,
self.heading_error_rate,
label='heading_error_rate')
ax[1].plot(self.controltime,
self.lateral_error_rate,
label='lateral_error_rate')
ax[1].legend(fontsize='medium')
ax[1].grid(True)
ax[1].set_title('IMU Info')
ax[1].set_xlabel('Time')
ax[2].plot(self.canbustime,
self.canbus_steerfbk,
label='Steering Feedback')
ax[2].plot(self.controltime, self.steercmd, label='Steering Command')
ax[2].plot(self.controltime, self.curvature, label='Curvature')
ax[2].legend(fontsize='medium')
ax[2].grid(True)
ax[2].set_title('Steering Info')
ax[2].set_xlabel('Time-s')
ax[2].set_xlabel('Steering-%')
if len(self.mode_time) % 2 == 1:
self.mode_time.append(self.controltime[-1])
for i in range(0, len(self.mode_time), 2):
ax[0].axvspan(self.mode_time[i],
self.mode_time[i + 1],
fc='0.1',
alpha=0.1)
ax[1].axvspan(self.mode_time[i],
self.mode_time[i + 1],
fc='0.1',
alpha=0.1)
ax[2].axvspan(self.mode_time[i],
self.mode_time[i + 1],
fc='0.1',
alpha=0.1)
plt.draw()
def plot_lateral_all(self):
"""
Plot plot_lateral_all
"""
print("ploting Lateral Error")
fig, ax = plt.subplots(2, 2)
ax[0, 0].get_shared_x_axes().join(ax[0, 0], ax[0, 0])
ax[0, 0].get_shared_x_axes().join(ax[0, 0], ax[0, 1])
ax[0, 0].get_shared_x_axes().join(ax[0, 0], ax[1, 0])
ax[0, 0].get_shared_x_axes().join(ax[0, 0], ax[1, 1])
ax[0, 0].plot(self.controltime,
self.heading_error,
label='heading_error')
ax[0, 0].plot(self.controltime,
self.lateral_error,
label='lateral_error')
ax[0, 0].plot(self.controltime,
self.heading_error_feedback,
label='lateral_error_feedback')
ax[0, 0].plot(self.controltime,
self.lateral_error_feedback,
label='lateral_error_feedback')
ax[0, 0].legend(fontsize='medium')
ax[0, 0].grid(True)
ax[0, 0].set_title('Error Info')
ax[0, 0].set_xlabel('Time')
ax[0, 1].plot(self.controltime,
self.steer_angle_lateral_contribution,
label='steer_angle_lateral_contribution')
ax[0, 1].plot(self.controltime,
self.steer_angle_lateral_rate_contribution,
label='steer_angle_lateral_rate_contribution')
ax[0, 1].plot(self.controltime,
self.steer_angle_heading_contribution,
label='steer_angle_heading_contribution')
ax[0, 1].plot(self.controltime,
self.steer_angle_heading_rate_contribution,
label='steer_angle_heading_rate_contribution')
ax[0, 1].legend(fontsize='medium')
ax[0, 1].grid(True)
ax[0, 1].set_title('IMU Info')
ax[0, 1].set_xlabel('Time')
ax[1, 0].plot(self.canbustime,
self.canbus_steerfbk,
label='Steering Feedback')
ax[1, 0].plot(self.controltime, self.steercmd, label='Steering Command')
ax[1, 0].plot(self.controltime, self.curvature, label='Curvature')
ax[1, 0].legend(fontsize='medium')
ax[1, 0].grid(True)
ax[1, 0].set_title('Steering Info')
ax[1, 0].set_xlabel('Time-s')
ax[1, 0].set_xlabel('Steering-%')
ax[1, 1].plot(self.controltime, self.steer_angle, label='steer_angle')
ax[1, 1].plot(self.controltime,
self.steer_angle_feedback,
label='steer_angle_feedback')
ax[1, 1].plot(self.controltime,
self.steer_angle_feedforward,
label='steer_angle_feedforward')
ax[1, 1].plot(self.controltime,
self.steer_angle_feedback_augment,
label='steer_angle_feedback_augment')
ax[1, 1].legend(fontsize='medium')
ax[1, 1].grid(True)
ax[1, 1].set_title('steer_angle Info')
ax[1, 1].set_xlabel('Time-s')
ax[1, 1].set_xlabel('Steering-%')
if len(self.mode_time) % 2 == 1:
self.mode_time.append(self.controltime[-1])
for i in range(0, len(self.mode_time), 2):
ax[0, 0].axvspan(self.mode_time[i],
self.mode_time[i + 1],
fc='0.1',
alpha=0.1)
ax[0, 1].axvspan(self.mode_time[i],
self.mode_time[i + 1],
fc='0.1',
alpha=0.1)
ax[1, 0].axvspan(self.mode_time[i],
self.mode_time[i + 1],
fc='0.1',
alpha=0.1)
ax[1, 1].axvspan(self.mode_time[i],
self.mode_time[i + 1],
fc='0.1',
alpha=0.1)
plt.draw()
def plot_steering(self):
"""
Plot plot_heading_error
"""
print("ploting Heading Error")
fig, ax = plt.subplots(2, 1)
ax[0].plot(self.canbustime,
self.canbus_steerfbk,
label='Steering Feedback')
ax[0].plot(self.controltime, self.steercmd, label='Steering Command')
ax[0].plot(self.controltime, self.curvature, label='Curvature')
ax[0].legend(fontsize='medium')
ax[0].grid(True)
ax[0].set_title('Steering Info')
ax[0].set_xlabel('Time-s')
ax[0].set_xlabel('Steering-%')
ax[1].plot(self.speed_lookup,
self.acceleration_lookup,
label='Table Lookup')
ax[1].plot(self.target_speed, self.target_acceleration, label='Target')
ax[1].legend(fontsize='medium')
ax[1].grid(True)
ax[1].set_title('Calibration Lookup')
ax[1].set_xlabel('Speed')
ax[1].set_ylabel('Acceleration')
if len(self.mode_time) % 2 == 1:
self.mode_time.append(self.controltime[-1])
for i in range(0, len(self.mode_time), 2):
ax[0].axvspan(self.mode_time[i],
self.mode_time[i + 1],
fc='0.1',
alpha=0.1)
ax[1].axvspan(self.mode_time[i],
self.mode_time[i + 1],
fc='0.1',
alpha=0.1)
plt.draw()
def plot_localization(self):
"""
Plot localization
"""
print("ploting Localization")
self.axarr.plot(self.planningx,
self.planningy,
color='blue',
linestyle='--',
label='planning path')
self.axarr.plot(self.carx,
self.cary,
color='red',
label='localization pose')
self.axarr.plot(self.planning_pathx,
self.planning_pathy,
color='green',
label='planning path remain')
legend = self.axarr.legend(fontsize='small')
frame = legend.get_frame()
frame.set_alpha(1)
frame.set_facecolor('none')
self.axarr.grid(True)
self.axarr.set_title('Trajectory')
self.axarr.set_xlabel('x')
self.axarr.set_ylabel('y')
self.axarr.axis('equal')
plt.draw()
def add_longitudinal_sheet(self):
sheet = book.add_worksheet('longitudinal')
# 设置单元格居中,自动换行
book_format = book.add_format({'align': 'center', 'text_wrap': True})
sheet.write(0, 0, 'controltime', book_format)
sheet.write(0, 1, 'canbustime', book_format)
sheet.write(0, 2, 'current_speed', book_format)
sheet.write(0, 3, 'speed_reference', book_format)
sheet.write(0, 4, 'current_station', book_format)
sheet.write(0, 5, 'station_reference', book_format)
sheet.write(0, 6, 'station_error_limited', book_format)
sheet.write(0, 7, 'speed_error', book_format)
sheet.write(0, 8, 'speed_offset', book_format)
sheet.write(0, 9, 'speed_controller_input_limited', book_format)
sheet.write(0, 10, 'acc_open', book_format)
sheet.write(0, 11, 'acc_close', book_format)
sheet.write(0, 12, 'acceleration_lookup', book_format)
sheet.write(0, 13, 'throttlecmd', book_format)
sheet.write(0, 14, 'throttlefbk', book_format)
sheet.write(0, 15, 'brakecmd', book_format)
sheet.write(0, 16, 'brakefbk', book_format)
sheet.write(0, 17, 'is_full_stop', book_format)
sheet.write(0, 18, 'pid_saturation_status', book_format)
sheet.write(0, 19, 'drivingAction', book_format)
sheet.write(0, 20, 'path_remain', book_format)
sheet.write_column(1, 0, self.controltime, book_format)
sheet.write_column(1, 1, self.canbustime, book_format)
sheet.write_column(1, 2, self.current_speed, book_format)
sheet.write_column(1, 3, self.speed_reference, book_format)
sheet.write_column(1, 4, self.current_station, book_format)
sheet.write_column(1, 5, self.station_reference, book_format)
sheet.write_column(1, 6, self.station_error_limited, book_format)
sheet.write_column(1, 7, self.speed_error, book_format)
sheet.write_column(1, 8, self.speed_offset, book_format)
sheet.write_column(1, 9, self.speed_controller_input_limited,
book_format)
sheet.write_column(1, 10, self.acc_open, book_format)
sheet.write_column(1, 11, self.acc_close, book_format)
sheet.write_column(1, 12, self.acceleration_lookup, book_format)
sheet.write_column(1, 13, self.throttlecmd, book_format)
sheet.write_column(1, 14, self.canbus_throttlefbk, book_format)
sheet.write_column(1, 15, self.brakecmd, book_format)
sheet.write_column(1, 16, self.canbus_brakefbk, book_format)
sheet.write_column(1, 17, self.is_full_stop, book_format)
sheet.write_column(1, 18, self.pid_saturation_status, book_format)
sheet.write_column(1, 19, self.drivingAction, book_format)
sheet.write_column(1, 17, self.path_remain, book_format)
# 设置0行行高
sheet.set_row(0, 45)
sheet.set_row(1, 25)
# 设置0列每个单元格宽度
sheet.set_column(0, 0, 12)
# 设置1-19列每个单元格宽度
sheet.set_column(1, 16, 8)
sheet.set_column(17, 19, 7)
def add_lateral_sheet(self):
sheet = book.add_worksheet('lateral')
# 设置单元格居中,自动换行
book_format = book.add_format({'align': 'center', 'text_wrap': True})
sheet.write(0, 0, 'controltime', book_format)
sheet.write(0, 1, 'canbustime', book_format)
sheet.write(0, 2, 'heading_error', book_format)
sheet.write(0, 3, 'lateral_error', book_format)
sheet.write(0, 4, 'heading_error_rate', book_format)
sheet.write(0, 5, 'lateral_error_rate', book_format)
sheet.write(0, 6, 'steercmd', book_format)
sheet.write(0, 7, 'steerfbk', book_format)
sheet.write(0, 8, 'curvature', book_format)
sheet.write_column(1, 0, self.controltime, book_format)
sheet.write_column(1, 1, self.canbustime, book_format)
sheet.write_column(1, 2, self.heading_error, book_format)
sheet.write_column(1, 3, self.lateral_error, book_format)
sheet.write_column(1, 4, self.heading_error_rate, book_format)
sheet.write_column(1, 5, self.lateral_error_rate, book_format)
sheet.write_column(1, 6, self.steercmd, book_format)
sheet.write_column(1, 7, self.canbus_steerfbk, book_format)
sheet.write_column(1, 8, self.curvature, book_format)
# 设置0行行高
sheet.set_row(0, 45)
sheet.set_row(1, 25)
# 设置0列每个单元格宽度
sheet.set_column(0, 0, 12)
# 设置1-19列每个单元格宽度
sheet.set_column(1, 16, 8)
sheet.set_column(17, 19, 7)
def add_planning_sheet(self, entity):
# 设置单元格居中,自动换行
book_format = book.add_format({'align': 'center', 'text_wrap': True})
pathx_sheet.write_row(self.count, 1, self.planning_pathx, book_format)
pathy_sheet.write_row(self.count, 1, self.planning_pathy, book_format)
paths_sheet.write_row(self.count, 1, self.planning_paths, book_format)
patha_sheet.write_row(self.count, 1, self.planning_patha, book_format)
pathv_sheet.write_row(self.count, 1, self.planning_pathv, book_format)
pathx_sheet.write(self.count, 0, entity.header.timestamp_sec,
book_format)
pathy_sheet.write(self.count, 0, entity.header.timestamp_sec,
book_format)
paths_sheet.write(self.count, 0, entity.header.timestamp_sec,
book_format)
patha_sheet.write(self.count, 0, entity.header.timestamp_sec,
book_format)
pathv_sheet.write(self.count, 0, entity.header.timestamp_sec,
book_format)
def add_localization_sheet(self):
sheet = book.add_worksheet('localization')
# 设置单元格居中,自动换行
book_format = book.add_format({'align': 'center', 'text_wrap': True})
sheet.write(0, 0, 'cartime', book_format)
sheet.write(0, 1, 'carx', book_format)
sheet.write(0, 2, 'cary', book_format)
sheet.write_column(1, 0, self.cartime, book_format)
sheet.write_column(1, 1, self.carx, book_format)
sheet.write_column(1, 2, self.cary, book_format)
def show_longitudinal(self):
"""
ploting Longitudinal
"""
self.plot_station_speed()
self.plot_speed_pid()
self.plot_chassis()
self.add_longitudinal_sheet()
# plt.show()
def show_lateral(self):
"""
Plot everything in time domain
"""
print("ploting Lateral")
self.plot_lateral_all()
# self.plot_heading()
# self.plot_steering()
self.add_lateral_sheet()
# plt.show()
def show_localization(self):
self.plot_localization()
self.add_localization_sheet()
def press(self, event):
"""
Keyboard events during plotting
"""
if event.key == 'q' or event.key == 'Q':
plt.close('all')
def Print_len(self):
"""
Print_len
"""
print("Print_len")
print(str(len(self.controltime)) + "-controltime")
print(str(len(self.planningtime)) + "-planningtime")
print(str(len(self.localizationtime)) + "-localizationtime")
print(str(len(self.canbustime)) + "-canbustime")
print(str(len(self.station_reference)) + "-station_reference")
print(str(len(self.current_station)) + "-current_station")
print(str(len(self.station_error)) + "-station_error")
print(str(len(self.station_error_limited)) + "-station_error_limited")
print(str(len(self.speed_reference)) + "-speed_reference")
print(str(len(self.current_speed)) + "-current_speed")
print(str(len(self.speed_error)) + "-speed_error")
print(str(len(self.speed_offset)) + "-speed_offset")
print(
str(len(self.speed_controller_input_limited)) +
"-speed_controller_input_limited")
print(str(len(self.acc_open)) + "-acc_open")
print(str(len(self.acc_close)) + "-acc_close")
print(
str(len(self.slope_offset_compensation)) +
"-slope_offset_compensation")
print(str(len(self.acceleration_lookup)) + "-acceleration_lookup")
print(str(len(self.speed_lookup)) + "-speed_lookup")
print(str(len(self.calibration_value)) + "-calibration_value")
print(str(len(self.throttlecmd)) + "-throttlecmd")
print(str(len(self.canbus_throttlefbk)) + "-throttlefbk")
print(str(len(self.brakecmd)) + "-brakecmd")
print(str(len(self.canbus_brakefbk)) + "-brakefbk")
print(str(len(self.is_full_stop)) + "-is_full_stop")
print(str(len(self.pid_saturation_status)) + "-pid_saturation_status")
print(str(len(self.heading_error)) + "-heading_error")
print(str(len(self.lateral_error)) + "-lateral_error")
print(str(len(self.heading_error_rate)) + "-heading_error_rate")
print(str(len(self.steercmd)) + "-steercmd")
print(str(len(self.canbus_steerfbk)) + "-steerfbk")
print(str(len(self.canbus_speed)) + "-speed")
print(str(len(self.curvature)) + "-curvature")
print(str(len(self.carx)) + "-carx")
print(str(len(self.cary)) + "-cary")
print(str(len(self.cartime)) + "-cartime")
print(str(len(self.planning_pathx)) + "-planning_pathx")
print(str(len(self.planning_pathy)) + "-planning_pathy")
print(str(len(self.planningx)) + "-planningx")
print(str(len(self.planningy)) + "-planningy")
print(str(len(self.drivingAction)) + "-drivingAction")
print(str(len(self.canbus_Driving_mode)) + "-Driving_mode")
print(str(len(self.trajectory_type)) + "-trajectory_type")
print(str(len(self.path_remain)) + "-path_remain")
print(str(len(self.acc_lon)) + "-acc_lon")
print(str(len(self.gear_mode_time)) + "-gear_mode_time")
print(str(len(self.mode_time)) + "-mode_time")
def is_record_file(path):
"""Naive check if a path is a record."""
return path.endswith('.record') or \
fnmatch.fnmatch(path, '*.record.?????') or \
fnmatch.fnmatch(path, '*.record.????')
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description='Process and analyze control and planning data')
parser.add_argument('--bag', type=str, help='use Rosbag')
parser.add_argument('--path', type=str, help='path for bag files')
args = parser.parse_args()
fig, axarr = plt.subplots()
controlinfo = ControlInfo(axarr)
if args.path:
dir_path = args.path
#create datafile dir
datafile_path = args.path + "/data_dir"
isExists = os.path.exists(datafile_path)
if not isExists:
os.makedirs(datafile_path)
print('Create success the file:', datafile_path)
else:
print('The file already exists:', datafile_path)
shutil.rmtree(datafile_path)
os.makedirs(datafile_path)
print(datafile_path + 'recreate success')
#create datafile
excel_name = 'data.xlsx'
book = xlsxwriter.Workbook(datafile_path + '/' + excel_name)
book_format = book.add_format({'align': 'center', 'text_wrap': True})
#add_worksheet
if controlinfo.show_planning_flag:
pathx_sheet = book.add_worksheet('planning_pathx')
pathy_sheet = book.add_worksheet('planning_pathy')
paths_sheet = book.add_worksheet('planning_paths')
patha_sheet = book.add_worksheet('planning_patha')
pathv_sheet = book.add_worksheet('planning_pathv')
pathx_sheet.write(0, 0, "timestamp_sec", book_format)
pathy_sheet.write(0, 0, "timestamp_sec", book_format)
paths_sheet.write(0, 0, "timestamp_sec", book_format)
patha_sheet.write(0, 0, "timestamp_sec", book_format)
pathv_sheet.write(0, 0, "timestamp_sec", book_format)
if os.path.isdir(dir_path):
dirs = os.listdir(dir_path)
dirs.sort()
for file in dirs:
#print "os.path.splitext(file)[1]", os.path.splitext(file)[1]
if is_record_file(file):
controlinfo.read_bag(dir_path + file)
elif args.bag:
#create datafile dir
datafile_path = args.bag + "_dir"
isExists = os.path.exists(datafile_path)
if not isExists:
os.makedirs(datafile_path)
print('Create success the file:', datafile_path)
else:
print('The file already exists:', datafile_path)
shutil.rmtree(datafile_path)
os.makedirs(datafile_path)
print(datafile_path + 'recreate success')
#create datafile
excel_name = 'data.xlsx'
book = xlsxwriter.Workbook(datafile_path + '/' + excel_name)
book_format = book.add_format({'align': 'center', 'text_wrap': True})
#add_worksheet
if controlinfo.show_planning_flag:
pathx_sheet = book.add_worksheet('planning_pathx')
pathy_sheet = book.add_worksheet('planning_pathy')
paths_sheet = book.add_worksheet('planning_paths')
patha_sheet = book.add_worksheet('planning_patha')
pathv_sheet = book.add_worksheet('planning_pathv')
pathx_sheet.write(0, 0, "timestamp_sec", book_format)
pathy_sheet.write(0, 0, "timestamp_sec", book_format)
paths_sheet.write(0, 0, "timestamp_sec", book_format)
patha_sheet.write(0, 0, "timestamp_sec", book_format)
pathv_sheet.write(0, 0, "timestamp_sec", book_format)
controlinfo.read_bag(args.bag)
else:
cyber.init()
# rospy.init_node('control_info', anonymous=True)
node = cyber.Node("rtk_recorder")
planningsub = node.create_reader('/apollo/planning',
planning_pb2.ADCTrajectory,
controlinfo.callback_planning)
localizationsub = node.create_reader(
'/apollo/localization/pose', localization_pb2.LocalizationEstimate,
controlinfo.callback_localization)
controlsub = node.create_reader('/apollo/control',
control_cmd_pb2.ControlCommand,
controlinfo.callback_control)
canbussub = node.create_reader('/apollo/canbus/chassis',
chassis_pb2.Chassis,
controlinfo.callback_canbus)
raw_input("Press Enter To Stop")
controlinfo.Print_len()
# controlinfo.show_longitudinal()
controlinfo.show_lateral()
controlinfo.show_localization()
controlinfo.show_longitudinal_all()
book.close()
fig.canvas.mpl_connect('key_press_event', controlinfo.press)
plt.show()
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/map_gen/map_gen_two_lanes_right_ext.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
import math
import sys
from modules.common_msgs.map_msgs import map_pb2
from modules.common_msgs.map_msgs import map_lane_pb2
from modules.common_msgs.map_msgs import map_road_pb2
from shapely.geometry import LineString, Point
LANE_WIDTH = 3.3
def convert(p, p2, distance):
delta_y = p2.y - p.y
delta_x = p2.x - p.x
# print math.atan2(delta_y, delta_x)
left_angle = math.atan2(delta_y, delta_x) + math.pi / 2.0
right_angle = math.atan2(delta_y, delta_x) - math.pi / 2.0
# print angle
lp = []
lp.append(p.x + (math.cos(left_angle) * distance))
lp.append(p.y + (math.sin(left_angle) * distance))
rp = []
rp.append(p.x + (math.cos(right_angle) * distance))
rp.append(p.y + (math.sin(right_angle) * distance))
return lp, rp
def shift(p, p2, distance, isleft=True):
delta_y = p2.y - p.y
delta_x = p2.x - p.x
# print math.atan2(delta_y, delta_x)
angle = 0
if isleft:
angle = math.atan2(delta_y, delta_x) + math.pi / 2.0
else:
angle = math.atan2(delta_y, delta_x) - math.pi / 2.0
# print angle
p1n = []
p1n.append(p.x + (math.cos(angle) * distance))
p1n.append(p.y + (math.sin(angle) * distance))
p2n = []
p2n.append(p2.x + (math.cos(angle) * distance))
p2n.append(p2.y + (math.sin(angle) * distance))
return Point(p1n), Point(p2n)
def create_lane(map, id):
lane = map.lane.add()
lane.id.id = str(id)
lane.type = map_lane_pb2.Lane.CITY_DRIVING
lane.direction = map_lane_pb2.Lane.FORWARD
lane.length = 100.0
lane.speed_limit = 20.0
lane.turn = map_lane_pb2.Lane.NO_TURN
#lane.predecessor_id.add().id = str(id - 1)
#lane.successor_id.add().id = str(id + 1)
left_boundary = lane.left_boundary.curve.segment.add()
right_boundary = lane.right_boundary.curve.segment.add()
central = lane.central_curve.segment.add()
central.length = 100.0
type = lane.left_boundary.boundary_type.add()
type.s = 0
type.types.append(map_lane_pb2.LaneBoundaryType.DOTTED_YELLOW)
lane.right_boundary.length = 100.0
type = lane.right_boundary.boundary_type.add()
type.s = 0
type.types.append(map_lane_pb2.LaneBoundaryType.DOTTED_YELLOW)
lane.left_boundary.length = 100.0
return lane, central, left_boundary, right_boundary
fpath = sys.argv[1]
f = open(fpath, 'r')
points = []
for line in f:
line = line.replace("\n", '')
data = line.split(',')
x = float(data[0])
y = float(data[1])
points.append((x, y))
path = LineString(points)
length = int(path.length)
fmap = open(sys.argv[2], 'w')
id = 0
map = map_pb2.Map()
road = map.road.add()
road.id.id = "1"
section = road.section.add()
section.id.id = "2"
lane = None
lane_n1 = None
for i in range(length - 1):
if i % 100 == 0:
id += 1
if lane is not None:
lane.successor_id.add().id = str(id)
if lane_n1 is not None:
lane_n1.successor_id.add().id = str(id + 1000)
lane, central, left_boundary, right_boundary = create_lane(map, id)
lane_n1, central_n1, left_boundary_n1, right_boundary_n1 = create_lane(
map, id + 1000)
section.lane_id.add().id = str(id)
section.lane_id.add().id = str(id + 1000)
left_edge = section.boundary.outer_polygon.edge.add()
left_edge.type = map_road_pb2.BoundaryEdge.LEFT_BOUNDARY
left_edge_segment = left_edge.curve.segment.add()
right_edge = section.boundary.outer_polygon.edge.add()
right_edge.type = map_road_pb2.BoundaryEdge.RIGHT_BOUNDARY
right_edge_segment = right_edge.curve.segment.add()
lane.right_neighbor_forward_lane_id.add().id = str(id + 1000)
lane_n1.left_neighbor_forward_lane_id.add().id = str(id)
if i > 0:
lane.predecessor_id.add().id = str(id - 1)
lane_n1.predecessor_id.add().id = str(id - 1 + 1000)
right_edge_point = right_edge_segment.line_segment.point.add()
left_edge_point = left_edge_segment.line_segment.point.add()
left_bound_point = left_boundary.line_segment.point.add()
right_bound_point = right_boundary.line_segment.point.add()
central_point = central.line_segment.point.add()
p = path.interpolate(i - 1)
p2 = path.interpolate(i - 1 + 0.5)
distance = LANE_WIDTH / 2.0
lp, rp = convert(p, p2, distance)
left_bound_point.y = lp[1]
left_bound_point.x = lp[0]
right_bound_point.y = rp[1]
right_bound_point.x = rp[0]
central_point.x = p.x
central_point.y = p.y
left_edge_point.y = lp[1]
left_edge_point.x = lp[0]
left_sample = lane.left_sample.add()
left_sample.s = 0
left_sample.width = LANE_WIDTH / 2.0
right_sample = lane.right_sample.add()
right_sample.s = 0
right_sample.width = LANE_WIDTH / 2.0
#####
left_bound_point = left_boundary_n1.line_segment.point.add()
right_bound_point = right_boundary_n1.line_segment.point.add()
central_point = central_n1.line_segment.point.add()
p = path.interpolate(i - 1)
p2 = path.interpolate(i - 1 + 0.5)
distance = LANE_WIDTH
p, p2 = shift(p, p2, distance, False)
distance = LANE_WIDTH / 2.0
lp, rp = convert(p, p2, distance)
left_bound_point.y = lp[1]
left_bound_point.x = lp[0]
right_bound_point.y = rp[1]
right_bound_point.x = rp[0]
central_point.x = p.x
central_point.y = p.y
right_edge_point.y = rp[1]
right_edge_point.x = rp[0]
left_sample = lane_n1.left_sample.add()
left_sample.s = 0
left_sample.width = LANE_WIDTH / 2.0
right_sample = lane_n1.right_sample.add()
right_sample.s = 0
right_sample.width = LANE_WIDTH / 2.0
right_edge_point = right_edge_segment.line_segment.point.add()
left_edge_point = left_edge_segment.line_segment.point.add()
left_bound_point = left_boundary.line_segment.point.add()
right_bound_point = right_boundary.line_segment.point.add()
central_point = central.line_segment.point.add()
p = path.interpolate(i)
p2 = path.interpolate(i + 0.5)
distance = LANE_WIDTH / 2.0
lp, rp = convert(p, p2, distance)
central_point.x = p.x
central_point.y = p.y
left_bound_point.y = lp[1]
left_bound_point.x = lp[0]
right_bound_point.y = rp[1]
right_bound_point.x = rp[0]
left_edge_point.y = lp[1]
left_edge_point.x = lp[0]
left_sample = lane.left_sample.add()
left_sample.s = i % 100 + 1
left_sample.width = LANE_WIDTH / 2.0
right_sample = lane.right_sample.add()
right_sample.s = i % 100 + 1
right_sample.width = LANE_WIDTH / 2.0
################
left_bound_point = left_boundary_n1.line_segment.point.add()
right_bound_point = right_boundary_n1.line_segment.point.add()
central_point = central_n1.line_segment.point.add()
p = path.interpolate(i)
p2 = path.interpolate(i + 0.5)
distance = LANE_WIDTH
p, p2 = shift(p, p2, distance, False)
distance = LANE_WIDTH / 2.0
lp, rp = convert(p, p2, distance)
central_point.x = p.x
central_point.y = p.y
left_bound_point.y = lp[1]
left_bound_point.x = lp[0]
right_bound_point.y = rp[1]
right_bound_point.x = rp[0]
right_edge_point.y = rp[1]
right_edge_point.x = rp[0]
left_sample = lane_n1.left_sample.add()
left_sample.s = i % 100 + 1
left_sample.width = LANE_WIDTH / 2.0
right_sample = lane_n1.right_sample.add()
right_sample.s = i % 100 + 1
right_sample.width = LANE_WIDTH / 2.0
fmap.write(str(map))
fmap.close()
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/map_gen/plot_path.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
import sys
import matplotlib.pyplot as plt
f = open(sys.argv[1], 'r')
xs = []
ys = []
for line in f:
line = line.replace("\n", '')
data = line.split(',')
x = float(data[0])
y = float(data[1])
xs.append(x)
ys.append(y)
f.close()
fig = plt.figure()
ax = plt.subplot2grid((1, 1), (0, 0))
ax.plot(xs, ys, "b-", lw=3, alpha=0.8)
ax.axis('equal')
plt.show()
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/map_gen/map_gen_single_lane.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
import math
import sys
from modules.common_msgs.map_msgs import map_pb2
from modules.common_msgs.map_msgs import map_lane_pb2
from modules.common_msgs.map_msgs import map_road_pb2
from shapely.geometry import LineString, Point
LANE_WIDTH = 3.3
def convert(p, p2, distance):
delta_y = p2.y - p.y
delta_x = p2.x - p.x
# print math.atan2(delta_y, delta_x)
left_angle = math.atan2(delta_y, delta_x) + math.pi / 2.0
right_angle = math.atan2(delta_y, delta_x) - math.pi / 2.0
# print angle
lp = []
lp.append(p.x + (math.cos(left_angle) * distance))
lp.append(p.y + (math.sin(left_angle) * distance))
rp = []
rp.append(p.x + (math.cos(right_angle) * distance))
rp.append(p.y + (math.sin(right_angle) * distance))
return lp, rp
def shift(p, p2, distance, isleft=True):
delta_y = p2.y - p.y
delta_x = p2.x - p.x
# print math.atan2(delta_y, delta_x)
angle = 0
if isleft:
angle = math.atan2(delta_y, delta_x) + math.pi / 2.0
else:
angle = math.atan2(delta_y, delta_x) - math.pi / 2.0
# print angle
p1n = []
p1n.append(p.x + (math.cos(angle) * distance))
p1n.append(p.y + (math.sin(angle) * distance))
p2n = []
p2n.append(p2.x + (math.cos(angle) * distance))
p2n.append(p2.y + (math.sin(angle) * distance))
return Point(p1n), Point(p2n)
def create_lane(map, id):
lane = map.lane.add()
lane.id.id = str(id)
lane.type = map_lane_pb2.Lane.CITY_DRIVING
lane.direction = map_lane_pb2.Lane.FORWARD
lane.length = 100.0
lane.speed_limit = 20.0
lane.turn = map_lane_pb2.Lane.NO_TURN
#lane.predecessor_id.add().id = str(id - 1)
#lane.successor_id.add().id = str(id + 1)
left_boundary = lane.left_boundary.curve.segment.add()
right_boundary = lane.right_boundary.curve.segment.add()
central = lane.central_curve.segment.add()
central.length = 100.0
type = lane.left_boundary.boundary_type.add()
type.s = 0
type.types.append(map_lane_pb2.LaneBoundaryType.DOTTED_YELLOW)
lane.right_boundary.length = 100.0
type = lane.right_boundary.boundary_type.add()
type.s = 0
type.types.append(map_lane_pb2.LaneBoundaryType.DOTTED_YELLOW)
lane.left_boundary.length = 100.0
return lane, central, left_boundary, right_boundary
fpath = sys.argv[1]
f = open(fpath, 'r')
points = []
for line in f:
line = line.replace("\n", '')
data = line.split(',')
x = float(data[0])
y = float(data[1])
points.append((x, y))
path = LineString(points)
length = int(path.length)
extra_roi_extension = float(sys.argv[3])
fmap = open(sys.argv[2], 'w')
id = 0
map = map_pb2.Map()
road = map.road.add()
road.id.id = "1"
section = road.section.add()
section.id.id = "2"
lane = None
for i in range(length - 1):
if i % 100 == 0:
id += 1
if lane is not None:
lane.successor_id.add().id = str(id)
lane, central, left_boundary, right_boundary = create_lane(map, id)
section.lane_id.add().id = str(id)
left_edge = section.boundary.outer_polygon.edge.add()
left_edge.type = map_road_pb2.BoundaryEdge.LEFT_BOUNDARY
left_edge_segment = left_edge.curve.segment.add()
right_edge = section.boundary.outer_polygon.edge.add()
right_edge.type = map_road_pb2.BoundaryEdge.RIGHT_BOUNDARY
right_edge_segment = right_edge.curve.segment.add()
if i > 0:
lane.predecessor_id.add().id = str(id - 1)
left_bound_point = left_boundary.line_segment.point.add()
right_bound_point = right_boundary.line_segment.point.add()
central_point = central.line_segment.point.add()
right_edge_point = right_edge_segment.line_segment.point.add()
left_edge_point = left_edge_segment.line_segment.point.add()
p = path.interpolate(i - 1)
p2 = path.interpolate(i - 1 + 0.5)
distance = LANE_WIDTH / 2.0
lp, rp = convert(p, p2, distance)
left_bound_point.y = lp[1]
left_bound_point.x = lp[0]
right_bound_point.y = rp[1]
right_bound_point.x = rp[0]
lp, rp = convert(p, p2, distance + extra_roi_extension)
left_edge_point.y = lp[1]
left_edge_point.x = lp[0]
right_edge_point.y = rp[1]
right_edge_point.x = rp[0]
central_point.x = p.x
central_point.y = p.y
left_sample = lane.left_sample.add()
left_sample.s = 0
left_sample.width = LANE_WIDTH / 2.0
right_sample = lane.right_sample.add()
right_sample.s = 0
right_sample.width = LANE_WIDTH / 2.0
left_bound_point = left_boundary.line_segment.point.add()
right_bound_point = right_boundary.line_segment.point.add()
central_point = central.line_segment.point.add()
right_edge_point = right_edge_segment.line_segment.point.add()
left_edge_point = left_edge_segment.line_segment.point.add()
p = path.interpolate(i)
p2 = path.interpolate(i + 0.5)
distance = LANE_WIDTH / 2.0
lp, rp = convert(p, p2, distance)
central_point.x = p.x
central_point.y = p.y
left_bound_point.y = lp[1]
left_bound_point.x = lp[0]
right_bound_point.y = rp[1]
right_bound_point.x = rp[0]
left_edge_point.y = lp[1]
left_edge_point.x = lp[0]
right_edge_point.y = rp[1]
right_edge_point.x = rp[0]
left_sample = lane.left_sample.add()
left_sample.s = i % 100 + 1
left_sample.width = LANE_WIDTH / 2.0
right_sample = lane.right_sample.add()
right_sample.s = i % 100 + 1
right_sample.width = LANE_WIDTH / 2.0
fmap.write(str(map))
fmap.close()
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/map_gen/BUILD
|
load("@rules_python//python:defs.bzl", "py_binary")
load("//tools/install:install.bzl", "install")
package(default_visibility = ["//visibility:public"])
py_binary(
name = "add_signal",
srcs = ["add_signal.py"],
deps = [
"//modules/common_msgs/map_msgs:map_overlap_py_pb2",
"//modules/common_msgs/map_msgs:map_py_pb2",
"//modules/common_msgs/map_msgs:map_signal_py_pb2",
],
)
py_binary(
name = "extract_path",
srcs = ["extract_path.py"],
deps = [
"//cyber/python/cyber_py3:cyber",
"//cyber/python/cyber_py3:record",
"//modules/common_msgs/localization_msgs:localization_py_pb2",
],
)
py_binary(
name = "map_gen_single_lane",
srcs = ["map_gen_single_lane.py"],
deps = [
"//modules/common_msgs/map_msgs:map_lane_py_pb2",
"//modules/common_msgs/map_msgs:map_py_pb2",
"//modules/common_msgs/map_msgs:map_road_py_pb2",
],
)
py_binary(
name = "map_gen_two_lanes_right_ext",
srcs = ["map_gen_two_lanes_right_ext.py"],
deps = [
"//modules/common_msgs/map_msgs:map_lane_py_pb2",
"//modules/common_msgs/map_msgs:map_py_pb2",
"//modules/common_msgs/map_msgs:map_road_py_pb2",
],
)
py_binary(
name = "map_gen",
srcs = ["map_gen.py"],
deps = [
"//modules/common_msgs/map_msgs:map_lane_py_pb2",
"//modules/common_msgs/map_msgs:map_py_pb2",
],
)
install(
name = "install",
py_dest = "tools/map_gen",
targets = [
"add_signal",
"extract_path",
"map_gen_single_lane",
"map_gen_two_lanes_right_ext",
"map_gen",
]
)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/map_gen/map_gen.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
import math
import sys
from modules.common_msgs.map_msgs import map_pb2
from modules.common_msgs.map_msgs import map_lane_pb2
from shapely.geometry import LineString, Point
LANE_WIDTH = 3.3
def convert(p, p2, distance):
delta_y = p2.y - p.y
delta_x = p2.x - p.x
# print math.atan2(delta_y, delta_x)
left_angle = math.atan2(delta_y, delta_x) + math.pi / 2.0
right_angle = math.atan2(delta_y, delta_x) - math.pi / 2.0
# print angle
lp = []
lp.append(p.x + (math.cos(left_angle) * distance))
lp.append(p.y + (math.sin(left_angle) * distance))
rp = []
rp.append(p.x + (math.cos(right_angle) * distance))
rp.append(p.y + (math.sin(right_angle) * distance))
return lp, rp
def shift(p, p2, distance, isleft=True):
delta_y = p2.y - p.y
delta_x = p2.x - p.x
# print math.atan2(delta_y, delta_x)
angle = 0
if isleft:
angle = math.atan2(delta_y, delta_x) + math.pi / 2.0
else:
angle = math.atan2(delta_y, delta_x) - math.pi / 2.0
# print angle
p1n = []
p1n.append(p.x + (math.cos(angle) * distance))
p1n.append(p.y + (math.sin(angle) * distance))
p2n = []
p2n.append(p2.x + (math.cos(angle) * distance))
p2n.append(p2.y + (math.sin(angle) * distance))
return Point(p1n), Point(p2n)
def create_lane(map, id):
lane = map.lane.add()
lane.id.id = str(id)
lane.type = map_lane_pb2.Lane.CITY_DRIVING
lane.direction = map_lane_pb2.Lane.FORWARD
lane.length = 100.0
lane.speed_limit = 20.0
lane.turn = map_lane_pb2.Lane.NO_TURN
lane.predecessor_id.add().id = str(id - 1)
lane.successor_id.add().id = str(id + 1)
left_boundary = lane.left_boundary.curve.segment.add()
right_boundary = lane.right_boundary.curve.segment.add()
central = lane.central_curve.segment.add()
central.length = 100.0
type = lane.left_boundary.boundary_type.add()
type.s = 0
type.types.append(map_lane_pb2.LaneBoundaryType.DOTTED_YELLOW)
lane.right_boundary.length = 100.0
type = lane.right_boundary.boundary_type.add()
type.s = 0
type.types.append(map_lane_pb2.LaneBoundaryType.DOTTED_YELLOW)
lane.left_boundary.length = 100.0
return lane, central, left_boundary, right_boundary
fpath = sys.argv[1]
points = []
with open(fpath, 'r') as f:
for line in f:
line = line.replace("\n", '')
data = line.split(',')
x = float(data[0])
y = float(data[1])
points.append((x, y))
path = LineString(points)
length = int(path.length)
fmap = open("map_" + fpath.split("/")[-1] + ".txt", 'w')
id = 0
map = map_pb2.Map()
road = map.road.add()
road.id.id = "1"
section = road.section.add()
section.id.id = "2"
lane = None
for i in range(length - 1):
if i % 100 == 0:
id += 1
lane, central, left_boundary, right_boundary = create_lane(map, id)
lane_n1, central_n1, left_boundary_n1, right_boundary_n1 = create_lane(
map, id + 1000)
lane_n2, central_n2, left_boundary_n2, right_boundary_n2 = create_lane(
map, id + 2000)
section.lane_id.add().id = str(id)
section.lane_id.add().id = str(id + 1000)
section.lane_id.add().id = str(id + 2000)
lane.left_neighbor_forward_lane_id.add().id = str(id + 1000)
lane_n1.left_neighbor_forward_lane_id.add().id = str(id + 2000)
lane_n2.right_neighbor_forward_lane_id.add().id = str(id + 1000)
lane_n1.right_neighbor_forward_lane_id.add().id = str(id)
if i > 0:
left_bound_point = left_boundary.line_segment.point.add()
right_bound_point = right_boundary.line_segment.point.add()
central_point = central.line_segment.point.add()
p = path.interpolate(i - 1)
p2 = path.interpolate(i - 1 + 0.5)
distance = LANE_WIDTH / 2.0
lp, rp = convert(p, p2, distance)
left_bound_point.y = lp[1]
left_bound_point.x = lp[0]
right_bound_point.y = rp[1]
right_bound_point.x = rp[0]
central_point.x = p.x
central_point.y = p.y
left_sample = lane.left_sample.add()
left_sample.s = 0
left_sample.width = LANE_WIDTH / 2.0
right_sample = lane.right_sample.add()
right_sample.s = 0
right_sample.width = LANE_WIDTH / 2.0
#####
left_bound_point = left_boundary_n1.line_segment.point.add()
right_bound_point = right_boundary_n1.line_segment.point.add()
central_point = central_n1.line_segment.point.add()
p = path.interpolate(i - 1)
p2 = path.interpolate(i - 1 + 0.5)
distance = LANE_WIDTH
p, p2 = shift(p, p2, distance)
distance = LANE_WIDTH / 2.0
lp, rp = convert(p, p2, distance)
left_bound_point.y = lp[1]
left_bound_point.x = lp[0]
right_bound_point.y = rp[1]
right_bound_point.x = rp[0]
central_point.x = p.x
central_point.y = p.y
left_sample = lane_n1.left_sample.add()
left_sample.s = 0
left_sample.width = LANE_WIDTH / 2.0
right_sample = lane_n1.right_sample.add()
right_sample.s = 0
right_sample.width = LANE_WIDTH / 2.0
#####
left_bound_point = left_boundary_n2.line_segment.point.add()
right_bound_point = right_boundary_n2.line_segment.point.add()
central_point = central_n2.line_segment.point.add()
p = path.interpolate(i - 1)
p2 = path.interpolate(i - 1 + 0.5)
distance = LANE_WIDTH * 2.0
p, p2 = shift(p, p2, distance)
distance = LANE_WIDTH / 2.0
lp, rp = convert(p, p2, distance)
left_bound_point.y = lp[1]
left_bound_point.x = lp[0]
right_bound_point.y = rp[1]
right_bound_point.x = rp[0]
central_point.x = p.x
central_point.y = p.y
left_sample = lane_n2.left_sample.add()
left_sample.s = 0
left_sample.width = LANE_WIDTH / 2.0
right_sample = lane_n2.right_sample.add()
right_sample.s = 0
right_sample.width = LANE_WIDTH / 2.0
left_bound_point = left_boundary.line_segment.point.add()
right_bound_point = right_boundary.line_segment.point.add()
central_point = central.line_segment.point.add()
p = path.interpolate(i)
p2 = path.interpolate(i + 0.5)
distance = LANE_WIDTH / 2.0
lp, rp = convert(p, p2, distance)
central_point.x = p.x
central_point.y = p.y
left_bound_point.y = lp[1]
left_bound_point.x = lp[0]
right_bound_point.y = rp[1]
right_bound_point.x = rp[0]
left_sample = lane.left_sample.add()
left_sample.s = i % 100 + 1
left_sample.width = LANE_WIDTH / 2.0
right_sample = lane.right_sample.add()
right_sample.s = i % 100 + 1
right_sample.width = LANE_WIDTH / 2.0
################
left_bound_point = left_boundary_n1.line_segment.point.add()
right_bound_point = right_boundary_n1.line_segment.point.add()
central_point = central_n1.line_segment.point.add()
p = path.interpolate(i)
p2 = path.interpolate(i + 0.5)
distance = LANE_WIDTH
p, p2 = shift(p, p2, distance)
distance = LANE_WIDTH / 2.0
lp, rp = convert(p, p2, distance)
central_point.x = p.x
central_point.y = p.y
left_bound_point.y = lp[1]
left_bound_point.x = lp[0]
right_bound_point.y = rp[1]
right_bound_point.x = rp[0]
left_sample = lane_n1.left_sample.add()
left_sample.s = i % 100 + 1
left_sample.width = LANE_WIDTH / 2.0
right_sample = lane_n1.right_sample.add()
right_sample.s = i % 100 + 1
right_sample.width = LANE_WIDTH / 2.0
################
left_bound_point = left_boundary_n2.line_segment.point.add()
right_bound_point = right_boundary_n2.line_segment.point.add()
central_point = central_n2.line_segment.point.add()
p = path.interpolate(i)
p2 = path.interpolate(i + 0.5)
distance = 6.6
p, p2 = shift(p, p2, distance)
distance = LANE_WIDTH / 2.0
lp, rp = convert(p, p2, distance)
central_point.x = p.x
central_point.y = p.y
left_bound_point.y = lp[1]
left_bound_point.x = lp[0]
right_bound_point.y = rp[1]
right_bound_point.x = rp[0]
left_sample = lane_n2.left_sample.add()
left_sample.s = i % 100 + 1
left_sample.width = LANE_WIDTH / 2.0
right_sample = lane_n2.right_sample.add()
right_sample.s = i % 100 + 1
right_sample.width = LANE_WIDTH / 2.0
fmap.write(str(map))
fmap.close()
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/map_gen/add_signal.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
import sys
from modules.common_msgs.map_msgs import map_pb2
from modules.common_msgs.map_msgs import map_signal_pb2
from modules.common_msgs.map_msgs import map_overlap_pb2
from google.protobuf import text_format
from shapely.geometry import LineString, Point
if len(sys.argv) < 3:
print('Usage: %s [map_file] [signal_file]' % sys.argv[0])
sys.exit(0)
map_file = sys.argv[1]
signal_file = sys.argv[2]
with open(map_file, 'r') as fmap:
map_data = fmap.read()
map = map_pb2.Map()
text_format.Parse(map_data, map)
with open(signal_file, 'r') as fsignal:
signal_data = fsignal.read()
signal = map_signal_pb2.Signal()
text_format.Parse(signal_data, signal)
lanes = {}
lanes_map = {}
for lane in map.lane:
lane_points = []
lanes_map[lane.id.id] = lane
for segment in lane.central_curve.segment:
for point in segment.line_segment.point:
lane_points.append((point.x, point.y))
lane_string = LineString(lane_points)
lanes[lane.id.id] = lane_string
lines = {}
for stop_line in signal.stop_line:
stop_line_points = []
for segment in stop_line.segment:
for point in segment.line_segment.point:
stop_line_points.append((point.x, point.y))
stop_line_string = LineString(stop_line_points)
for lane_id, lane_string in lanes.items():
p = stop_line_string.intersection(lane_string)
if type(p) == Point:
s = lane_string.project(p)
overlap = map.overlap.add()
overlap.id.id = str(lane_id) + "_" + str(signal.id.id)
obj = overlap.object.add()
obj.id.id = signal.id.id
obj.signal_overlap_info.CopyFrom(
map_overlap_pb2.SignalOverlapInfo())
obj = overlap.object.add()
obj.id.id = lane_id
obj.lane_overlap_info.start_s = s
obj.lane_overlap_info.end_s = s + 0.1
obj.lane_overlap_info.is_merge = False
signal.overlap_id.add().id = overlap.id.id
lanes_map[lane_id].overlap_id.add().id = overlap.id.id
map.signal.add().CopyFrom(signal)
with open(map_file + "_" + fsignal_file, 'w') as fmap:
fmap.write(str(map))
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/map_gen/extract_path.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
"""
Extract localization message from data record file,
and save them into specified file
Usage:
extract_path.py save_fileName bag1 bag2
See the gflags for more optional args.
"""
import sys
from cyber.python.cyber_py3 import cyber
from cyber.python.cyber_py3.record import RecordReader
from modules.common_msgs.localization_msgs import localization_pb2
if len(sys.argv) < 3:
print("Usage: %s <filename> <fbags>" % sys.argv[0])
sys.exit(0)
filename = sys.argv[1]
fbags = sys.argv[2:]
with open(filename, 'w') as f:
for fbag in fbags:
reader = RecordReader(fbag)
for msg in reader.read_messages():
if msg.topic == "/apollo/localization/pose":
localization = localization_pb2.LocalizationEstimate()
localization.ParseFromString(msg.message)
x = localization.pose.position.x
y = localization.pose.position.y
f.write(str(x) + "," + str(y) + "\n")
print("File written to: %s" % filename)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/ota/create_sec_package.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
import secure_upgrade_export as sec_api
import os
import sys
sys.path.append('/home/caros/secure_upgrade/python')
root_config_path = "/home/caros/secure_upgrade/config/secure_config.json"
ret = sec_api.init_secure_upgrade(root_config_path)
if ret is True:
print('Security environment init successfully!')
else:
print('Security environment init failed!')
exit(1)
homedir = os.environ['HOME']
release_tgz = homedir + '/.cache/apollo_release.tar.gz'
sec_release_tgz = homedir + '/.cache/sec_apollo_release.tar.gz'
package_token = homedir + '/.cache/package_token'
ret = sec_api.sec_upgrade_get_package(
release_tgz, sec_release_tgz, package_token)
if ret is True:
print('Security package generated successfully!')
else:
print('Security package generated failed!')
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/ota/config.ini
|
[Host]
ip: 180.76.145.202
port: 5000
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/ota/ota.cert
|
-----BEGIN CERTIFICATE-----
MIIFozCCA4ugAwIBAgIJAMvsOaOMZCjpMA0GCSqGSIb3DQEBCwUAMGgxCzAJBgNV
BAYTAkNOMRAwDgYDVQQIDAdCZWlqaW5nMRAwDgYDVQQHDAdCZWlqaW5nMQ4wDAYD
VQQKDAVCYWlkdTEMMAoGA1UECwwDSURHMRcwFQYDVQQDDA4xODAuNzYuMTQ1LjIw
MjAeFw0xNzEyMjYyMzU2NDBaFw0yNzEyMjQyMzU2NDBaMGgxCzAJBgNVBAYTAkNO
MRAwDgYDVQQIDAdCZWlqaW5nMRAwDgYDVQQHDAdCZWlqaW5nMQ4wDAYDVQQKDAVC
YWlkdTEMMAoGA1UECwwDSURHMRcwFQYDVQQDDA4xODAuNzYuMTQ1LjIwMjCCAiIw
DQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBALOEBanzSF/+Deg1DmjRLxnfsAKr
D/mR717RLCc92LsLujfKjHIhfy/NBOxGlrWhc7ScAp5mcSnFeByEXhyLUnd7pXuy
6DLvdrmDJExiciaRkz0zmoPO7H1LjzdPbcnkLz7zPrFG3zCBhLaZIHZukvS73vcK
OGxhX+9MXTlwl9nsC8lGx6ZNLSj5f8KVOpdy2P7Jeus5rdUBEthpjIpXMOgfDiaz
LcGrw5oBD38NwA6n5PGbgCOSkGM/GDmgBUeHxLirBsJncJPcgznLRgqrpiHizNsY
hijAH7qxn/JsF08w2YzVad5CSE8FLBElnGBrj6O0VmlWwoleKqhRCJXeqt+M+J2x
ccUyBA7dHmGhW3ELIwmIIA2fYrRm/s0SnZi9iDuwnHCHSe362kDXdl6l3WkjH34w
z1LsYlXV1rVyzu20sc98Irq+JvpP8rbY/PGg38UqyvcSJUdbrThEOcWbVuEqHbFO
iBdW8+WgBLDnp+4Q/uTFWSDl+vw3M0U3gTGhAPMYDDkjQyeGTAsXxQFplenpppAi
ycaap2+IAeJ0nQI94bhz8WBiEDfMqqUecWhnvwgDGjTRYdF+vNn7ZtsbkvdwckEe
ra8pDs/5uDMU8fCW48bkdo0QOYSTc3zufkN+mJiCQ+4kTuK+URGVCaZL9+GvTkhO
kQP8X8VtnqImEYWFAgMBAAGjUDBOMB0GA1UdDgQWBBSB4MbBrVai2n0XnQHLwIcg
xKKmbDAfBgNVHSMEGDAWgBSB4MbBrVai2n0XnQHLwIcgxKKmbDAMBgNVHRMEBTAD
AQH/MA0GCSqGSIb3DQEBCwUAA4ICAQAvZ/BU6ZdIDc12hFnOc4YXQld2uCApbznX
TuGqVedL/vcx5lwzGnbpJJQEg8BePLZSZznpP4h4UAhruTEzbYkaXibEgVD4k9wv
e/XEYaDQ07VKaRMEeuq8IKb5w9MXMENquN/YIvAmlRtVYgCuBUal9AZJulbXhD6E
HYuvPAMuuBUVINBcSPhby3UzY/yMP7VKDV3+QagRGZuelAjM9zzUY2BtHUPPkxgP
HAc+5clb2yi0wpHo1thHcm9DhN1cp9raYwHNiVIKKXV+RBlCKYX/huL3MyJPC5Pk
AdPrKe/yPMBPoISrEFeJta142/l2ywz1XVkUjeVBZzXDx01SJw5ta7iYKqcjfha2
e2dGOJTg1U6cJftlkUB1bM4QnRf5QQIJ7Q06lOkcAGYuLBHlVJmkeSMEOOdXyaXY
ylV/wbQIzfL4t8DRkw+ZjUEvTcrJqXe6RgahpqD4SYTJoasYEVmmNfWVQVNTN9Wj
nbtyx3YFlecfYz+aJfAvNxpL0EZdGlUm0heIYn09dXknUQAfUQ/pkVLVkXWsy7WM
ddHiNjZjITt2N/3QQWaJJ16hPHcbFXqsSyfnLEjDTXp/Xy7DjWHJYlYEB1sScWlp
sB9arnO1iIRp5vLFjs3f6QDNPt6rygLses5/oZMzjUteFHoIKFoGBItjVdQkYGn6
UyVKS7Me6A==
-----END CERTIFICATE-----
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/ota/verify_client.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
"""OTA verify client"""
import os
import requests
import sys
from configparser import ConfigParser
import secure_upgrade_export as sec_api
from modules.data.proto.static_info_pb2 import VehicleInfo
import modules.tools.common.proto_utils as proto_utils
sys.path.append('/home/caros/secure_upgrade/python')
root_config_path = "/home/caros/secure_upgrade/config/secure_config.json"
ret = sec_api.init_secure_upgrade(root_config_path)
if ret is True:
print('Security environment init successfully!')
else:
print('Security environment init failed!')
sys.exit(1)
def verify():
# Generate orig update package
token_file_name = os.environ['HOME'] + '/.cache/apollo_update/auth_token'
with open(token_file_name, 'r') as token_file:
auth_token = token_file.read()
sec_package = os.environ['HOME'] + '/.cache/sec_apollo_release.tar.gz'
orig_package = os.environ['HOME'] + '/.cache/apollo_release.tar.gz'
ret = sec_api.sec_upgrade_verify_package(auth_token, sec_package,
orig_package)
if ret is True:
print('Verify package successfully!')
sys.exit(0)
else:
print('Verify package failed!!!')
sys.exit(1)
if __name__ == "__main__":
verify()
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/ota/query_client.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
import os
import requests
import sys
from configparser import ConfigParser
import secure_upgrade_export as sec_api
import urllib3
from modules.data.proto.static_info_pb2 import VehicleInfo
import modules.tools.common.proto_utils as proto_utils
sys.path.append('/home/caros/secure_upgrade/python')
root_config_path = '/home/caros/secure_upgrade/config/secure_config.json'
ret = sec_api.init_secure_upgrade(root_config_path)
if ret is False:
print('Failed to initialize security environment!')
sys.exit(1)
def query():
vehicle_info = VehicleInfo()
VEHICLE_INFO_FILE = os.path.join(
os.path.dirname(__file__), 'vehicle_info.pb.txt')
try:
proto_utils.get_pb_from_text_file(VEHICLE_INFO_FILE, vehicle_info)
except IOError:
print('vehicle_info.pb.txt cannot be open file.')
sys.exit(1)
# Setup server url
config = ConfigParser()
CONFIG_FILE = os.path.join(os.path.dirname(__file__), 'config.ini')
config.read(CONFIG_FILE)
ip = config.get('Host', 'ip')
port = config.get('Host', 'port')
url = 'https://' + ip + ':' + port + '/query'
# Generate device token
ret = sec_api.sec_upgrade_get_device_token()
if ret[0] is False:
print('Failed to get device token.')
sys.exit(1)
dev_token = ret[1]
# setup car info
brand = VehicleInfo.Brand.Name(vehicle_info.brand)
model = VehicleInfo.Model.Name(vehicle_info.model)
vin = vehicle_info.vehicle_config.vehicle_id.vin
META_FILE = '/apollo/meta.ini'
config.read(META_FILE)
car_info = {
"car_type": brand + "." + model,
"tag": config.get('Release', 'tag'),
"vin": vin,
"token": dev_token
}
urllib3.disable_warnings()
CERT_FILE = os.path.join(os.path.dirname(__file__), 'ota.cert')
r = requests.post(url, json=car_info, verify=CERT_FILE)
if r.status_code == 200:
auth_token = r.json().get("auth_token")
if auth_token == "":
print('Cannot get authorize token!')
sys.exit(1)
else:
token_file_name = os.environ['HOME'] + \
'/.cache/apollo_update/auth_token'
apollo_update = os.path.dirname(token_file_name)
if not os.path.exists(apollo_update):
os.makedirs(apollo_update)
with open(token_file_name, 'w') as token_file:
token_file.write(auth_token)
tag = r.json().get("tag")
print(tag)
sys.exit(0)
elif r.status_code == 204:
print('Release is up to date.')
sys.exit(0)
elif r.status_code == 400:
print('Invalid car type.')
else:
print('Cannot connect to server.')
sys.exit(1)
if __name__ == '__main__':
query()
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/ota/update_client.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
import requests
import os
import sys
import urllib3
from configparser import ConfigParser
from modules.data.proto.static_info_pb2 import VehicleInfo
import modules.tools.common.proto_utils as proto_utils
def update():
# setup server url
config = ConfigParser()
CONFIG_FILE = os.path.join(os.path.dirname(__file__), 'config.ini')
config.read(CONFIG_FILE)
ip = config.get('Host', 'ip')
port = config.get('Host', 'port')
url = 'https://' + ip + ':' + port + '/update'
# setup car info
vehicle_info = VehicleInfo()
VEHICLE_INFO_FILE = os.path.join(
os.path.dirname(__file__), 'vehicle_info.pb.txt')
try:
proto_utils.get_pb_from_text_file(VEHICLE_INFO_FILE, vehicle_info)
except IOError:
print("vehicle_info.pb.txt cannot be open file.")
exit()
brand = VehicleInfo.Brand.Name(vehicle_info.brand)
model = VehicleInfo.Model.Name(vehicle_info.model)
vin = vehicle_info.vehicle_config.vehicle_id.vin
car_info = {
"car_type": brand + "." + model,
"tag": sys.argv[1],
"vin": vin,
}
urllib3.disable_warnings()
CERT_FILE = os.path.join(os.path.dirname(__file__), 'ota.cert')
r = requests.post(url, json=car_info, verify=CERT_FILE)
if r.status_code == 200:
print("Update successfully.")
sys.exit(0)
elif r.status_code == 400:
print("Invalid Request.")
else:
print("Cannot connect to server.")
sys.exit(1)
if __name__ == "__main__":
update()
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/realtime_plot/xyitem.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
"""
X Y Item
"""
import math
import numpy as np
from matplotlib import lines
from matplotlib import patches
class Xyitem(object):
"""XY item to plot"""
def __init__(self, ax, windowsize, vehiclelength, title, xlabel, ylabel):
self.ax = ax
self.windowsize = windowsize
self.vehiclelength = vehiclelength
self.ax.set_title(title)
self.ax.set_xlabel(xlabel, fontsize=10)
self.ax.set_ylabel(ylabel, fontsize=10)
self.lines = []
self.pathstartx = []
self.pathstarty = []
self.carxhist = []
self.caryhist = []
self.targetx = []
self.targety = []
self.pathstartidx = -1
self.carxyhistidx = -1
self.carposidx = -1
self.targethistidx = -1
self.axx = float('inf')
self.axy = float('inf')
self.planningavailable = False
def reset(self):
"""Reset"""
del self.pathstartx[:]
del self.pathstarty[:]
del self.carxhist[:]
del self.caryhist[:]
del self.targetx[:]
del self.targety[:]
self.ax.cla()
self.pathstartidx = -1
self.carxyhistidx = -1
self.carposidx = -1
self.targethistidx = -1
self.axx = float('inf')
self.axy = float('inf')
self.planningavailable = False
def new_planning(self, time, x, y):
"""new planning"""
self.planningtime = time
self.planningx = x
self.planningy = y
self.pathstartx.append(x[0])
self.pathstarty.append(y[0])
if self.pathstartidx == -1:
self.ax.plot(
self.pathstartx,
self.pathstarty,
color='red',
marker='*',
ls='None')
self.pathstartidx = len(self.ax.lines) - 1
self.current_line = lines.Line2D(x, y, color='red', lw=1.5)
self.ax.add_line(self.current_line)
else:
self.ax.lines[self.pathstartidx].set_data(self.pathstartx,
self.pathstarty)
self.current_line.set_data(x, y)
self.planningavailable = True
def new_carstatus(self, time, x, y, heading, steer_angle, autodriving):
"""new carstatus"""
self.carxhist.append(x)
self.caryhist.append(y)
angle = math.degrees(heading) - 90
carcolor = 'red' if autodriving else 'blue'
if self.carxyhistidx == -1:
self.ax.plot(self.carxhist, self.caryhist, color="blue")
self.carxyhistidx = len(self.ax.lines) - 1
self.ax.plot(
self.carxhist,
self.caryhist,
marker=(3, 0, angle),
markersize=20,
mfc=carcolor)
self.carposidx = len(self.ax.lines) - 1
else:
self.ax.lines[self.carxyhistidx].set_data(self.carxhist,
self.caryhist)
self.ax.lines[self.carposidx].set_data(x, y)
self.ax.lines[self.carposidx].set_marker((3, 0, angle))
self.ax.lines[self.carposidx].set_mfc(carcolor)
self.ax.patches[0].remove()
if self.planningavailable:
xtarget = np.interp(time, self.planningtime, self.planningx)
self.targetx.append(xtarget)
ytarget = np.interp(time, self.planningtime, self.planningy)
self.targety.append(ytarget)
if self.targethistidx == -1:
self.ax.plot(self.targetx, self.targety, color="green", lw=1.5)
self.targethistidx = len(self.ax.lines) - 1
else:
self.ax.lines[self.targethistidx].set_data(
self.targetx, self.targety)
self.ax.add_patch(self.gen_steer_curve(x, y, heading, steer_angle))
# Update Window X, Y Axis Limits
xcenter = x + math.cos(heading) * 40
ycenter = y + math.sin(heading) * 40
if xcenter >= (self.axx + 20) or xcenter <= (self.axx - 20) or \
ycenter >= (self.axy + 20) or ycenter <= (self.axy - 20):
scale = self.ax.get_window_extent(
)._transform._boxout._bbox.get_points()[1]
original = self.ax.get_position().get_points()
finalscale = (original[1] - original[0]) * scale
ratio = finalscale[1] / finalscale[0]
self.axx = xcenter
self.axy = ycenter
self.ax.set_xlim(
[xcenter - self.windowsize, xcenter + self.windowsize])
self.ax.set_ylim([
ycenter - self.windowsize * ratio,
ycenter + self.windowsize * ratio
])
def gen_steer_curve(self, x, y, heading, steer_angle):
"""Generate Steering Curve to predict car trajectory"""
if abs(math.tan(math.radians(steer_angle))) > 0.0001:
R = self.vehiclelength / math.tan(math.radians(steer_angle))
else:
R = 100000
radius = abs(R)
lengthangle = 7200 / (2 * math.pi * radius)
if R >= 0:
centerangle = math.pi / 2 + heading
startangle = math.degrees(heading - math.pi / 2)
theta1 = 0
theta2 = lengthangle
else:
centerangle = heading - math.pi / 2
startangle = math.degrees(math.pi / 2 + heading)
theta1 = -lengthangle
theta2 = 0
centerx = x + math.cos(centerangle) * radius
centery = y + math.sin(centerangle) * radius
curve = patches.Arc(
(centerx, centery),
2 * radius,
2 * radius,
angle=startangle,
theta1=theta1,
theta2=theta2,
linewidth=2,
zorder=2)
return curve
def draw_lines(self):
"""plot lines"""
for polygon in self.ax.patches:
self.ax.draw_artist(polygon)
for line in self.ax.lines:
self.ax.draw_artist(line)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/realtime_plot/realtime_plot.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
"""Real Time Plotting of planning and control"""
import math
import sys
import threading
import gflags
import matplotlib.pyplot as plt
import numpy as np
from cyber.python.cyber_py3 import cyber
from modules.tools.realtime_plot.item import Item
from modules.common_msgs.chassis_msgs.chassis_pb2 import Chassis
from modules.common_msgs.localization_msgs.localization_pb2 import LocalizationEstimate
from modules.common_msgs.planning_msgs.planning_pb2 import ADCTrajectory
from modules.tools.realtime_plot.stitem import Stitem
from modules.tools.realtime_plot.xyitem import Xyitem
import modules.tools.common.proto_utils as proto_utils
VehicleLength = 2.85
HistLine2display = 2 # The number of lines to display
MaxSteerAngle = 470 # Maximum Steering Angle
SteerRatio = 16
WindowSize = 80
FLAGS = gflags.FLAGS
gflags.DEFINE_boolean('show_heading', False,
'Show heading instead of acceleration')
gflags.DEFINE_boolean('show_st_graph', False, 'Show st graph')
class Plotter(object):
"""Plotter Class"""
def __init__(self, ax1, ax2, ax3, ax4, stgraph):
self.ax = [ax1, ax2, ax3, ax4]
self.updategraph = False
self.planningavailable = False
self.closed = False
self.carspeed = 0.0
self.steer_angle = 0.0
self.autodrive = False
self.carcurvature = 0.0
self.stgraph = stgraph
self.lock = threading.Lock()
def callback_planning(self, data):
"""New Planning Trajectory"""
if self.stgraph:
st_s, st_t, polygons_s, polygons_t = proto_utils.flatten(
data.debug.planning_data.st_graph,
['speed_profile.s',
'speed_profile.t',
'boundary.point.s',
'boundary.point.t'])
with self.lock:
for i in range(len(st_s)):
self.ax[i].new_planning(st_t[i], st_s[i],
polygons_t[i], polygons_s[i])
else:
if len(data.trajectory_point) == 0:
print(data)
return
x, y, speed, theta, kappa, acc, relative_time = np.array(
proto_utils.flatten(data.trajectory_point,
['path_point.x',
'path_point.y',
'v',
'path_point.theta',
'path_point.kappa',
'a',
'relative_time']))
relative_time += data.header.timestamp_sec
with self.lock:
self.ax[0].new_planning(relative_time, x, y)
self.ax[1].new_planning(relative_time, speed)
if self.ax[2].title == "Curvature":
self.ax[2].new_planning(relative_time, kappa)
if self.ax[3].title == "Heading":
self.ax[3].new_planning(relative_time, theta)
else:
self.ax[3].new_planning(relative_time, acc)
def callback_chassis(self, data):
"""New localization pose"""
if self.stgraph:
return
self.carspeed = data.speed_mps
self.steer_angle = \
data.steering_percentage / 100 * MaxSteerAngle / SteerRatio
self.autodrive = (data.driving_mode == Chassis.COMPLETE_AUTO_DRIVE)
self.carcurvature = math.tan(
math.radians(self.steer_angle)) / VehicleLength
def callback_localization(self, data):
"""New localization pose"""
if self.stgraph:
return
carheading = data.pose.heading
carx = data.pose.position.x
cary = data.pose.position.y
cartime = data.header.timestamp_sec
with self.lock:
self.ax[0].new_carstatus(cartime, carx, cary, carheading,
self.steer_angle, self.autodrive)
self.ax[1].new_carstatus(cartime, self.carspeed, self.autodrive)
self.ax[2].new_carstatus(
cartime, self.carcurvature, self.autodrive)
if self.ax[3].title == "Heading":
self.ax[3].new_carstatus(cartime, carheading, self.autodrive)
else:
acc = data.pose.linear_acceleration_vrf.y
self.ax[3].new_carstatus(cartime, acc, self.autodrive)
def press(self, event):
"""Keyboard events during plotting"""
if event.key == 'q' or event.key == 'Q':
plt.close('all')
self.closed = True
if event.key == 'x' or event.key == 'X':
self.updategraph = True
if event.key == 'a' or event.key == 'A':
fig = plt.gcf()
fig.gca().autoscale()
fig.canvas.draw()
if event.key == 'n' or event.key == 'N':
with self.lock:
for ax in self.ax:
ax.reset()
self.updategraph = True
def main(argv):
"""Main function"""
argv = FLAGS(argv)
print("""
Keyboard Shortcut:
[q]: Quit Tool
[s]: Save Figure
[a]: Auto-adjust x, y axis to display entire plot
[x]: Update Figure to Display last few Planning Trajectory instead of all
[h][r]: Go back Home, Display all Planning Trajectory
[f]: Toggle Full Screen
[n]: Reset all Plots
[b]: Unsubscribe Topics
Legend Description:
Red Line: Current Planning Trajectory
Blue Line: Past Car Status History
Green Line: Past Planning Target History at every Car Status Frame
Cyan Dashed Line: Past Planning Trajectory Frames
""")
cyber.init()
planning_sub = cyber.Node("stat_planning")
fig = plt.figure()
if not FLAGS.show_st_graph:
ax1 = plt.subplot(2, 2, 1)
item1 = Xyitem(ax1, WindowSize, VehicleLength, "Trajectory", "X [m]",
"Y [m]")
ax2 = plt.subplot(2, 2, 2)
item2 = Item(ax2, "Speed", "Time [sec]", "Speed [m/s]", 0, 30)
ax3 = plt.subplot(2, 2, 3, sharex=ax2)
item3 = Item(ax3, "Curvature", "Time [sec]", "Curvature [m-1]", -0.2,
0.2)
ax4 = plt.subplot(2, 2, 4, sharex=ax2)
if not FLAGS.show_heading:
item4 = Item(ax4, "Acceleration", "Time [sec]",
"Acceleration [m/sec^2]", -5, 5)
else:
item4 = Item(ax4, "Heading", "Time [sec]", "Heading [radian]", -4,
4)
else:
ax1 = plt.subplot(2, 2, 1)
item1 = Stitem(ax1, "ST Graph", "Time [sec]", "S [m]")
ax2 = plt.subplot(2, 2, 2)
item2 = Stitem(ax2, "ST Graph", "Time [sec]", "S [m]")
ax3 = plt.subplot(2, 2, 3)
item3 = Stitem(ax3, "ST Graph", "Time [sec]", "S [m]")
ax4 = plt.subplot(2, 2, 4)
item4 = Stitem(ax4, "ST Graph", "Time [sec]", "S [m]")
plt.tight_layout(pad=0.20)
plt.ion()
plt.show()
plotter = Plotter(item1, item2, item3, item4, FLAGS.show_st_graph)
fig.canvas.mpl_connect('key_press_event', plotter.press)
planning_sub.create_reader('/apollo/planning',
ADCTrajectory, plotter.callback_planning)
if not FLAGS.show_st_graph:
localization_sub = cyber.Node("localization_sub")
localization_sub.create_reader('/apollo/localization/pose',
LocalizationEstimate, plotter.callback_localization)
chassis_sub = cyber.Node("chassis_sub")
chassis_sub.create_reader('/apollo/canbus/chassis',
Chassis, plotter.callback_chassis)
while not cyber.is_shutdown():
ax1.draw_artist(ax1.patch)
ax2.draw_artist(ax2.patch)
ax3.draw_artist(ax3.patch)
ax4.draw_artist(ax4.patch)
with plotter.lock:
item1.draw_lines()
item2.draw_lines()
item3.draw_lines()
item4.draw_lines()
fig.canvas.blit(ax1.bbox)
fig.canvas.blit(ax2.bbox)
fig.canvas.blit(ax3.bbox)
fig.canvas.blit(ax4.bbox)
fig.canvas.flush_events()
if __name__ == '__main__':
main(sys.argv)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/realtime_plot/BUILD
|
load("@rules_python//python:defs.bzl", "py_binary", "py_library")
load("//tools/install:install.bzl", "install")
package(default_visibility = ["//visibility:public"])
py_library(
name = "item",
srcs = ["item.py"],
)
py_binary(
name = "realtime_plot",
srcs = ["realtime_plot.py"],
deps = [
":item",
":stitem",
":xyitem",
"//cyber/python/cyber_py3:cyber",
"//modules/common_msgs/chassis_msgs:chassis_py_pb2",
"//modules/common_msgs/localization_msgs:localization_py_pb2",
"//modules/common_msgs/planning_msgs:planning_py_pb2",
"//modules/tools/common:proto_utils",
],
)
py_library(
name = "stitem",
srcs = ["stitem.py"],
)
py_library(
name = "xyitem",
srcs = ["xyitem.py"],
)
install(
name = "install",
py_dest = "tools/realtime_plot",
targets = [
":realtime_plot",
]
)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/realtime_plot/stitem.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
"""S T Item"""
import numpy as np
from matplotlib import lines
from matplotlib.patches import Polygon
class Stitem(object):
"""Specific item to plot"""
def __init__(self, ax, title, xlabel, ylabel):
self.ax = ax
self.title = title
self.ax.set_title(title)
self.ax.set_xlabel(xlabel, fontsize=10)
self.ax.set_ylabel(ylabel, fontsize=10)
self.planningavailable = False
def reset(self):
"""Reset"""
self.ax.cla()
self.ax.set_xlim([-0.1, 0.1])
self.ax.set_ylim([-0.1, 0.1])
def new_planning(self, time, values, polygons_t, polygons_s):
"""new planning"""
max_time = max(time) + 1
max_value = max(values) + 1
if self.planningavailable == False:
self.ax.set_xlim([0, max_time])
self.ax.set_ylim([0, max_value])
self.ymax = max_value
self.tmax = max_time
self.current_line = lines.Line2D(time, values, color='red', lw=1.5)
self.ax.add_line(self.current_line)
else:
self.current_line.set_data(time, values)
_, xmax = self.ax.get_xlim()
if max_time > xmax:
self.ax.set_xlim([0, max_time])
_, ymax = self.ax.get_ylim()
if max_value > ymax:
self.ax.set_ylim([0, max_value])
self.ax.patches = []
for i in range(len(polygons_s)):
points = np.vstack((polygons_t[i], polygons_s[i])).T
polygon = Polygon(points)
self.ax.add_patch(polygon)
self.planningavailable = True
def draw_lines(self):
"""plot lines"""
for polygon in self.ax.patches:
self.ax.draw_artist(polygon)
for line in self.ax.lines:
self.ax.draw_artist(line)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/realtime_plot/item.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
"""
Time Value Item
"""
import numpy
from matplotlib import lines
class Item(object):
"""
Specific item to plot
"""
def __init__(self, ax, title, xlabel, ylabel, ymin, ymax):
self.ax = ax
self.title = title
self.ax.set_title(title)
self.ax.set_xlabel(xlabel, fontsize=10)
self.ax.set_ylabel(ylabel, fontsize=10)
self.ymin = ymin
self.ymax = ymax
self.ax.set_ylim([ymin, ymax])
self.lines = []
self.cartimehist = []
self.carvaluehist = []
self.targettime = []
self.targethist = []
self.targethistidx = -1
self.histidx = -1
self.prev_auto = False
self.planningavailable = False
def reset(self):
"""
Reset
"""
del self.lines[:]
del self.cartimehist[:]
del self.carvaluehist[:]
del self.targettime[:]
del self.targethist[:]
self.ax.cla()
self.ax.set_ylim([self.ymin, self.ymax])
self.targethistidx = -1
self.histidx = -1
self.prev_auto = False
self.planningavailable = False
def new_planning(self, time, values):
"""
new planning
"""
self.planningtime = time
self.planningvalues = values
if self.planningavailable == False:
self.ax.set_xlim([time[0] - 1, time[-1] + 10])
self.current_line = lines.Line2D(time, values, color='red', lw=1.5)
self.ax.add_line(self.current_line)
else:
self.current_line.set_data(time, values)
xmin, xmax = self.ax.get_xlim()
if (time[-1] >= (xmax - 1)):
self.ax.set_xlim([time[0] - 1, time[-1] + 10])
self.planningavailable = True
def new_carstatus(self, time, value, autodriving):
"""
new carstatus
"""
if autodriving and not self.prev_auto:
self.starttime = time
self.endtime = time + 50
self.ax.axvspan(self.starttime, self.endtime, fc='0.1', alpha=0.3)
elif autodriving and time >= (self.endtime - 20):
self.endtime = time + 50
self.ax.patches[-1].remove()
self.ax.axvspan(self.starttime, self.endtime, fc='0.1', alpha=0.3)
elif not autodriving and self.prev_auto:
self.endtime = time
self.ax.patches[-1].remove()
self.ax.axvspan(self.starttime, self.endtime, fc='0.1', alpha=0.3)
self.prev_auto = autodriving
self.cartimehist.append(time)
self.carvaluehist.append(value)
if self.planningavailable:
target = numpy.interp(time, self.planningtime, self.planningvalues)
self.targettime.append(time)
self.targethist.append(target)
if self.targethistidx == -1:
self.ax.plot(
self.targettime, self.targethist, color='green', lw=1.5)
self.targethistidx = len(self.ax.lines) - 1
else:
self.ax.lines[self.targethistidx].set_data(
self.targettime, self.targethist)
if self.histidx == -1:
self.ax.plot(self.cartimehist, self.carvaluehist, color='blue')
self.histidx = len(self.ax.lines) - 1
else:
self.ax.lines[self.histidx].set_data(self.cartimehist,
self.carvaluehist)
def draw_lines(self):
"""
plot lines
"""
for polygon in self.ax.patches:
self.ax.draw_artist(polygon)
for line in self.ax.lines:
self.ax.draw_artist(line)
| 0
|
apollo_public_repos/apollo/modules/tools
|
apollo_public_repos/apollo/modules/tools/replay/replay_file.py
|
#!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
#
# Licensed 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.
###############################################################################
"""
This program can replay a message pb file
"""
import os.path
import sys
import argparse
import glob
import time
from google.protobuf import text_format
from cyber.python.cyber_py3 import cyber
import modules.tools.common.proto_utils as proto_utils
from modules.tools.common.message_manager import PbMessageManager
g_message_manager = PbMessageManager()
def topic_publisher(topic, filename, period):
"""publisher"""
cyber.init()
node = cyber.Node("replay_file")
meta_msg = None
msg = None
if not topic:
print("Topic not specified, start to guess")
meta_msg, msg = g_message_manager.parse_file(filename)
topic = meta_msg.topic()
else:
meta_msg = g_message_manager.get_msg_meta_by_topic(topic)
if not meta_msg:
print("Failed to find meta info for topic: %s" % (topic))
return False
msg = meta_msg.parse_file(filename)
if not msg:
print("Failed to parse file[%s] with topic[%s]" % (filename,
topic))
return False
if not msg or not meta_msg:
print("Unknown topic: %s" % topic)
return False
writer = node.create_writer(topic, meta_msg.msg_type)
if period == 0:
while not cyber.is_shutdown():
input("Press any key to publish one message...")
writer.write(msg)
print("Topic[%s] message published" % topic)
else:
print("started to publish topic[%s] message with rate period %s" %
(topic, period))
while not cyber.is_shutdown():
writer.write(msg)
time.sleep(period)
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description="replay a planning result pb file")
parser.add_argument(
"filename", action="store", type=str, help="planning result files")
parser.add_argument(
"--topic", action="store", type=str, help="set the planning topic")
parser.add_argument(
"--period",
action="store",
type=float,
default=0.1,
help="set the topic publish time duration")
args = parser.parse_args()
period = 0.0 # use step by step mode
if args.period: # play with a given period, (1.0 / frequency)
period = args.period
to_replay = args.filename
files = []
if os.path.isdir(args.filename):
files = glob.glob(args.filename + "/*")
i = 0
for f in files:
print("%d %s" % (i, f))
i += 1
str_input = input("Select message by number: ")
try:
selected_file = int(str_input)
if selected_file < 0 or selected_file > len(files):
print("%d is an invalid number" % selected_file)
except:
print("%s is not a number" % str_input)
print("Will publish file[%d]: %s" % (selected_file,
files[selected_file]))
to_replay = files[selected_file]
topic_publisher(args.topic, to_replay, period)
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.