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/canbus_vehicle/gem
|
apollo_public_repos/apollo/modules/canbus_vehicle/gem/protocol/date_time_rpt_83.h
|
/******************************************************************************
* 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.
*****************************************************************************/
#pragma once
#include "modules/canbus_vehicle/gem/proto/gem.pb.h"
#include "modules/drivers/canbus/can_comm/protocol_data.h"
namespace apollo {
namespace canbus {
namespace gem {
class Datetimerpt83 : public ::apollo::drivers::canbus::ProtocolData<
::apollo::canbus::Gem> {
public:
static const int32_t ID;
Datetimerpt83();
void Parse(const std::uint8_t* bytes, int32_t length,
Gem* chassis) const override;
private:
// config detail: {'name': 'TIME_SECOND', 'offset': 0.0, 'precision': 1.0,
// 'len': 8, 'is_signed_var': False, 'physical_range': '[0|60]', 'bit': 47,
// 'type': 'int', 'order': 'motorola', 'physical_unit': 'sec'}
int time_second(const std::uint8_t* bytes, const int32_t length) const;
// config detail: {'name': 'TIME_MINUTE', 'offset': 0.0, 'precision': 1.0,
// 'len': 8, 'is_signed_var': False, 'physical_range': '[0|60]', 'bit': 39,
// 'type': 'int', 'order': 'motorola', 'physical_unit': 'min'}
int time_minute(const std::uint8_t* bytes, const int32_t length) const;
// config detail: {'name': 'TIME_HOUR', 'offset': 0.0, 'precision': 1.0,
// 'len': 8, 'is_signed_var': False, 'physical_range': '[0|23]', 'bit': 31,
// 'type': 'int', 'order': 'motorola', 'physical_unit': 'hr'}
int time_hour(const std::uint8_t* bytes, const int32_t length) const;
// config detail: {'name': 'DATE_DAY', 'offset': 1.0, 'precision': 1.0, 'len':
// 8, 'is_signed_var': False, 'physical_range': '[1|31]', 'bit': 23, 'type':
// 'int', 'order': 'motorola', 'physical_unit': 'dy'}
int date_day(const std::uint8_t* bytes, const int32_t length) const;
// config detail: {'name': 'DATE_MONTH', 'offset': 1.0, 'precision': 1.0,
// 'len': 8, 'is_signed_var': False, 'physical_range': '[1|12]', 'bit': 15,
// 'type': 'int', 'order': 'motorola', 'physical_unit': 'mon'}
int date_month(const std::uint8_t* bytes, const int32_t length) const;
// config detail: {'name': 'DATE_YEAR', 'offset': 2000.0, 'precision': 1.0,
// 'len': 8, 'is_signed_var': False, 'physical_range': '[2000|2255]', 'bit':
// 7, 'type': 'int', 'order': 'motorola', 'physical_unit': 'yr'}
int date_year(const std::uint8_t* bytes, const int32_t length) const;
};
} // namespace gem
} // namespace canbus
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/canbus_vehicle/gem
|
apollo_public_repos/apollo/modules/canbus_vehicle/gem/protocol/accel_cmd_67.cc
|
/******************************************************************************
* 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.
*****************************************************************************/
#include "modules/canbus_vehicle/gem/protocol/accel_cmd_67.h"
#include "modules/drivers/canbus/common/byte.h"
namespace apollo {
namespace canbus {
namespace gem {
using ::apollo::drivers::canbus::Byte;
const int32_t Accelcmd67::ID = 0x67;
// public
Accelcmd67::Accelcmd67() { Reset(); }
uint32_t Accelcmd67::GetPeriod() const {
// TODO(QiL) :modify every protocol's period manually
static const uint32_t PERIOD = 20 * 1000;
return PERIOD;
}
void Accelcmd67::UpdateData(uint8_t* data) {
set_p_accel_cmd(data, accel_cmd_);
}
void Accelcmd67::Reset() {
// TODO(QiL) :you should check this manually
accel_cmd_ = 0.0;
}
Accelcmd67* Accelcmd67::set_accel_cmd(double accel_cmd) {
accel_cmd_ = accel_cmd;
return this;
}
// config detail: {'name': 'ACCEL_CMD', 'offset': 0.0, 'precision': 0.001,
// 'len': 16, 'is_signed_var': False, 'physical_range': '[0|1]', 'bit': 7,
// 'type': 'double', 'order': 'motorola', 'physical_unit': '%'}
void Accelcmd67::set_p_accel_cmd(uint8_t* data, double accel_cmd) {
accel_cmd = ProtocolData::BoundedValue(0.0, 1.0, accel_cmd);
int x = static_cast<int>(accel_cmd / 0.001000);
uint8_t t = 0;
t = static_cast<uint8_t>(x & 0xFF);
Byte to_set0(data + 1);
to_set0.set_value(t, 0, 8);
x >>= 8;
t = static_cast<uint8_t>(x & 0xFF);
Byte to_set1(data + 0);
to_set1.set_value(t, 0, 8);
}
} // namespace gem
} // namespace canbus
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/canbus_vehicle/gem
|
apollo_public_repos/apollo/modules/canbus_vehicle/gem/protocol/headlight_cmd_76.cc
|
/******************************************************************************
* 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.
*****************************************************************************/
#include "modules/canbus_vehicle/gem/protocol/headlight_cmd_76.h"
#include "modules/drivers/canbus/common/byte.h"
namespace apollo {
namespace canbus {
namespace gem {
using ::apollo::drivers::canbus::Byte;
const int32_t Headlightcmd76::ID = 0x76;
// public
Headlightcmd76::Headlightcmd76() { Reset(); }
uint32_t Headlightcmd76::GetPeriod() const {
// TODO(QiL) :modify every protocol's period manually
static const uint32_t PERIOD = 20 * 1000;
return PERIOD;
}
void Headlightcmd76::UpdateData(uint8_t* data) {
set_p_headlight_cmd(data, headlight_cmd_);
}
void Headlightcmd76::Reset() {
// TODO(QiL) :you should check this manually
headlight_cmd_ = Headlight_cmd_76::HEADLIGHT_CMD_HEADLIGHTS_OFF;
}
Headlightcmd76* Headlightcmd76::set_headlight_cmd(
Headlight_cmd_76::Headlight_cmdType headlight_cmd) {
headlight_cmd_ = headlight_cmd;
return this;
}
// config detail: {'name': 'HEADLIGHT_CMD', 'enum': {0:
// 'HEADLIGHT_CMD_HEADLIGHTS_OFF', 1: 'HEADLIGHT_CMD_LOW_BEAMS', 2:
// 'HEADLIGHT_CMD_HIGH_BEAMS'}, 'precision': 1.0, 'len': 8, 'is_signed_var':
// False, 'offset': 0.0, 'physical_range': '[0|2]', 'bit': 7, 'type': 'enum',
// 'order': 'motorola', 'physical_unit': ''}
void Headlightcmd76::set_p_headlight_cmd(
uint8_t* data, Headlight_cmd_76::Headlight_cmdType headlight_cmd) {
uint8_t x = headlight_cmd;
Byte to_set(data + 0);
to_set.set_value(static_cast<uint8_t>(x), 0, 8);
}
} // namespace gem
} // namespace canbus
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/canbus_vehicle/gem
|
apollo_public_repos/apollo/modules/canbus_vehicle/gem/protocol/BUILD
|
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test")
load("//tools:cpplint.bzl", "cpplint")
package(default_visibility = ["//visibility:public"])
CANBUS_COPTS = ["-DMODULE_NAME=\\\"canbus\\\""]
cc_library(
name = "canbus_gem_protocol",
srcs = [
"accel_cmd_67.cc",
"accel_rpt_68.cc",
"brake_cmd_6b.cc",
"brake_motor_rpt_1_70.cc",
"brake_motor_rpt_2_71.cc",
"brake_motor_rpt_3_72.cc",
"brake_rpt_6c.cc",
"date_time_rpt_83.cc",
"global_cmd_69.cc",
"global_rpt_6a.cc",
"headlight_cmd_76.cc",
"headlight_rpt_77.cc",
"horn_cmd_78.cc",
"horn_rpt_79.cc",
"lat_lon_heading_rpt_82.cc",
"parking_brake_status_rpt_80.cc",
"shift_cmd_65.cc",
"shift_rpt_66.cc",
"steering_cmd_6d.cc",
"steering_motor_rpt_1_73.cc",
"steering_motor_rpt_2_74.cc",
"steering_motor_rpt_3_75.cc",
"steering_rpt_1_6e.cc",
"turn_cmd_63.cc",
"turn_rpt_64.cc",
"vehicle_speed_rpt_6f.cc",
"wheel_speed_rpt_7a.cc",
"wiper_cmd_90.cc",
"wiper_rpt_91.cc",
"yaw_rate_rpt_81.cc",
],
hdrs = [
"accel_cmd_67.h",
"accel_rpt_68.h",
"brake_cmd_6b.h",
"brake_motor_rpt_1_70.h",
"brake_motor_rpt_2_71.h",
"brake_motor_rpt_3_72.h",
"brake_rpt_6c.h",
"date_time_rpt_83.h",
"global_cmd_69.h",
"global_rpt_6a.h",
"headlight_cmd_76.h",
"headlight_rpt_77.h",
"horn_cmd_78.h",
"horn_rpt_79.h",
"lat_lon_heading_rpt_82.h",
"parking_brake_status_rpt_80.h",
"shift_cmd_65.h",
"shift_rpt_66.h",
"steering_cmd_6d.h",
"steering_motor_rpt_1_73.h",
"steering_motor_rpt_2_74.h",
"steering_motor_rpt_3_75.h",
"steering_rpt_1_6e.h",
"turn_cmd_63.h",
"turn_rpt_64.h",
"vehicle_speed_rpt_6f.h",
"wheel_speed_rpt_7a.h",
"wiper_cmd_90.h",
"wiper_rpt_91.h",
"yaw_rate_rpt_81.h",
],
copts = CANBUS_COPTS,
deps = [
"//modules/canbus_vehicle/gem/proto:gem_cc_proto",
"//modules/drivers/canbus/can_comm:message_manager_base",
"//modules/drivers/canbus/common:canbus_common",
],
)
cc_test(
name = "accel_rpt_68_test",
size = "small",
srcs = ["accel_rpt_68_test.cc"],
deps = [
"//modules/canbus_vehicle/gem/protocol:canbus_gem_protocol",
"@com_google_googletest//:gtest_main",
],
linkstatic = True,
)
cc_test(
name = "brake_rpt_6c_test",
size = "small",
srcs = ["brake_rpt_6c_test.cc"],
deps = [
"//modules/canbus_vehicle/gem/protocol:canbus_gem_protocol",
"@com_google_googletest//:gtest_main",
],
linkstatic = True,
)
cc_test(
name = "wheel_speed_rpt_7a_test",
size = "small",
srcs = ["wheel_speed_rpt_7a_test.cc"],
deps = [
"//modules/canbus_vehicle/gem/protocol:canbus_gem_protocol",
"@com_google_googletest//:gtest_main",
],
)
cc_test(
name = "yaw_rate_rpt_81_test",
size = "small",
srcs = ["yaw_rate_rpt_81_test.cc"],
deps = [
"//modules/canbus_vehicle/gem/protocol:canbus_gem_protocol",
"@com_google_googletest//:gtest_main",
],
)
cc_test(
name = "wiper_rpt_91_test",
size = "small",
srcs = ["wiper_rpt_91_test.cc"],
deps = [
"//modules/canbus_vehicle/gem/protocol:canbus_gem_protocol",
"@com_google_googletest//:gtest_main",
],
linkstatic = True,
)
cc_test(
name = "brake_motor_rpt_1_70_test",
size = "small",
srcs = ["brake_motor_rpt_1_70_test.cc"],
deps = [
"//modules/canbus_vehicle/gem/protocol:canbus_gem_protocol",
"@com_google_googletest//:gtest_main",
],
)
cc_test(
name = "brake_motor_rpt_2_71_test",
size = "small",
srcs = ["brake_motor_rpt_2_71_test.cc"],
deps = [
"//modules/canbus_vehicle/gem/protocol:canbus_gem_protocol",
"@com_google_googletest//:gtest_main",
],
)
cc_test(
name = "brake_motor_rpt_3_72_test",
size = "small",
srcs = ["brake_motor_rpt_3_72_test.cc"],
deps = [
"//modules/canbus_vehicle/gem/protocol:canbus_gem_protocol",
"@com_google_googletest//:gtest_main",
],
)
cc_test(
name = "date_time_rpt_83_test",
size = "small",
srcs = ["date_time_rpt_83_test.cc"],
deps = [
"//modules/canbus_vehicle/gem/protocol:canbus_gem_protocol",
"@com_google_googletest//:gtest_main",
],
)
cc_test(
name = "global_rpt_6a_test",
size = "small",
srcs = ["global_rpt_6a_test.cc"],
deps = [
"//modules/canbus_vehicle/gem/protocol:canbus_gem_protocol",
"@com_google_googletest//:gtest_main",
],
linkstatic = True,
)
cc_test(
name = "lat_lon_heading_rpt_82_test",
size = "small",
srcs = ["lat_lon_heading_rpt_82_test.cc"],
deps = [
"//modules/canbus_vehicle/gem/protocol:canbus_gem_protocol",
"@com_google_googletest//:gtest_main",
],
linkstatic = True,
)
cc_test(
name = "steering_motor_rpt_1_73_test",
size = "small",
srcs = ["steering_motor_rpt_1_73_test.cc"],
deps = [
"//modules/canbus_vehicle/gem/protocol:canbus_gem_protocol",
"@com_google_googletest//:gtest_main",
],
linkstatic = True,
)
cc_test(
name = "steering_motor_rpt_2_74_test",
size = "small",
srcs = ["steering_motor_rpt_2_74_test.cc"],
deps = [
"//modules/canbus_vehicle/gem/protocol:canbus_gem_protocol",
"@com_google_googletest//:gtest_main",
],
linkstatic = True,
)
cc_test(
name = "steering_motor_rpt_3_75_test",
size = "small",
srcs = ["steering_motor_rpt_3_75_test.cc"],
deps = [
"//modules/canbus_vehicle/gem/protocol:canbus_gem_protocol",
"@com_google_googletest//:gtest_main",
],
linkstatic = True,
)
cc_test(
name = "steering_rpt_1_6e_test",
size = "small",
srcs = ["steering_rpt_1_6e_test.cc"],
deps = [
"//modules/canbus_vehicle/gem/protocol:canbus_gem_protocol",
"@com_google_googletest//:gtest_main",
],
linkstatic = True,
)
cc_test(
name = "accel_cmd_67_test",
size = "small",
srcs = ["accel_cmd_67_test.cc"],
deps = [
"//modules/canbus_vehicle/gem/protocol:canbus_gem_protocol",
"@com_google_googletest//:gtest_main",
],
linkstatic = True,
)
cpplint()
| 0
|
apollo_public_repos/apollo/modules/canbus_vehicle/gem
|
apollo_public_repos/apollo/modules/canbus_vehicle/gem/protocol/brake_motor_rpt_2_71.cc
|
/******************************************************************************
* 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.
*****************************************************************************/
#include "modules/canbus_vehicle/gem/protocol/brake_motor_rpt_2_71.h"
#include "glog/logging.h"
#include "modules/drivers/canbus/common/byte.h"
#include "modules/drivers/canbus/common/canbus_consts.h"
namespace apollo {
namespace canbus {
namespace gem {
using ::apollo::drivers::canbus::Byte;
Brakemotorrpt271::Brakemotorrpt271() {}
const int32_t Brakemotorrpt271::ID = 0x71;
void Brakemotorrpt271::Parse(const std::uint8_t* bytes, int32_t length,
Gem* chassis) const {
chassis->mutable_brake_motor_rpt_2_71()->set_encoder_temperature(
encoder_temperature(bytes, length));
chassis->mutable_brake_motor_rpt_2_71()->set_motor_temperature(
motor_temperature(bytes, length));
chassis->mutable_brake_motor_rpt_2_71()->set_angular_speed(
angular_speed(bytes, length));
}
// config detail: {'name': 'encoder_temperature', 'offset': -40.0,
// 'precision': 1.0, 'len': 16, 'is_signed_var': True, 'physical_range':
// '[-32808|32727]', 'bit': 7, 'type': 'int', 'order': 'motorola',
// 'physical_unit': 'deg C'}
int Brakemotorrpt271::encoder_temperature(const std::uint8_t* bytes,
int32_t length) const {
Byte t0(bytes + 0);
int32_t x = t0.get_byte(0, 8);
Byte t1(bytes + 1);
int32_t t = t1.get_byte(0, 8);
x <<= 8;
x |= t;
x <<= 16;
x >>= 16;
int ret = x + -40;
return ret;
}
// config detail: {'name': 'motor_temperature', 'offset': -40.0,
// 'precision': 1.0, 'len': 16, 'is_signed_var': True, 'physical_range':
// '[-32808|32727]', 'bit': 23, 'type': 'int', 'order': 'motorola',
// 'physical_unit': 'deg C'}
int Brakemotorrpt271::motor_temperature(const std::uint8_t* bytes,
int32_t length) const {
Byte t0(bytes + 2);
int32_t x = t0.get_byte(0, 8);
Byte t1(bytes + 3);
int32_t t = t1.get_byte(0, 8);
x <<= 8;
x |= t;
x <<= 16;
x >>= 16;
int ret = x + -40;
return ret;
}
// config detail: {'name': 'angular_speed', 'offset': 0.0, 'precision': 0.001,
// 'len': 32, 'is_signed_var': False, 'physical_range': '[0|4294967.295]',
// 'bit': 39, 'type': 'double', 'order': 'motorola', 'physical_unit': 'rev/s'}
double Brakemotorrpt271::angular_speed(const std::uint8_t* bytes,
int32_t length) const {
Byte t0(bytes + 4);
int32_t x = t0.get_byte(0, 8);
Byte t1(bytes + 5);
int32_t t = t1.get_byte(0, 8);
x <<= 8;
x |= t;
Byte t2(bytes + 6);
t = t2.get_byte(0, 8);
x <<= 8;
x |= t;
Byte t3(bytes + 7);
t = t3.get_byte(0, 8);
x <<= 8;
x |= t;
double ret = x * 0.001000;
return ret;
}
} // namespace gem
} // namespace canbus
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/canbus_vehicle/gem
|
apollo_public_repos/apollo/modules/canbus_vehicle/gem/protocol/steering_motor_rpt_3_75.cc
|
/******************************************************************************
* 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.
*****************************************************************************/
#include "modules/canbus_vehicle/gem/protocol/steering_motor_rpt_3_75.h"
#include "glog/logging.h"
#include "modules/drivers/canbus/common/byte.h"
#include "modules/drivers/canbus/common/canbus_consts.h"
namespace apollo {
namespace canbus {
namespace gem {
using ::apollo::drivers::canbus::Byte;
Steeringmotorrpt375::Steeringmotorrpt375() {}
const int32_t Steeringmotorrpt375::ID = 0x75;
void Steeringmotorrpt375::Parse(const std::uint8_t* bytes, int32_t length,
Gem* chassis) const {
chassis->mutable_steering_motor_rpt_3_75()->set_torque_output(
torque_output(bytes, length));
chassis->mutable_steering_motor_rpt_3_75()->set_torque_input(
torque_input(bytes, length));
}
// config detail: {'name': 'torque_output', 'offset': 0.0, 'precision': 0.001,
// 'len': 32, 'is_signed_var': True, 'physical_range':
// '[-2147483.648|2147483.647]', 'bit': 7, 'type': 'double', 'order':
// 'motorola', 'physical_unit': 'N-m'}
double Steeringmotorrpt375::torque_output(const std::uint8_t* bytes,
int32_t length) const {
Byte t0(bytes + 0);
int32_t x = t0.get_byte(0, 8);
Byte t1(bytes + 1);
int32_t t = t1.get_byte(0, 8);
x <<= 8;
x |= t;
Byte t2(bytes + 2);
t = t2.get_byte(0, 8);
x <<= 8;
x |= t;
Byte t3(bytes + 3);
t = t3.get_byte(0, 8);
x <<= 8;
x |= t;
x <<= 0;
x >>= 0;
double ret = x * 0.001000;
return ret;
}
// config detail: {'name': 'torque_input', 'offset': 0.0, 'precision': 0.001,
// 'len': 32, 'is_signed_var': True, 'physical_range':
// '[-2147483.648|2147483.647]', 'bit': 39, 'type': 'double', 'order':
// 'motorola', 'physical_unit': 'N-m'}
double Steeringmotorrpt375::torque_input(const std::uint8_t* bytes,
int32_t length) const {
Byte t0(bytes + 4);
int32_t x = t0.get_byte(0, 8);
Byte t1(bytes + 5);
int32_t t = t1.get_byte(0, 8);
x <<= 8;
x |= t;
Byte t2(bytes + 6);
t = t2.get_byte(0, 8);
x <<= 8;
x |= t;
Byte t3(bytes + 7);
t = t3.get_byte(0, 8);
x <<= 8;
x |= t;
x <<= 0;
x >>= 0;
double ret = x * 0.001000;
return ret;
}
} // namespace gem
} // namespace canbus
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/canbus_vehicle/gem
|
apollo_public_repos/apollo/modules/canbus_vehicle/gem/protocol/steering_cmd_6d.cc
|
/******************************************************************************
* 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.
*****************************************************************************/
#include "modules/canbus_vehicle/gem/protocol/steering_cmd_6d.h"
#include "modules/drivers/canbus/common/byte.h"
namespace apollo {
namespace canbus {
namespace gem {
using ::apollo::drivers::canbus::Byte;
const int32_t Steeringcmd6d::ID = 0x6D;
// public
Steeringcmd6d::Steeringcmd6d() { Reset(); }
uint32_t Steeringcmd6d::GetPeriod() const {
// TODO(QiL) :modify every protocol's period manually
static const uint32_t PERIOD = 20 * 1000;
return PERIOD;
}
void Steeringcmd6d::UpdateData(uint8_t* data) {
set_p_position_value(data, position_value_);
set_p_speed_limit(data, speed_limit_);
}
void Steeringcmd6d::Reset() {
// TODO(QiL) :you should check this manually
position_value_ = 0.0;
speed_limit_ = 0.0;
}
Steeringcmd6d* Steeringcmd6d::set_position_value(double position_value) {
position_value_ = position_value;
return this;
}
// config detail: {'name': 'POSITION_VALUE', 'offset': 0.0, 'precision': 0.001,
// 'len': 32, 'is_signed_var': True, 'physical_range':
// '[-2147483.648|2147483.647]', 'bit': 7, 'type': 'double', 'order':
// 'motorola', 'physical_unit': 'radians'}
void Steeringcmd6d::set_p_position_value(uint8_t* data, double position_value) {
position_value =
ProtocolData::BoundedValue(-2147483.648, 2147483.647, position_value);
int x = static_cast<int>(position_value / 0.001000);
uint8_t t = 0;
t = static_cast<uint8_t>(x & 0xFF);
Byte to_set0(data + 3);
to_set0.set_value(t, 0, 8);
x >>= 8;
t = static_cast<uint8_t>(x & 0xFF);
Byte to_set1(data + 2);
to_set1.set_value(t, 0, 8);
x >>= 8;
t = static_cast<uint8_t>(x & 0xFF);
Byte to_set2(data + 1);
to_set2.set_value(t, 0, 8);
x >>= 8;
t = static_cast<uint8_t>(x & 0xFF);
Byte to_set3(data + 0);
to_set3.set_value(t, 0, 8);
}
Steeringcmd6d* Steeringcmd6d::set_speed_limit(double speed_limit) {
speed_limit_ = speed_limit;
return this;
}
// config detail: {'name': 'SPEED_LIMIT', 'offset': 0.0, 'precision': 0.001,
// 'len': 16, 'is_signed_var': False, 'physical_range': '[0|65.535]', 'bit': 39,
// 'type': 'double', 'order': 'motorola', 'physical_unit': 'rad/s'}
void Steeringcmd6d::set_p_speed_limit(uint8_t* data, double speed_limit) {
speed_limit = ProtocolData::BoundedValue(0.0, 65.535, speed_limit);
int x = static_cast<int>(speed_limit / 0.001000);
uint8_t t = 0;
t = static_cast<uint8_t>(x & 0xFF);
Byte to_set0(data + 7);
to_set0.set_value(t, 0, 8);
x >>= 8;
t = static_cast<uint8_t>(x & 0xFF);
Byte to_set1(data + 6);
to_set1.set_value(t, 0, 8);
x >>= 8;
t = static_cast<uint8_t>(x & 0xFF);
Byte to_set2(data + 5);
to_set2.set_value(t, 0, 8);
x >>= 8;
t = static_cast<uint8_t>(x & 0xFF);
Byte to_set3(data + 4);
to_set3.set_value(t, 0, 8);
}
} // namespace gem
} // namespace canbus
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/canbus_vehicle/gem
|
apollo_public_repos/apollo/modules/canbus_vehicle/gem/protocol/global_rpt_6a.h
|
/******************************************************************************
* 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.
*****************************************************************************/
#pragma once
#include "modules/canbus_vehicle/gem/proto/gem.pb.h"
#include "modules/drivers/canbus/can_comm/protocol_data.h"
namespace apollo {
namespace canbus {
namespace gem {
class Globalrpt6a : public ::apollo::drivers::canbus::ProtocolData<
::apollo::canbus::Gem> {
public:
static const int32_t ID;
Globalrpt6a();
void Parse(const std::uint8_t* bytes, int32_t length,
Gem* chassis) const override;
private:
// config detail: {'name': 'PACMOD_STATUS', 'enum': {0:
// 'PACMOD_STATUS_CONTROL_DISABLED', 1: 'PACMOD_STATUS_CONTROL_ENABLED'},
// 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0,
// 'physical_range': '[0|1]', 'bit': 0, 'type': 'enum', 'order': 'motorola',
// 'physical_unit': ''}
Global_rpt_6a::Pacmod_statusType pacmod_status(const std::uint8_t* bytes,
const int32_t length) const;
// config detail: {'name': 'OVERRIDE_STATUS', 'enum': {0:
// 'OVERRIDE_STATUS_NOT_OVERRIDDEN', 1: 'OVERRIDE_STATUS_OVERRIDDEN'},
// 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0,
// 'physical_range': '[0|1]', 'bit': 1, 'type': 'enum', 'order': 'motorola',
// 'physical_unit': ''}
Global_rpt_6a::Override_statusType override_status(
const std::uint8_t* bytes, const int32_t length) const;
// config detail: {'name': 'VEH_CAN_TIMEOUT', 'offset': 0.0, 'precision': 1.0,
// 'len': 1, 'is_signed_var': False, 'physical_range': '[0|1]', 'bit': 2,
// 'type': 'bool', 'order': 'motorola', 'physical_unit': ''}
bool veh_can_timeout(const std::uint8_t* bytes, const int32_t length) const;
// config detail: {'name': 'STR_CAN_TIMEOUT', 'offset': 0.0, 'precision': 1.0,
// 'len': 1, 'is_signed_var': False, 'physical_range': '[0|1]', 'bit': 3,
// 'type': 'bool', 'order': 'motorola', 'physical_unit': ''}
bool str_can_timeout(const std::uint8_t* bytes, const int32_t length) const;
// config detail: {'name': 'BRK_CAN_TIMEOUT', 'enum': {0:
// 'BRK_CAN_TIMEOUT_NO_ACTIVE_CAN_TIMEOUT', 1:
// 'BRK_CAN_TIMEOUT_ACTIVE_CAN_TIMEOUT'}, 'precision': 1.0, 'len': 1,
// 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 4,
// 'type': 'enum', 'order': 'motorola', 'physical_unit': ''}
Global_rpt_6a::Brk_can_timeoutType brk_can_timeout(
const std::uint8_t* bytes, const int32_t length) const;
// config detail: {'name': 'USR_CAN_TIMEOUT', 'offset': 0.0, 'precision': 1.0,
// 'len': 1, 'is_signed_var': False, 'physical_range': '[0|1]', 'bit': 5,
// 'type': 'bool', 'order': 'motorola', 'physical_unit': ''}
bool usr_can_timeout(const std::uint8_t* bytes, const int32_t length) const;
// config detail: {'name': 'USR_CAN_READ_ERRORS', 'offset': 0.0,
// 'precision': 1.0, 'len': 16, 'is_signed_var': False, 'physical_range':
// '[0|65535]', 'bit': 55, 'type': 'int', 'order': 'motorola',
// 'physical_unit': ''}
int usr_can_read_errors(const std::uint8_t* bytes,
const int32_t length) const;
};
} // namespace gem
} // namespace canbus
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/canbus_vehicle/gem
|
apollo_public_repos/apollo/modules/canbus_vehicle/gem/protocol/steering_motor_rpt_3_75.h
|
/******************************************************************************
* 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.
*****************************************************************************/
#pragma once
#include "modules/canbus_vehicle/gem/proto/gem.pb.h"
#include "modules/drivers/canbus/can_comm/protocol_data.h"
namespace apollo {
namespace canbus {
namespace gem {
class Steeringmotorrpt375 : public ::apollo::drivers::canbus::ProtocolData<
::apollo::canbus::Gem> {
public:
static const int32_t ID;
Steeringmotorrpt375();
void Parse(const std::uint8_t* bytes, int32_t length,
Gem* chassis) const override;
private:
// config detail: {'name': 'TORQUE_OUTPUT', 'offset': 0.0, 'precision': 0.001,
// 'len': 32, 'is_signed_var': True, 'physical_range':
// '[-2147483.648|2147483.647]', 'bit': 7, 'type': 'double', 'order':
// 'motorola', 'physical_unit': 'N-m'}
double torque_output(const std::uint8_t* bytes, const int32_t length) const;
// config detail: {'name': 'TORQUE_INPUT', 'offset': 0.0, 'precision': 0.001,
// 'len': 32, 'is_signed_var': True, 'physical_range':
// '[-2147483.648|2147483.647]', 'bit': 39, 'type': 'double', 'order':
// 'motorola', 'physical_unit': 'N-m'}
double torque_input(const std::uint8_t* bytes, const int32_t length) const;
};
} // namespace gem
} // namespace canbus
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/canbus_vehicle/gem
|
apollo_public_repos/apollo/modules/canbus_vehicle/gem/protocol/date_time_rpt_83.cc
|
/******************************************************************************
* 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.
*****************************************************************************/
#include "modules/canbus_vehicle/gem/protocol/date_time_rpt_83.h"
#include "glog/logging.h"
#include "modules/drivers/canbus/common/byte.h"
#include "modules/drivers/canbus/common/canbus_consts.h"
namespace apollo {
namespace canbus {
namespace gem {
using ::apollo::drivers::canbus::Byte;
Datetimerpt83::Datetimerpt83() {}
const int32_t Datetimerpt83::ID = 0x83;
void Datetimerpt83::Parse(const std::uint8_t* bytes, int32_t length,
Gem* chassis) const {
chassis->mutable_date_time_rpt_83()->set_time_second(
time_second(bytes, length));
chassis->mutable_date_time_rpt_83()->set_time_minute(
time_minute(bytes, length));
chassis->mutable_date_time_rpt_83()->set_time_hour(
time_hour(bytes, length));
chassis->mutable_date_time_rpt_83()->set_date_day(
date_day(bytes, length));
chassis->mutable_date_time_rpt_83()->set_date_month(
date_month(bytes, length));
chassis->mutable_date_time_rpt_83()->set_date_year(
date_year(bytes, length));
}
// config detail: {'name': 'time_second', 'offset': 0.0, 'precision': 1.0,
// 'len': 8, 'is_signed_var': False, 'physical_range': '[0|60]', 'bit': 47,
// 'type': 'int', 'order': 'motorola', 'physical_unit': 'sec'}
int Datetimerpt83::time_second(const std::uint8_t* bytes,
int32_t length) const {
Byte t0(bytes + 5);
int32_t x = t0.get_byte(0, 8);
int ret = x;
return ret;
}
// config detail: {'name': 'time_minute', 'offset': 0.0, 'precision': 1.0,
// 'len': 8, 'is_signed_var': False, 'physical_range': '[0|60]', 'bit': 39,
// 'type': 'int', 'order': 'motorola', 'physical_unit': 'min'}
int Datetimerpt83::time_minute(const std::uint8_t* bytes,
int32_t length) const {
Byte t0(bytes + 4);
int32_t x = t0.get_byte(0, 8);
int ret = x;
return ret;
}
// config detail: {'name': 'time_hour', 'offset': 0.0, 'precision': 1.0, 'len':
// 8, 'is_signed_var': False, 'physical_range': '[0|23]', 'bit': 31, 'type':
// 'int', 'order': 'motorola', 'physical_unit': 'hr'}
int Datetimerpt83::time_hour(const std::uint8_t* bytes, int32_t length) const {
Byte t0(bytes + 3);
int32_t x = t0.get_byte(0, 8);
int ret = x;
return ret;
}
// config detail: {'name': 'date_day', 'offset': 1.0, 'precision': 1.0, 'len':
// 8, 'is_signed_var': False, 'physical_range': '[1|31]', 'bit': 23, 'type':
// 'int', 'order': 'motorola', 'physical_unit': 'dy'}
int Datetimerpt83::date_day(const std::uint8_t* bytes, int32_t length) const {
Byte t0(bytes + 2);
int32_t x = t0.get_byte(0, 8);
int ret = x + 1;
return ret;
}
// config detail: {'name': 'date_month', 'offset': 1.0, 'precision': 1.0, 'len':
// 8, 'is_signed_var': False, 'physical_range': '[1|12]', 'bit': 15, 'type':
// 'int', 'order': 'motorola', 'physical_unit': 'mon'}
int Datetimerpt83::date_month(const std::uint8_t* bytes, int32_t length) const {
Byte t0(bytes + 1);
int32_t x = t0.get_byte(0, 8);
int ret = x + 1;
return ret;
}
// config detail: {'name': 'date_year', 'offset': 2000.0, 'precision': 1.0,
// 'len': 8, 'is_signed_var': False, 'physical_range': '[2000|2255]', 'bit': 7,
// 'type': 'int', 'order': 'motorola', 'physical_unit': 'yr'}
int Datetimerpt83::date_year(const std::uint8_t* bytes, int32_t length) const {
Byte t0(bytes + 0);
int32_t x = t0.get_byte(0, 8);
int ret = x + 2000;
return ret;
}
} // namespace gem
} // namespace canbus
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/canbus_vehicle/gem
|
apollo_public_repos/apollo/modules/canbus_vehicle/gem/protocol/steering_rpt_1_6e.h
|
/******************************************************************************
* 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.
*****************************************************************************/
#pragma once
#include "modules/canbus_vehicle/gem/proto/gem.pb.h"
#include "modules/drivers/canbus/can_comm/protocol_data.h"
namespace apollo {
namespace canbus {
namespace gem {
class Steeringrpt16e : public ::apollo::drivers::canbus::ProtocolData<
::apollo::canbus::Gem> {
public:
static const int32_t ID;
Steeringrpt16e();
void Parse(const std::uint8_t* bytes, int32_t length,
Gem* chassis) const override;
private:
// config detail: {'name': 'MANUAL_INPUT', 'offset': 0.0, 'precision': 0.001,
// 'len': 16, 'is_signed_var': True, 'physical_range': '[-32.768|32.767]',
// 'bit': 7, 'type': 'double', 'order': 'motorola', 'physical_unit': 'rad/s'}
double manual_input(const std::uint8_t* bytes, const int32_t length) const;
// config detail: {'name': 'COMMANDED_VALUE', 'offset': 0.0, 'precision':
// 0.001, 'len': 16, 'is_signed_var': True, 'physical_range':
// '[-32.768|32.767]', 'bit': 23, 'type': 'double', 'order': 'motorola',
// 'physical_unit': 'rad/s'}
double commanded_value(const std::uint8_t* bytes, const int32_t length) const;
// config detail: {'name': 'OUTPUT_VALUE', 'offset': 0.0, 'precision': 0.001,
// 'len': 16, 'is_signed_var': True, 'physical_range': '[-32.768|32.767]',
// 'bit': 39, 'type': 'double', 'order': 'motorola', 'physical_unit': 'rad/s'}
double output_value(const std::uint8_t* bytes, const int32_t length) const;
};
} // namespace gem
} // namespace canbus
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/canbus_vehicle/gem
|
apollo_public_repos/apollo/modules/canbus_vehicle/gem/protocol/lat_lon_heading_rpt_82.cc
|
/******************************************************************************
* 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.
*****************************************************************************/
#include "modules/canbus_vehicle/gem/protocol/lat_lon_heading_rpt_82.h"
#include "glog/logging.h"
#include "modules/drivers/canbus/common/byte.h"
#include "modules/drivers/canbus/common/canbus_consts.h"
namespace apollo {
namespace canbus {
namespace gem {
using ::apollo::drivers::canbus::Byte;
Latlonheadingrpt82::Latlonheadingrpt82() {}
const int32_t Latlonheadingrpt82::ID = 0x82;
void Latlonheadingrpt82::Parse(const std::uint8_t* bytes, int32_t length,
Gem* chassis) const {
chassis->mutable_lat_lon_heading_rpt_82()->set_heading(
heading(bytes, length));
chassis->mutable_lat_lon_heading_rpt_82()->set_longitude_seconds(
longitude_seconds(bytes, length));
chassis->mutable_lat_lon_heading_rpt_82()->set_longitude_minutes(
longitude_minutes(bytes, length));
chassis->mutable_lat_lon_heading_rpt_82()->set_longitude_degrees(
longitude_degrees(bytes, length));
chassis->mutable_lat_lon_heading_rpt_82()->set_latitude_seconds(
latitude_seconds(bytes, length));
chassis->mutable_lat_lon_heading_rpt_82()->set_latitude_minutes(
latitude_minutes(bytes, length));
chassis->mutable_lat_lon_heading_rpt_82()->set_latitude_degrees(
latitude_degrees(bytes, length));
}
// config detail: {'name': 'heading', 'offset': 0.0, 'precision': 0.01, 'len':
// 16, 'is_signed_var': True, 'physical_range': '[-327.68|327.67]', 'bit': 55,
// 'type': 'double', 'order': 'motorola', 'physical_unit': 'deg'}
double Latlonheadingrpt82::heading(const std::uint8_t* bytes,
int32_t length) const {
Byte t0(bytes + 6);
int32_t x = t0.get_byte(0, 8);
Byte t1(bytes + 7);
int32_t t = t1.get_byte(0, 8);
x <<= 8;
x |= t;
x <<= 16;
x >>= 16;
double ret = x * 0.010000;
return ret;
}
// config detail: {'name': 'longitude_seconds', 'offset': 0.0, 'precision': 1.0,
// 'len': 8, 'is_signed_var': True, 'physical_range': '[-128|127]', 'bit': 47,
// 'type': 'int', 'order': 'motorola', 'physical_unit': 'sec'}
int Latlonheadingrpt82::longitude_seconds(const std::uint8_t* bytes,
int32_t length) const {
Byte t0(bytes + 5);
int32_t x = t0.get_byte(0, 8);
x <<= 24;
x >>= 24;
int ret = x;
return ret;
}
// config detail: {'name': 'longitude_minutes', 'offset': 0.0, 'precision': 1.0,
// 'len': 8, 'is_signed_var': True, 'physical_range': '[-128|127]', 'bit': 39,
// 'type': 'int', 'order': 'motorola', 'physical_unit': 'min'}
int Latlonheadingrpt82::longitude_minutes(const std::uint8_t* bytes,
int32_t length) const {
Byte t0(bytes + 4);
int32_t x = t0.get_byte(0, 8);
x <<= 24;
x >>= 24;
int ret = x;
return ret;
}
// config detail: {'name': 'longitude_degrees', 'offset': 0.0, 'precision': 1.0,
// 'len': 8, 'is_signed_var': True, 'physical_range': '[-128|127]', 'bit': 31,
// 'type': 'int', 'order': 'motorola', 'physical_unit': 'deg'}
int Latlonheadingrpt82::longitude_degrees(const std::uint8_t* bytes,
int32_t length) const {
Byte t0(bytes + 3);
int32_t x = t0.get_byte(0, 8);
x <<= 24;
x >>= 24;
int ret = x;
return ret;
}
// config detail: {'name': 'latitude_seconds', 'offset': 0.0, 'precision': 1.0,
// 'len': 8, 'is_signed_var': True, 'physical_range': '[-128|127]', 'bit': 23,
// 'type': 'int', 'order': 'motorola', 'physical_unit': 'sec'}
int Latlonheadingrpt82::latitude_seconds(const std::uint8_t* bytes,
int32_t length) const {
Byte t0(bytes + 2);
int32_t x = t0.get_byte(0, 8);
x <<= 24;
x >>= 24;
int ret = x;
return ret;
}
// config detail: {'name': 'latitude_minutes', 'offset': 0.0, 'precision': 1.0,
// 'len': 8, 'is_signed_var': True, 'physical_range': '[-128|127]', 'bit': 15,
// 'type': 'int', 'order': 'motorola', 'physical_unit': 'min'}
int Latlonheadingrpt82::latitude_minutes(const std::uint8_t* bytes,
int32_t length) const {
Byte t0(bytes + 1);
int32_t x = t0.get_byte(0, 8);
x <<= 24;
x >>= 24;
int ret = x;
return ret;
}
// config detail: {'name': 'latitude_degrees', 'offset': 0.0, 'precision': 1.0,
// 'len': 8, 'is_signed_var': True, 'physical_range': '[-128|127]', 'bit': 7,
// 'type': 'int', 'order': 'motorola', 'physical_unit': 'deg'}
int Latlonheadingrpt82::latitude_degrees(const std::uint8_t* bytes,
int32_t length) const {
Byte t0(bytes + 0);
int32_t x = t0.get_byte(0, 8);
x <<= 24;
x >>= 24;
int ret = x;
return ret;
}
} // namespace gem
} // namespace canbus
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/canbus_vehicle/gem
|
apollo_public_repos/apollo/modules/canbus_vehicle/gem/protocol/accel_cmd_67.h
|
/******************************************************************************
* 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.
*****************************************************************************/
#pragma once
#include "modules/canbus_vehicle/gem/proto/gem.pb.h"
#include "modules/drivers/canbus/can_comm/protocol_data.h"
namespace apollo {
namespace canbus {
namespace gem {
class Accelcmd67
: public ::apollo::drivers::canbus::ProtocolData<::apollo::canbus::Gem> {
public:
static const int32_t ID;
Accelcmd67();
uint32_t GetPeriod() const override;
void UpdateData(uint8_t* data) override;
void Reset() override;
// config detail: {'name': 'ACCEL_CMD', 'offset': 0.0, 'precision': 0.001,
// 'len': 16, 'is_signed_var': False, 'physical_range': '[0|1]', 'bit': 7,
// 'type': 'double', 'order': 'motorola', 'physical_unit': '%'}
Accelcmd67* set_accel_cmd(double accel_cmd);
private:
// config detail: {'name': 'ACCEL_CMD', 'offset': 0.0, 'precision': 0.001,
// 'len': 16, 'is_signed_var': False, 'physical_range': '[0|1]', 'bit': 7,
// 'type': 'double', 'order': 'motorola', 'physical_unit': '%'}
void set_p_accel_cmd(uint8_t* data, double accel_cmd);
private:
double accel_cmd_;
};
} // namespace gem
} // namespace canbus
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/canbus_vehicle/gem
|
apollo_public_repos/apollo/modules/canbus_vehicle/gem/protocol/global_cmd_69.cc
|
/******************************************************************************
* 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.
*****************************************************************************/
#include "modules/canbus_vehicle/gem/protocol/global_cmd_69.h"
#include "modules/drivers/canbus/common/byte.h"
namespace apollo {
namespace canbus {
namespace gem {
using ::apollo::drivers::canbus::Byte;
const int32_t Globalcmd69::ID = 0x69;
// public
Globalcmd69::Globalcmd69() { Reset(); }
uint32_t Globalcmd69::GetPeriod() const {
// TODO(QiL) :modify every protocol's period manually
static const uint32_t PERIOD = 20 * 1000;
return PERIOD;
}
void Globalcmd69::UpdateData(uint8_t* data) {
set_p_pacmod_enable(data, pacmod_enable_);
set_p_clear_override(data, clear_override_);
set_p_ignore_override(data, ignore_override_);
}
void Globalcmd69::Reset() {
// TODO(QiL) :you should check this manually
pacmod_enable_ = Global_cmd_69::PACMOD_ENABLE_CONTROL_DISABLED;
clear_override_ = Global_cmd_69::CLEAR_OVERRIDE_DON_T_CLEAR_ACTIVE_OVERRIDES;
ignore_override_ = Global_cmd_69::IGNORE_OVERRIDE_DON_T_IGNORE_USER_OVERRIDES;
}
Globalcmd69* Globalcmd69::set_pacmod_enable(
Global_cmd_69::Pacmod_enableType pacmod_enable) {
pacmod_enable_ = pacmod_enable;
return this;
}
// config detail: {'name': 'PACMOD_ENABLE', 'enum': {0:
// 'PACMOD_ENABLE_CONTROL_DISABLED', 1: 'PACMOD_ENABLE_CONTROL_ENABLED'},
// 'precision': 1.0, 'len': 1, 'is_signed_var': False, 'offset': 0.0,
// 'physical_range': '[0|1]', 'bit': 0, 'type': 'enum', 'order': 'motorola',
// 'physical_unit': ''}
void Globalcmd69::set_p_pacmod_enable(
uint8_t* data, Global_cmd_69::Pacmod_enableType pacmod_enable) {
uint8_t x = pacmod_enable;
Byte to_set(data + 0);
to_set.set_value(static_cast<uint8_t>(x), 0, 1);
}
Globalcmd69* Globalcmd69::set_clear_override(
Global_cmd_69::Clear_overrideType clear_override) {
clear_override_ = clear_override;
return this;
}
// config detail: {'name': 'CLEAR_OVERRIDE', 'enum': {0:
// 'CLEAR_OVERRIDE_DON_T_CLEAR_ACTIVE_OVERRIDES', 1:
// 'CLEAR_OVERRIDE_CLEAR_ACTIVE_OVERRIDES'}, 'precision': 1.0, 'len': 1,
// 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 1,
// 'type': 'enum', 'order': 'motorola', 'physical_unit': ''}
void Globalcmd69::set_p_clear_override(
uint8_t* data, Global_cmd_69::Clear_overrideType clear_override) {
uint8_t x = clear_override;
Byte to_set(data + 0);
to_set.set_value(static_cast<uint8_t>(x), 1, 1);
}
Globalcmd69* Globalcmd69::set_ignore_override(
Global_cmd_69::Ignore_overrideType ignore_override) {
ignore_override_ = ignore_override;
return this;
}
// config detail: {'name': 'IGNORE_OVERRIDE', 'enum': {0:
// 'IGNORE_OVERRIDE_DON_T_IGNORE_USER_OVERRIDES', 1:
// 'IGNORE_OVERRIDE_IGNORE_USER_OVERRIDES'}, 'precision': 1.0, 'len': 1,
// 'is_signed_var': False, 'offset': 0.0, 'physical_range': '[0|1]', 'bit': 2,
// 'type': 'enum', 'order': 'motorola', 'physical_unit': ''}
void Globalcmd69::set_p_ignore_override(
uint8_t* data, Global_cmd_69::Ignore_overrideType ignore_override) {
uint8_t x = ignore_override;
Byte to_set(data + 0);
to_set.set_value(static_cast<uint8_t>(x), 2, 1);
}
} // namespace gem
} // namespace canbus
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/canbus_vehicle/gem
|
apollo_public_repos/apollo/modules/canbus_vehicle/gem/protocol/shift_cmd_65.cc
|
/******************************************************************************
* 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.
*****************************************************************************/
#include "modules/canbus_vehicle/gem/protocol/shift_cmd_65.h"
#include "modules/drivers/canbus/common/byte.h"
namespace apollo {
namespace canbus {
namespace gem {
using ::apollo::drivers::canbus::Byte;
const int32_t Shiftcmd65::ID = 0x65;
// public
Shiftcmd65::Shiftcmd65() { Reset(); }
uint32_t Shiftcmd65::GetPeriod() const {
// TODO(QiL) :modify every protocol's period manually
static const uint32_t PERIOD = 20 * 1000;
return PERIOD;
}
void Shiftcmd65::UpdateData(uint8_t* data) {
set_p_shift_cmd(data, shift_cmd_);
}
void Shiftcmd65::Reset() {
// TODO(QiL) :you should check this manually
shift_cmd_ = Shift_cmd_65::SHIFT_CMD_PARK;
}
Shiftcmd65* Shiftcmd65::set_shift_cmd(Shift_cmd_65::Shift_cmdType shift_cmd) {
shift_cmd_ = shift_cmd;
return this;
}
// config detail: {'description':
// 'FORWARD_is_also_LOW_on_vehicles_with_LOW/HIGH,_PARK_and_HIGH_only_available_on_certain_Vehicles',
// 'enum': {0: 'SHIFT_CMD_PARK', 1: 'SHIFT_CMD_REVERSE', 2: 'SHIFT_CMD_NEUTRAL',
// 3: 'SHIFT_CMD_FORWARD', 4: 'SHIFT_CMD_LOW'}, 'precision': 1.0, 'len': 8,
// 'name': 'SHIFT_CMD', 'is_signed_var': False, 'offset': 0.0, 'physical_range':
// '[0|4]', 'bit': 7, 'type': 'enum', 'order': 'motorola', 'physical_unit': ''}
void Shiftcmd65::set_p_shift_cmd(uint8_t* data,
Shift_cmd_65::Shift_cmdType shift_cmd) {
uint8_t x = shift_cmd;
Byte to_set(data + 0);
to_set.set_value(static_cast<uint8_t>(x), 0, 8);
}
} // namespace gem
} // namespace canbus
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules
|
apollo_public_repos/apollo/modules/prediction/prediction_component_test.cc
|
/******************************************************************************
* 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.
*****************************************************************************/
#include "modules/prediction/prediction_component.h"
#include "cyber/init.h"
#include "gtest/gtest.h"
namespace apollo {
namespace prediction {
TEST(PredictionComponentTest, Simple) {
cyber::Init("prediction_component_test");
PredictionComponent prediction_component;
EXPECT_EQ(prediction_component.Name(), "prediction");
}
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules
|
apollo_public_repos/apollo/modules/prediction/cyberfile.xml
|
<package format="2">
<name>prediction</name>
<version>local</version>
<description>
The Prediction module studies and predicts the behavior of all the obstacles detected by the perception module.
Prediction receives obstacle data along with basic perception information including positions, headings, velocities,
accelerations, and then generates predicted trajectories with probabilities for those obstacles.
</description>
<maintainer email="apollo-support@baidu.com">Apollo</maintainer>
<license>Apache License 2.0</license>
<url type="website">https://www.apollo.auto/</url>
<url type="repository">https://github.com/ApolloAuto/apollo</url>
<url type="bugtracker">https://github.com/ApolloAuto/apollo/issues</url>
<depend repo_name="com_google_absl" lib_names="absl">3rd-absl-dev</depend>
<depend repo_name="com_google_googletest" lib_names="gtest,gtest_main">3rd-gtest-dev</depend>
<depend repo_name="eigen">3rd-eigen3-dev</depend>
<depend repo_name="opencv" lib_names="core,highgui,imgproc,imgcodecs">3rd-opencv-dev</depend>
<depend repo_name="com_github_gflags_gflags" lib_names="gflags">3rd-gflags-dev</depend>
<depend repo_name="boost">3rd-boost-dev</depend>
<depend repo_name="com_github_jbeder_yaml_cpp" lib_names="yaml-cpp">3rd-yaml-cpp-dev</depend>
<depend type="binary" repo_name="cyber">cyber-dev</depend>
<depend type="binary" repo_name="common" lib_names="common">common-dev</depend>
<depend type="binary" repo_name="map" lib_names="map">map-dev</depend>
<depend type="binary" repo_name="transform" lib_names="transform">transform-dev</depend>
<depend repo_name="common-msgs" lib_names="common-msgs">common-msgs-dev</depend>
<depend so_names="numa">libnuma-dev</depend>
<depend repo_name="libtorch_cpu" lib_names="libtorch_cpu">3rd-libtorch-cpu-dev</depend>
<depend>3rd-mkl-dev</depend>
<depend expose="False">3rd-pcl-dev</depend>
<depend expose="False">3rd-rules-python-dev</depend>
<depend expose="False">3rd-grpc-dev</depend>
<depend expose="False">3rd-bazel-skylib-dev</depend>
<depend expose="False">3rd-rules-proto-dev</depend>
<depend expose="False">3rd-py-dev</depend>
<depend expose="False">3rd-gpus-dev</depend>
<type>module</type>
<src_path url="https://github.com/ApolloAuto/apollo">//modules/prediction</src_path>
</package>
| 0
|
apollo_public_repos/apollo/modules
|
apollo_public_repos/apollo/modules/prediction/README.md
|
# Prediction
## Introduction
The Prediction module studies and predicts the behavior of all the obstacles detected by the perception module.
Prediction receives obstacle data along with basic perception information including positions, headings, velocities, accelerations, and then generates predicted trajectories with probabilities for those obstacles.
In **Apollo 5.5**, the Prediction module introduces a new model - **Caution Obstacle**. Together with aggressively emphasizing on caution when proceeding to a junction, this model will now scan all obstacles that have entered the junction as long as computing resources permit. The Semantic LSTM Evaluator and the Extrapolation Predictor have also been introduced in Apolo 5.5 to support the Caution Obstacle model.
```
Note:
The Prediction module only predicts the behavior of obstacles and not the EGO car. The Planning module plans the trajectory of the EGO car.
```
## Input
* Obstacles information from the perception module
* Localization information from the localization module
* Planning trajectory of the previous computing cycle from the planning module
## Output
* Obstacles annotated with predicted trajectories and their priorities. Obstacle priority is now calculated as individual scenarios are prioritized differently. The priorities include: ignore, caution and normal (default)
## Functionalities
Based on the figure below, the prediction module comprises 4 main functionalities: Container, Scenario, Evaluator and Predictor. Container, Evaluator and Predictor existed in Apollo 3.0. In Apollo 3.5, we introduced the Scenario functionality as we have moved towards a more scenario-based approach for Apollo's autonomous driving capabilities.

### Container
Container stores input data from subscribed channels. Current supported
inputs are **_perception obstacles_**, **_vehicle localization_** and **_vehicle planning_**.
### Scenario
The Scenario sub-module analyzes scenarios that includes the ego vehicle.
Currently, we have two defined scenarios:
- **Cruise** : this scenario includes Lane keeping and following
- **Junction** : this scenario involves junctions. Junctions can either have traffic lights and/or STOP signs
### Obstacles
- **Ignore**: these obstacles will not affect the ego car's trajectory and can be safely ignored (E.g. the obstacle is too far away)
- **Caution**: these obstacles have a high possibility of interacting with the ego car
- **Normal**: the obstacles that do not fall under ignore or caution are placed by default under normal
### Evaluator
The Evaluator predicts path and speed separately for any given obstacle.
An evaluator evaluates a path by outputting a probability for it (lane
sequence) using the given model stored in _prediction/data/_.
The list of available evaluators include:
* **Cost evaluator**: probability is calculated by a set of cost functions
* **MLP evaluator**: probability is calculated using an MLP model
* **RNN evaluator**: probability is calculated using an RNN model
* **Cruise MLP + CNN-1d evaluator**: probability is calculated using a mix of MLP and CNN-1d models for the cruise scenario
* **Junction MLP evaluator**: probability is calculated using an MLP model for junction scenario
* **Junction Map evaluator**: probability is calculated using an semantic map-based CNN model for junction scenario. This evaluator was created for caution level obstacles
* **Social Interaction evaluator**: this model is used for pedestrians, for short term trajectory prediction. It uses social LSTM. This evaluator was created for caution level obstacles
* **Semantic LSTM evaluator**: this evaluator is used in the new Caution Obstacle model to generate short term trajectory points which are calculated using CNN and LSTM. Both vehicles and pedestrians are using this same model, but with different parameters
* **Vectornet LSTM evaluator**: this evaluator is used in place of Semantic LSTM evaluator to generate short term trajectory points for "Caution" tagged obstacles. More detail is in [vectornet lstm evaluator readme](https://github.com/ApolloAuto/apollo/docs/technical_documents/vectornet_lstm_evaluator.md).
* **Jointly prediction planning evaluator**: this evaluator is used in the new Interactive Obstacle(vehicle-type) model to generate short term trajectory points which are calculated using Vectornet and LSTM. By considering ADC's trajectory info, the obstacle trajectory prediction can be more accurate under interaction scenario. Please refer [jointly prediction planning evaluator](https://github.com/ApolloAuto/apollo/blob/master/docs/07_Prediction/jointly_prediction_planning_evaluator.md).
### Predictor
Predictor generates predicted trajectories for obstacles. Currently, the supported predictors include:
* **Empty**: obstacles have no predicted trajectories
* **Single lane**: Obstacles move along a single lane in highway navigation mode. Obstacles not on lane will be ignored.
* **Lane sequence**: obstacle moves along the lanes
* **Move sequence**: obstacle moves along the lanes by following its kinetic pattern
* **Free movement**: obstacle moves freely
* **Regional movement**: obstacle moves in a possible region
* **Junction**: Obstacles move toward junction exits with high probabilities
* **Interaction predictor**: compute the likelihood to create posterior prediction results after all evaluators have run. This predictor was created for caution level obstacles
* **Extrapolation predictor**: extends the Semantic LSTM evaluator's results to create an 8 sec trajectory.
## Prediction Architecture
The prediction module estimates the future motion trajectories for all perceived obstacles. The output prediction message wraps the perception information. Prediction both subscribes to and is triggered by perception obstacle messages, as shown below:

The prediction module also takes messages from both localization and planning as input. The structure is shown below:

## Related Paper
1. [Xu K, Xiao X, Miao J, Luo Q. "Data Driven Prediction Architecture for Autonomous Driving and its Application on Apollo Platform." *arXiv preprint arXiv:2006.06715.* ](https://arxiv.org/pdf/2006.06715.pdf)
| 0
|
apollo_public_repos/apollo/modules
|
apollo_public_repos/apollo/modules/prediction/README_cn.md
|
# 预测
## 介绍
预测模块从感知模块接收障碍物,其基本感知信息包括位置、方向、速度、加速度,并生成不同概率的预测轨迹。
## 输入
* 障碍物
* 定位
## 输出
* 具有预测轨迹的障碍物
## 功能
* 容器
容器存储来自订阅通道的输入数据。目前支持的输入是感知模块的障碍物,车辆定位和车辆规划。
* 评估器
评估器对任何给定的障碍分别预测路径和速度。评估器通过使用存储在prediction/data/模型中的给定模型输出路径的概率来评估路径(车道序列)。
将提供三种类型的评估器,包括:
* 成本评估器:概率是由一组成本函数计算的。
* MLP评估器:用MLP模型计算概率
* RNN评估器:用RNN模型计算概率
* 预测规划交互评估器:可以参考 [预测规划交互评估器简介](https://github.com/ApolloAuto/apollo/blob/master/docs/technical_documents/jointly_prediction_planning_evaluator_cn.md).
* 预测器
预测器生成障碍物的预测轨迹。当前支持的预测器包括:
* 空:障碍物没有预测的轨迹
* 单行道:在公路导航模式下障碍物沿着单条车道移动。不在车道上的障碍物将被忽略。
* 车道顺序:障碍物沿车道移动
* 移动序列:障碍物沿其运动模式沿车道移动
* 自由运动:障碍物自由移动
* 区域运动:障碍物在可能的区域中移动
| 0
|
apollo_public_repos/apollo/modules
|
apollo_public_repos/apollo/modules/prediction/prediction_component.h
|
/******************************************************************************
* 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.
*****************************************************************************/
/**
* @file
*/
#pragma once
#include <memory>
#include <string>
#include "cyber/time/time.h"
#include "cyber/component/component.h"
#include "modules/prediction/common/message_process.h"
#include "modules/prediction/container/adc_trajectory/adc_trajectory_container.h"
#include "modules/prediction/submodules/submodule_output.h"
#include "modules/common_msgs/storytelling_msgs/story.pb.h"
/**
* @namespace apollo::prediction
* @brief apollo::prediction
*/
namespace apollo {
namespace prediction {
class PredictionComponent
: public cyber::Component<perception::PerceptionObstacles> {
public:
/**
* @brief Destructor
*/
~PredictionComponent();
/**
* @brief Get name of the node
* @return Name of the node
*/
std::string Name() const;
/**
* @brief Initialize the node
* @return If initialized
*/
bool Init() override;
/**
* @brief Data callback upon receiving a perception obstacle message.
* @param Perception obstacle message.
*/
bool Proc(const std::shared_ptr<perception::PerceptionObstacles>&) override;
/**
* @brief Load and process feature proto file.
* @param a bin file including a sequence of feature proto.
*/
void OfflineProcessFeatureProtoFile(const std::string& features_proto_file);
private:
bool ContainerSubmoduleProcess(
const std::shared_ptr<perception::PerceptionObstacles>&);
bool PredictionEndToEndProc(
const std::shared_ptr<perception::PerceptionObstacles>&);
double component_start_time_ = 0.0;
double frame_start_time_ = 0.0;
std::shared_ptr<cyber::Reader<planning::ADCTrajectory>> planning_reader_;
std::shared_ptr<cyber::Reader<localization::LocalizationEstimate>>
localization_reader_;
std::shared_ptr<cyber::Reader<storytelling::Stories>> storytelling_reader_;
std::shared_ptr<cyber::Writer<PredictionObstacles>> prediction_writer_;
std::shared_ptr<cyber::Writer<SubmoduleOutput>> container_writer_;
std::shared_ptr<cyber::Writer<ADCTrajectoryContainer>> adc_container_writer_;
std::shared_ptr<cyber::Writer<perception::PerceptionObstacles>>
perception_obstacles_writer_;
std::shared_ptr<ContainerManager> container_manager_;
std::unique_ptr<EvaluatorManager> evaluator_manager_;
std::unique_ptr<PredictorManager> predictor_manager_;
std::unique_ptr<ScenarioManager> scenario_manager_;
};
CYBER_REGISTER_COMPONENT(PredictionComponent)
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules
|
apollo_public_repos/apollo/modules/prediction/prediction.BUILD
|
load("@rules_cc//cc:defs.bzl", "cc_library")
cc_library(
name = "prediction",
includes = ["include"],
hdrs = glob(["include/**/*.h"]),
srcs = glob(["lib/**/lib*.so*"]),
include_prefix = "modules/prediction",
strip_include_prefix = "include",
visibility = ["//visibility:public"],
)
| 0
|
apollo_public_repos/apollo/modules
|
apollo_public_repos/apollo/modules/prediction/prediction_component.cc
|
/******************************************************************************
* 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.
*****************************************************************************/
#include "modules/prediction/prediction_component.h"
#include "cyber/common/file.h"
#include "cyber/record/record_reader.h"
#include "cyber/time/clock.h"
#include "modules/common/adapters/adapter_gflags.h"
#include "modules/common/util/message_util.h"
#include "modules/prediction/common/feature_output.h"
#include "modules/prediction/common/junction_analyzer.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_system_gflags.h"
#include "modules/prediction/common/validation_checker.h"
#include "modules/prediction/evaluator/evaluator_manager.h"
#include "modules/prediction/predictor/predictor_manager.h"
#include "modules/prediction/proto/offline_features.pb.h"
#include "modules/prediction/proto/prediction_conf.pb.h"
#include "modules/prediction/scenario/scenario_manager.h"
#include "modules/common/util/data_extraction.h"
namespace apollo {
namespace prediction {
using apollo::common::adapter::AdapterConfig;
using apollo::cyber::Clock;
using apollo::perception::PerceptionObstacles;
using apollo::planning::ADCTrajectory;
PredictionComponent::~PredictionComponent() {}
std::string PredictionComponent::Name() const {
return FLAGS_prediction_module_name;
}
void PredictionComponent::OfflineProcessFeatureProtoFile(
const std::string& features_proto_file_name) {
auto obstacles_container_ptr =
container_manager_->GetContainer<ObstaclesContainer>(
AdapterConfig::PERCEPTION_OBSTACLES);
obstacles_container_ptr->Clear();
Features features;
apollo::cyber::common::GetProtoFromBinaryFile(features_proto_file_name,
&features);
for (const Feature& feature : features.feature()) {
obstacles_container_ptr->InsertFeatureProto(feature);
Obstacle* obstacle_ptr = obstacles_container_ptr->GetObstacle(feature.id());
if (!obstacle_ptr) {
continue;
}
evaluator_manager_->EvaluateObstacle(obstacle_ptr, obstacles_container_ptr);
}
}
bool PredictionComponent::Init() {
component_start_time_ = Clock::NowInSeconds();
container_manager_ = std::make_shared<ContainerManager>();
evaluator_manager_.reset(new EvaluatorManager());
predictor_manager_.reset(new PredictorManager());
scenario_manager_.reset(new ScenarioManager());
PredictionConf prediction_conf;
if (!ComponentBase::GetProtoConfig(&prediction_conf)) {
AERROR << "Unable to load prediction conf file: "
<< ComponentBase::ConfigFilePath();
return false;
}
ADEBUG << "Prediction config file is loaded into: "
<< prediction_conf.ShortDebugString();
if (!MessageProcess::Init(container_manager_.get(), evaluator_manager_.get(),
predictor_manager_.get(), prediction_conf)) {
return false;
}
planning_reader_ = node_->CreateReader<ADCTrajectory>(
prediction_conf.topic_conf().planning_trajectory_topic(), nullptr);
localization_reader_ =
node_->CreateReader<localization::LocalizationEstimate>(
prediction_conf.topic_conf().localization_topic(), nullptr);
storytelling_reader_ = node_->CreateReader<storytelling::Stories>(
prediction_conf.topic_conf().storytelling_topic(), nullptr);
prediction_writer_ = node_->CreateWriter<PredictionObstacles>(
prediction_conf.topic_conf().prediction_topic());
container_writer_ = node_->CreateWriter<SubmoduleOutput>(
prediction_conf.topic_conf().container_topic_name());
adc_container_writer_ = node_->CreateWriter<ADCTrajectoryContainer>(
prediction_conf.topic_conf().adccontainer_topic_name());
perception_obstacles_writer_ = node_->CreateWriter<PerceptionObstacles>(
prediction_conf.topic_conf().perception_obstacles_topic_name());
return true;
}
bool PredictionComponent::Proc(
const std::shared_ptr<PerceptionObstacles>& perception_obstacles) {
if (FLAGS_use_lego) {
return ContainerSubmoduleProcess(perception_obstacles);
}
return PredictionEndToEndProc(perception_obstacles);
}
bool PredictionComponent::ContainerSubmoduleProcess(
const std::shared_ptr<PerceptionObstacles>& perception_obstacles) {
constexpr static size_t kHistorySize = 10;
const auto frame_start_time = Clock::Now();
// Read localization info. and call OnLocalization to update
// the PoseContainer.
localization_reader_->Observe();
auto ptr_localization_msg = localization_reader_->GetLatestObserved();
if (ptr_localization_msg == nullptr) {
AERROR << "Prediction: cannot receive any localization message.";
return false;
}
MessageProcess::OnLocalization(container_manager_.get(),
*ptr_localization_msg);
// Read planning info. of last frame and call OnPlanning to update
// the ADCTrajectoryContainer
planning_reader_->Observe();
auto ptr_trajectory_msg = planning_reader_->GetLatestObserved();
if (ptr_trajectory_msg != nullptr) {
MessageProcess::OnPlanning(container_manager_.get(), *ptr_trajectory_msg);
}
// Read storytelling message and call OnStorytelling to update the
// StoryTellingContainer
storytelling_reader_->Observe();
auto ptr_storytelling_msg = storytelling_reader_->GetLatestObserved();
if (ptr_storytelling_msg != nullptr) {
MessageProcess::OnStoryTelling(container_manager_.get(),
*ptr_storytelling_msg);
}
MessageProcess::ContainerProcess(container_manager_, *perception_obstacles,
scenario_manager_.get());
auto obstacles_container_ptr =
container_manager_->GetContainer<ObstaclesContainer>(
AdapterConfig::PERCEPTION_OBSTACLES);
CHECK_NOTNULL(obstacles_container_ptr);
auto adc_trajectory_container_ptr =
container_manager_->GetContainer<ADCTrajectoryContainer>(
AdapterConfig::PLANNING_TRAJECTORY);
CHECK_NOTNULL(adc_trajectory_container_ptr);
SubmoduleOutput submodule_output =
obstacles_container_ptr->GetSubmoduleOutput(kHistorySize,
frame_start_time);
submodule_output.set_curr_scenario(scenario_manager_->scenario());
container_writer_->Write(submodule_output);
adc_container_writer_->Write(*adc_trajectory_container_ptr);
perception_obstacles_writer_->Write(*perception_obstacles);
return true;
}
bool PredictionComponent::PredictionEndToEndProc(
const std::shared_ptr<PerceptionObstacles>& perception_obstacles) {
if (FLAGS_prediction_test_mode &&
(Clock::NowInSeconds() - component_start_time_ >
FLAGS_prediction_test_duration)) {
ADEBUG << "Prediction finished running in test mode";
}
// Update relative map if needed
if (FLAGS_use_navigation_mode && !PredictionMap::Ready()) {
AERROR << "Relative map is empty.";
return false;
}
frame_start_time_ = Clock::NowInSeconds();
auto end_time1 = std::chrono::system_clock::now();
// Read localization info. and call OnLocalization to update
// the PoseContainer.
localization_reader_->Observe();
auto ptr_localization_msg = localization_reader_->GetLatestObserved();
if (ptr_localization_msg == nullptr) {
AERROR << "Prediction: cannot receive any localization message.";
return false;
}
MessageProcess::OnLocalization(container_manager_.get(),
*ptr_localization_msg);
auto end_time2 = std::chrono::system_clock::now();
std::chrono::duration<double> diff = end_time2 - end_time1;
ADEBUG << "Time for updating PoseContainer: " << diff.count() * 1000
<< " msec.";
// Read storytelling message and call OnStorytelling to update the
// StoryTellingContainer
storytelling_reader_->Observe();
auto ptr_storytelling_msg = storytelling_reader_->GetLatestObserved();
if (ptr_storytelling_msg != nullptr) {
MessageProcess::OnStoryTelling(container_manager_.get(),
*ptr_storytelling_msg);
}
// Read planning info. of last frame and call OnPlanning to update
// the ADCTrajectoryContainer
planning_reader_->Observe();
auto ptr_trajectory_msg = planning_reader_->GetLatestObserved();
if (ptr_trajectory_msg != nullptr) {
MessageProcess::OnPlanning(container_manager_.get(), *ptr_trajectory_msg);
}
auto end_time3 = std::chrono::system_clock::now();
diff = end_time3 - end_time2;
ADEBUG << "Time for updating ADCTrajectoryContainer: " << diff.count() * 1000
<< " msec.";
// Get all perception_obstacles of this frame and call OnPerception to
// process them all.
auto perception_msg = *perception_obstacles;
PredictionObstacles prediction_obstacles;
MessageProcess::OnPerception(
perception_msg, container_manager_, evaluator_manager_.get(),
predictor_manager_.get(), scenario_manager_.get(), &prediction_obstacles);
auto end_time4 = std::chrono::system_clock::now();
diff = end_time4 - end_time3;
ADEBUG << "Time for updating PerceptionContainer: " << diff.count() * 1000
<< " msec.";
// Postprocess prediction obstacles message
prediction_obstacles.set_start_timestamp(frame_start_time_);
prediction_obstacles.set_end_timestamp(Clock::NowInSeconds());
prediction_obstacles.mutable_header()->set_lidar_timestamp(
perception_msg.header().lidar_timestamp());
prediction_obstacles.mutable_header()->set_camera_timestamp(
perception_msg.header().camera_timestamp());
prediction_obstacles.mutable_header()->set_radar_timestamp(
perception_msg.header().radar_timestamp());
prediction_obstacles.set_perception_error_code(perception_msg.error_code());
if (FLAGS_prediction_test_mode) {
for (auto const& prediction_obstacle :
prediction_obstacles.prediction_obstacle()) {
for (auto const& trajectory : prediction_obstacle.trajectory()) {
for (auto const& trajectory_point : trajectory.trajectory_point()) {
if (!ValidationChecker::ValidTrajectoryPoint(trajectory_point)) {
AERROR << "Invalid trajectory point ["
<< trajectory_point.ShortDebugString() << "]";
break;
}
}
}
}
}
auto end_time5 = std::chrono::system_clock::now();
diff = end_time5 - end_time1;
ADEBUG << "End to end time elapsed: " << diff.count() * 1000 << " msec.";
// Publish output
common::util::FillHeader(node_->Name(), &prediction_obstacles);
prediction_writer_->Write(prediction_obstacles);
return true;
}
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules
|
apollo_public_repos/apollo/modules/prediction/BUILD
|
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library", "cc_test")
load("//tools/install:install.bzl", "install", "install_files", "install_src_files")
load("//tools:cpplint.bzl", "cpplint")
package(default_visibility = ["//visibility:public"])
PREDICTION_COPTS = ["-DMODULE_NAME=\\\"prediction\\\""]
install(
name = "prediction_testdata_install",
data_dest = "prediction/addition_data",
data = [":prediction_testdata"],
)
cc_library(
name = "prediction_component_lib",
srcs = ["prediction_component.cc"],
hdrs = ["prediction_component.h"],
copts = PREDICTION_COPTS,
deps = [
"//cyber",
"//modules/common/adapters:adapter_gflags",
"//modules/prediction/common:message_process",
"//modules/prediction/evaluator:evaluator_manager",
"//modules/prediction/predictor:predictor_manager",
"//modules/prediction/proto:offline_features_cc_proto",
"//modules/prediction/scenario:scenario_manager",
"//modules/prediction/submodules:evaluator_submodule_lib",
"//modules/prediction/submodules:predictor_submodule_lib",
"//modules/prediction/submodules:submodule_output",
"//modules/common/util:util_tool",
],
alwayslink = True,
)
cc_test(
name = "prediction_component_test",
size = "small",
srcs = ["prediction_component_test.cc"],
data = [
":prediction_conf",
":prediction_data",
":prediction_testdata",
],
linkopts = [
"-lgomp",
],
deps = [
":prediction_component_lib",
],
linkstatic = True,
)
cc_binary(
name = "libprediction_component.so",
linkshared = True,
linkstatic = True,
deps = [":prediction_component_lib"],
)
install(
name = "install",
library_dest = "prediction/lib",
data_dest = "prediction",
data = [
":runtime_data",
":cyberfile.xml",
":prediction.BUILD",
],
targets = [
":libprediction_component.so",
],
deps = [
":pb_hdrs",
"//modules/prediction/pipeline:install",
"//modules/prediction/common:install",
"//modules/prediction/submodules:install",
":prediction_testdata_install",
"//modules/prediction/proto:py_pb_prediction",
],
)
install(
name = "pb_hdrs",
data_dest = "prediction/include",
data = [
"//modules/prediction/proto:fnn_model_base_cc_proto",
"//modules/prediction/proto:fnn_vehicle_model_cc_proto",
"//modules/prediction/proto:network_layers_cc_proto",
"//modules/prediction/proto:network_model_cc_proto",
"//modules/prediction/proto:offline_features_cc_proto",
"//modules/prediction/proto:prediction_conf_cc_proto",
"//modules/prediction/proto:vector_net_cc_proto",
],
)
install_src_files(
name = "install_src",
deps = [
":install_prediction_src",
":install_prediction_hdrs"
],
)
install_src_files(
name = "install_prediction_src",
src_dir = ["."],
dest = "prediction/src",
filter = "*",
)
install_src_files(
name = "install_prediction_hdrs",
src_dir = ["."],
dest = "prediction/include",
filter = "*.h",
)
filegroup(
name = "runtime_data",
srcs = [
":prediction_data",
":prediction_conf",
] + glob([
"dag/*.dag",
"launch/*.launch",
]),
)
filegroup(
name = "prediction_data",
srcs = glob([
"data/*.pt",
"data/*.bin",
]),
)
filegroup(
name = "prediction_conf",
srcs = glob([
"conf/*.conf",
"conf/*.txt",
]),
)
filegroup(
name = "prediction_testdata",
srcs = glob(["testdata/**"]),
)
cpplint()
| 0
|
apollo_public_repos/apollo/modules/prediction
|
apollo_public_repos/apollo/modules/prediction/testdata/perception_vehicles_pedestrians.pb.txt
|
header {
timestamp_sec: 1501183430.161906
module_name: "perception"
sequence_num: 15839
}
perception_obstacle {
id: 0
position {
x: -449.952,
y: -161.917,
z: 0.0
}
theta: -0.349
velocity {
x: 18.794
y: -6.839
z: 0
}
length: 4
width: 2
height: 1
tracking_time: 1
type: VEHICLE
timestamp: 1501183430.1619561
}
perception_obstacle {
id: 1
position {
x: -458.941,
y: -159.240,
z: 0.0
}
theta: -0.349
velocity {
x: 18.794
y: -6.839
z: 0
}
length: 4
width: 2
height: 1
tracking_time: 1
type: VEHICLE
timestamp: 1501183430.1619561
}
perception_obstacle {
id: 2
position {
x: -469.239,
y: -156.665,
z: 0.0
}
theta: -0.349
velocity {
x: 18.794
y: -6.839
z: 0
}
length: 4
width: 2
height: 1
tracking_time: 1
type: VEHICLE
timestamp: 1501183430.1619561
}
perception_obstacle {
id: 3
position {
x: -461.000,
y: -155.018,
z: 0.0
}
theta: -0.349
velocity {
x: 18.794
y: -6.839
z: 0
}
length: 4
width: 2
height: 1
tracking_time: 1
type: VEHICLE
timestamp: 1501183430.1619561
}
perception_obstacle {
id: 101
position {
x: -438.879,
y: -161.931,
z: 0.0
}
theta: 1.222
velocity {
x: 1.710
y: 4.699
z: 0
}
length: 0.5
width: 0.5
height: 1.8
tracking_time: 1
type: PEDESTRIAN
timestamp: 1501183430.161906
}
perception_obstacle {
id: 102
position {
x: -411.557,
y: -182.382,
z: 0.0
}
theta: -0.200
velocity {
x: 0.001
y: 0.001
z: 0
}
length: 0.5
width: 0.5
height: 1.6
tracking_time: 1
type: PEDESTRIAN
timestamp: 1501183430.161906
}
| 0
|
apollo_public_repos/apollo/modules/prediction
|
apollo_public_repos/apollo/modules/prediction/testdata/single_perception_vehicle_injunction.pb.txt
|
header {
timestamp_sec: 1501183430.161906
module_name: "perception"
sequence_num: 15839
}
perception_obstacle {
id: 1
position {
x: -433.500,
y: -166.300,
z: 0.0
}
theta: -0.349
velocity {
x: 18.794
y: -6.839
z: 0
}
length: 4
width: 2
height: 1
tracking_time: 1
type: VEHICLE
timestamp: 1501183430.1619561
}
| 0
|
apollo_public_repos/apollo/modules/prediction
|
apollo_public_repos/apollo/modules/prediction/testdata/single_perception_cyclist_onlane.pb.txt
|
header {
timestamp_sec: 1501183430.161906
module_name: "perception"
sequence_num: 15839
}
perception_obstacle {
id: 1
position {
x: -458.941,
y: -159.240,
z: 0.0
}
theta: -0.349
velocity {
x: 18.794
y: -6.839
z: 0
}
length: 4
width: 2
height: 1
tracking_time: 1
type: BICYCLE
timestamp: 1501183430.1619561
}
| 0
|
apollo_public_repos/apollo/modules/prediction
|
apollo_public_repos/apollo/modules/prediction/testdata/adapter_conf.pb.txt
|
config {
type: PERCEPTION_OBSTACLES
mode: RECEIVE_ONLY
message_history_limit: 1
}
config {
type: LOCALIZATION
mode: RECEIVE_ONLY
message_history_limit: 10
}
config {
type: PREDICTION
mode: PUBLISH_ONLY
message_history_limit: 10
}
is_ros: true
| 0
|
apollo_public_repos/apollo/modules/prediction
|
apollo_public_repos/apollo/modules/prediction/testdata/single_perception_vehicle_offlane.pb.txt
|
header {
timestamp_sec: 1501183430.161906
module_name: "perception"
sequence_num: 15839
}
perception_obstacle {
id: 15
position {
x: -438.614,
y: -173.366,
z: 0.0
}
theta: -0.349
velocity {
x: 6.839
y: 18.794
z: 0
}
length: 4
width: 2
height: 1
tracking_time: 1
type: VEHICLE
timestamp: 1501183430.1619561
}
| 0
|
apollo_public_repos/apollo/modules/prediction
|
apollo_public_repos/apollo/modules/prediction/testdata/single_perception_vehicle_onlane.pb.txt
|
header {
timestamp_sec: 1501183430.161906
module_name: "perception"
sequence_num: 15839
}
perception_obstacle {
id: 1
position {
x: -458.941,
y: -159.240,
z: 0.0
}
theta: -0.349
velocity {
x: 18.794
y: -6.839
z: 0
}
length: 4
width: 2
height: 1
tracking_time: 1
type: VEHICLE
timestamp: 1501183430.1619561
}
| 0
|
apollo_public_repos/apollo/modules/prediction
|
apollo_public_repos/apollo/modules/prediction/testdata/multiple_perception_pedestrians.pb.txt
|
header {
timestamp_sec: 1501183430.161906
module_name: "perception"
sequence_num: 15839
}
perception_obstacle {
id: 101
position {
x: -438.879,
y: -161.931,
z: 0.0
}
theta: 1.222
velocity {
x: 1.710
y: 4.699
z: 0
}
length: 0.5
width: 0.5
height: 1.8
tracking_time: 1
type: PEDESTRIAN
timestamp: 1501183430.161906
}
perception_obstacle {
id: 102
position {
x: -411.557,
y: -182.382,
z: 0.0
}
theta: -0.200
velocity {
x: 0.001
y: 0.001
z: 0
}
length: 0.5
width: 0.5
height: 1.6
tracking_time: 1
type: PEDESTRIAN
timestamp: 1501183430.161906
}
| 0
|
apollo_public_repos/apollo/modules/prediction
|
apollo_public_repos/apollo/modules/prediction/testdata/prediction_conf.pb.txt
|
obstacle_conf {
obstacle_type: VEHICLE
obstacle_status: ON_LANE
evaluator_type: MLP_EVALUATOR
predictor_type: LANE_SEQUENCE_PREDICTOR
}
obstacle_conf {
obstacle_type: VEHICLE
obstacle_status: OFF_LANE
predictor_type: FREE_MOVE_PREDICTOR
}
obstacle_conf {
obstacle_type: PEDESTRIAN
predictor_type: REGIONAL_PREDICTOR
}
| 0
|
apollo_public_repos/apollo/modules/prediction/testdata
|
apollo_public_repos/apollo/modules/prediction/testdata/frame_sequence/frame_1.pb.txt
|
header {
timestamp_sec: 0.0
module_name: "perception"
sequence_num: 0
}
perception_obstacle {
id: 1
position {
x: -458.941,
y: -159.240,
z: 0.0
}
theta: -0.349
velocity {
x: 18.794
y: -6.839
z: 0
}
length: 4
width: 2
height: 1
tracking_time: 1
type: VEHICLE
timestamp: 0.0
}
perception_obstacle {
id: 101
position {
x: -438.879,
y: -161.931,
z: 0.0
}
theta: 1.222
velocity {
x: 1.710
y: 4.699
z: 0
}
length: 0.5
width: 0.5
height: 1.8
tracking_time: 1
type: PEDESTRIAN
timestamp: 0.0
}
| 0
|
apollo_public_repos/apollo/modules/prediction/testdata
|
apollo_public_repos/apollo/modules/prediction/testdata/frame_sequence/frame_3.pb.txt
|
header {
timestamp_sec: 0.2
module_name: "perception"
sequence_num: 2
}
perception_obstacle {
id: 1
position {
x: -455.182,
y: -160.608,
z: 0.0
}
theta: -0.352
velocity {
x: 17.994
y: -6.839
z: 0
}
length: 4
width: 2
height: 1
tracking_time: 1
type: VEHICLE
timestamp: 0.2
}
perception_obstacle {
id: 101
position {
x: -438.537,
y: -160.991,
z: 0.0
}
theta: 1.220
velocity {
x: 1.710
y: 4.699
z: 0
}
length: 0.5
width: 0.5
height: 1.8
tracking_time: 1
type: PEDESTRIAN
timestamp: 0.2
}
| 0
|
apollo_public_repos/apollo/modules/prediction/testdata
|
apollo_public_repos/apollo/modules/prediction/testdata/frame_sequence/frame_2.pb.txt
|
header {
timestamp_sec: 0.1
module_name: "perception"
sequence_num: 1
}
perception_obstacle {
id: 1
position {
x: -457.010,
y: -160.023,
z: 0.0
}
theta: -0.352
velocity {
x: 17.994
y: -6.839
z: 0
}
length: 4
width: 2
height: 1
tracking_time: 1
type: VEHICLE
timestamp: 0.1
}
perception_obstacle {
id: 101
position {
x: -438.610,
y: -161.521,
z: 0.0
}
theta: 1.220
velocity {
x: 1.710
y: 4.699
z: 0
}
length: 0.5
width: 0.5
height: 1.8
tracking_time: 1
type: PEDESTRIAN
timestamp: 0.1
}
| 0
|
apollo_public_repos/apollo/modules/prediction
|
apollo_public_repos/apollo/modules/prediction/evaluator/evaluator.h
|
/******************************************************************************
* 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.
*****************************************************************************/
/**
* @file
* @brief Define the data container base class
*/
#pragma once
#include <string>
#include <utility>
#include <vector>
#include "modules/prediction/container/obstacles/obstacle.h"
#include "modules/prediction/container/obstacles/obstacles_container.h"
#include "modules/prediction/container/adc_trajectory/adc_trajectory_container.h"
/**
* @namespace apollo::prediction
* @brief apollo::prediction
*/
namespace apollo {
namespace prediction {
class Evaluator {
public:
/**
* @brief Constructor
*/
Evaluator() = default;
/**
* @brief Destructor
*/
virtual ~Evaluator() = default;
// TODO(all): Need to merge the following two functions into a single one.
// Can try using proto to pass static/dynamic env info.
/**
* @brief Evaluate an obstacle
* @param Obstacle pointer
* @param Obstacles container
*/
virtual bool Evaluate(Obstacle* obstacle,
ObstaclesContainer* obstacles_container) = 0;
/**
* @brief Evaluate an obstacle
* @param Obstacle pointer
* @param Obstacles container
* @param vector of all Obstacles
*/
virtual bool Evaluate(Obstacle* obstacle,
ObstaclesContainer* obstacles_container,
std::vector<Obstacle*> dynamic_env) {
return Evaluate(obstacle, obstacles_container);
}
/**
* @brief Evaluate an obstacle
* @param ADC trajectory container
* @param Obstacle pointer
* @param Obstacles container
*/
virtual bool Evaluate(const ADCTrajectoryContainer* adc_trajectory_container,
Obstacle* obstacle,
ObstaclesContainer* obstacles_container) {
return Evaluate(obstacle, obstacles_container);
}
/**
* @brief Get the name of evaluator
*/
virtual std::string GetName() = 0;
protected:
// Helper function to convert world coordinates to relative coordinates
// around the obstacle of interest.
std::pair<double, double> WorldCoordToObjCoord(
std::pair<double, double> input_world_coord,
std::pair<double, double> obj_world_coord, double obj_world_angle) {
double x_diff = input_world_coord.first - obj_world_coord.first;
double y_diff = input_world_coord.second - obj_world_coord.second;
double rho = std::sqrt(x_diff * x_diff + y_diff * y_diff);
double theta = std::atan2(y_diff, x_diff) - obj_world_angle;
return std::make_pair(std::cos(theta) * rho, std::sin(theta) * rho);
}
std::pair<double, double> WorldCoordToObjCoordNorth(
std::pair<double, double> input_world_coord,
std::pair<double, double> obj_world_coord, double obj_world_angle) {
double x_diff = input_world_coord.first - obj_world_coord.first;
double y_diff = input_world_coord.second - obj_world_coord.second;
double theta = M_PI / 2 - obj_world_angle;
double x = std::cos(theta) * x_diff - std::sin(theta) * y_diff;
double y = std::sin(theta) * x_diff + std::cos(theta) * y_diff;
return std::make_pair(x, y);
}
double WorldAngleToObjAngle(double input_world_angle,
double obj_world_angle) {
return common::math::NormalizeAngle(input_world_angle - obj_world_angle);
}
Eigen::MatrixXf VectorToMatrixXf(const std::vector<double>& nums,
const int start_index, const int end_index) {
CHECK_LT(start_index, end_index);
CHECK_GE(start_index, 0);
CHECK_LE(end_index, static_cast<int>(nums.size()));
Eigen::MatrixXf output_matrix;
output_matrix.resize(1, end_index - start_index);
for (int i = start_index; i < end_index; ++i) {
output_matrix(0, i - start_index) = static_cast<float>(nums[i]);
}
return output_matrix;
}
Eigen::MatrixXf VectorToMatrixXf(const std::vector<double>& nums,
const int start_index, const int end_index,
const int output_num_row,
const int output_num_col) {
CHECK_LT(start_index, end_index);
CHECK_GE(start_index, 0);
CHECK_LE(end_index, static_cast<int>(nums.size()));
CHECK_EQ(end_index - start_index, output_num_row * output_num_col);
Eigen::MatrixXf output_matrix;
output_matrix.resize(output_num_row, output_num_col);
int input_index = start_index;
for (int i = 0; i < output_num_row; ++i) {
for (int j = 0; j < output_num_col; ++j) {
output_matrix(i, j) = static_cast<float>(nums[input_index]);
++input_index;
}
}
CHECK_EQ(input_index, end_index);
return output_matrix;
}
protected:
ObstacleConf::EvaluatorType evaluator_type_;
};
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/prediction
|
apollo_public_repos/apollo/modules/prediction/evaluator/evaluator_manager.h
|
/******************************************************************************
* 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.
*****************************************************************************/
/**
* @file
* @brief Use evaluator manager to manage all evaluators
*/
#pragma once
#include <list>
#include <map>
#include <memory>
#include <unordered_map>
#include <vector>
#include "cyber/common/macros.h"
#include "modules/prediction/common/semantic_map.h"
#include "modules/prediction/evaluator/evaluator.h"
#include "modules/prediction/proto/prediction_conf.pb.h"
#include "modules/prediction/pipeline/vector_net.h"
/**
* @namespace apollo::prediction
* @brief apollo::prediction
*/
namespace apollo {
namespace prediction {
class EvaluatorManager {
public:
/**
* @brief Constructor
*/
EvaluatorManager();
/**
* @brief Destructor
*/
virtual ~EvaluatorManager() = default;
/**
* @brief Initializer
* @param Prediction config
*/
void Init(const PredictionConf& config);
/**
* @brief Get evaluator
* @return Pointer to the evaluator
*/
Evaluator* GetEvaluator(const ObstacleConf::EvaluatorType& type);
/**
* @brief Run evaluators
*/
void Run(const ADCTrajectoryContainer* adc_trajectory_container,
ObstaclesContainer* obstacles_container);
void EvaluateObstacle(const ADCTrajectoryContainer* adc_trajectory_container,
Obstacle* obstacle,
ObstaclesContainer* obstacles_container,
std::vector<Obstacle*> dynamic_env);
void EvaluateObstacle(Obstacle* obstacle,
ObstaclesContainer* obstacles_container);
private:
void BuildObstacleIdHistoryMap(ObstaclesContainer* obstacles_container,
size_t max_num_frame);
void DumpCurrentFrameEnv(ObstaclesContainer* obstacles_container);
/**
* @brief Register an evaluator by type
* @param Evaluator type
*/
void RegisterEvaluator(const ObstacleConf::EvaluatorType& type);
/**
* @brief Create an evaluator by type
* @param Evaluator type
* @return A unique pointer to the evaluator
*/
std::unique_ptr<Evaluator> CreateEvaluator(
const ObstacleConf::EvaluatorType& type);
/**
* @brief Register all evaluators
*/
void RegisterEvaluators();
private:
std::map<ObstacleConf::EvaluatorType, std::unique_ptr<Evaluator>> evaluators_;
ObstacleConf::EvaluatorType vehicle_on_lane_evaluator_ =
ObstacleConf::CRUISE_MLP_EVALUATOR;
ObstacleConf::EvaluatorType vehicle_on_lane_caution_evaluator_ =
ObstacleConf::CRUISE_MLP_EVALUATOR;
ObstacleConf::EvaluatorType vehicle_in_junction_evaluator_ =
ObstacleConf::JUNCTION_MLP_EVALUATOR;
ObstacleConf::EvaluatorType vehicle_in_junction_caution_evaluator_ =
ObstacleConf::JUNCTION_MAP_EVALUATOR;
ObstacleConf::EvaluatorType vehicle_default_caution_evaluator_ =
ObstacleConf::SEMANTIC_LSTM_EVALUATOR;
ObstacleConf::EvaluatorType cyclist_on_lane_evaluator_ =
ObstacleConf::CYCLIST_KEEP_LANE_EVALUATOR;
ObstacleConf::EvaluatorType pedestrian_evaluator_ =
ObstacleConf::SEMANTIC_LSTM_EVALUATOR;
ObstacleConf::EvaluatorType vectornet_evaluator_ =
ObstacleConf::VECTORNET_EVALUATOR;
ObstacleConf::EvaluatorType default_on_lane_evaluator_ =
ObstacleConf::MLP_EVALUATOR;
ObstacleConf::EvaluatorType interaction_evaluator_ =
ObstacleConf::JOINTLY_PREDICTION_PLANNING_EVALUATOR;
std::unordered_map<int, ObstacleHistory> obstacle_id_history_map_;
std::unique_ptr<SemanticMap> semantic_map_;
};
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/prediction
|
apollo_public_repos/apollo/modules/prediction/evaluator/evaluator_manager.cc
|
/******************************************************************************
* 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.
*****************************************************************************/
#include "modules/prediction/evaluator/evaluator_manager.h"
#include <algorithm>
#include "modules/common/configs/vehicle_config_helper.h"
#include "modules/prediction/common/feature_output.h"
#include "modules/prediction/common/prediction_constants.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_system_gflags.h"
#include "modules/prediction/common/prediction_thread_pool.h"
#include "modules/prediction/container/container_manager.h"
#include "modules/prediction/container/obstacles/obstacles_container.h"
#include "modules/prediction/evaluator/cyclist/cyclist_keep_lane_evaluator.h"
#include "modules/prediction/evaluator/vehicle/cost_evaluator.h"
#include "modules/prediction/evaluator/vehicle/cruise_mlp_evaluator.h"
#include "modules/prediction/evaluator/vehicle/junction_map_evaluator.h"
#include "modules/prediction/evaluator/vehicle/junction_mlp_evaluator.h"
#include "modules/prediction/evaluator/vehicle/lane_aggregating_evaluator.h"
#include "modules/prediction/evaluator/vehicle/lane_scanning_evaluator.h"
#include "modules/prediction/evaluator/vehicle/mlp_evaluator.h"
#include "modules/prediction/evaluator/vehicle/semantic_lstm_evaluator.h"
#include "modules/prediction/evaluator/vehicle/jointly_prediction_planning_evaluator.h"
#include "modules/prediction/evaluator/vehicle/vectornet_evaluator.h"
namespace apollo {
namespace prediction {
using apollo::perception::PerceptionObstacle;
using IdObstacleListMap = std::unordered_map<int, std::list<Obstacle*>>;
namespace {
bool IsTrainable(const Feature& feature) {
if (feature.id() == FLAGS_ego_vehicle_id) {
return false;
}
if (feature.priority().priority() == ObstaclePriority::IGNORE ||
feature.is_still() || feature.type() != PerceptionObstacle::VEHICLE) {
return false;
}
return true;
}
void GroupObstaclesByObstacleIds(ObstaclesContainer* const obstacles_container,
IdObstacleListMap* const id_obstacle_map) {
int caution_thread_idx = 0;
for (int obstacle_id :
obstacles_container->curr_frame_considered_obstacle_ids()) {
Obstacle* obstacle_ptr = obstacles_container->GetObstacle(obstacle_id);
if (obstacle_ptr == nullptr) {
AERROR << "Null obstacle [" << obstacle_id << "] found";
continue;
}
if (obstacle_ptr->IsStill()) {
ADEBUG << "Ignore still obstacle [" << obstacle_id << "]";
continue;
}
const Feature& feature = obstacle_ptr->latest_feature();
if (feature.priority().priority() == ObstaclePriority::IGNORE) {
ADEBUG << "Skip ignored obstacle [" << obstacle_id << "]";
continue;
} else if (feature.priority().priority() == ObstaclePriority::CAUTION) {
caution_thread_idx = caution_thread_idx % FLAGS_max_caution_thread_num;
(*id_obstacle_map)[caution_thread_idx].push_back(obstacle_ptr);
ADEBUG << "Cautioned obstacle [" << obstacle_id << "] for thread"
<< caution_thread_idx;
++caution_thread_idx;
} else {
int normal_thread_num =
FLAGS_max_thread_num - FLAGS_max_caution_thread_num;
int id_mod =
obstacle_id % normal_thread_num + FLAGS_max_caution_thread_num;
(*id_obstacle_map)[id_mod].push_back(obstacle_ptr);
ADEBUG << "Normal obstacle [" << obstacle_id << "] for thread" << id_mod;
}
}
}
} // namespace
EvaluatorManager::EvaluatorManager() {}
void EvaluatorManager::RegisterEvaluators() {
RegisterEvaluator(ObstacleConf::MLP_EVALUATOR);
RegisterEvaluator(ObstacleConf::COST_EVALUATOR);
RegisterEvaluator(ObstacleConf::CRUISE_MLP_EVALUATOR);
RegisterEvaluator(ObstacleConf::JUNCTION_MLP_EVALUATOR);
RegisterEvaluator(ObstacleConf::CYCLIST_KEEP_LANE_EVALUATOR);
RegisterEvaluator(ObstacleConf::LANE_SCANNING_EVALUATOR);
RegisterEvaluator(ObstacleConf::LANE_AGGREGATING_EVALUATOR);
RegisterEvaluator(ObstacleConf::JUNCTION_MAP_EVALUATOR);
RegisterEvaluator(ObstacleConf::SEMANTIC_LSTM_EVALUATOR);
RegisterEvaluator(ObstacleConf::JOINTLY_PREDICTION_PLANNING_EVALUATOR);
RegisterEvaluator(ObstacleConf::VECTORNET_EVALUATOR);
}
void EvaluatorManager::Init(const PredictionConf& config) {
if (FLAGS_enable_semantic_map) {
semantic_map_.reset(new SemanticMap());
semantic_map_->Init();
ADEBUG << "Init SemanticMap instance.";
}
RegisterEvaluators();
for (const auto& obstacle_conf : config.obstacle_conf()) {
if (!obstacle_conf.has_obstacle_type()) {
AERROR << "Obstacle config [" << obstacle_conf.ShortDebugString()
<< "] has not defined obstacle type.";
continue;
}
if (!obstacle_conf.has_evaluator_type()) {
ADEBUG << "Obstacle config [" << obstacle_conf.ShortDebugString()
<< "] has not defined evaluator type.";
continue;
}
if (obstacle_conf.has_obstacle_status()) {
switch (obstacle_conf.obstacle_type()) {
case PerceptionObstacle::VEHICLE: {
if (obstacle_conf.obstacle_status() == ObstacleConf::ON_LANE) {
if (obstacle_conf.priority_type() == ObstaclePriority::CAUTION) {
vehicle_on_lane_caution_evaluator_ =
obstacle_conf.evaluator_type();
} else {
vehicle_on_lane_evaluator_ = obstacle_conf.evaluator_type();
}
}
if (obstacle_conf.obstacle_status() == ObstacleConf::IN_JUNCTION) {
if (obstacle_conf.priority_type() == ObstaclePriority::CAUTION) {
vehicle_in_junction_caution_evaluator_ =
obstacle_conf.evaluator_type();
} else {
vehicle_in_junction_evaluator_ = obstacle_conf.evaluator_type();
}
}
break;
}
case PerceptionObstacle::BICYCLE: {
if (obstacle_conf.obstacle_status() == ObstacleConf::ON_LANE) {
cyclist_on_lane_evaluator_ = obstacle_conf.evaluator_type();
}
break;
}
case PerceptionObstacle::PEDESTRIAN: {
if (FLAGS_prediction_offline_mode ==
PredictionConstants::kDumpDataForLearning ||
obstacle_conf.priority_type() == ObstaclePriority::CAUTION) {
pedestrian_evaluator_ = obstacle_conf.evaluator_type();
break;
}
}
case PerceptionObstacle::UNKNOWN: {
if (obstacle_conf.obstacle_status() == ObstacleConf::ON_LANE) {
default_on_lane_evaluator_ = obstacle_conf.evaluator_type();
}
break;
}
default: {
break;
}
}
} else if (obstacle_conf.has_interactive_tag()) {
interaction_evaluator_ = obstacle_conf.evaluator_type();
}
}
AINFO << "Defined vehicle on lane obstacle evaluator ["
<< vehicle_on_lane_evaluator_ << "]";
AINFO << "Defined cyclist on lane obstacle evaluator ["
<< cyclist_on_lane_evaluator_ << "]";
AINFO << "Defined default on lane obstacle evaluator ["
<< default_on_lane_evaluator_ << "]";
}
Evaluator* EvaluatorManager::GetEvaluator(
const ObstacleConf::EvaluatorType& type) {
auto it = evaluators_.find(type);
return it != evaluators_.end() ? it->second.get() : nullptr;
}
void EvaluatorManager::Run(
const ADCTrajectoryContainer* adc_trajectory_container,
ObstaclesContainer* obstacles_container) {
if (FLAGS_enable_semantic_map ||
FLAGS_prediction_offline_mode == PredictionConstants::kDumpFrameEnv) {
size_t max_num_frame = 10;
if (FLAGS_prediction_offline_mode == PredictionConstants::kDumpFrameEnv) {
max_num_frame = 20;
}
BuildObstacleIdHistoryMap(obstacles_container, max_num_frame);
DumpCurrentFrameEnv(obstacles_container);
if (FLAGS_prediction_offline_mode == PredictionConstants::kDumpFrameEnv) {
return;
}
semantic_map_->RunCurrFrame(obstacle_id_history_map_);
}
std::vector<Obstacle*> dynamic_env;
if (FLAGS_enable_multi_thread) {
IdObstacleListMap id_obstacle_map;
GroupObstaclesByObstacleIds(obstacles_container, &id_obstacle_map);
PredictionThreadPool::ForEach(
id_obstacle_map.begin(), id_obstacle_map.end(),
[&](IdObstacleListMap::iterator::value_type& obstacles_iter) {
for (auto obstacle_ptr : obstacles_iter.second) {
EvaluateObstacle(adc_trajectory_container, obstacle_ptr,
obstacles_container, dynamic_env);
}
});
} else {
for (int id : obstacles_container->curr_frame_considered_obstacle_ids()) {
Obstacle* obstacle = obstacles_container->GetObstacle(id);
if (obstacle == nullptr) {
continue;
}
if (obstacle->IsStill()) {
ADEBUG << "Ignore still obstacle [" << id << "] in evaluator_manager";
continue;
}
EvaluateObstacle(adc_trajectory_container, obstacle,
obstacles_container, dynamic_env);
}
}
}
void EvaluatorManager::EvaluateObstacle(
const ADCTrajectoryContainer* adc_trajectory_container,
Obstacle* obstacle,
ObstaclesContainer* obstacles_container,
std::vector<Obstacle*> dynamic_env) {
Evaluator* evaluator = nullptr;
// Select different evaluators depending on the obstacle's type.
switch (obstacle->type()) {
case PerceptionObstacle::VEHICLE: {
if (obstacle->IsCaution() && !obstacle->IsSlow()) {
if (obstacle->IsInteractiveObstacle()) {
evaluator = GetEvaluator(interaction_evaluator_);
} else if (obstacle->IsNearJunction()) {
evaluator = GetEvaluator(vehicle_in_junction_caution_evaluator_);
} else if (obstacle->IsOnLane()) {
evaluator = GetEvaluator(vehicle_on_lane_caution_evaluator_);
} else {
evaluator = GetEvaluator(vehicle_default_caution_evaluator_);
}
CHECK_NOTNULL(evaluator);
// Evaluate and break if success
if (evaluator->GetName() == "JOINTLY_PREDICTION_PLANNING_EVALUATOR") {
if (evaluator->Evaluate(adc_trajectory_container,
obstacle, obstacles_container)) {
break;
} else {
AERROR << "Obstacle: " << obstacle->id()
<< " interaction evaluator failed,"
<< " downgrade to normal level!";
}
} else {
if (evaluator->Evaluate(obstacle, obstacles_container)) {
break;
} else {
AERROR << "Obstacle: " << obstacle->id()
<< " caution evaluator failed, downgrade to normal level!";
}
}
}
// if obstacle is not caution or caution_evaluator run failed
if (obstacle->HasJunctionFeatureWithExits() &&
!obstacle->IsCloseToJunctionExit()) {
evaluator = GetEvaluator(vehicle_in_junction_evaluator_);
} else if (obstacle->IsOnLane()) {
evaluator = GetEvaluator(vehicle_on_lane_evaluator_);
} else {
ADEBUG << "Obstacle: " << obstacle->id()
<< " is neither on lane, nor in junction. Skip evaluating.";
break;
}
CHECK_NOTNULL(evaluator);
if (evaluator->GetName() == "LANE_SCANNING_EVALUATOR") {
evaluator->Evaluate(obstacle, obstacles_container, dynamic_env);
} else {
evaluator->Evaluate(obstacle, obstacles_container);
}
break;
}
case PerceptionObstacle::BICYCLE: {
if (obstacle->IsOnLane()) {
evaluator = GetEvaluator(cyclist_on_lane_evaluator_);
CHECK_NOTNULL(evaluator);
evaluator->Evaluate(obstacle, obstacles_container);
}
break;
}
case PerceptionObstacle::PEDESTRIAN: {
if (FLAGS_prediction_offline_mode ==
PredictionConstants::kDumpDataForLearning ||
obstacle->latest_feature().priority().priority() ==
ObstaclePriority::CAUTION) {
evaluator = GetEvaluator(pedestrian_evaluator_);
CHECK_NOTNULL(evaluator);
evaluator->Evaluate(obstacle, obstacles_container);
break;
}
}
default: {
if (obstacle->IsOnLane()) {
evaluator = GetEvaluator(default_on_lane_evaluator_);
CHECK_NOTNULL(evaluator);
evaluator->Evaluate(obstacle, obstacles_container);
}
break;
}
}
}
void EvaluatorManager::EvaluateObstacle(
Obstacle* obstacle, ObstaclesContainer* obstacles_container) {
std::vector<Obstacle*> dummy_dynamic_env;
ADCTrajectoryContainer* adc_trajectory_container = nullptr;
EvaluateObstacle(adc_trajectory_container, obstacle,
obstacles_container, dummy_dynamic_env);
}
void EvaluatorManager::BuildObstacleIdHistoryMap(
ObstaclesContainer* obstacles_container, size_t max_num_frame) {
obstacle_id_history_map_.clear();
std::vector<int> obstacle_ids =
obstacles_container->curr_frame_movable_obstacle_ids();
obstacle_ids.push_back(FLAGS_ego_vehicle_id);
for (int id : obstacle_ids) {
Obstacle* obstacle = obstacles_container->GetObstacle(id);
if (obstacle == nullptr || obstacle->history_size() == 0) {
continue;
}
size_t num_frames = std::min(max_num_frame, obstacle->history_size());
for (size_t i = 0; i < num_frames; ++i) {
const Feature& obstacle_feature = obstacle->feature(i);
Feature feature;
feature.set_id(obstacle_feature.id());
feature.set_timestamp(obstacle_feature.timestamp());
feature.set_type(obstacle_feature.type());
feature.mutable_position()->CopyFrom(obstacle_feature.position());
feature.set_theta(obstacle_feature.velocity_heading());
feature.mutable_interactive_tag()->CopyFrom(
obstacle_feature.interactive_tag());
feature.mutable_priority()->CopyFrom(obstacle_feature.priority());
if (obstacle_feature.id() != FLAGS_ego_vehicle_id) {
feature.mutable_polygon_point()->CopyFrom(
obstacle_feature.polygon_point());
feature.set_length(obstacle_feature.length());
feature.set_width(obstacle_feature.width());
} else {
const auto& vehicle_config =
common::VehicleConfigHelper::Instance()->GetConfig();
feature.set_length(vehicle_config.vehicle_param().length());
feature.set_width(vehicle_config.vehicle_param().width());
}
obstacle_id_history_map_[id].add_feature()->CopyFrom(feature);
}
obstacle_id_history_map_[id].set_is_trainable(
IsTrainable(obstacle->latest_feature()));
}
}
void EvaluatorManager::DumpCurrentFrameEnv(
ObstaclesContainer* obstacles_container) {
FrameEnv curr_frame_env;
curr_frame_env.set_timestamp(obstacles_container->timestamp());
for (const auto obstacle_id_history_pair : obstacle_id_history_map_) {
int id = obstacle_id_history_pair.first;
if (id != FLAGS_ego_vehicle_id) {
curr_frame_env.add_obstacles_history()->CopyFrom(
obstacle_id_history_pair.second);
} else {
curr_frame_env.mutable_ego_history()->CopyFrom(
obstacle_id_history_pair.second);
}
}
FeatureOutput::InsertFrameEnv(curr_frame_env);
}
std::unique_ptr<Evaluator> EvaluatorManager::CreateEvaluator(
const ObstacleConf::EvaluatorType& type) {
std::unique_ptr<Evaluator> evaluator_ptr(nullptr);
switch (type) {
case ObstacleConf::MLP_EVALUATOR: {
evaluator_ptr.reset(new MLPEvaluator());
break;
}
case ObstacleConf::CRUISE_MLP_EVALUATOR: {
evaluator_ptr.reset(new CruiseMLPEvaluator());
break;
}
case ObstacleConf::JUNCTION_MLP_EVALUATOR: {
evaluator_ptr.reset(new JunctionMLPEvaluator());
break;
}
case ObstacleConf::COST_EVALUATOR: {
evaluator_ptr.reset(new CostEvaluator());
break;
}
case ObstacleConf::CYCLIST_KEEP_LANE_EVALUATOR: {
evaluator_ptr.reset(new CyclistKeepLaneEvaluator());
break;
}
case ObstacleConf::LANE_SCANNING_EVALUATOR: {
evaluator_ptr.reset(new LaneScanningEvaluator());
break;
}
case ObstacleConf::LANE_AGGREGATING_EVALUATOR: {
evaluator_ptr.reset(new LaneAggregatingEvaluator());
break;
}
case ObstacleConf::JUNCTION_MAP_EVALUATOR: {
evaluator_ptr.reset(new JunctionMapEvaluator(semantic_map_.get()));
break;
}
case ObstacleConf::SEMANTIC_LSTM_EVALUATOR: {
evaluator_ptr.reset(new SemanticLSTMEvaluator(semantic_map_.get()));
break;
}
case ObstacleConf::JOINTLY_PREDICTION_PLANNING_EVALUATOR: {
evaluator_ptr.reset(new JointlyPredictionPlanningEvaluator());
break;
}
case ObstacleConf::VECTORNET_EVALUATOR: {
evaluator_ptr.reset(new VectornetEvaluator());
break;
}
default: {
break;
}
}
return evaluator_ptr;
}
void EvaluatorManager::RegisterEvaluator(
const ObstacleConf::EvaluatorType& type) {
evaluators_[type] = CreateEvaluator(type);
AINFO << "Evaluator [" << type << "] is registered.";
}
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/prediction
|
apollo_public_repos/apollo/modules/prediction/evaluator/evaluator_manager_test.cc
|
/******************************************************************************
* 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.
*****************************************************************************/
#include "modules/prediction/evaluator/evaluator_manager.h"
#include "cyber/common/file.h"
#include "modules/prediction/common/kml_map_based_test.h"
#include "modules/prediction/container/container_manager.h"
#include "modules/prediction/container/obstacles/obstacles_container.h"
namespace apollo {
namespace prediction {
using apollo::common::adapter::AdapterConfig;
class EvaluatorManagerTest : public KMLMapBasedTest {
public:
virtual void SetUp() {
const std::string file =
"modules/prediction/testdata/single_perception_vehicle_onlane.pb.txt";
ACHECK(cyber::common::GetProtoFromFile(file, &perception_obstacles_));
}
protected:
apollo::perception::PerceptionObstacles perception_obstacles_;
common::adapter::AdapterManagerConfig adapter_conf_;
PredictionConf prediction_conf_;
};
TEST_F(EvaluatorManagerTest, General) {
std::string conf_file = "modules/prediction/testdata/adapter_conf.pb.txt";
bool ret_load_conf =
cyber::common::GetProtoFromFile(conf_file, &adapter_conf_);
EXPECT_TRUE(ret_load_conf);
EXPECT_TRUE(adapter_conf_.IsInitialized());
ContainerManager container_manager;
container_manager.Init(adapter_conf_);
auto adc_trajectory_container =
container_manager.GetContainer<ADCTrajectoryContainer>(
AdapterConfig::PLANNING_TRAJECTORY);
auto obstacles_container =
container_manager.GetContainer<ObstaclesContainer>(
AdapterConfig::PERCEPTION_OBSTACLES);
CHECK_NOTNULL(obstacles_container);
obstacles_container->Insert(perception_obstacles_);
EvaluatorManager evaluator_manager;
evaluator_manager.Init(prediction_conf_);
evaluator_manager.Run(adc_trajectory_container,
obstacles_container);
Obstacle* obstacle_ptr = obstacles_container->GetObstacle(1);
EXPECT_NE(obstacle_ptr, nullptr);
const Feature& feature = obstacle_ptr->latest_feature();
const LaneGraph& lane_graph = feature.lane().lane_graph();
for (const auto& lane_sequence : lane_graph.lane_sequence()) {
EXPECT_TRUE(lane_sequence.has_probability());
}
}
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/prediction
|
apollo_public_repos/apollo/modules/prediction/evaluator/BUILD
|
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test")
load("//tools:cpplint.bzl", "cpplint")
package(default_visibility = ["//visibility:public"])
cc_library(
name = "evaluator_manager",
srcs = ["evaluator_manager.cc"],
hdrs = ["evaluator_manager.h"],
copts = [
"-DMODULE_NAME=\\\"prediction\\\"",
],
deps = [
"//modules/common/configs:vehicle_config_helper",
"//modules/prediction/common:feature_output",
"//modules/prediction/common:prediction_gflags",
"//modules/prediction/common:prediction_thread_pool",
"//modules/prediction/common:semantic_map",
"//modules/prediction/container/obstacles:obstacles_container",
"//modules/prediction/evaluator/cyclist:cyclist_keep_lane_evaluator",
"//modules/prediction/evaluator/vehicle:cost_evaluator",
"//modules/prediction/evaluator/vehicle:cruise_mlp_evaluator",
"//modules/prediction/evaluator/vehicle:junction_map_evaluator",
"//modules/prediction/evaluator/vehicle:junction_mlp_evaluator",
"//modules/prediction/evaluator/vehicle:lane_aggregating_evaluator",
"//modules/prediction/evaluator/vehicle:lane_scanning_evaluator",
"//modules/prediction/evaluator/vehicle:mlp_evaluator",
"//modules/prediction/evaluator/vehicle:semantic_lstm_evaluator",
"//modules/prediction/evaluator/vehicle:jointly_prediction_planning_evaluator",
"//modules/prediction/evaluator/vehicle:vectornet_evaluator",
"//modules/prediction/proto:prediction_conf_cc_proto",
"//modules/prediction/pipeline:vector_net",
"//third_party:libtorch",
]
)
cc_test(
name = "evaluator_manager_test",
size = "small",
srcs = ["evaluator_manager_test.cc"],
data = [
"//modules/prediction:prediction_data",
"//modules/prediction:prediction_testdata",
],
linkopts = [
"-lgomp",
],
deps = [
"//modules/prediction/common:kml_map_based_test",
"//modules/prediction/evaluator:evaluator_manager",
],
linkstatic = True,
)
cc_library(
name = "evaluator",
hdrs = ["evaluator.h"],
deps = [
"//modules/prediction/container/obstacles:obstacle",
"//modules/prediction/container/adc_trajectory:adc_trajectory_container",
],
)
cpplint()
| 0
|
apollo_public_repos/apollo/modules/prediction/evaluator
|
apollo_public_repos/apollo/modules/prediction/evaluator/vehicle/jointly_prediction_planning_evaluator.h
|
/******************************************************************************
* Copyright 2021 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.
*****************************************************************************/
#pragma once
#include <string>
#include <utility>
#include <vector>
#include "modules/prediction/evaluator/evaluator.h"
#include "torch/extension.h"
#include "torch/script.h"
#include "modules/prediction/container/container_manager.h"
#include "modules/prediction/pipeline/vector_net.h"
namespace apollo {
namespace prediction {
using apollo::common::TrajectoryPoint;
class JointlyPredictionPlanningEvaluator : public Evaluator {
public:
/**
* @brief Constructor
*/
JointlyPredictionPlanningEvaluator();
/**
* @brief Destructor
*/
virtual ~JointlyPredictionPlanningEvaluator() = default;
/**
* @brief Clear obstacle feature map
*/
void Clear();
/**
* @brief Process obstacle position to vector
* @param Obstacles pointer
* @param Obstacles container
* @param Tensor: target obstacle position
* @param Tensor: target obstacle position step
* @param Tensor: vector mask
* @param Tensor: all obstacle position
* @param Tensor: all obstacle p_id
* @param Tensor: all obstacle length
*/
bool VectornetProcessObstaclePosition(Obstacle* obstacle_ptr,
ObstaclesContainer* obstacles_container,
torch::Tensor* ptr_target_obs_pos,
torch::Tensor* ptr_target_obs_pos_step,
torch::Tensor* ptr_vector_mask,
torch::Tensor* ptr_all_obstacle_pos,
torch::Tensor* ptr_all_obs_p_id,
torch::Tensor* ptr_obs_length);
/**
* @brief Process map data to vector
* @param FeatureVector: map feature vector
* @param int: obstacle number
* @param PidVector: map p_id vector
* @param Tensor: map data
* @param Tensor: map data p_id
*/
bool VectornetProcessMapData(FeatureVector *map_feature,
PidVector *map_p_id,
const int obs_num,
torch::Tensor* ptr_map_data,
torch::Tensor* ptr_all_map_p_id,
torch::Tensor* ptr_vector_mask);
/**
* @brief Override Evaluate
* @param Obstacle pointer
* @param Obstacles container
*/
bool Evaluate(Obstacle* obstacle_ptr,
ObstaclesContainer* obstacles_container) override;
/**
* @brief Override Evaluate
* @param ADC trajectory container
* @param Obstacle pointer
* @param Obstacles container
*/
bool Evaluate(const ADCTrajectoryContainer* adc_trajectory_container,
Obstacle* obstacle_ptr,
ObstaclesContainer* obstacles_container) override;
/**
* @brief Extract all obstacles history
* @param Obstacles container
* Feature container in a vector for receiving the obstacle history
*/
bool ExtractObstaclesHistory(
Obstacle* obstacle_ptr, ObstaclesContainer* obstacles_container,
std::vector<std::pair<double, double>>* curr_pos_history,
std::vector<std::pair<double, double>>* all_obs_length,
std::vector<std::vector<std::pair<double, double>>>* all_obs_pos_history,
torch::Tensor* vector_mask);
/**
* @brief Extract adc trajectory and convert world coord to obstacle coord
* @param Obstacle pointer
* Feature container in a vector for receiving the obstacle history
*/
bool ExtractADCTrajectory(
std::vector<TrajectoryPoint>* trajectory_points,
Obstacle* obstacle_ptr,
std::vector<std::pair<double, double>>* acd_traj_curr_pos);
/**
* @brief Get the name of evaluator.
*/
std::string GetName() override {
return "JOINTLY_PREDICTION_PLANNING_EVALUATOR";
}
private:
/**
* @brief Load model file
*/
void LoadModel();
private:
torch::jit::script::Module torch_vehicle_model_;
at::Tensor torch_default_output_tensor_;
torch::Device device_;
VectorNet vector_net_;
};
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/prediction/evaluator
|
apollo_public_repos/apollo/modules/prediction/evaluator/vehicle/junction_map_evaluator.h
|
/******************************************************************************
* 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.
*****************************************************************************/
#pragma once
#include <memory>
#include <string>
#include <vector>
#include "modules/prediction/common/semantic_map.h"
#include "modules/prediction/container/obstacles/obstacles_container.h"
#include "modules/prediction/evaluator/evaluator.h"
#include "torch/extension.h"
#include "torch/script.h"
namespace apollo {
namespace prediction {
class JunctionMapEvaluator : public Evaluator {
public:
/**
* @brief Constructor
*/
JunctionMapEvaluator() = delete;
explicit JunctionMapEvaluator(SemanticMap* semantic_map);
/**
* @brief Destructor
*/
virtual ~JunctionMapEvaluator() = default;
/**
* @brief Clear obstacle feature map
*/
void Clear();
/**
* @brief Override Evaluate
* @param Obstacle pointer
* @param Obstacles container
*/
bool Evaluate(Obstacle* obstacle_ptr,
ObstaclesContainer* obstacles_container) override;
/**
* @brief Extract feature vector
* @param Obstacle pointer
* Feature container in a vector for receiving the feature values
*/
bool ExtractFeatureValues(Obstacle* obstacle_ptr,
std::vector<double>* feature_values);
/**
* @brief Get the name of evaluator.
*/
std::string GetName() override { return "JUNCTION_MAP_EVALUATOR"; }
private:
/**
* @brief Load model file
*/
void LoadModel();
private:
// junction exit mask
static const size_t JUNCTION_FEATURE_SIZE = 12;
torch::jit::script::Module torch_model_;
torch::Device device_;
SemanticMap* semantic_map_;
};
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/prediction/evaluator
|
apollo_public_repos/apollo/modules/prediction/evaluator/vehicle/semantic_lstm_evaluator.h
|
/******************************************************************************
* 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.
*****************************************************************************/
#pragma once
#include <string>
#include <utility>
#include <vector>
#include "modules/prediction/common/semantic_map.h"
#include "modules/prediction/evaluator/evaluator.h"
#include "torch/extension.h"
#include "torch/script.h"
namespace apollo {
namespace prediction {
class SemanticLSTMEvaluator : public Evaluator {
public:
/**
* @brief Constructor
*/
SemanticLSTMEvaluator() = delete;
explicit SemanticLSTMEvaluator(SemanticMap* semantic_map);
/**
* @brief Destructor
*/
virtual ~SemanticLSTMEvaluator() = default;
/**
* @brief Clear obstacle feature map
*/
void Clear();
/**
* @brief Override Evaluate
* @param Obstacle pointer
* @param Obstacles container
*/
bool Evaluate(Obstacle* obstacle_ptr,
ObstaclesContainer* obstacles_container) override;
/**
* @brief Extract obstacle history
* @param Obstacle pointer
* Feature container in a vector for receiving the obstacle history
*/
bool ExtractObstacleHistory(
Obstacle* obstacle_ptr,
std::vector<std::pair<double, double>>* pos_history);
/**
* @brief Get the name of evaluator.
*/
std::string GetName() override { return "SEMANTIC_LSTM_EVALUATOR"; }
private:
/**
* @brief Load model file
*/
void LoadModel();
private:
torch::jit::script::Module torch_vehicle_model_;
torch::jit::script::Module torch_pedestrian_model_;
at::Tensor torch_default_output_tensor_;
torch::Device device_;
SemanticMap* semantic_map_;
};
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/prediction/evaluator
|
apollo_public_repos/apollo/modules/prediction/evaluator/vehicle/mlp_evaluator.cc
|
/******************************************************************************
* 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.
*****************************************************************************/
#include "modules/prediction/evaluator/vehicle/mlp_evaluator.h"
#include <limits>
#include "cyber/common/file.h"
#include "modules/prediction/common/feature_output.h"
#include "modules/prediction/common/prediction_constants.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_system_gflags.h"
#include "modules/prediction/common/prediction_util.h"
#include "modules/prediction/common/validation_checker.h"
namespace apollo {
namespace prediction {
namespace {
using apollo::common::math::Sigmoid;
double ComputeMean(const std::vector<double>& nums, size_t start, size_t end) {
int count = 0;
double sum = 0.0;
for (size_t i = start; i <= end && i < nums.size(); i++) {
sum += nums[i];
++count;
}
return (count == 0) ? 0.0 : sum / count;
}
} // namespace
MLPEvaluator::MLPEvaluator() {
evaluator_type_ = ObstacleConf::MLP_EVALUATOR;
LoadModel(FLAGS_evaluator_vehicle_mlp_file);
}
void MLPEvaluator::Clear() {}
bool MLPEvaluator::Evaluate(Obstacle* obstacle_ptr,
ObstaclesContainer* obstacles_container) {
Clear();
CHECK_NOTNULL(obstacle_ptr);
CHECK_LE(LANE_FEATURE_SIZE, 4 * FLAGS_max_num_lane_point);
obstacle_ptr->SetEvaluatorType(evaluator_type_);
int id = obstacle_ptr->id();
if (!obstacle_ptr->latest_feature().IsInitialized()) {
AERROR << "Obstacle [" << id << "] has no latest feature.";
return false;
}
Feature* latest_feature_ptr = obstacle_ptr->mutable_latest_feature();
CHECK_NOTNULL(latest_feature_ptr);
if (!latest_feature_ptr->has_lane() ||
!latest_feature_ptr->lane().has_lane_graph()) {
ADEBUG << "Obstacle [" << id << "] has no lane graph.";
return false;
}
double speed = latest_feature_ptr->speed();
LaneGraph* lane_graph_ptr =
latest_feature_ptr->mutable_lane()->mutable_lane_graph();
CHECK_NOTNULL(lane_graph_ptr);
if (lane_graph_ptr->lane_sequence().empty()) {
AERROR << "Obstacle [" << id << "] has no lane sequences.";
return false;
}
std::vector<double> obstacle_feature_values;
SetObstacleFeatureValues(obstacle_ptr, &obstacle_feature_values);
if (obstacle_feature_values.size() != OBSTACLE_FEATURE_SIZE) {
ADEBUG << "Obstacle [" << id << "] has fewer than "
<< "expected obstacle feature_values "
<< obstacle_feature_values.size() << ".";
return false;
}
for (int i = 0; i < lane_graph_ptr->lane_sequence_size(); ++i) {
LaneSequence* lane_sequence_ptr = lane_graph_ptr->mutable_lane_sequence(i);
ACHECK(lane_sequence_ptr != nullptr);
std::vector<double> lane_feature_values;
SetLaneFeatureValues(obstacle_ptr, lane_sequence_ptr, &lane_feature_values);
if (lane_feature_values.size() != LANE_FEATURE_SIZE) {
ADEBUG << "Obstacle [" << id << "] has fewer than "
<< "expected lane feature_values" << lane_feature_values.size()
<< ".";
continue;
}
std::vector<double> feature_values;
feature_values.insert(feature_values.end(), obstacle_feature_values.begin(),
obstacle_feature_values.end());
feature_values.insert(feature_values.end(), lane_feature_values.begin(),
lane_feature_values.end());
// Insert features to DataForLearning
if (FLAGS_prediction_offline_mode ==
PredictionConstants::kDumpDataForLearning &&
!obstacle_ptr->IsNearJunction()) {
FeatureOutput::InsertDataForLearning(*latest_feature_ptr, feature_values,
"mlp", lane_sequence_ptr);
ADEBUG << "Save extracted features for learning locally.";
return true; // Skip Compute probability for offline mode
}
double probability = ComputeProbability(feature_values);
double centripetal_acc_probability =
ValidationChecker::ProbabilityByCentripetalAcceleration(
*lane_sequence_ptr, speed);
probability *= centripetal_acc_probability;
lane_sequence_ptr->set_probability(probability);
}
return true;
}
void MLPEvaluator::ExtractFeatureValues(Obstacle* obstacle_ptr,
LaneSequence* lane_sequence_ptr,
std::vector<double>* feature_values) {
int id = obstacle_ptr->id();
std::vector<double> obstacle_feature_values;
SetObstacleFeatureValues(obstacle_ptr, &obstacle_feature_values);
if (obstacle_feature_values.size() != OBSTACLE_FEATURE_SIZE) {
ADEBUG << "Obstacle [" << id << "] has fewer than "
<< "expected obstacle feature_values "
<< obstacle_feature_values.size() << ".";
return;
}
std::vector<double> lane_feature_values;
SetLaneFeatureValues(obstacle_ptr, lane_sequence_ptr, &lane_feature_values);
if (lane_feature_values.size() != LANE_FEATURE_SIZE) {
ADEBUG << "Obstacle [" << id << "] has fewer than "
<< "expected lane feature_values" << lane_feature_values.size()
<< ".";
return;
}
feature_values->insert(feature_values->end(), obstacle_feature_values.begin(),
obstacle_feature_values.end());
feature_values->insert(feature_values->end(), lane_feature_values.begin(),
lane_feature_values.end());
}
void MLPEvaluator::SaveOfflineFeatures(
LaneSequence* sequence, const std::vector<double>& feature_values) {
for (double feature_value : feature_values) {
sequence->mutable_features()->add_mlp_features(feature_value);
}
}
void MLPEvaluator::SetObstacleFeatureValues(
Obstacle* obstacle_ptr, std::vector<double>* feature_values) {
feature_values->clear();
feature_values->reserve(OBSTACLE_FEATURE_SIZE);
std::vector<double> thetas;
std::vector<double> lane_ls;
std::vector<double> dist_lbs;
std::vector<double> dist_rbs;
std::vector<int> lane_types;
std::vector<double> speeds;
std::vector<double> timestamps;
double duration =
obstacle_ptr->timestamp() - FLAGS_prediction_trajectory_time_length;
int count = 0;
for (std::size_t i = 0; i < obstacle_ptr->history_size(); ++i) {
const Feature& feature = obstacle_ptr->feature(i);
if (!feature.IsInitialized()) {
continue;
}
if (feature.timestamp() < duration) {
break;
}
if (feature.has_lane() && feature.lane().has_lane_feature()) {
thetas.push_back(feature.lane().lane_feature().angle_diff());
lane_ls.push_back(feature.lane().lane_feature().lane_l());
dist_lbs.push_back(feature.lane().lane_feature().dist_to_left_boundary());
dist_rbs.push_back(
feature.lane().lane_feature().dist_to_right_boundary());
lane_types.push_back(feature.lane().lane_feature().lane_turn_type());
timestamps.push_back(feature.timestamp());
speeds.push_back(feature.speed());
++count;
}
}
if (count <= 0) {
return;
}
size_t curr_size = 5;
size_t hist_size = obstacle_ptr->history_size();
double theta_mean = ComputeMean(thetas, 0, hist_size - 1);
double theta_filtered = ComputeMean(thetas, 0, curr_size - 1);
double lane_l_mean = ComputeMean(lane_ls, 0, hist_size - 1);
double lane_l_filtered = ComputeMean(lane_ls, 0, curr_size - 1);
double speed_mean = ComputeMean(speeds, 0, hist_size - 1);
double time_diff = timestamps.front() - timestamps.back();
double dist_lb_rate = (timestamps.size() > 1)
? (dist_lbs.front() - dist_lbs.back()) / time_diff
: 0.0;
double dist_rb_rate = (timestamps.size() > 1)
? (dist_rbs.front() - dist_rbs.back()) / time_diff
: 0.0;
double delta_t = 0.0;
if (timestamps.size() > 1) {
delta_t = (timestamps.front() - timestamps.back()) /
static_cast<double>(timestamps.size() - 1);
}
double angle_curr = ComputeMean(thetas, 0, curr_size - 1);
double angle_prev = ComputeMean(thetas, curr_size, 2 * curr_size - 1);
double angle_diff =
(hist_size >= 2 * curr_size) ? angle_curr - angle_prev : 0.0;
double lane_l_curr = ComputeMean(lane_ls, 0, curr_size - 1);
double lane_l_prev = ComputeMean(lane_ls, curr_size, 2 * curr_size - 1);
double lane_l_diff =
(hist_size >= 2 * curr_size) ? lane_l_curr - lane_l_prev : 0.0;
double angle_diff_rate = 0.0;
double lane_l_diff_rate = 0.0;
if (delta_t > std::numeric_limits<double>::epsilon()) {
angle_diff_rate = angle_diff / (delta_t * static_cast<double>(curr_size));
lane_l_diff_rate = lane_l_diff / (delta_t * static_cast<float>(curr_size));
}
double acc = 0.0;
if (speeds.size() >= 3 * curr_size &&
delta_t > std::numeric_limits<double>::epsilon()) {
double speed_1 = ComputeMean(speeds, 0, curr_size - 1);
double speed_2 = ComputeMean(speeds, curr_size, 2 * curr_size - 1);
double speed_3 = ComputeMean(speeds, 2 * curr_size, 3 * curr_size - 1);
acc = (speed_1 - 2 * speed_2 + speed_3) /
(static_cast<float>(curr_size) * static_cast<float>(curr_size) *
delta_t * delta_t);
}
double dist_lb_rate_curr = 0.0;
if (hist_size >= 2 * curr_size &&
delta_t > std::numeric_limits<double>::epsilon()) {
double dist_lb_curr = ComputeMean(dist_lbs, 0, curr_size - 1);
double dist_lb_prev = ComputeMean(dist_lbs, curr_size, 2 * curr_size - 1);
dist_lb_rate_curr = (dist_lb_curr - dist_lb_prev) /
(static_cast<float>(curr_size) * delta_t);
}
double dist_rb_rate_curr = 0.0;
if (hist_size >= 2 * curr_size &&
delta_t > std::numeric_limits<double>::epsilon()) {
double dist_rb_curr = ComputeMean(dist_rbs, 0, curr_size - 1);
double dist_rb_prev = ComputeMean(dist_rbs, curr_size, 2 * curr_size - 1);
dist_rb_rate_curr = (dist_rb_curr - dist_rb_prev) /
(static_cast<float>(curr_size) * delta_t);
}
// setup obstacle feature values
feature_values->push_back(theta_filtered);
feature_values->push_back(theta_mean);
feature_values->push_back(theta_filtered - theta_mean);
feature_values->push_back(angle_diff);
feature_values->push_back(angle_diff_rate);
feature_values->push_back(lane_l_filtered);
feature_values->push_back(lane_l_mean);
feature_values->push_back(lane_l_filtered - lane_l_mean);
feature_values->push_back(lane_l_diff);
feature_values->push_back(lane_l_diff_rate);
feature_values->push_back(speed_mean);
feature_values->push_back(acc);
feature_values->push_back(dist_lbs.front());
feature_values->push_back(dist_lb_rate);
feature_values->push_back(dist_lb_rate_curr);
feature_values->push_back(dist_rbs.front());
feature_values->push_back(dist_rb_rate);
feature_values->push_back(dist_rb_rate_curr);
feature_values->push_back(lane_types.front() == 0 ? 1.0 : 0.0);
feature_values->push_back(lane_types.front() == 1 ? 1.0 : 0.0);
feature_values->push_back(lane_types.front() == 2 ? 1.0 : 0.0);
feature_values->push_back(lane_types.front() == 3 ? 1.0 : 0.0);
}
void MLPEvaluator::SetLaneFeatureValues(Obstacle* obstacle_ptr,
LaneSequence* lane_sequence_ptr,
std::vector<double>* feature_values) {
feature_values->clear();
feature_values->reserve(LANE_FEATURE_SIZE);
const Feature& feature = obstacle_ptr->latest_feature();
if (!feature.IsInitialized()) {
ADEBUG << "Obstacle [" << obstacle_ptr->id() << "] has no latest feature.";
return;
} else if (!feature.has_position()) {
ADEBUG << "Obstacle [" << obstacle_ptr->id() << "] has no position.";
return;
}
double heading = feature.velocity_heading();
for (int i = 0; i < lane_sequence_ptr->lane_segment_size(); ++i) {
if (feature_values->size() >= LANE_FEATURE_SIZE) {
break;
}
const LaneSegment& lane_segment = lane_sequence_ptr->lane_segment(i);
for (int j = 0; j < lane_segment.lane_point_size(); ++j) {
if (feature_values->size() >= LANE_FEATURE_SIZE) {
break;
}
const LanePoint& lane_point = lane_segment.lane_point(j);
if (!lane_point.has_position()) {
AERROR << "Lane point has no position.";
continue;
}
double diff_x = lane_point.position().x() - feature.position().x();
double diff_y = lane_point.position().y() - feature.position().y();
double angle = std::atan2(diff_y, diff_x);
feature_values->push_back(std::sin(angle - heading));
feature_values->push_back(lane_point.relative_l());
feature_values->push_back(lane_point.heading());
feature_values->push_back(lane_point.angle_diff());
}
}
std::size_t size = feature_values->size();
while (size >= 4 && size < LANE_FEATURE_SIZE) {
double heading_diff = feature_values->operator[](size - 4);
double lane_l_diff = feature_values->operator[](size - 3);
double heading = feature_values->operator[](size - 2);
double angle_diff = feature_values->operator[](size - 1);
feature_values->push_back(heading_diff);
feature_values->push_back(lane_l_diff);
feature_values->push_back(heading);
feature_values->push_back(angle_diff);
size = feature_values->size();
}
}
void MLPEvaluator::LoadModel(const std::string& model_file) {
model_ptr_.reset(new FnnVehicleModel());
ACHECK(model_ptr_ != nullptr);
ACHECK(cyber::common::GetProtoFromFile(model_file, model_ptr_.get()))
<< "Unable to load model file: " << model_file << ".";
AINFO << "Succeeded in loading the model file: " << model_file << ".";
}
double MLPEvaluator::ComputeProbability(
const std::vector<double>& feature_values) {
CHECK_NOTNULL(model_ptr_.get());
double probability = 0.0;
if (model_ptr_->dim_input() != static_cast<int>(feature_values.size())) {
ADEBUG << "Model feature size not consistent with model proto definition. "
<< "model input dim = " << model_ptr_->dim_input()
<< "; feature value size = " << feature_values.size();
return probability;
}
std::vector<double> layer_input;
layer_input.reserve(model_ptr_->dim_input());
std::vector<double> layer_output;
// normalization
for (int i = 0; i < model_ptr_->dim_input(); ++i) {
double mean = model_ptr_->samples_mean().columns(i);
double std = model_ptr_->samples_std().columns(i);
layer_input.push_back(
apollo::prediction::math_util::Normalize(feature_values[i], mean, std));
}
for (int i = 0; i < model_ptr_->num_layer(); ++i) {
if (i > 0) {
layer_input.swap(layer_output);
layer_output.clear();
}
const Layer& layer = model_ptr_->layer(i);
for (int col = 0; col < layer.layer_output_dim(); ++col) {
double neuron_output = layer.layer_bias().columns(col);
for (int row = 0; row < layer.layer_input_dim(); ++row) {
double weight = layer.layer_input_weight().rows(row).columns(col);
neuron_output += (layer_input[row] * weight);
}
if (layer.layer_activation_func() == Layer::RELU) {
neuron_output = apollo::prediction::math_util::Relu(neuron_output);
} else if (layer.layer_activation_func() == Layer::SIGMOID) {
neuron_output = Sigmoid(neuron_output);
} else if (layer.layer_activation_func() == Layer::TANH) {
neuron_output = std::tanh(neuron_output);
} else {
AERROR << "Undefined activation function ["
<< layer.layer_activation_func()
<< "]. A default sigmoid will be used instead.";
neuron_output = Sigmoid(neuron_output);
}
layer_output.push_back(neuron_output);
}
}
if (layer_output.size() != 1) {
AERROR << "Model output layer has incorrect # outputs: "
<< layer_output.size();
} else {
probability = layer_output[0];
}
return probability;
}
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/prediction/evaluator
|
apollo_public_repos/apollo/modules/prediction/evaluator/vehicle/junction_map_evaluator.cc
|
/******************************************************************************
* 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.
*****************************************************************************/
#include "modules/prediction/evaluator/vehicle/junction_map_evaluator.h"
#include <unordered_map>
#include <utility>
#include <omp.h>
#include "cyber/common/file.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_map.h"
#include "modules/prediction/common/prediction_system_gflags.h"
#include "modules/prediction/common/prediction_util.h"
namespace apollo {
namespace prediction {
JunctionMapEvaluator::JunctionMapEvaluator(SemanticMap* semantic_map)
: device_(torch::kCPU), semantic_map_(semantic_map) {
evaluator_type_ = ObstacleConf::JUNCTION_MAP_EVALUATOR;
LoadModel();
}
void JunctionMapEvaluator::Clear() {}
bool JunctionMapEvaluator::Evaluate(Obstacle* obstacle_ptr,
ObstaclesContainer* obstacles_container) {
// Sanity checks.
omp_set_num_threads(1);
obstacle_ptr->SetEvaluatorType(evaluator_type_);
Clear();
CHECK_NOTNULL(obstacle_ptr);
int id = obstacle_ptr->id();
if (!obstacle_ptr->latest_feature().IsInitialized()) {
AERROR << "Obstacle [" << id << "] has no latest feature.";
return false;
}
Feature* latest_feature_ptr = obstacle_ptr->mutable_latest_feature();
CHECK_NOTNULL(latest_feature_ptr);
// Assume obstacle is NOT closed to any junction exit
if (!latest_feature_ptr->has_junction_feature() ||
latest_feature_ptr->junction_feature().junction_exit_size() < 2) {
ADEBUG << "Obstacle [" << id << "] has less than two junction_exits.";
return false;
}
// Extract features of junction_exit_mask
std::vector<double> feature_values;
if (!ExtractFeatureValues(obstacle_ptr, &feature_values)) {
ADEBUG << "Obstacle [" << id << "] failed to extract junction exit mask";
return false;
}
if (!FLAGS_enable_semantic_map) {
ADEBUG << "Not enable semantic map, exit junction_map_evaluator.";
return false;
}
cv::Mat feature_map;
if (!semantic_map_->GetMapById(id, &feature_map)) {
return false;
}
// Build input features for torch
std::vector<torch::jit::IValue> torch_inputs;
// Process the feature_map
cv::cvtColor(feature_map, feature_map, cv::COLOR_BGR2RGB);
cv::Mat img_float;
feature_map.convertTo(img_float, CV_32F, 1.0 / 255);
torch::Tensor img_tensor = torch::from_blob(img_float.data, {1, 224, 224, 3});
img_tensor = img_tensor.permute({0, 3, 1, 2});
img_tensor[0][0] = img_tensor[0][0].sub(0.485).div(0.229);
img_tensor[0][1] = img_tensor[0][1].sub(0.456).div(0.224);
img_tensor[0][2] = img_tensor[0][2].sub(0.406).div(0.225);
// Process junction_exit_mask
torch::Tensor junction_exit_mask =
torch::zeros({1, static_cast<int>(feature_values.size())});
for (size_t i = 0; i < feature_values.size(); ++i) {
junction_exit_mask[0][i] = static_cast<float>(feature_values[i]);
}
torch_inputs.push_back(
c10::ivalue::Tuple::create({std::move(img_tensor.to(device_)),
std::move(junction_exit_mask.to(device_))}));
// Compute probability
std::vector<double> probability;
at::Tensor torch_output_tensor =
torch_model_.forward(torch_inputs).toTensor().to(torch::kCPU);
auto torch_output = torch_output_tensor.accessor<float, 2>();
for (int i = 0; i < torch_output.size(1); ++i) {
probability.push_back(static_cast<double>(torch_output[0][i]));
}
std::unordered_map<std::string, double> junction_exit_prob;
for (const JunctionExit& junction_exit :
latest_feature_ptr->junction_feature().junction_exit()) {
double x =
junction_exit.exit_position().x() - latest_feature_ptr->position().x();
double y =
junction_exit.exit_position().y() - latest_feature_ptr->position().y();
double angle =
std::atan2(y, x) - std::atan2(latest_feature_ptr->raw_velocity().y(),
latest_feature_ptr->raw_velocity().x());
double d_idx = (angle / (2.0 * M_PI) + 1.0 / 24.0) * 12.0;
int idx = static_cast<int>(floor(d_idx >= 0 ? d_idx : d_idx + 12));
junction_exit_prob[junction_exit.exit_lane_id()] = probability[idx];
}
// assign all lane_sequence probability
LaneGraph* lane_graph_ptr =
latest_feature_ptr->mutable_lane()->mutable_lane_graph();
CHECK_NOTNULL(lane_graph_ptr);
if (lane_graph_ptr->lane_sequence().empty()) {
AERROR << "Obstacle [" << id << "] has no lane sequences.";
return false;
}
for (int i = 0; i < lane_graph_ptr->lane_sequence_size(); ++i) {
LaneSequence* lane_sequence_ptr = lane_graph_ptr->mutable_lane_sequence(i);
CHECK_NOTNULL(lane_sequence_ptr);
for (const LaneSegment& lane_segment : lane_sequence_ptr->lane_segment()) {
if (junction_exit_prob.find(lane_segment.lane_id()) !=
junction_exit_prob.end()) {
lane_sequence_ptr->set_probability(
junction_exit_prob[lane_segment.lane_id()]);
}
}
}
return true;
}
bool JunctionMapEvaluator::ExtractFeatureValues(
Obstacle* obstacle_ptr, std::vector<double>* feature_values) {
feature_values->clear();
feature_values->resize(JUNCTION_FEATURE_SIZE, 0.0);
Feature* feature_ptr = obstacle_ptr->mutable_latest_feature();
if (!feature_ptr->has_position()) {
ADEBUG << "Obstacle [" << obstacle_ptr->id() << "] has no position.";
return false;
}
double heading = std::atan2(feature_ptr->raw_velocity().y(),
feature_ptr->raw_velocity().x());
if (!feature_ptr->has_junction_feature()) {
AERROR << "Obstacle [" << obstacle_ptr->id()
<< "] has no junction_feature.";
return false;
}
int num_junction_exit = feature_ptr->junction_feature().junction_exit_size();
for (int i = 0; i < num_junction_exit; ++i) {
const JunctionExit& junction_exit =
feature_ptr->junction_feature().junction_exit(i);
double x = junction_exit.exit_position().x() - feature_ptr->position().x();
double y = junction_exit.exit_position().y() - feature_ptr->position().y();
double diff_x = std::cos(-heading) * x - std::sin(-heading) * y;
double diff_y = std::sin(-heading) * x + std::cos(-heading) * y;
double angle = std::atan2(diff_y, diff_x);
double d_idx = (angle / (2.0 * M_PI) + 1.0 / 24.0) * 12.0;
int idx = static_cast<int>(floor(d_idx >= 0 ? d_idx : d_idx + 12));
feature_values->at(idx) = 1.0;
}
return true;
}
void JunctionMapEvaluator::LoadModel() {
if (FLAGS_use_cuda && torch::cuda::is_available()) {
ADEBUG << "CUDA is available";
device_ = torch::Device(torch::kCUDA);
}
torch::set_num_threads(1);
torch_model_ =
torch::jit::load(FLAGS_torch_vehicle_junction_map_file, device_);
}
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/prediction/evaluator
|
apollo_public_repos/apollo/modules/prediction/evaluator/vehicle/lane_aggregating_evaluator.h
|
/******************************************************************************
* 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.
*****************************************************************************/
/**
* @file
* @brief Define the lane aggregating evaluator class
*/
#pragma once
#include <string>
#include <vector>
#include "torch/script.h"
#include "torch/torch.h"
#include "modules/prediction/container/obstacles/obstacles_container.h"
#include "modules/prediction/evaluator/evaluator.h"
/**
* @namespace apollo::prediction
* @brief apollo::prediction
*/
namespace apollo {
namespace prediction {
class LaneAggregatingEvaluator : public Evaluator {
public:
/**
* @brief Constructor
*/
LaneAggregatingEvaluator();
/**
* @brief Destructor
*/
virtual ~LaneAggregatingEvaluator() = default;
/**
* @brief Override Evaluate
* @param Obstacle pointer
* @param Obstacles container
*/
bool Evaluate(Obstacle* obstacle_ptr,
ObstaclesContainer* obstacles_container) override;
/**
* @brief Get the name of evaluator.
*/
std::string GetName() override { return "LANE_AGGREGATING_EVALUATOR"; }
private:
/**
* @brief Extract the features for obstacles
* @param Obstacle pointer
* A vector of doubles to be filled up with extracted features
*/
bool ExtractObstacleFeatures(const Obstacle* obstacle_ptr,
std::vector<double>* feature_values);
/**
* @brief Set lane feature vector
* @param Obstacle pointer
* A vector of doubles to be filled up with extracted features
*/
bool ExtractStaticEnvFeatures(
const Obstacle* obstacle_ptr, const LaneGraph* lane_graph_ptr,
std::vector<std::vector<double>>* feature_values,
std::vector<int>* lane_sequence_idx_to_remove);
torch::Tensor AggregateLaneEncodings(
const std::vector<torch::Tensor>& lane_encoding_list);
torch::Tensor LaneEncodingMaxPooling(
const std::vector<torch::Tensor>& lane_encoding_list);
torch::Tensor LaneEncodingAvgPooling(
const std::vector<torch::Tensor>& lane_encoding_list);
std::vector<double> StableSoftmax(
const std::vector<double>& prediction_scores);
void LoadModel();
private:
torch::jit::script::Module torch_obstacle_encoding_;
torch::jit::script::Module torch_lane_encoding_;
torch::jit::script::Module torch_prediction_layer_;
torch::Device device_;
static const size_t OBSTACLE_FEATURE_SIZE = 20 * 9;
static const size_t SINGLE_LANE_FEATURE_SIZE = 4;
static const size_t LANE_POINTS_SIZE = 100; // 50m
static const size_t BACKWARD_LANE_POINTS_SIZE = 50; // 25m
static const size_t OBSTACLE_ENCODING_SIZE = 128;
static const size_t SINGLE_LANE_ENCODING_SIZE = 128;
static const size_t AGGREGATED_ENCODING_SIZE = 256;
};
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/prediction/evaluator
|
apollo_public_repos/apollo/modules/prediction/evaluator/vehicle/cost_evaluator.cc
|
/******************************************************************************
* 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.
*****************************************************************************/
#include "modules/prediction/evaluator/vehicle/cost_evaluator.h"
#include "modules/prediction/common/prediction_util.h"
namespace apollo {
namespace prediction {
CostEvaluator::CostEvaluator() {
evaluator_type_ = ObstacleConf::COST_EVALUATOR;
}
bool CostEvaluator::Evaluate(Obstacle* obstacle_ptr,
ObstaclesContainer* obstacles_container) {
CHECK_NOTNULL(obstacle_ptr);
obstacle_ptr->SetEvaluatorType(evaluator_type_);
int id = obstacle_ptr->id();
if (!obstacle_ptr->latest_feature().IsInitialized()) {
AERROR << "Obstacle [" << id << "] has no latest feature.";
return false;
}
Feature* latest_feature_ptr = obstacle_ptr->mutable_latest_feature();
CHECK_NOTNULL(latest_feature_ptr);
if (!latest_feature_ptr->has_lane() ||
!latest_feature_ptr->lane().has_lane_graph()) {
ADEBUG << "Obstacle [" << id << "] has no lane graph.";
return false;
}
double obstacle_length = 0.0;
if (latest_feature_ptr->has_length()) {
obstacle_length = latest_feature_ptr->length();
}
double obstacle_width = 0.0;
if (latest_feature_ptr->has_width()) {
obstacle_width = latest_feature_ptr->width();
}
LaneGraph* lane_graph_ptr =
latest_feature_ptr->mutable_lane()->mutable_lane_graph();
CHECK_NOTNULL(lane_graph_ptr);
if (lane_graph_ptr->lane_sequence().empty()) {
AERROR << "Obstacle [" << id << "] has no lane sequences.";
return false;
}
for (int i = 0; i < lane_graph_ptr->lane_sequence_size(); ++i) {
LaneSequence* lane_sequence_ptr = lane_graph_ptr->mutable_lane_sequence(i);
CHECK_NOTNULL(lane_sequence_ptr);
double probability =
ComputeProbability(obstacle_length, obstacle_width, *lane_sequence_ptr);
lane_sequence_ptr->set_probability(probability);
}
return true;
}
double CostEvaluator::ComputeProbability(const double obstacle_length,
const double obstacle_width,
const LaneSequence& lane_sequence) {
double front_lateral_distance_cost =
FrontLateralDistanceCost(obstacle_length, obstacle_width, lane_sequence);
return apollo::common::math::Sigmoid(front_lateral_distance_cost);
}
double CostEvaluator::FrontLateralDistanceCost(
const double obstacle_length, const double obstacle_width,
const LaneSequence& lane_sequence) {
if (lane_sequence.lane_segment().empty() ||
lane_sequence.lane_segment(0).lane_point().empty()) {
AWARN << "Empty lane sequence.";
return 0.0;
}
const LanePoint& lane_point = lane_sequence.lane_segment(0).lane_point(0);
double lane_l = -lane_point.relative_l();
double distance = std::abs(lane_l - obstacle_length / 2.0 *
std::sin(lane_point.angle_diff()));
double half_lane_width = lane_point.width() / 2.0;
return half_lane_width - distance;
}
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/prediction/evaluator
|
apollo_public_repos/apollo/modules/prediction/evaluator/vehicle/lane_scanning_evaluator.cc
|
/******************************************************************************
* 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.
*****************************************************************************/
#include "modules/prediction/evaluator/vehicle/lane_scanning_evaluator.h"
#include <algorithm>
#include <utility>
#include <omp.h>
#include "cyber/common/file.h"
#include "modules/common/math/vec2d.h"
#include "modules/common_msgs/basic_msgs/pnc_point.pb.h"
#include "modules/prediction/common/feature_output.h"
#include "modules/prediction/common/prediction_constants.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_system_gflags.h"
#include "modules/prediction/container/container_manager.h"
namespace apollo {
namespace prediction {
using apollo::common::TrajectoryPoint;
using apollo::common::math::Vec2d;
LaneScanningEvaluator::LaneScanningEvaluator() : device_(torch::kCPU) {
evaluator_type_ = ObstacleConf::LANE_SCANNING_EVALUATOR;
LoadModel();
}
bool LaneScanningEvaluator::Evaluate(Obstacle* obstacle_ptr,
ObstaclesContainer* obstacles_container) {
std::vector<Obstacle*> dummy_dynamic_env;
Evaluate(obstacle_ptr, obstacles_container, dummy_dynamic_env);
return true;
}
bool LaneScanningEvaluator::Evaluate(Obstacle* obstacle_ptr,
ObstaclesContainer* obstacles_container,
std::vector<Obstacle*> dynamic_env) {
// Sanity checks.
omp_set_num_threads(1);
CHECK_NOTNULL(obstacle_ptr);
obstacle_ptr->SetEvaluatorType(evaluator_type_);
int id = obstacle_ptr->id();
if (!obstacle_ptr->latest_feature().IsInitialized()) {
AERROR << "Obstacle [" << id << "] has no latest feature.";
return false;
}
Feature* latest_feature_ptr = obstacle_ptr->mutable_latest_feature();
CHECK_NOTNULL(latest_feature_ptr);
if (!latest_feature_ptr->has_lane() ||
!latest_feature_ptr->lane().has_lane_graph_ordered()) {
AERROR << "Obstacle [" << id << "] has no lane graph.";
return false;
}
LaneGraph* lane_graph_ptr =
latest_feature_ptr->mutable_lane()->mutable_lane_graph_ordered();
CHECK_NOTNULL(lane_graph_ptr);
if (lane_graph_ptr->lane_sequence().empty()) {
AERROR << "Obstacle [" << id << "] has no lane sequences.";
return false;
}
ADEBUG << "There are " << lane_graph_ptr->lane_sequence_size()
<< " lane sequences to scan.";
// Extract features, and:
// - if in offline mode, save it locally for training.
// - if in online mode, pass it through trained model to evaluate.
std::vector<double> feature_values;
ExtractFeatures(obstacle_ptr, lane_graph_ptr, &feature_values);
std::vector<std::string> string_feature_values;
ExtractStringFeatures(*lane_graph_ptr, &string_feature_values);
std::vector<double> labels = {0.0};
if (FLAGS_prediction_offline_mode ==
PredictionConstants::kDumpDataForLearning) {
std::string learning_data_tag = "vehicle_cruise";
if (latest_feature_ptr->has_junction_feature()) {
learning_data_tag = "vehicle_junction";
}
FeatureOutput::InsertDataForLearning(*latest_feature_ptr, feature_values,
string_feature_values,
learning_data_tag, nullptr);
ADEBUG << "Save extracted features for learning locally.";
return true;
}
feature_values.push_back(static_cast<double>(MAX_NUM_LANE));
std::vector<torch::jit::IValue> torch_inputs;
torch::Tensor torch_input =
torch::zeros({1, static_cast<int>(feature_values.size())});
for (size_t i = 0; i < feature_values.size(); ++i) {
torch_input[0][i] = static_cast<float>(feature_values[i]);
}
torch_inputs.push_back(std::move(torch_input));
ModelInference(torch_inputs, torch_lane_scanning_model_, latest_feature_ptr);
return true;
}
bool LaneScanningEvaluator::ExtractStringFeatures(
const LaneGraph& lane_graph,
std::vector<std::string>* const string_feature_values) {
for (const LaneSequence& lane_sequence : lane_graph.lane_sequence()) {
string_feature_values->push_back("|");
for (int i = lane_sequence.adc_lane_segment_idx();
i < static_cast<int>(lane_sequence.lane_segment_size()); ++i) {
string_feature_values->push_back(lane_sequence.lane_segment(i).lane_id());
}
}
return true;
}
bool LaneScanningEvaluator::ExtractFeatures(
const Obstacle* obstacle_ptr, const LaneGraph* lane_graph_ptr,
std::vector<double>* feature_values) {
// Sanity checks.
CHECK_NOTNULL(obstacle_ptr);
int id = obstacle_ptr->id();
CHECK_NOTNULL(lane_graph_ptr);
// Extract obstacle related features.
std::vector<double> obstacle_feature_values;
if (!ExtractObstacleFeatures(obstacle_ptr, &obstacle_feature_values)) {
ADEBUG << "Failed to extract obstacle features for obs_id = " << id;
}
if (obstacle_feature_values.size() != OBSTACLE_FEATURE_SIZE) {
ADEBUG << "Obstacle [" << id << "] has fewer than "
<< "expected obstacle feature_values "
<< obstacle_feature_values.size() << ".";
return false;
}
ADEBUG << "Obstacle feature size = " << obstacle_feature_values.size();
feature_values->insert(feature_values->end(), obstacle_feature_values.begin(),
obstacle_feature_values.end());
// Extract static environmental (lane-related) features.
std::vector<double> static_feature_values;
std::vector<int> lane_sequence_idx_to_remove;
if (!ExtractStaticEnvFeatures(obstacle_ptr, lane_graph_ptr,
&static_feature_values,
&lane_sequence_idx_to_remove)) {
AERROR << "Failed to extract static environmental features around obs_id = "
<< id;
}
if (static_feature_values.size() %
(SINGLE_LANE_FEATURE_SIZE *
(LANE_POINTS_SIZE + BACKWARD_LANE_POINTS_SIZE)) !=
0) {
AERROR << "Obstacle [" << id << "] has incorrect static env feature size: "
<< static_feature_values.size() << ".";
return false;
}
feature_values->insert(feature_values->end(), static_feature_values.begin(),
static_feature_values.end());
return true;
}
bool LaneScanningEvaluator::ExtractObstacleFeatures(
const Obstacle* obstacle_ptr, std::vector<double>* feature_values) {
// Sanity checks.
CHECK_NOTNULL(obstacle_ptr);
feature_values->clear();
FLAGS_cruise_historical_frame_length = 20;
int max_num_poly_pt = 20;
std::vector<double> has_history(FLAGS_cruise_historical_frame_length, 1.0);
std::vector<std::pair<double, double>> pos_history(
FLAGS_cruise_historical_frame_length, std::make_pair(0.0, 0.0));
std::vector<std::pair<double, double>> vel_history(
FLAGS_cruise_historical_frame_length, std::make_pair(0.0, 0.0));
std::vector<std::pair<double, double>> acc_history(
FLAGS_cruise_historical_frame_length, std::make_pair(0.0, 0.0));
std::vector<double> vel_heading_history(FLAGS_cruise_historical_frame_length,
0.0);
std::vector<double> vel_heading_changing_rate_history(
FLAGS_cruise_historical_frame_length, 0.0);
std::vector<std::vector<std::pair<double, double>>> polygon_points_history(
FLAGS_cruise_historical_frame_length,
std::vector<std::pair<double, double>>(max_num_poly_pt,
std::make_pair(0.0, 0.0)));
// Get obstacle's current position to set up the relative coord. system.
const Feature& obs_curr_feature = obstacle_ptr->latest_feature();
double obs_curr_heading = obs_curr_feature.velocity_heading();
std::pair<double, double> obs_curr_pos = std::make_pair(
obs_curr_feature.position().x(), obs_curr_feature.position().y());
double prev_timestamp = obs_curr_feature.timestamp();
// Starting from the most recent timestamp and going backward.
ADEBUG << "Obstacle has " << obstacle_ptr->history_size()
<< " history timestamps.";
for (std::size_t i = 0; i < std::min(obstacle_ptr->history_size(),
FLAGS_cruise_historical_frame_length);
++i) {
const Feature& feature = obstacle_ptr->feature(i);
if (!feature.IsInitialized()) {
has_history[i] = 0.0;
continue;
}
if (i != 0 && has_history[i - 1] == 0.0) {
has_history[i] = 0.0;
continue;
}
// Extract normalized position info.
if (feature.has_position()) {
pos_history[i] =
std::make_pair(feature.position().x(), feature.position().y());
} else {
has_history[i] = 0.0;
}
// Extract normalized velocity info.
if (feature.has_velocity()) {
auto vel_end = WorldCoordToObjCoord(
std::make_pair(feature.velocity().x(), feature.velocity().y()),
obs_curr_pos, obs_curr_heading);
auto vel_begin = WorldCoordToObjCoord(std::make_pair(0.0, 0.0),
obs_curr_pos, obs_curr_heading);
vel_history[i] = std::make_pair(vel_end.first - vel_begin.first,
vel_end.second - vel_begin.second);
} else {
has_history[i] = 0.0;
}
// Extract normalized acceleration info.
if (feature.has_acceleration()) {
auto acc_end =
WorldCoordToObjCoord(std::make_pair(feature.acceleration().x(),
feature.acceleration().y()),
obs_curr_pos, obs_curr_heading);
auto acc_begin = WorldCoordToObjCoord(std::make_pair(0.0, 0.0),
obs_curr_pos, obs_curr_heading);
acc_history[i] = std::make_pair(acc_end.first - acc_begin.first,
acc_end.second - acc_begin.second);
} else {
has_history[i] = 0.0;
}
// Extract velocity heading info.
if (feature.has_velocity_heading()) {
vel_heading_history[i] = feature.velocity_heading();
if (i != 0) {
vel_heading_changing_rate_history[i] =
(vel_heading_history[i] - vel_heading_history[i - 1]) /
(feature.timestamp() - prev_timestamp + FLAGS_double_precision);
prev_timestamp = feature.timestamp();
}
} else {
has_history[i] = 0.0;
}
// Extract polygon-point info.
for (int j = 0; j < feature.polygon_point_size(); ++j) {
if (j >= max_num_poly_pt) {
break;
}
polygon_points_history[i][j].first = feature.polygon_point(j).x();
polygon_points_history[i][j].second = feature.polygon_point(j).y();
}
}
for (std::size_t i = obstacle_ptr->history_size();
i < FLAGS_cruise_historical_frame_length; ++i) {
has_history[i] = 0.0;
}
// Update the extracted features into the feature_values vector.
for (std::size_t i = 0; i < FLAGS_cruise_historical_frame_length; i++) {
feature_values->push_back(has_history[i]);
feature_values->push_back(pos_history[i].first);
feature_values->push_back(pos_history[i].second);
feature_values->push_back(vel_history[i].first);
feature_values->push_back(vel_history[i].second);
feature_values->push_back(acc_history[i].first);
feature_values->push_back(acc_history[i].second);
feature_values->push_back(vel_heading_history[i]);
feature_values->push_back(vel_heading_changing_rate_history[i]);
for (int j = 0; j < max_num_poly_pt; ++j) {
feature_values->push_back(polygon_points_history[i][j].first);
feature_values->push_back(polygon_points_history[i][j].second);
}
}
return true;
}
bool LaneScanningEvaluator::ExtractStaticEnvFeatures(
const Obstacle* obstacle_ptr, const LaneGraph* lane_graph_ptr,
std::vector<double>* feature_values,
std::vector<int>* lane_sequence_idx_to_remove) {
// Sanity checks.
CHECK_NOTNULL(lane_graph_ptr);
feature_values->clear();
// Get obstacle's current position to set up the relative coord. system.
const Feature& obs_curr_feature = obstacle_ptr->latest_feature();
double obs_curr_heading = obs_curr_feature.velocity_heading();
std::pair<double, double> obs_curr_pos = std::make_pair(
obs_curr_feature.position().x(), obs_curr_feature.position().y());
// Go through every lane-sequence (ordered from left to right) and
// extract needed features.
for (int i = 0; i < lane_graph_ptr->lane_sequence_size(); ++i) {
// Get all the properties of the current lane-sequence.
// Go through all the lane-points to fill up the feature_values.
const LaneSequence& lane_sequence = lane_graph_ptr->lane_sequence(i);
// Extract features from backward lane-points.
size_t count = 0;
std::vector<double> backward_feature_values;
for (int j = lane_sequence.adc_lane_segment_idx(); j >= 0; --j) {
if (count >= SINGLE_LANE_FEATURE_SIZE * BACKWARD_LANE_POINTS_SIZE) {
break;
}
const LaneSegment& lane_segment = lane_sequence.lane_segment(j);
int k_starting_idx = lane_segment.lane_point_size() - 1;
if (j == lane_sequence.adc_lane_segment_idx()) {
k_starting_idx = std::min(lane_segment.adc_lane_point_idx(),
lane_segment.lane_point_size() - 1);
}
for (int k = k_starting_idx; k >= 0; --k) {
if (count >= SINGLE_LANE_FEATURE_SIZE * BACKWARD_LANE_POINTS_SIZE) {
break;
}
const LanePoint& lane_point = lane_segment.lane_point(k);
std::pair<double, double> relative_s_l =
WorldCoordToObjCoord(std::make_pair(lane_point.position().x(),
lane_point.position().y()),
obs_curr_pos, obs_curr_heading);
double relative_ang =
WorldAngleToObjAngle(lane_point.heading(), obs_curr_heading);
backward_feature_values.push_back(lane_point.kappa());
backward_feature_values.push_back(relative_ang);
backward_feature_values.push_back(relative_s_l.first);
backward_feature_values.push_back(relative_s_l.second);
count += 4;
}
}
// If lane-points are not enough, then extrapolate linearly.
while (count >= SINGLE_LANE_FEATURE_SIZE * 2 &&
count < SINGLE_LANE_FEATURE_SIZE * BACKWARD_LANE_POINTS_SIZE) {
std::size_t s = backward_feature_values.size();
double relative_l_new =
2 * backward_feature_values[s - 1] - backward_feature_values[s - 5];
double relative_s_new =
2 * backward_feature_values[s - 2] - backward_feature_values[s - 6];
double relative_ang_new = backward_feature_values[s - 3];
backward_feature_values.push_back(0.0);
backward_feature_values.push_back(relative_ang_new);
backward_feature_values.push_back(relative_s_new);
backward_feature_values.push_back(relative_l_new);
count += 4;
}
for (int j = static_cast<int>(backward_feature_values.size()) - 1; j >= 0;
--j) {
feature_values->push_back(backward_feature_values[j]);
}
// Extract features from forward lane-points.
count = 0;
for (int j = lane_sequence.adc_lane_segment_idx();
j < lane_sequence.lane_segment_size(); ++j) {
if (count >= SINGLE_LANE_FEATURE_SIZE * LANE_POINTS_SIZE) {
break;
}
const LaneSegment& lane_segment = lane_sequence.lane_segment(j);
int k_starting_idx = 0;
if (j == lane_sequence.adc_lane_segment_idx()) {
k_starting_idx = std::min(lane_segment.adc_lane_point_idx(),
lane_segment.lane_point_size() - 1);
}
for (int k = k_starting_idx; k < lane_segment.lane_point_size(); ++k) {
if (count >= SINGLE_LANE_FEATURE_SIZE * LANE_POINTS_SIZE) {
break;
}
const LanePoint& lane_point = lane_segment.lane_point(k);
std::pair<double, double> relative_s_l =
WorldCoordToObjCoord(std::make_pair(lane_point.position().x(),
lane_point.position().y()),
obs_curr_pos, obs_curr_heading);
double relative_ang =
WorldAngleToObjAngle(lane_point.heading(), obs_curr_heading);
feature_values->push_back(relative_s_l.second);
feature_values->push_back(relative_s_l.first);
feature_values->push_back(relative_ang);
feature_values->push_back(lane_point.kappa());
count += 4;
}
}
// If lane-points are not enough, then extrapolate linearly.
while (count >= SINGLE_LANE_FEATURE_SIZE * 2 &&
count < SINGLE_LANE_FEATURE_SIZE * LANE_POINTS_SIZE) {
std::size_t s = feature_values->size();
double relative_l_new = 2 * feature_values->operator[](s - 4) -
feature_values->operator[](s - 8);
double relative_s_new = 2 * feature_values->operator[](s - 3) -
feature_values->operator[](s - 7);
double relative_ang_new = feature_values->operator[](s - 2);
feature_values->push_back(relative_l_new);
feature_values->push_back(relative_s_new);
feature_values->push_back(relative_ang_new);
feature_values->push_back(0.0);
count += 4;
}
}
if (FLAGS_prediction_offline_mode ==
PredictionConstants::kDumpDataForLearning) {
// Early exit without appending zero for offline_dataforlearn_dump
return true;
}
size_t max_feature_size =
LANE_POINTS_SIZE * SINGLE_LANE_FEATURE_SIZE * MAX_NUM_LANE;
while (feature_values->size() < max_feature_size) {
feature_values->push_back(0.0);
}
return true;
}
void LaneScanningEvaluator::LoadModel() {
if (FLAGS_use_cuda && torch::cuda::is_available()) {
ADEBUG << "CUDA is available";
device_ = torch::Device(torch::kCUDA);
}
torch::set_num_threads(1);
torch_lane_scanning_model_ =
torch::jit::load(FLAGS_torch_vehicle_lane_scanning_file, device_);
}
void LaneScanningEvaluator::ModelInference(
const std::vector<torch::jit::IValue>& torch_inputs,
torch::jit::script::Module torch_model, Feature* feature_ptr) {
auto torch_output_tensor = torch_model.forward(torch_inputs).toTensor();
auto torch_output = torch_output_tensor.accessor<float, 3>();
for (size_t i = 0; i < SHORT_TERM_TRAJECTORY_SIZE; ++i) {
TrajectoryPoint point;
double dx = static_cast<double>(torch_output[0][0][i]);
double dy =
static_cast<double>(torch_output[0][0][i + SHORT_TERM_TRAJECTORY_SIZE]);
Vec2d offset(dx, dy);
Vec2d rotated_offset = offset.rotate(feature_ptr->velocity_heading());
double point_x = feature_ptr->position().x() + rotated_offset.x();
double point_y = feature_ptr->position().y() + rotated_offset.y();
point.mutable_path_point()->set_x(point_x);
point.mutable_path_point()->set_y(point_y);
point.set_relative_time(static_cast<double>(i) *
FLAGS_prediction_trajectory_time_resolution);
feature_ptr->add_short_term_predicted_trajectory_points()->CopyFrom(point);
}
}
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/prediction/evaluator
|
apollo_public_repos/apollo/modules/prediction/evaluator/vehicle/mlp_evaluator_test.cc
|
/******************************************************************************
* 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.
*****************************************************************************/
#include "modules/prediction/evaluator/vehicle/mlp_evaluator.h"
#include "cyber/common/file.h"
#include "modules/prediction/common/kml_map_based_test.h"
#include "modules/prediction/container/obstacles/obstacles_container.h"
namespace apollo {
namespace prediction {
class MLPEvaluatorTest : public KMLMapBasedTest {
public:
void SetUp() override {
const std::string file =
"modules/prediction/testdata/single_perception_vehicle_onlane.pb.txt";
ACHECK(cyber::common::GetProtoFromFile(file, &perception_obstacles_));
}
protected:
apollo::perception::PerceptionObstacles perception_obstacles_;
};
TEST_F(MLPEvaluatorTest, OnLaneCase) {
EXPECT_DOUBLE_EQ(perception_obstacles_.header().timestamp_sec(),
1501183430.161906);
apollo::perception::PerceptionObstacle perception_obstacle =
perception_obstacles_.perception_obstacle(0);
EXPECT_EQ(perception_obstacle.id(), 1);
MLPEvaluator mlp_evaluator;
ObstaclesContainer container;
container.Insert(perception_obstacles_);
container.BuildLaneGraph();
Obstacle* obstacle_ptr = container.GetObstacle(1);
EXPECT_NE(obstacle_ptr, nullptr);
mlp_evaluator.Evaluate(obstacle_ptr, &container);
const Feature& feature = obstacle_ptr->latest_feature();
const LaneGraph& lane_graph = feature.lane().lane_graph();
for (const auto& lane_sequence : lane_graph.lane_sequence()) {
EXPECT_TRUE(lane_sequence.has_probability());
}
mlp_evaluator.Clear();
}
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/prediction/evaluator
|
apollo_public_repos/apollo/modules/prediction/evaluator/vehicle/lane_aggregating_evaluator.cc
|
/******************************************************************************
* 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.
*****************************************************************************/
#include "modules/prediction/evaluator/vehicle/lane_aggregating_evaluator.h"
#include <algorithm>
#include <utility>
#include "modules/common/math/vec2d.h"
#include "modules/prediction/common/feature_output.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_system_gflags.h"
#include "modules/prediction/container/container_manager.h"
#include "modules/prediction/container/pose/pose_container.h"
namespace apollo {
namespace prediction {
LaneAggregatingEvaluator::LaneAggregatingEvaluator() : device_(torch::kCPU) {
evaluator_type_ = ObstacleConf::LANE_AGGREGATING_EVALUATOR;
LoadModel();
}
void LaneAggregatingEvaluator::LoadModel() {
torch::set_num_threads(1);
torch_obstacle_encoding_ = torch::jit::load(
FLAGS_torch_lane_aggregating_obstacle_encoding_file, device_);
torch_lane_encoding_ = torch::jit::load(
FLAGS_torch_lane_aggregating_lane_encoding_file, device_);
torch_prediction_layer_ = torch::jit::load(
FLAGS_torch_lane_aggregating_prediction_layer_file, device_);
}
bool LaneAggregatingEvaluator::Evaluate(
Obstacle* obstacle_ptr, ObstaclesContainer* obstacles_container) {
// Sanity checks.
CHECK_NOTNULL(obstacle_ptr);
obstacle_ptr->SetEvaluatorType(evaluator_type_);
int id = obstacle_ptr->id();
if (!obstacle_ptr->latest_feature().IsInitialized()) {
AERROR << "Obstacle [" << id << "] has no latest feature.";
return false;
}
Feature* latest_feature_ptr = obstacle_ptr->mutable_latest_feature();
CHECK_NOTNULL(latest_feature_ptr);
if (!latest_feature_ptr->has_lane() ||
!latest_feature_ptr->lane().has_lane_graph_ordered()) {
AERROR << "Obstacle [" << id << "] has no lane graph.";
return false;
}
LaneGraph* lane_graph_ptr =
latest_feature_ptr->mutable_lane()->mutable_lane_graph_ordered();
CHECK_NOTNULL(lane_graph_ptr);
if (lane_graph_ptr->lane_sequence().empty()) {
AERROR << "Obstacle [" << id << "] has no lane sequences.";
return false;
}
ADEBUG << "There are " << lane_graph_ptr->lane_sequence_size()
<< " lane sequences to scan.";
// Extract features, and do model inferencing.
// 1. Encode the obstacle features.
std::vector<double> obstacle_feature_values;
if (!ExtractObstacleFeatures(obstacle_ptr, &obstacle_feature_values)) {
ADEBUG << "Failed to extract obstacle features for obs_id = " << id;
}
if (obstacle_feature_values.size() != OBSTACLE_FEATURE_SIZE) {
ADEBUG << "Obstacle [" << id << "] has fewer than "
<< "expected obstacle feature_values "
<< obstacle_feature_values.size() << ".";
return false;
}
ADEBUG << "Obstacle feature size = " << obstacle_feature_values.size();
std::vector<torch::jit::IValue> obstacle_encoding_inputs;
torch::Tensor obstacle_encoding_inputs_tensor =
torch::zeros({1, static_cast<int>(obstacle_feature_values.size())});
for (size_t i = 0; i < obstacle_feature_values.size(); ++i) {
obstacle_encoding_inputs_tensor[0][i] =
static_cast<float>(obstacle_feature_values[i]);
}
obstacle_encoding_inputs.push_back(
std::move(obstacle_encoding_inputs_tensor));
torch::Tensor obstalce_encoding =
torch_obstacle_encoding_.forward(obstacle_encoding_inputs)
.toTensor()
.to(torch::kCPU);
// 2. Encode the lane features.
std::vector<std::vector<double>> lane_feature_values;
std::vector<int> lane_sequence_idx_to_remove;
if (!ExtractStaticEnvFeatures(obstacle_ptr, lane_graph_ptr,
&lane_feature_values,
&lane_sequence_idx_to_remove)) {
AERROR << "Failed to extract static environmental features around obs_id = "
<< id;
}
std::vector<torch::Tensor> lane_encoding_list;
for (const auto& single_lane_feature_values : lane_feature_values) {
if (single_lane_feature_values.size() !=
SINGLE_LANE_FEATURE_SIZE *
(LANE_POINTS_SIZE + BACKWARD_LANE_POINTS_SIZE)) {
AERROR << "Obstacle [" << id << "] has incorrect lane feature size.";
return false;
}
std::vector<torch::jit::IValue> single_lane_encoding_inputs;
torch::Tensor single_lane_encoding_inputs_tensor =
torch::zeros({1, SINGLE_LANE_FEATURE_SIZE * LANE_POINTS_SIZE});
for (size_t i = 0; i < SINGLE_LANE_FEATURE_SIZE * LANE_POINTS_SIZE; ++i) {
single_lane_encoding_inputs_tensor[0][i] = static_cast<float>(
single_lane_feature_values[i + SINGLE_LANE_FEATURE_SIZE *
BACKWARD_LANE_POINTS_SIZE]);
}
single_lane_encoding_inputs.push_back(
std::move(single_lane_encoding_inputs_tensor));
torch::Tensor single_lane_encoding =
torch_lane_encoding_.forward(single_lane_encoding_inputs)
.toTensor()
.to(torch::kCPU);
lane_encoding_list.push_back(std::move(single_lane_encoding));
}
// 3. Aggregate the lane features.
// torch::Tensor aggregated_lane_encoding =
// AggregateLaneEncodings(lane_encoding_list);
// 4. Make prediction.
std::vector<double> prediction_scores;
for (size_t i = 0; i < lane_encoding_list.size(); ++i) {
std::vector<torch::jit::IValue> prediction_layer_inputs;
torch::Tensor prediction_layer_inputs_tensor = torch::zeros(
{1, OBSTACLE_ENCODING_SIZE + SINGLE_LANE_ENCODING_SIZE + 1});
for (size_t j = 0; j < OBSTACLE_ENCODING_SIZE; ++j) {
prediction_layer_inputs_tensor[0][j] = obstalce_encoding[0][j];
}
for (size_t j = 0; j + 1 < SINGLE_LANE_ENCODING_SIZE; ++j) {
prediction_layer_inputs_tensor[0][OBSTACLE_ENCODING_SIZE + j] =
lane_encoding_list[i][0][j];
}
prediction_layer_inputs_tensor[0][OBSTACLE_ENCODING_SIZE +
SINGLE_LANE_ENCODING_SIZE - 1] =
static_cast<float>(lane_feature_values[i][SINGLE_LANE_FEATURE_SIZE *
BACKWARD_LANE_POINTS_SIZE]);
prediction_layer_inputs_tensor[0][OBSTACLE_ENCODING_SIZE +
SINGLE_LANE_ENCODING_SIZE] = 0.0;
// for (size_t j = 0; j < AGGREGATED_ENCODING_SIZE; ++j) {
// prediction_layer_inputs_tensor[0][OBSTACLE_ENCODING_SIZE +
// SINGLE_LANE_ENCODING_SIZE + j] =
// aggregated_lane_encoding[0][j];
// }
prediction_layer_inputs.push_back(
std::move(prediction_layer_inputs_tensor));
torch::Tensor prediction_layer_output =
torch_prediction_layer_.forward(prediction_layer_inputs)
.toTensor()
.to(torch::kCPU);
auto prediction_score = prediction_layer_output.accessor<float, 2>();
prediction_scores.push_back(static_cast<double>(prediction_score[0][0]));
}
// Pass the predicted result to the predictor to plot trajectory.
std::vector<double> output_probabilities = StableSoftmax(prediction_scores);
for (int i = 0; i < lane_graph_ptr->lane_sequence_size(); ++i) {
lane_graph_ptr->mutable_lane_sequence(i)->set_probability(
output_probabilities[i]);
ADEBUG << output_probabilities[i];
}
*(latest_feature_ptr->mutable_lane()->mutable_lane_graph()) = *lane_graph_ptr;
return true;
}
bool LaneAggregatingEvaluator::ExtractObstacleFeatures(
const Obstacle* obstacle_ptr, std::vector<double>* feature_values) {
// Sanity checks.
CHECK_NOTNULL(obstacle_ptr);
feature_values->clear();
FLAGS_cruise_historical_frame_length = 20;
std::vector<double> has_history(FLAGS_cruise_historical_frame_length, 1.0);
std::vector<std::pair<double, double>> pos_history(
FLAGS_cruise_historical_frame_length, std::make_pair(0.0, 0.0));
std::vector<std::pair<double, double>> vel_history(
FLAGS_cruise_historical_frame_length, std::make_pair(0.0, 0.0));
std::vector<std::pair<double, double>> acc_history(
FLAGS_cruise_historical_frame_length, std::make_pair(0.0, 0.0));
std::vector<double> vel_heading_history(FLAGS_cruise_historical_frame_length,
0.0);
std::vector<double> vel_heading_changing_rate_history(
FLAGS_cruise_historical_frame_length, 0.0);
// Get obstacle's current position to set up the relative coord. system.
const Feature& obs_curr_feature = obstacle_ptr->latest_feature();
double obs_curr_heading = obs_curr_feature.velocity_heading();
std::pair<double, double> obs_curr_pos = std::make_pair(
obs_curr_feature.position().x(), obs_curr_feature.position().y());
double prev_timestamp = obs_curr_feature.timestamp();
// Starting from the most recent timestamp and going backward.
ADEBUG << "Obstacle has " << obstacle_ptr->history_size()
<< " history timestamps.";
for (std::size_t i = 0; i < std::min(obstacle_ptr->history_size(),
FLAGS_cruise_historical_frame_length);
++i) {
const Feature& feature = obstacle_ptr->feature(i);
if (!feature.IsInitialized()) {
has_history[i] = 0.0;
continue;
}
if (i != 0 && has_history[i - 1] == 0.0) {
has_history[i] = 0.0;
continue;
}
// Extract normalized position info.
if (feature.has_position()) {
pos_history[i] = WorldCoordToObjCoord(
std::make_pair(feature.position().x(), feature.position().y()),
obs_curr_pos, obs_curr_heading);
} else {
has_history[i] = 0.0;
}
// Extract normalized velocity info.
if (feature.has_velocity()) {
auto vel_end = WorldCoordToObjCoord(
std::make_pair(feature.velocity().x(), feature.velocity().y()),
obs_curr_pos, obs_curr_heading);
auto vel_begin = WorldCoordToObjCoord(std::make_pair(0.0, 0.0),
obs_curr_pos, obs_curr_heading);
vel_history[i] = std::make_pair(vel_end.first - vel_begin.first,
vel_end.second - vel_begin.second);
} else {
has_history[i] = 0.0;
}
// Extract normalized acceleration info.
if (feature.has_acceleration()) {
auto acc_end =
WorldCoordToObjCoord(std::make_pair(feature.acceleration().x(),
feature.acceleration().y()),
obs_curr_pos, obs_curr_heading);
auto acc_begin = WorldCoordToObjCoord(std::make_pair(0.0, 0.0),
obs_curr_pos, obs_curr_heading);
acc_history[i] = std::make_pair(acc_end.first - acc_begin.first,
acc_end.second - acc_begin.second);
} else {
has_history[i] = 0.0;
}
// Extract velocity heading info.
if (feature.has_velocity_heading()) {
vel_heading_history[i] =
WorldAngleToObjAngle(feature.velocity_heading(), obs_curr_heading);
if (i != 0) {
vel_heading_changing_rate_history[i] =
(vel_heading_history[i] - vel_heading_history[i - 1]) /
(feature.timestamp() - prev_timestamp + FLAGS_double_precision);
prev_timestamp = feature.timestamp();
}
} else {
has_history[i] = 0.0;
}
}
for (std::size_t i = obstacle_ptr->history_size();
i < FLAGS_cruise_historical_frame_length; ++i) {
has_history[i] = 0.0;
}
// Update the extracted features into the feature_values vector.
for (std::size_t i = 0; i < FLAGS_cruise_historical_frame_length; i++) {
feature_values->push_back(has_history[i]);
feature_values->push_back(pos_history[i].first);
feature_values->push_back(pos_history[i].second);
feature_values->push_back(vel_history[i].first);
feature_values->push_back(vel_history[i].second);
feature_values->push_back(acc_history[i].first);
feature_values->push_back(acc_history[i].second);
feature_values->push_back(vel_heading_history[i]);
feature_values->push_back(vel_heading_changing_rate_history[i]);
}
return true;
}
bool LaneAggregatingEvaluator::ExtractStaticEnvFeatures(
const Obstacle* obstacle_ptr, const LaneGraph* lane_graph_ptr,
std::vector<std::vector<double>>* feature_values,
std::vector<int>* lane_sequence_idx_to_remove) {
// Sanity checks.
CHECK_NOTNULL(lane_graph_ptr);
feature_values->clear();
// Get obstacle's current position to set up the relative coord. system.
const Feature& obs_curr_feature = obstacle_ptr->latest_feature();
double obs_curr_heading = obs_curr_feature.velocity_heading();
std::pair<double, double> obs_curr_pos = std::make_pair(
obs_curr_feature.position().x(), obs_curr_feature.position().y());
// Go through every lane-sequence (ordered from left to right) and
// extract needed features.
for (int i = 0; i < lane_graph_ptr->lane_sequence_size(); ++i) {
// Get all the properties of the current lane-sequence.
// Go through all the lane-points to fill up the feature_values.
const LaneSequence& lane_sequence = lane_graph_ptr->lane_sequence(i);
std::vector<double> curr_feature_values;
// Extract features from backward lane-points.
size_t count = 0;
std::vector<double> backward_feature_values;
for (int j = lane_sequence.adc_lane_segment_idx(); j >= 0; --j) {
if (count >= SINGLE_LANE_FEATURE_SIZE * BACKWARD_LANE_POINTS_SIZE) {
break;
}
const LaneSegment& lane_segment = lane_sequence.lane_segment(j);
int k_starting_idx = lane_segment.lane_point_size() - 1;
if (j == lane_sequence.adc_lane_segment_idx()) {
k_starting_idx = std::min(lane_segment.adc_lane_point_idx(),
lane_segment.lane_point_size() - 1);
}
for (int k = k_starting_idx; k >= 0; --k) {
if (count >= SINGLE_LANE_FEATURE_SIZE * BACKWARD_LANE_POINTS_SIZE) {
break;
}
const LanePoint& lane_point = lane_segment.lane_point(k);
std::pair<double, double> relative_s_l =
WorldCoordToObjCoord(std::make_pair(lane_point.position().x(),
lane_point.position().y()),
obs_curr_pos, obs_curr_heading);
double relative_ang =
WorldAngleToObjAngle(lane_point.heading(), obs_curr_heading);
backward_feature_values.push_back(lane_point.kappa());
backward_feature_values.push_back(relative_ang);
backward_feature_values.push_back(relative_s_l.first);
backward_feature_values.push_back(relative_s_l.second);
count += 4;
}
}
// If lane-points are not enough, then extrapolate linearly.
while (count >= SINGLE_LANE_FEATURE_SIZE * 2 &&
count < SINGLE_LANE_FEATURE_SIZE * BACKWARD_LANE_POINTS_SIZE) {
std::size_t s = backward_feature_values.size();
double relative_l_new =
2 * backward_feature_values[s - 1] - backward_feature_values[s - 5];
double relative_s_new =
2 * backward_feature_values[s - 2] - backward_feature_values[s - 6];
double relative_ang_new = backward_feature_values[s - 3];
backward_feature_values.push_back(0.0);
backward_feature_values.push_back(relative_ang_new);
backward_feature_values.push_back(relative_s_new);
backward_feature_values.push_back(relative_l_new);
count += 4;
}
for (int j = static_cast<int>(backward_feature_values.size()) - 1; j >= 0;
--j) {
curr_feature_values.push_back(backward_feature_values[j]);
}
// Extract features from forward lane-points.
count = 0;
for (int j = lane_sequence.adc_lane_segment_idx();
j < lane_sequence.lane_segment_size(); ++j) {
if (count >= SINGLE_LANE_FEATURE_SIZE * LANE_POINTS_SIZE) {
break;
}
const LaneSegment& lane_segment = lane_sequence.lane_segment(j);
int k_starting_idx = 0;
if (j == lane_sequence.adc_lane_segment_idx()) {
k_starting_idx = std::min(lane_segment.adc_lane_point_idx(),
lane_segment.lane_point_size() - 1);
}
for (int k = k_starting_idx; k < lane_segment.lane_point_size(); ++k) {
if (count >= SINGLE_LANE_FEATURE_SIZE * LANE_POINTS_SIZE) {
break;
}
const LanePoint& lane_point = lane_segment.lane_point(k);
std::pair<double, double> relative_s_l =
WorldCoordToObjCoord(std::make_pair(lane_point.position().x(),
lane_point.position().y()),
obs_curr_pos, obs_curr_heading);
double relative_ang =
WorldAngleToObjAngle(lane_point.heading(), obs_curr_heading);
curr_feature_values.push_back(relative_s_l.second);
curr_feature_values.push_back(relative_s_l.first);
curr_feature_values.push_back(relative_ang);
curr_feature_values.push_back(lane_point.kappa());
count += 4;
}
}
// If lane-points are not enough, then extrapolate linearly.
while (count >= SINGLE_LANE_FEATURE_SIZE * 2 &&
count < SINGLE_LANE_FEATURE_SIZE * LANE_POINTS_SIZE) {
std::size_t s = curr_feature_values.size();
double relative_l_new =
2 * curr_feature_values[s - 4] - curr_feature_values[s - 8];
double relative_s_new =
2 * curr_feature_values[s - 3] - curr_feature_values[s - 7];
double relative_ang_new = curr_feature_values[s - 2];
curr_feature_values.push_back(relative_l_new);
curr_feature_values.push_back(relative_s_new);
curr_feature_values.push_back(relative_ang_new);
curr_feature_values.push_back(0.0);
count += 4;
}
feature_values->push_back(curr_feature_values);
}
return true;
}
torch::Tensor LaneAggregatingEvaluator::AggregateLaneEncodings(
const std::vector<torch::Tensor>& lane_encoding_list) {
torch::Tensor output_tensor =
torch::zeros({1, SINGLE_LANE_ENCODING_SIZE * 2});
torch::Tensor max_pooling_tensor = LaneEncodingMaxPooling(lane_encoding_list);
torch::Tensor avg_pooling_tensor = LaneEncodingAvgPooling(lane_encoding_list);
for (size_t i = 0; i < SINGLE_LANE_ENCODING_SIZE; ++i) {
output_tensor[0][i] = max_pooling_tensor[0][i];
}
for (size_t i = 0; i < SINGLE_LANE_ENCODING_SIZE; ++i) {
output_tensor[0][SINGLE_LANE_ENCODING_SIZE + i] = avg_pooling_tensor[0][i];
}
return output_tensor;
}
torch::Tensor LaneAggregatingEvaluator::LaneEncodingMaxPooling(
const std::vector<torch::Tensor>& lane_encoding_list) {
ACHECK(!lane_encoding_list.empty());
torch::Tensor output_tensor = lane_encoding_list[0];
for (size_t i = 1; i < lane_encoding_list.size(); ++i) {
for (size_t j = 0; j < SINGLE_LANE_ENCODING_SIZE; ++j) {
output_tensor[0][j] =
torch::max(output_tensor[0][j], lane_encoding_list[i][0][j]);
}
}
return output_tensor;
}
torch::Tensor LaneAggregatingEvaluator::LaneEncodingAvgPooling(
const std::vector<torch::Tensor>& lane_encoding_list) {
ACHECK(!lane_encoding_list.empty());
torch::Tensor output_tensor = lane_encoding_list[0];
for (size_t i = 1; i < lane_encoding_list.size(); ++i) {
for (size_t j = 0; j < SINGLE_LANE_ENCODING_SIZE; ++j) {
output_tensor[0][j] += lane_encoding_list[i][0][j];
}
}
torch::Tensor lane_encoding_list_size = torch::zeros({1});
lane_encoding_list_size[0] = static_cast<float>(lane_encoding_list.size());
for (size_t i = 0; i < SINGLE_LANE_ENCODING_SIZE; ++i) {
output_tensor[0][i] /= lane_encoding_list_size[0];
}
return output_tensor;
}
std::vector<double> LaneAggregatingEvaluator::StableSoftmax(
const std::vector<double>& prediction_scores) {
double max_score = prediction_scores[0];
for (const auto& prediction_score : prediction_scores) {
max_score = std::fmax(max_score, prediction_score);
}
std::vector<double> output_probabilities;
for (const auto& prediction_score : prediction_scores) {
output_probabilities.push_back(std::exp(prediction_score - max_score));
}
double denominator = 0.0;
for (const auto& element : output_probabilities) {
denominator += element;
}
for (auto& element : output_probabilities) {
element = element / denominator;
}
return output_probabilities;
}
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/prediction/evaluator
|
apollo_public_repos/apollo/modules/prediction/evaluator/vehicle/junction_mlp_evaluator.h
|
/******************************************************************************
* 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.
*****************************************************************************/
#pragma once
#include <string>
#include <vector>
#include "torch/script.h"
#include "torch/torch.h"
#include "modules/prediction/container/obstacles/obstacles_container.h"
#include "modules/prediction/evaluator/evaluator.h"
namespace apollo {
namespace prediction {
class JunctionMLPEvaluator : public Evaluator {
public:
/**
* @brief Constructor
*/
JunctionMLPEvaluator();
/**
* @brief Destructor
*/
virtual ~JunctionMLPEvaluator() = default;
/**
* @brief Clear obstacle feature map
*/
void Clear();
/**
* @brief Override Evaluate
* @param Obstacle pointer
* @param Obstacles container
*/
bool Evaluate(Obstacle* obstacle_ptr,
ObstaclesContainer* obstacles_container) override;
/**
* @brief Extract feature vector
* @param Obstacle pointer
* @param Obstacles container
* @param Feature container in a vector for receiving the feature values
*/
void ExtractFeatureValues(Obstacle* obstacle_ptr,
ObstaclesContainer* obstacles_container,
std::vector<double>* feature_values);
/**
* @brief Get the name of evaluator.
*/
std::string GetName() override { return "JUNCTION_MLP_EVALUATOR"; }
private:
/**
* @brief Set obstacle feature vector
* @param Obstacle pointer
* Feature container in a vector for receiving the feature values
*/
void SetObstacleFeatureValues(Obstacle* obstacle_ptr,
std::vector<double>* const feature_values);
/**
* @brief Set ego vehicle feature vector
* @param Obstacle pointer
* @param Obstacles container
* @param Feature container in a vector for receiving the feature values
*/
void SetEgoVehicleFeatureValues(Obstacle* obstacle_ptr,
ObstaclesContainer* obstacles_container,
std::vector<double>* const feature_values);
/**
* @brief Set junction feature vector
* @param Obstacle pointer
* Feature container in a vector for receiving the feature values
*/
void SetJunctionFeatureValues(Obstacle* obstacle_ptr,
std::vector<double>* const feature_values);
/**
* @brief Load model file
*/
void LoadModel();
private:
// obstacle feature with 4 basic features and 5 frames of history position
static const size_t OBSTACLE_FEATURE_SIZE = 4 + 2 * 5;
// ego vehicle feature of position and velocity
static const size_t EGO_VEHICLE_FEATURE_SIZE = 4;
// junction feature on 12 fan area 8 dim each
static const size_t JUNCTION_FEATURE_SIZE = 12 * 8;
torch::jit::script::Module torch_model_;
torch::Device device_;
};
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/prediction/evaluator
|
apollo_public_repos/apollo/modules/prediction/evaluator/vehicle/vectornet_evaluator.h
|
/******************************************************************************
* Copyright 2021 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.
*****************************************************************************/
#pragma once
#include <string>
#include <utility>
#include <vector>
#include "torch/extension.h"
#include "torch/script.h"
#include "modules/prediction/evaluator/evaluator.h"
#include "modules/prediction/pipeline/vector_net.h"
namespace apollo {
namespace prediction {
class VectornetEvaluator : public Evaluator {
public:
/**
* @brief Constructor
*/
VectornetEvaluator();
/**
* @brief Destructor
*/
virtual ~VectornetEvaluator() = default;
/**
* @brief Clear obstacle feature map
*/
void Clear();
/**
* @brief Process obstacle position to vector
* @param Obstacles pointer
* @param Obstacles container
* @param Tensor: target obstacle position
* @param Tensor: target obstacle position step
* @param Tensor: vector mask
* @param Tensor: all obstacle position
* @param Tensor: all obstacle p_id
* @param Tensor: all obstacle length
*/
bool VectornetProcessObstaclePosition(Obstacle* obstacle_ptr,
ObstaclesContainer* obstacles_container,
torch::Tensor* ptr_target_obs_pos,
torch::Tensor* ptr_target_obs_pos_step,
torch::Tensor* ptr_vector_mask,
torch::Tensor* ptr_obstacle_data,
torch::Tensor* ptr_all_obs_p_id);
/**
* @brief Process map data to vector
* @param FeatureVector: map feature vector
* @param int: obstacle number
* @param PidVector: map p_id vector
* @param Tensor: map data
* @param Tensor: map data p_id
*/
bool VectornetProcessMapData(FeatureVector *map_feature,
PidVector *map_p_id,
const int obs_num,
torch::Tensor* ptr_map_data,
torch::Tensor* ptr_all_map_p_id,
torch::Tensor* ptr_vector_mask);
/**
* @brief Override Evaluate
* @param Obstacle pointer
* @param Obstacles container
*/
bool Evaluate(Obstacle* obstacle_ptr,
ObstaclesContainer* obstacles_container) override;
/**
* @brief Extract all obstacles history
* @param Obstacles container
* Feature container in a vector for receiving the obstacle history
*/
bool ExtractObstaclesHistory(
Obstacle* obstacle_ptr, ObstaclesContainer* obstacles_container,
std::vector<std::pair<double, double>>* curr_pos_history,
std::vector<std::pair<double, double>>* all_obs_length,
std::vector<std::vector<std::pair<double, double>>>* all_obs_pos_history,
torch::Tensor* vector_mask);
/**
* @brief Get the name of evaluator.
*/
std::string GetName() override { return "VECTORNET_EVALUATOR"; }
private:
/**
* @brief Load model file
*/
void LoadModel();
private:
torch::jit::script::Module torch_vehicle_model_;
at::Tensor torch_default_output_tensor_;
torch::Device device_;
VectorNet vector_net_;
};
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/prediction/evaluator
|
apollo_public_repos/apollo/modules/prediction/evaluator/vehicle/junction_mlp_evaluator.cc
|
/******************************************************************************
* 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.
*****************************************************************************/
#include "modules/prediction/evaluator/vehicle/junction_mlp_evaluator.h"
#include <algorithm>
#include <unordered_map>
#include <utility>
#include <omp.h>
#include "cyber/common/file.h"
#include "modules/common/adapters/proto/adapter_config.pb.h"
#include "modules/common/math/vec2d.h"
#include "modules/prediction/common/feature_output.h"
#include "modules/prediction/common/prediction_constants.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_map.h"
#include "modules/prediction/common/prediction_system_gflags.h"
#include "modules/prediction/common/prediction_util.h"
#include "modules/prediction/container/container_manager.h"
#include "modules/prediction/container/obstacles/obstacles_container.h"
namespace apollo {
namespace prediction {
using apollo::prediction::math_util::ComputePolynomial;
using apollo::prediction::math_util::EvaluateCubicPolynomial;
namespace {
double ComputeMean(const std::vector<double>& nums, size_t start, size_t end) {
int count = 0;
double sum = 0.0;
for (size_t i = start; i <= end && i < nums.size(); i++) {
sum += nums[i];
++count;
}
return (count == 0) ? 0.0 : sum / count;
}
} // namespace
JunctionMLPEvaluator::JunctionMLPEvaluator() : device_(torch::kCPU) {
evaluator_type_ = ObstacleConf::JUNCTION_MLP_EVALUATOR;
LoadModel();
}
void JunctionMLPEvaluator::Clear() {}
bool JunctionMLPEvaluator::Evaluate(Obstacle* obstacle_ptr,
ObstaclesContainer* obstacles_container) {
// Sanity checks.
omp_set_num_threads(1);
Clear();
CHECK_NOTNULL(obstacle_ptr);
obstacle_ptr->SetEvaluatorType(evaluator_type_);
int id = obstacle_ptr->id();
if (!obstacle_ptr->latest_feature().IsInitialized()) {
AERROR << "Obstacle [" << id << "] has no latest feature.";
return false;
}
Feature* latest_feature_ptr = obstacle_ptr->mutable_latest_feature();
CHECK_NOTNULL(latest_feature_ptr);
// Assume obstacle is NOT closed to any junction exit
if (!latest_feature_ptr->has_junction_feature() ||
latest_feature_ptr->junction_feature().junction_exit_size() < 1) {
ADEBUG << "Obstacle [" << id << "] has no junction_exit.";
return false;
}
std::vector<double> feature_values;
ExtractFeatureValues(obstacle_ptr, obstacles_container, &feature_values);
// Insert features to DataForLearning
if (FLAGS_prediction_offline_mode ==
PredictionConstants::kDumpDataForLearning) {
FeatureOutput::InsertDataForLearning(*latest_feature_ptr, feature_values,
"junction", nullptr);
ADEBUG << "Save extracted features for learning locally.";
return true; // Skip Compute probability for offline mode
}
std::vector<torch::jit::IValue> torch_inputs;
int input_dim = static_cast<int>(
OBSTACLE_FEATURE_SIZE + EGO_VEHICLE_FEATURE_SIZE + JUNCTION_FEATURE_SIZE);
torch::Tensor torch_input = torch::zeros({1, input_dim});
for (size_t i = 0; i < feature_values.size(); ++i) {
torch_input[0][i] = static_cast<float>(feature_values[i]);
}
torch_inputs.push_back(std::move(torch_input.to(device_)));
std::vector<double> probability;
if (latest_feature_ptr->junction_feature().junction_exit_size() > 1) {
at::Tensor torch_output_tensor =
torch_model_.forward(torch_inputs).toTensor().to(torch::kCPU);
auto torch_output = torch_output_tensor.accessor<float, 2>();
for (int i = 0; i < torch_output.size(1); ++i) {
probability.push_back(static_cast<double>(torch_output[0][i]));
}
} else {
for (int i = 0; i < 12; ++i) {
probability.push_back(feature_values[OBSTACLE_FEATURE_SIZE +
EGO_VEHICLE_FEATURE_SIZE + 8 * i]);
}
}
for (double prob : probability) {
latest_feature_ptr->mutable_junction_feature()
->add_junction_mlp_probability(prob);
}
// assign all lane_sequence probability
LaneGraph* lane_graph_ptr =
latest_feature_ptr->mutable_lane()->mutable_lane_graph();
CHECK_NOTNULL(lane_graph_ptr);
if (lane_graph_ptr->lane_sequence().empty()) {
AERROR << "Obstacle [" << id << "] has no lane sequences.";
return false;
}
std::unordered_map<std::string, double> junction_exit_prob;
for (const JunctionExit& junction_exit :
latest_feature_ptr->junction_feature().junction_exit()) {
double x =
junction_exit.exit_position().x() - latest_feature_ptr->position().x();
double y =
junction_exit.exit_position().y() - latest_feature_ptr->position().y();
double angle =
std::atan2(y, x) - std::atan2(latest_feature_ptr->raw_velocity().y(),
latest_feature_ptr->raw_velocity().x());
double d_idx = (angle / (2.0 * M_PI) + 1.0 / 24.0) * 12.0;
int idx = static_cast<int>(floor(d_idx >= 0 ? d_idx : d_idx + 12));
junction_exit_prob[junction_exit.exit_lane_id()] = probability[idx];
}
for (int i = 0; i < lane_graph_ptr->lane_sequence_size(); ++i) {
LaneSequence* lane_sequence_ptr = lane_graph_ptr->mutable_lane_sequence(i);
CHECK_NOTNULL(lane_sequence_ptr);
for (const LaneSegment& lane_segment : lane_sequence_ptr->lane_segment()) {
if (junction_exit_prob.find(lane_segment.lane_id()) !=
junction_exit_prob.end()) {
lane_sequence_ptr->set_probability(
junction_exit_prob[lane_segment.lane_id()]);
}
}
}
return true;
}
void JunctionMLPEvaluator::ExtractFeatureValues(
Obstacle* obstacle_ptr, ObstaclesContainer* obstacles_container,
std::vector<double>* feature_values) {
CHECK_NOTNULL(obstacle_ptr);
int id = obstacle_ptr->id();
std::vector<double> obstacle_feature_values;
SetObstacleFeatureValues(obstacle_ptr, &obstacle_feature_values);
if (obstacle_feature_values.size() != OBSTACLE_FEATURE_SIZE) {
AERROR << "Obstacle [" << id << "] has fewer than "
<< "expected obstacle feature_values "
<< obstacle_feature_values.size() << ".";
return;
}
std::vector<double> ego_vehicle_feature_values;
SetEgoVehicleFeatureValues(obstacle_ptr, obstacles_container,
&ego_vehicle_feature_values);
if (ego_vehicle_feature_values.size() != EGO_VEHICLE_FEATURE_SIZE) {
AERROR << "Obstacle [" << id << "] has fewer than "
<< "expected ego vehicle feature_values"
<< ego_vehicle_feature_values.size() << ".";
return;
}
std::vector<double> junction_feature_values;
SetJunctionFeatureValues(obstacle_ptr, &junction_feature_values);
if (junction_feature_values.size() != JUNCTION_FEATURE_SIZE) {
AERROR << "Obstacle [" << id << "] has fewer than "
<< "expected junction feature_values"
<< junction_feature_values.size() << ".";
return;
}
feature_values->insert(feature_values->end(), obstacle_feature_values.begin(),
obstacle_feature_values.end());
feature_values->insert(feature_values->end(),
ego_vehicle_feature_values.begin(),
ego_vehicle_feature_values.end());
feature_values->insert(feature_values->end(), junction_feature_values.begin(),
junction_feature_values.end());
}
void JunctionMLPEvaluator::SetObstacleFeatureValues(
Obstacle* obstacle_ptr, std::vector<double>* feature_values) {
feature_values->clear();
feature_values->reserve(OBSTACLE_FEATURE_SIZE);
const Feature& feature = obstacle_ptr->latest_feature();
if (!feature.has_position()) {
ADEBUG << "Obstacle [" << obstacle_ptr->id() << "] has no position.";
return;
}
std::pair<double, double> obs_curr_pos =
std::make_pair(feature.position().x(), feature.position().y());
double obs_curr_heading = feature.velocity_heading();
bool has_history = false;
std::vector<std::pair<double, double>> pos_history(
FLAGS_junction_historical_frame_length, std::make_pair(0.0, 0.0));
if (obstacle_ptr->history_size() > FLAGS_junction_historical_frame_length) {
has_history = true;
for (std::size_t i = 0; i < FLAGS_junction_historical_frame_length; ++i) {
const Feature& feature = obstacle_ptr->feature(i + 1);
if (!feature.IsInitialized()) {
has_history = false;
break;
}
if (feature.has_position()) {
pos_history[i] = WorldCoordToObjCoord(
std::make_pair(feature.position().x(), feature.position().y()),
obs_curr_pos, obs_curr_heading);
}
}
}
feature_values->push_back(feature.speed());
feature_values->push_back(feature.acc());
feature_values->push_back(feature.junction_feature().junction_range());
if (has_history) {
feature_values->push_back(1.0);
} else {
feature_values->push_back(0.0);
}
for (std::size_t i = 0; i < FLAGS_junction_historical_frame_length; i++) {
feature_values->push_back(pos_history[i].first);
feature_values->push_back(pos_history[i].second);
}
}
void JunctionMLPEvaluator::SetEgoVehicleFeatureValues(
Obstacle* obstacle_ptr, ObstaclesContainer* obstacles_container,
std::vector<double>* const feature_values) {
feature_values->clear();
*feature_values = std::vector<double>(4, 0.0);
auto ego_pose_obstacle_ptr =
obstacles_container->GetObstacle(FLAGS_ego_vehicle_id);
if (ego_pose_obstacle_ptr == nullptr ||
ego_pose_obstacle_ptr->history_size() == 0) {
(*feature_values)[0] = 100.0;
(*feature_values)[1] = 100.0;
return;
}
const auto ego_position = ego_pose_obstacle_ptr->latest_feature().position();
const auto ego_velocity = ego_pose_obstacle_ptr->latest_feature().velocity();
CHECK_GT(obstacle_ptr->history_size(), 0U);
const Feature& obstacle_feature = obstacle_ptr->latest_feature();
apollo::common::math::Vec2d ego_relative_position(
ego_position.x() - obstacle_feature.position().x(),
ego_position.y() - obstacle_feature.position().y());
apollo::common::math::Vec2d ego_relative_velocity(ego_velocity.x(),
ego_velocity.y());
ego_relative_velocity.rotate(-obstacle_feature.velocity_heading());
(*feature_values)[0] = ego_relative_position.x();
(*feature_values)[1] = ego_relative_position.y();
(*feature_values)[2] = ego_relative_velocity.x();
(*feature_values)[3] = ego_relative_velocity.y();
ADEBUG << "ego relative pos = {" << ego_relative_position.x() << ", "
<< ego_relative_position.y() << "} "
<< "ego_relative_velocity = {" << ego_relative_velocity.x() << ", "
<< ego_relative_velocity.y() << "}";
}
void JunctionMLPEvaluator::SetJunctionFeatureValues(
Obstacle* obstacle_ptr, std::vector<double>* feature_values) {
feature_values->clear();
feature_values->reserve(JUNCTION_FEATURE_SIZE);
Feature* feature_ptr = obstacle_ptr->mutable_latest_feature();
if (!feature_ptr->has_position()) {
ADEBUG << "Obstacle [" << obstacle_ptr->id() << "] has no position.";
return;
}
double heading = std::atan2(feature_ptr->raw_velocity().y(),
feature_ptr->raw_velocity().x());
if (!feature_ptr->has_junction_feature()) {
AERROR << "Obstacle [" << obstacle_ptr->id()
<< "] has no junction_feature.";
return;
}
std::string junction_id = feature_ptr->junction_feature().junction_id();
double junction_range = feature_ptr->junction_feature().junction_range();
for (int i = 0; i < 12; ++i) {
feature_values->push_back(0.0);
feature_values->push_back(0.0);
feature_values->push_back(0.0);
feature_values->push_back(1.0);
feature_values->push_back(1.0);
feature_values->push_back(1.0);
feature_values->push_back(0.0);
feature_values->push_back(0.0);
}
int num_junction_exit = feature_ptr->junction_feature().junction_exit_size();
for (int i = 0; i < num_junction_exit; ++i) {
const JunctionExit& junction_exit =
feature_ptr->junction_feature().junction_exit(i);
double x = junction_exit.exit_position().x() - feature_ptr->position().x();
double y = junction_exit.exit_position().y() - feature_ptr->position().y();
double diff_x = std::cos(-heading) * x - std::sin(-heading) * y;
double diff_y = std::sin(-heading) * x + std::cos(-heading) * y;
double diff_heading =
apollo::common::math::AngleDiff(heading, junction_exit.exit_heading());
double angle = std::atan2(diff_y, diff_x);
double d_idx = (angle / (2.0 * M_PI) + 1.0 / 24.0) * 12.0;
int idx = static_cast<int>(floor(d_idx >= 0 ? d_idx : d_idx + 12));
double speed = std::max(0.1, feature_ptr->speed());
double exit_time = std::hypot(diff_x, diff_y) / speed;
std::array<double, 2> start_x = {0, speed};
std::array<double, 2> end_x = {diff_x, std::cos(diff_heading) * speed};
std::array<double, 2> start_y = {0, 0};
std::array<double, 2> end_y = {diff_y, std::sin(diff_heading) * speed};
std::array<double, 4> x_coeffs =
ComputePolynomial<3>(start_x, end_x, exit_time);
std::array<double, 4> y_coeffs =
ComputePolynomial<3>(start_y, end_y, exit_time);
double t = 0.0;
double cost = 0.0;
while (t <= exit_time) {
double x_1 = EvaluateCubicPolynomial(x_coeffs, t, 1);
double x_2 = EvaluateCubicPolynomial(x_coeffs, t, 2);
double y_1 = EvaluateCubicPolynomial(y_coeffs, t, 1);
double y_2 = EvaluateCubicPolynomial(y_coeffs, t, 2);
// cost = curvature * v^2
cost = std::max(cost,
std::abs(x_1 * y_2 - y_1 * x_2) / std::hypot(x_1, y_1));
t += FLAGS_prediction_trajectory_time_resolution;
}
feature_values->operator[](idx * 8) = 1.0;
feature_values->operator[](idx * 8 + 1) = diff_x / junction_range;
feature_values->operator[](idx * 8 + 2) = diff_y / junction_range;
feature_values->operator[](idx * 8 + 3) =
std::sqrt(diff_x * diff_x + diff_y * diff_y) / junction_range;
feature_values->operator[](idx * 8 + 4) = diff_x;
feature_values->operator[](idx * 8 + 5) = diff_y;
feature_values->operator[](idx * 8 + 6) = diff_heading;
feature_values->operator[](idx * 8 + 7) = cost;
}
}
void JunctionMLPEvaluator::LoadModel() {
if (FLAGS_use_cuda && torch::cuda::is_available()) {
ADEBUG << "CUDA is available";
device_ = torch::Device(torch::kCUDA);
}
torch::set_num_threads(1);
torch_model_ =
torch::jit::load(FLAGS_torch_vehicle_junction_mlp_file, device_);
}
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/prediction/evaluator
|
apollo_public_repos/apollo/modules/prediction/evaluator/vehicle/junction_mlp_evaluator_test.cc
|
/******************************************************************************
* 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.
*****************************************************************************/
#include "modules/prediction/evaluator/vehicle/junction_mlp_evaluator.h"
#include "cyber/common/file.h"
#include "modules/prediction/common/junction_analyzer.h"
#include "modules/prediction/common/kml_map_based_test.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/container/obstacles/obstacles_container.h"
namespace apollo {
namespace prediction {
class JunctionMLPEvaluatorTest : public KMLMapBasedTest {
public:
void SetUp() override {
const std::string file =
"modules/prediction/testdata/"
"single_perception_vehicle_injunction.pb.txt";
ACHECK(cyber::common::GetProtoFromFile(file, &perception_obstacles_));
FLAGS_enable_all_junction = true;
}
protected:
apollo::perception::PerceptionObstacles perception_obstacles_;
};
TEST_F(JunctionMLPEvaluatorTest, InJunctionCase) {
EXPECT_DOUBLE_EQ(perception_obstacles_.header().timestamp_sec(),
1501183430.161906);
apollo::perception::PerceptionObstacle perception_obstacle =
perception_obstacles_.perception_obstacle(0);
EXPECT_EQ(perception_obstacle.id(), 1);
JunctionMLPEvaluator junction_mlp_evaluator;
ObstaclesContainer container;
container.GetJunctionAnalyzer()->Init("j2");
container.Insert(perception_obstacles_);
container.BuildJunctionFeature();
Obstacle* obstacle_ptr = container.GetObstacle(1);
EXPECT_NE(obstacle_ptr, nullptr);
junction_mlp_evaluator.Evaluate(obstacle_ptr, &container);
const JunctionFeature& junction_feature =
obstacle_ptr->latest_feature().junction_feature();
EXPECT_EQ(junction_feature.junction_id(), "j2");
EXPECT_GT(junction_feature.junction_exit_size(), 0);
for (const auto& junction_exit : junction_feature.junction_exit()) {
EXPECT_TRUE(junction_exit.has_exit_lane_id());
}
EXPECT_EQ(junction_feature.junction_mlp_probability_size(), 12);
junction_mlp_evaluator.Clear();
}
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/prediction/evaluator
|
apollo_public_repos/apollo/modules/prediction/evaluator/vehicle/cost_evaluator.h
|
/******************************************************************************
* 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.
*****************************************************************************/
#pragma once
#include <string>
#include "modules/prediction/evaluator/evaluator.h"
#include "modules/prediction/container/obstacles/obstacles_container.h"
namespace apollo {
namespace prediction {
class CostEvaluator : public Evaluator {
public:
/**
* @brief Constructor
*/
CostEvaluator();
/**
* @brief Destructor
*/
virtual ~CostEvaluator() = default;
/**
* @brief Override Evaluate
* @param Obstacle pointer
* @param Obstacles container
*/
bool Evaluate(Obstacle* obstacle_ptr,
ObstaclesContainer* obstacles_container) override;
/**
* @brief Get the name of evaluator.
*/
std::string GetName() override { return "COST_EVALUATOR"; }
private:
double ComputeProbability(const double obstacle_length,
const double obstacle_width,
const LaneSequence& lane_sequence);
double FrontLateralDistanceCost(const double obstacle_length,
const double obstacle_width,
const LaneSequence& lane_sequence);
};
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/prediction/evaluator
|
apollo_public_repos/apollo/modules/prediction/evaluator/vehicle/cost_evaluator_test.cc
|
/******************************************************************************
* 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.
*****************************************************************************/
#include "modules/prediction/evaluator/vehicle/cost_evaluator.h"
#include "cyber/common/file.h"
#include "modules/prediction/common/kml_map_based_test.h"
#include "modules/prediction/container/obstacles/obstacles_container.h"
namespace apollo {
namespace prediction {
class CostEvaluatorTest : public KMLMapBasedTest {
public:
void SetUp() override {
const std::string file =
"modules/prediction/testdata/single_perception_vehicle_onlane.pb.txt";
ACHECK(cyber::common::GetProtoFromFile(file, &perception_obstacles_));
}
protected:
apollo::perception::PerceptionObstacles perception_obstacles_;
};
TEST_F(CostEvaluatorTest, OnLaneCase) {
EXPECT_DOUBLE_EQ(perception_obstacles_.header().timestamp_sec(),
1501183430.161906);
apollo::perception::PerceptionObstacle perception_obstacle =
perception_obstacles_.perception_obstacle(0);
EXPECT_EQ(perception_obstacle.id(), 1);
CostEvaluator cost_evaluator;
ObstaclesContainer container;
container.Insert(perception_obstacles_);
Obstacle* obstacle_ptr = container.GetObstacle(1);
EXPECT_NE(obstacle_ptr, nullptr);
cost_evaluator.Evaluate(obstacle_ptr, &container);
const Feature& feature = obstacle_ptr->latest_feature();
const LaneGraph& lane_graph = feature.lane().lane_graph();
for (const auto& lane_sequence : lane_graph.lane_sequence()) {
EXPECT_TRUE(lane_sequence.has_probability());
}
}
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/prediction/evaluator
|
apollo_public_repos/apollo/modules/prediction/evaluator/vehicle/vectornet_evaluator.cc
|
/******************************************************************************
* Copyright 2021 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.
*****************************************************************************/
#include "modules/prediction/evaluator/vehicle/vectornet_evaluator.h"
#include <limits>
#include <omp.h>
#include "Eigen/Dense"
#include "cyber/common/file.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_map.h"
#include "modules/prediction/common/prediction_system_gflags.h"
#include "modules/prediction/common/prediction_util.h"
namespace apollo {
namespace prediction {
using apollo::common::TrajectoryPoint;
using apollo::common::math::Vec2d;
using apollo::prediction::VectorNet;
VectornetEvaluator::VectornetEvaluator() : device_(torch::kCPU) {
evaluator_type_ = ObstacleConf::VECTORNET_EVALUATOR;
LoadModel();
}
void VectornetEvaluator::Clear() {}
bool VectornetEvaluator::VectornetProcessObstaclePosition(
Obstacle* obstacle_ptr,
ObstaclesContainer* obstacles_container,
torch::Tensor* ptr_target_obs_pos,
torch::Tensor* ptr_target_obs_pos_step,
torch::Tensor* ptr_vector_mask,
torch::Tensor* ptr_obstacle_data,
torch::Tensor* ptr_all_obs_p_id) {
// Extract features of pos_history
std::vector<std::pair<double, double>> target_pos_history(20, {0.0, 0.0});
std::vector<std::pair<double, double>> all_obs_length;
std::vector<std::vector<std::pair<double, double>>> all_obs_pos_history;
if (!ExtractObstaclesHistory(obstacle_ptr, obstacles_container,
&target_pos_history, &all_obs_length,
&all_obs_pos_history, ptr_vector_mask)) {
ADEBUG << "Obstacle [" << obstacle_ptr->id()
<< "] failed to extract obstacle history";
return false;
}
for (int j = 0; j < 20; ++j) {
ptr_target_obs_pos->index_put_({19 - j, 0}, target_pos_history[j].first);
ptr_target_obs_pos->index_put_({19 - j, 1}, target_pos_history[j].second);
if (j == 19 || (j > 0 && target_pos_history[j + 1].first == 0.0)) {
break;
}
ptr_target_obs_pos_step->index_put_(
{19 - j, 0},
target_pos_history[j].first - target_pos_history[j + 1].first);
ptr_target_obs_pos_step->index_put_(
{19 - j, 1},
target_pos_history[j].second - target_pos_history[j + 1].second);
}
int obs_num =
obstacles_container->curr_frame_considered_obstacle_ids().size();
torch::Tensor all_obstacle_pos = torch::zeros({obs_num, 20, 2});
torch::Tensor obs_length_data = torch::zeros({obs_num, 2});
auto opts = torch::TensorOptions().dtype(torch::kDouble);
for (int i = 0; i < obs_num; ++i) {
std::vector<double> obs_p_id{std::numeric_limits<float>::max(),
std::numeric_limits<float>::max()};
for (int j = 0; j < 20; ++j) {
// Process obs pid
if (obs_p_id[0] > all_obs_pos_history[i][j].first) {
obs_p_id[0] = all_obs_pos_history[i][j].first;
}
if (obs_p_id[1] > all_obs_pos_history[i][j].second) {
obs_p_id[1] = all_obs_pos_history[i][j].second;
}
// Process obs pos history
all_obstacle_pos.index_put_(
{i, 19 - j, 0},
all_obs_pos_history[i][j].first);
all_obstacle_pos.index_put_(
{i, 19 - j, 1},
all_obs_pos_history[i][j].second);
}
ptr_all_obs_p_id->index_put_({i},
torch::from_blob(obs_p_id.data(), {2}, opts));
obs_length_data.index_put_({i, 0}, all_obs_length[i].first);
obs_length_data.index_put_({i, 1}, all_obs_length[i].second);
}
// Extend obs data to specific dimension
torch::Tensor obs_pos_data = torch::cat(
{all_obstacle_pos.index(
{torch::indexing::Slice(),
torch::indexing::Slice(torch::indexing::None, -1),
torch::indexing::Slice()}),
all_obstacle_pos.index({torch::indexing::Slice(),
torch::indexing::Slice(1, torch::indexing::None),
torch::indexing::Slice()})},
2);
// Add obs attribute
torch::Tensor obs_attr_agent =
torch::tensor({11.0, 4.0}).unsqueeze(0).unsqueeze(0).repeat({1, 19, 1});
torch::Tensor obs_attr_other =
torch::tensor({10.0, 4.0}).unsqueeze(0).unsqueeze(0).repeat(
{(obs_num - 1), 19, 1});
torch::Tensor obs_attr = torch::cat({obs_attr_agent, obs_attr_other}, 0);
// ADD obs id
// add 500 to avoid same id as in map_info
torch::Tensor obs_id =
torch::arange(500,
obs_num + 500).unsqueeze(1).repeat({1, 19}).unsqueeze(2);
// Process obs data
obs_length_data = obs_length_data.unsqueeze(1).repeat({1, 19, 1});
torch::Tensor obs_data_with_len =
torch::cat({obs_pos_data, obs_length_data}, 2);
torch::Tensor obs_data_with_attr =
torch::cat({obs_data_with_len, obs_attr}, 2);
torch::Tensor obs_data_with_id = torch::cat({obs_data_with_attr, obs_id}, 2);
*ptr_obstacle_data =
torch::cat({torch::zeros({obs_num, (50 - 19), 9}), obs_data_with_id}, 1);
return true;
}
bool VectornetEvaluator::VectornetProcessMapData(
FeatureVector* map_feature,
PidVector* map_p_id,
const int obs_num,
torch::Tensor* ptr_map_data,
torch::Tensor* ptr_all_map_p_id,
torch::Tensor* ptr_vector_mask) {
int map_polyline_num = map_feature->size();
for (int i = 0; i < map_polyline_num && obs_num + i < 450; ++i) {
size_t one_polyline_vector_size = map_feature->at(i).size();
if (one_polyline_vector_size < 50) {
ptr_vector_mask->index_put_({obs_num + i,
torch::indexing::Slice(
one_polyline_vector_size,
torch::indexing::None)},
1);
}
}
auto opts = torch::TensorOptions().dtype(torch::kDouble);
for (int i = 0; i < map_polyline_num && i + obs_num < 450; ++i) {
ptr_all_map_p_id->index_put_({i}, torch::from_blob(map_p_id->at(i).data(),
{2},
opts));
int one_polyline_vector_size = map_feature->at(i).size();
for (int j = 0; j < one_polyline_vector_size && j < 50; ++j) {
ptr_map_data->index_put_({i, j},
torch::from_blob(map_feature->at(i)[j].data(),
{9},
opts));
}
}
*ptr_map_data = ptr_map_data->toType(at::kFloat);
*ptr_all_map_p_id = ptr_all_map_p_id->toType(at::kFloat);
return true;
}
bool VectornetEvaluator::Evaluate(Obstacle* obstacle_ptr,
ObstaclesContainer* obstacles_container) {
omp_set_num_threads(1);
obstacle_ptr->SetEvaluatorType(evaluator_type_);
Clear();
CHECK_NOTNULL(obstacle_ptr);
int id = obstacle_ptr->id();
if (!obstacle_ptr->latest_feature().IsInitialized()) {
AERROR << "Obstacle [" << id << "] has no latest feature.";
return false;
}
int obs_num =
obstacles_container->curr_frame_considered_obstacle_ids().size();
auto start_time_obs = std::chrono::system_clock::now();
torch::Tensor target_obstacle_pos = torch::zeros({20, 2});
torch::Tensor target_obstacle_pos_step = torch::zeros({20, 2});
torch::Tensor vector_mask = torch::zeros({450, 50});
torch::Tensor obstacle_data = torch::zeros({obs_num, 20, 2});
torch::Tensor all_obs_p_id = torch::zeros({obs_num, 2});
// torch::Tensor obs_length_tmp = torch::zeros({obs_num, 2});
if (!VectornetProcessObstaclePosition(obstacle_ptr,
obstacles_container,
&target_obstacle_pos,
&target_obstacle_pos_step,
&vector_mask,
&obstacle_data,
&all_obs_p_id)) {
AERROR << "Obstacle [" << id << "] processing obstacle position fails.";
return false;
}
auto end_time_obs = std::chrono::system_clock::now();
std::chrono::duration<double> diff_obs = end_time_obs - start_time_obs;
AINFO << "obstacle vectors used time: " << diff_obs.count() * 1000 << " ms.";
Feature* latest_feature_ptr = obstacle_ptr->mutable_latest_feature();
CHECK_NOTNULL(latest_feature_ptr);
// Query the map data
FeatureVector map_feature;
PidVector map_p_id;
const double pos_x = latest_feature_ptr->position().x();
const double pos_y = latest_feature_ptr->position().y();
common::PointENU center_point
= common::util::PointFactory::ToPointENU(pos_x, pos_y);;
const double heading = latest_feature_ptr->velocity_heading();
auto start_time_query = std::chrono::system_clock::now();
if (!vector_net_.query(center_point, heading, &map_feature, &map_p_id)) {
return false;
}
auto end_time_query = std::chrono::system_clock::now();
std::chrono::duration<double> diff_query = end_time_query - start_time_query;
AINFO << "vectors query used time: " << diff_query.count() * 1000 << " ms.";
// process map data & map p id & v_mask for map polyline
int map_polyline_num = map_feature.size();
int data_length =
((obs_num + map_polyline_num) < 450) ? (obs_num + map_polyline_num) : 450;
// Process input tensor
auto start_time_data_prep = std::chrono::system_clock::now();
torch::Tensor map_data = torch::zeros({map_polyline_num, 50, 9});
torch::Tensor all_map_p_id = torch::zeros({map_polyline_num, 2});
if (!VectornetProcessMapData(&map_feature,
&map_p_id,
obs_num,
&map_data,
&all_map_p_id,
&vector_mask)) {
AERROR << "Obstacle [" << id << "] processing map data fails.";
return false;
}
// process p mask
torch::Tensor polyline_mask = torch::zeros({450});
if (data_length < 450) {
polyline_mask.index_put_(
{torch::indexing::Slice(data_length, torch::indexing::None)}, 1);
}
// Extend data & pid to specific demension
torch::Tensor data_tmp = torch::cat({obstacle_data, map_data}, 0);
torch::Tensor p_id_tmp = torch::cat({all_obs_p_id, all_map_p_id}, 0);
torch::Tensor vector_data;
torch::Tensor polyline_id;
if (data_length < 450) {
torch::Tensor data_zeros = torch::zeros({(450 - data_length), 50, 9});
torch::Tensor p_id_zeros = torch::zeros({(450 - data_length), 2});
vector_data = torch::cat({data_tmp, data_zeros}, 0);
polyline_id = torch::cat({p_id_tmp, p_id_zeros}, 0);
} else {
vector_data = data_tmp.index({torch::indexing::Slice(0, 450)});
polyline_id = p_id_tmp.index({torch::indexing::Slice(0, 450)});
}
// Empty rand mask as placeholder
auto rand_mask = torch::zeros({450}).toType(at::kBool);
// Change mask type to bool
auto bool_vector_mask = vector_mask.toType(at::kBool);
auto bool_polyline_mask = polyline_mask.toType(at::kBool);
// Build input features for torch
std::vector<torch::jit::IValue> torch_inputs;
torch_inputs.push_back(c10::ivalue::Tuple::create(
{std::move(target_obstacle_pos.unsqueeze(0).to(device_)),
std::move(target_obstacle_pos_step.unsqueeze(0).to(device_)),
std::move(vector_data.unsqueeze(0).to(device_)),
std::move(bool_vector_mask.unsqueeze(0).to(device_)),
std::move(bool_polyline_mask.unsqueeze(0).to(device_)),
std::move(rand_mask.unsqueeze(0).to(device_)),
std::move(polyline_id.unsqueeze(0).to(device_))}));
auto end_time_data_prep = std::chrono::system_clock::now();
std::chrono::duration<double> diff_data_prep =
end_time_data_prep - start_time_data_prep;
AINFO << "vectornet input tensor preparation used time: "
<< diff_data_prep.count() * 1000 << " ms.";
auto start_time_inference = std::chrono::system_clock::now();
at::Tensor torch_output_tensor = torch_default_output_tensor_;
torch_output_tensor =
torch_vehicle_model_.forward(torch_inputs).toTensor().to(torch::kCPU);
auto end_time_inference = std::chrono::system_clock::now();
std::chrono::duration<double> diff_inference =
end_time_inference - start_time_inference;
AINFO << "vectornet inference used time: " << diff_inference.count() * 1000
<< " ms.";
// Get the trajectory
auto start_time_output_process = std::chrono::system_clock::now();
auto torch_output = torch_output_tensor.accessor<float, 3>();
Trajectory* trajectory = latest_feature_ptr->add_predicted_trajectory();
trajectory->set_probability(1.0);
for (int i = 0; i < 30; ++i) {
double prev_x = pos_x;
double prev_y = pos_y;
if (i > 0) {
const auto& last_point = trajectory->trajectory_point(i - 1).path_point();
prev_x = last_point.x();
prev_y = last_point.y();
}
TrajectoryPoint* point = trajectory->add_trajectory_point();
double dx = static_cast<double>(torch_output[0][i][0]);
double dy = static_cast<double>(torch_output[0][i][1]);
double heading = latest_feature_ptr->velocity_heading();
Vec2d offset(dx, dy);
Vec2d rotated_offset = offset.rotate(heading - (M_PI / 2));
double point_x = pos_x + rotated_offset.x();
double point_y = pos_y + rotated_offset.y();
point->mutable_path_point()->set_x(point_x);
point->mutable_path_point()->set_y(point_y);
if (i < 10) { // use origin heading for the first second
point->mutable_path_point()->set_theta(
latest_feature_ptr->velocity_heading());
} else {
point->mutable_path_point()->set_theta(
std::atan2(trajectory->trajectory_point(i).path_point().y() -
trajectory->trajectory_point(i - 1).path_point().y(),
trajectory->trajectory_point(i).path_point().x() -
trajectory->trajectory_point(i - 1).path_point().x()));
}
point->set_relative_time(static_cast<double>(i) *
FLAGS_prediction_trajectory_time_resolution);
if (i == 0) {
point->set_v(latest_feature_ptr->speed());
} else {
double diff_x = point_x - prev_x;
double diff_y = point_y - prev_y;
point->set_v(std::hypot(diff_x, diff_y) /
FLAGS_prediction_trajectory_time_resolution);
}
}
auto end_time_output_process = std::chrono::system_clock::now();
std::chrono::duration<double> diff_output_process =
end_time_output_process - start_time_output_process;
AINFO << "vectornet output process used time: "
<< diff_output_process.count() * 1000 << " ms.";
return true;
}
bool VectornetEvaluator::ExtractObstaclesHistory(
Obstacle* obstacle_ptr, ObstaclesContainer* obstacles_container,
std::vector<std::pair<double, double>>* target_pos_history,
std::vector<std::pair<double, double>>* all_obs_length,
std::vector<std::vector<std::pair<double, double>>>* all_obs_pos_history,
torch::Tensor* vector_mask) {
const Feature& obs_curr_feature = obstacle_ptr->latest_feature();
double obs_curr_heading = obs_curr_feature.velocity_heading();
std::pair<double, double> obs_curr_pos = std::make_pair(
obs_curr_feature.position().x(), obs_curr_feature.position().y());
// Extract target obstacle history
for (std::size_t i = 0; i < obstacle_ptr->history_size() && i < 20; ++i) {
const Feature& target_feature = obstacle_ptr->feature(i);
if (!target_feature.IsInitialized()) {
break;
}
target_pos_history->at(i) =
WorldCoordToObjCoordNorth(
std::make_pair(target_feature.position().x(),
target_feature.position().y()),
obs_curr_pos, obs_curr_heading);
}
all_obs_length->emplace_back(
std::make_pair(obs_curr_feature.length(), obs_curr_feature.width()));
all_obs_pos_history->emplace_back(*target_pos_history);
// Extract other obstacles & convert pos to traget obstacle relative coord
std::vector<std::pair<double, double>> pos_history(20, {0.0, 0.0});
for (int id : obstacles_container->curr_frame_considered_obstacle_ids()) {
Obstacle* obstacle = obstacles_container->GetObstacle(id);
if (!obstacle) {
continue;
}
int target_id = obstacle_ptr->id();
if (id == target_id) {
continue;
}
const Feature& other_obs_curr_feature = obstacle->latest_feature();
all_obs_length->emplace_back(std::make_pair(
other_obs_curr_feature.length(), other_obs_curr_feature.width()));
size_t obs_his_size = obstacle->history_size();
obs_his_size = obs_his_size <= 20 ? obs_his_size : 20;
int cur_idx = all_obs_pos_history->size();
// if cur_dix >= 450, index_put_ discards it automatically.
if (obs_his_size > 1) {
vector_mask->index_put_({cur_idx,
torch::indexing::Slice(torch::indexing::None,
-(obs_his_size - 1))},
1);
} else {
vector_mask->index_put_({cur_idx,
torch::indexing::Slice(torch::indexing::None,
-1)},
1);
}
for (size_t i = 0; i < obs_his_size; ++i) {
const Feature& feature = obstacle->feature(i);
if (!feature.IsInitialized()) {
break;
}
pos_history[i] = WorldCoordToObjCoordNorth(
std::make_pair(feature.position().x(), feature.position().y()),
obs_curr_pos, obs_curr_heading);
}
all_obs_pos_history->emplace_back(pos_history);
}
return true;
}
void VectornetEvaluator::LoadModel() {
if (FLAGS_use_cuda && torch::cuda::is_available()) {
AINFO << "CUDA is available";
device_ = torch::Device(torch::kCUDA);
torch_vehicle_model_ =
torch::jit::load(FLAGS_torch_vehicle_vectornet_file, device_);
} else {
torch_vehicle_model_ =
torch::jit::load(FLAGS_torch_vehicle_vectornet_cpu_file, device_);
}
torch::set_num_threads(1);
// Fake intput for the first frame
torch::Tensor target_obstacle_pos = torch::randn({1, 20, 2});
torch::Tensor target_obstacle_pos_step = torch::randn({1, 20, 2});
torch::Tensor vector_data = torch::randn({1, 450, 50, 9});
torch::Tensor vector_mask = torch::randn({1, 450, 50}) > 0.9;
torch::Tensor polyline_mask = torch::randn({1, 450}) > 0.9;
torch::Tensor rand_mask = torch::zeros({1, 450});
torch::Tensor polyline_id = torch::randn({1, 450, 2});
std::vector<torch::jit::IValue> torch_inputs;
torch_inputs.push_back(c10::ivalue::Tuple::create(
{std::move(target_obstacle_pos.to(device_)),
std::move(target_obstacle_pos_step.to(device_)),
std::move(vector_data.to(device_)), std::move(vector_mask.to(device_)),
std::move(polyline_mask.to(device_)), std::move(rand_mask.to(device_)),
std::move(polyline_id.to(device_))}));
// Run one inference to avoid very slow first inference later
torch_default_output_tensor_ =
torch_vehicle_model_.forward(torch_inputs).toTensor().to(torch::kCPU);
torch_default_output_tensor_ =
torch_vehicle_model_.forward(torch_inputs).toTensor().to(torch::kCPU);
}
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/prediction/evaluator
|
apollo_public_repos/apollo/modules/prediction/evaluator/vehicle/jointly_prediction_planning_evaluator.cc
|
/******************************************************************************
* Copyright 2021 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.
*****************************************************************************/
#include "modules/prediction/evaluator/vehicle/jointly_prediction_planning_evaluator.h"
#include <limits>
#include <omp.h>
#include "Eigen/Dense"
#include "cyber/common/file.h"
#include "modules/common/math/linear_interpolation.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_map.h"
#include "modules/prediction/common/prediction_system_gflags.h"
#include "modules/prediction/common/prediction_util.h"
#include "modules/prediction/container/adc_trajectory/adc_trajectory_container.h"
namespace apollo {
namespace prediction {
using apollo::common::TrajectoryPoint;
using apollo::common::math::Vec2d;
using apollo::common::math::InterpolateUsingLinearApproximation;
using apollo::prediction::VectorNet;
JointlyPredictionPlanningEvaluator::JointlyPredictionPlanningEvaluator()
: device_(torch::kCPU) {
evaluator_type_ = ObstacleConf::JOINTLY_PREDICTION_PLANNING_EVALUATOR;
LoadModel();
}
void JointlyPredictionPlanningEvaluator::Clear() {}
bool JointlyPredictionPlanningEvaluator::VectornetProcessObstaclePosition(
Obstacle* obstacle_ptr,
ObstaclesContainer* obstacles_container,
torch::Tensor* ptr_target_obs_pos,
torch::Tensor* ptr_target_obs_pos_step,
torch::Tensor* ptr_vector_mask,
torch::Tensor* ptr_all_obstacle_pos,
torch::Tensor* ptr_all_obs_p_id,
torch::Tensor* ptr_obs_length) {
// obs data vector
// Extract features of pos_history
std::vector<std::pair<double, double>> target_pos_history(20, {0.0, 0.0});
std::vector<std::pair<double, double>> all_obs_length;
std::vector<std::vector<std::pair<double, double>>> all_obs_pos_history;
if (!ExtractObstaclesHistory(obstacle_ptr, obstacles_container,
&target_pos_history, &all_obs_length,
&all_obs_pos_history, ptr_vector_mask)) {
AERROR << "Obstacle [" << obstacle_ptr->id()
<< "] failed to extract obstacle history";
return false;
}
for (int j = 0; j < 20; ++j) {
ptr_target_obs_pos->index_put_({19 - j, 0}, target_pos_history[j].first);
ptr_target_obs_pos->index_put_({19 - j, 1}, target_pos_history[j].second);
if (j == 19 || (j > 0 && target_pos_history[j + 1].first == 0.0)) {
break;
}
ptr_target_obs_pos_step->index_put_(
{19 - j, 0},
target_pos_history[j].first - target_pos_history[j + 1].first);
ptr_target_obs_pos_step->index_put_(
{19 - j, 1},
target_pos_history[j].second - target_pos_history[j + 1].second);
}
int obs_num =
obstacles_container->curr_frame_considered_obstacle_ids().size();
for (int i = 0; i < obs_num; ++i) {
std::vector<double> obs_p_id{std::numeric_limits<float>::max(),
std::numeric_limits<float>::max()};
for (int j = 0; j < 20; ++j) {
// Process obs pid
if (obs_p_id[0] > all_obs_pos_history[i][j].first) {
obs_p_id[0] = all_obs_pos_history[i][j].first;
}
if (obs_p_id[1] > all_obs_pos_history[i][j].second) {
obs_p_id[1] = all_obs_pos_history[i][j].second;
}
// Process obs pos history
ptr_all_obstacle_pos->index_put_(
{i, 19 - j, 0},
all_obs_pos_history[i][j].first);
ptr_all_obstacle_pos->index_put_(
{i, 19 - j, 1},
all_obs_pos_history[i][j].second);
}
ptr_all_obs_p_id->index_put_({i, 0}, obs_p_id[0]);
ptr_all_obs_p_id->index_put_({i, 1}, obs_p_id[1]);
}
for (int i = 0; i < obs_num; ++i) {
ptr_obs_length->index_put_({i, 0}, all_obs_length[i].first);
ptr_obs_length->index_put_({i, 1}, all_obs_length[i].second);
}
return true;
}
bool JointlyPredictionPlanningEvaluator::VectornetProcessMapData(
FeatureVector* map_feature,
PidVector* map_p_id,
const int obs_num,
torch::Tensor* ptr_map_data,
torch::Tensor* ptr_all_map_p_id,
torch::Tensor* ptr_vector_mask) {
int map_polyline_num = map_feature->size();
for (int i = 0; i < map_polyline_num && obs_num + i < 450; ++i) {
size_t one_polyline_vector_size = map_feature->at(i).size();
if (one_polyline_vector_size < 50) {
ptr_vector_mask->index_put_({obs_num + i,
torch::indexing::Slice(
one_polyline_vector_size,
torch::indexing::None)},
1);
}
}
auto opts = torch::TensorOptions().dtype(torch::kDouble);
for (int i = 0; i < map_polyline_num && i + obs_num < 450; ++i) {
ptr_all_map_p_id->index_put_({i}, torch::from_blob(map_p_id->at(i).data(),
{2},
opts));
int one_polyline_vector_size = map_feature->at(i).size();
for (int j = 0; j < one_polyline_vector_size && j < 50; ++j) {
ptr_map_data->index_put_({i, j},
torch::from_blob(map_feature->at(i)[j].data(),
{9},
opts));
}
}
*ptr_map_data = ptr_map_data->toType(at::kFloat);
*ptr_all_map_p_id = ptr_all_map_p_id->toType(at::kFloat);
return true;
}
bool JointlyPredictionPlanningEvaluator::Evaluate(Obstacle* obstacle_ptr,
ObstaclesContainer* obstacles_container) {
const ADCTrajectoryContainer* adc_trajectory_container;
Evaluate(adc_trajectory_container, obstacle_ptr, obstacles_container);
return true;
}
bool JointlyPredictionPlanningEvaluator::Evaluate(
const ADCTrajectoryContainer* adc_trajectory_container,
Obstacle* obstacle_ptr,
ObstaclesContainer* obstacles_container) {
omp_set_num_threads(1);
obstacle_ptr->SetEvaluatorType(evaluator_type_);
Clear();
CHECK_NOTNULL(obstacle_ptr);
int id = obstacle_ptr->id();
if (!obstacle_ptr->latest_feature().IsInitialized()) {
AERROR << "Obstacle [" << id << "] has no latest feature.";
return false;
}
Feature* latest_feature_ptr = obstacle_ptr->mutable_latest_feature();
CHECK_NOTNULL(latest_feature_ptr);
if (adc_trajectory_container == nullptr) {
AERROR << "Null adc trajectory container";
return false;
}
int obs_num =
obstacles_container->curr_frame_considered_obstacle_ids().size();
auto start_time_obs = std::chrono::system_clock::now();
torch::Tensor target_obstacle_pos = torch::zeros({20, 2});
torch::Tensor target_obstacle_pos_step = torch::zeros({20, 2});
torch::Tensor vector_mask = torch::zeros({450, 50});
torch::Tensor all_obstacle_pos = torch::zeros({obs_num, 20, 2});
torch::Tensor all_obs_p_id = torch::zeros({obs_num, 2});
torch::Tensor obs_length_tmp = torch::zeros({obs_num, 2});
if (!VectornetProcessObstaclePosition(obstacle_ptr,
obstacles_container,
&target_obstacle_pos,
&target_obstacle_pos_step,
&vector_mask,
&all_obstacle_pos,
&all_obs_p_id,
&obs_length_tmp)) {
AERROR << "Obstacle [" << id << "] processing obstacle position fails.";
return false;
}
auto end_time_obs = std::chrono::system_clock::now();
std::chrono::duration<double> diff_obs = end_time_obs - start_time_obs;
ADEBUG << "obstacle vectors used time: " << diff_obs.count() * 1000 << " ms.";
// Query the map data vector
FeatureVector map_feature;
PidVector map_p_id;
double pos_x = latest_feature_ptr->position().x();
double pos_y = latest_feature_ptr->position().y();
common::PointENU center_point;
center_point.set_x(pos_x);
center_point.set_y(pos_y);
double heading = latest_feature_ptr->velocity_heading();
auto start_time_query = std::chrono::system_clock::now();
if (!vector_net_.query(center_point, heading, &map_feature, &map_p_id)) {
return false;
}
auto end_time_query = std::chrono::system_clock::now();
std::chrono::duration<double> diff_query = end_time_query - start_time_query;
ADEBUG << "vectors query used time: " << diff_query.count() * 1000 << " ms.";
// process map data & map p id & v_mask for map polyline
int map_polyline_num = map_feature.size();
int data_length =
((obs_num + map_polyline_num) < 450) ? (obs_num + map_polyline_num) : 450;
// Process input tensor
auto start_time_data_prep = std::chrono::system_clock::now();
int map_polyline_num_valid =
((obs_num + map_polyline_num) < 450) ? map_polyline_num : (450 - obs_num);
map_polyline_num_valid =
map_polyline_num_valid > 0 ? map_polyline_num_valid : 0;
torch::Tensor map_data = torch::zeros({map_polyline_num_valid, 50, 9});
torch::Tensor all_map_p_id = torch::zeros({map_polyline_num_valid, 2});
if (!VectornetProcessMapData(&map_feature,
&map_p_id,
obs_num,
&map_data,
&all_map_p_id,
&vector_mask)) {
AERROR << "Obstacle [" << id << "] processing map data fails.";
return false;
}
// process p mask
torch::Tensor polyline_mask = torch::zeros({450});
if (data_length < 450) {
polyline_mask.index_put_(
{torch::indexing::Slice(data_length, torch::indexing::None)}, 1);
}
// Extend obs data to specific dimension
torch::Tensor obs_pos_data = torch::cat(
{all_obstacle_pos.index(
{torch::indexing::Slice(),
torch::indexing::Slice(torch::indexing::None, -1),
torch::indexing::Slice()}),
all_obstacle_pos.index({torch::indexing::Slice(),
torch::indexing::Slice(1, torch::indexing::None),
torch::indexing::Slice()})},
2);
// Add obs length
torch::Tensor obs_length = obs_length_tmp.unsqueeze(1).repeat({1, 19, 1});
// Add obs attribute
torch::Tensor obs_attr_agent =
torch::tensor({11.0, 4.0}).unsqueeze(0).unsqueeze(0).repeat({1, 19, 1});
torch::Tensor obs_attr_other =
torch::tensor({10.0, 4.0}).unsqueeze(0).unsqueeze(0).repeat(
{(obs_num - 1), 19, 1});
torch::Tensor obs_attr = torch::cat({obs_attr_agent, obs_attr_other}, 0);
// ADD obs id
// add 500 to avoid same id as in map_info
torch::Tensor obs_id =
torch::arange(500, obs_num + 500).unsqueeze(1).repeat(
{1, 19}).unsqueeze(2);
// Process obs data
torch::Tensor obs_data_with_len = torch::cat({obs_pos_data, obs_length}, 2);
torch::Tensor obs_data_with_attr =
torch::cat({obs_data_with_len, obs_attr}, 2);
torch::Tensor obs_data_with_id = torch::cat({obs_data_with_attr, obs_id}, 2);
torch::Tensor obs_data_final =
torch::cat({torch::zeros({obs_num, (50 - 19), 9}), obs_data_with_id}, 1);
// Extend data & pid to specific demension
torch::Tensor data_tmp = torch::cat({obs_data_final, map_data}, 0);
torch::Tensor p_id_tmp = torch::cat({all_obs_p_id, all_map_p_id}, 0);
torch::Tensor vector_data;
torch::Tensor polyline_id;
if (data_length < 450) {
torch::Tensor data_zeros = torch::zeros({(450 - data_length), 50, 9});
torch::Tensor p_id_zeros = torch::zeros({(450 - data_length), 2});
vector_data = torch::cat({data_tmp, data_zeros}, 0);
polyline_id = torch::cat({p_id_tmp, p_id_zeros}, 0);
} else {
vector_data = data_tmp;
polyline_id = p_id_tmp;
}
// Empty rand mask as placeholder
auto rand_mask = torch::zeros({450}).toType(at::kBool);
// Change mask type to bool
auto bool_vector_mask = vector_mask.toType(at::kBool);
auto bool_polyline_mask = polyline_mask.toType(at::kBool);
// Process ADC trajectory & Extract features of ADC trajectory
std::vector<std::pair<double, double>> adc_traj_curr_pos(30, {0.0, 0.0});
torch::Tensor adc_trajectory = torch::zeros({1, 30, 6});
const auto& adc_traj = adc_trajectory_container->adc_trajectory();
size_t adc_traj_points_num = adc_traj.trajectory_point().size();
if (adc_traj_points_num < 1) {
AERROR << "adc_traj points num is " << adc_traj_points_num
<< " adc traj points are not enough";
return false;
}
std::vector<TrajectoryPoint> adc_traj_points;
// ADC trajectory info as model input needs to match with
// the predicted obstalce's timestamp.
double time_interval = obstacle_ptr->latest_feature().timestamp() -
adc_traj.header().timestamp_sec();
for (size_t i = 0; i < adc_traj_points_num - 1; ++i) {
double delta_time = time_interval -
adc_traj.trajectory_point(0).relative_time();
adc_traj_points.emplace_back(
InterpolateUsingLinearApproximation(
adc_traj.trajectory_point(i),
adc_traj.trajectory_point(i + 1), delta_time));
}
if (!ExtractADCTrajectory(&adc_traj_points,
obstacle_ptr, &adc_traj_curr_pos)) {
AERROR << "Failed to extract adc trajectory";
return false;
}
size_t traj_points_num = adc_traj_points.size();
for (size_t j = 0; j < 30; ++j) {
if (j > traj_points_num - 1) {
adc_trajectory[0][j][0] =
adc_traj_curr_pos[traj_points_num - 1].first;
adc_trajectory[0][j][1] =
adc_traj_curr_pos[traj_points_num - 1].second;
adc_trajectory[0][j][2] =
adc_traj_points[traj_points_num - 1].path_point().theta();
adc_trajectory[0][j][3] =
adc_traj_points[traj_points_num - 1].v();
adc_trajectory[0][j][4] =
adc_traj_points[traj_points_num - 1].a();
adc_trajectory[0][j][5] =
adc_traj_points[traj_points_num - 1].path_point().kappa();
} else {
adc_trajectory[0][j][0] =
adc_traj_curr_pos[j].first;
adc_trajectory[0][j][1] =
adc_traj_curr_pos[j].second;
adc_trajectory[0][j][2] =
adc_traj_points[j].path_point().theta();
adc_trajectory[0][j][3] =
adc_traj_points[j].v();
adc_trajectory[0][j][4] =
adc_traj_points[j].a();
adc_trajectory[0][j][5] =
adc_traj_points[j].path_point().kappa();
}
}
// Build input features for torch
std::vector<torch::jit::IValue> torch_inputs;
auto X_value = c10::ivalue::Tuple::create(
{std::move(target_obstacle_pos.unsqueeze(0).to(device_)),
std::move(target_obstacle_pos_step.unsqueeze(0).to(device_)),
std::move(vector_data.unsqueeze(0).to(device_)),
std::move(bool_vector_mask.unsqueeze(0).to(device_)),
std::move(bool_polyline_mask.unsqueeze(0).to(device_)),
std::move(rand_mask.unsqueeze(0).to(device_)),
std::move(polyline_id.unsqueeze(0).to(device_))});
torch_inputs.push_back(c10::ivalue::Tuple::create(
{X_value, std::move(adc_trajectory.to(device_))}));
auto end_time_data_prep = std::chrono::system_clock::now();
std::chrono::duration<double> diff_data_prep =
end_time_data_prep - start_time_data_prep;
ADEBUG << "vectornet input tensor prepration used time: "
<< diff_data_prep.count() * 1000 << " ms.";
// Compute pred_traj
auto start_time_inference = std::chrono::system_clock::now();
at::Tensor torch_output_tensor = torch_default_output_tensor_;
torch_output_tensor =
torch_vehicle_model_.forward(torch_inputs).toTensor().to(torch::kCPU);
auto end_time_inference = std::chrono::system_clock::now();
std::chrono::duration<double> diff_inference =
end_time_inference - start_time_inference;
ADEBUG << "vectornet-interaction inference used time: "
<< diff_inference.count() * 1000
<< " ms.";
// Get the trajectory
auto torch_output = torch_output_tensor.accessor<float, 3>();
Trajectory* trajectory = latest_feature_ptr->add_predicted_trajectory();
trajectory->set_probability(1.0);
for (int i = 0; i < 30; ++i) {
double prev_x = pos_x;
double prev_y = pos_y;
if (i > 0) {
const auto& last_point = trajectory->trajectory_point(i - 1).path_point();
prev_x = last_point.x();
prev_y = last_point.y();
}
TrajectoryPoint* point = trajectory->add_trajectory_point();
double dx = static_cast<double>(torch_output[0][i][0]);
double dy = static_cast<double>(torch_output[0][i][1]);
double heading = latest_feature_ptr->velocity_heading();
Vec2d offset(dx, dy);
Vec2d rotated_offset = offset.rotate(heading - (M_PI / 2));
double point_x = pos_x + rotated_offset.x();
double point_y = pos_y + rotated_offset.y();
point->mutable_path_point()->set_x(point_x);
point->mutable_path_point()->set_y(point_y);
if (i < 10) { // use origin heading for the first second
point->mutable_path_point()->set_theta(
latest_feature_ptr->velocity_heading());
} else {
point->mutable_path_point()->set_theta(
std::atan2(trajectory->trajectory_point(i).path_point().y() -
trajectory->trajectory_point(i - 1).path_point().y(),
trajectory->trajectory_point(i).path_point().x() -
trajectory->trajectory_point(i - 1).path_point().x()));
}
point->set_relative_time(static_cast<double>(i) *
FLAGS_prediction_trajectory_time_resolution);
if (i == 0) {
point->set_v(latest_feature_ptr->speed());
} else {
double diff_x = point_x - prev_x;
double diff_y = point_y - prev_y;
point->set_v(std::hypot(diff_x, diff_y) /
FLAGS_prediction_trajectory_time_resolution);
}
}
return true;
}
bool JointlyPredictionPlanningEvaluator::ExtractObstaclesHistory(
Obstacle* obstacle_ptr, ObstaclesContainer* obstacles_container,
std::vector<std::pair<double, double>>* target_pos_history,
std::vector<std::pair<double, double>>* all_obs_length,
std::vector<std::vector<std::pair<double, double>>>* all_obs_pos_history,
torch::Tensor* vector_mask) {
const Feature& obs_curr_feature = obstacle_ptr->latest_feature();
double obs_curr_heading = obs_curr_feature.velocity_heading();
std::pair<double, double> obs_curr_pos = std::make_pair(
obs_curr_feature.position().x(), obs_curr_feature.position().y());
// Extract target obstacle history
for (std::size_t i = 0; i < obstacle_ptr->history_size() && i < 20; ++i) {
const Feature& target_feature = obstacle_ptr->feature(i);
if (!target_feature.IsInitialized()) {
break;
}
target_pos_history->at(i) =
WorldCoordToObjCoordNorth(std::make_pair(target_feature.position().x(),
target_feature.position().y()),
obs_curr_pos, obs_curr_heading);
}
all_obs_length->emplace_back(
std::make_pair(obs_curr_feature.length(), obs_curr_feature.width()));
all_obs_pos_history->emplace_back(*target_pos_history);
// Extract other obstacles & convert pos to traget obstacle relative coord
std::vector<std::pair<double, double>> pos_history(20, {0.0, 0.0});
for (int id : obstacles_container->curr_frame_considered_obstacle_ids()) {
Obstacle* obstacle = obstacles_container->GetObstacle(id);
if (!obstacle) {
continue;
}
int target_id = obstacle_ptr->id();
if (id == target_id) {
continue;
}
const Feature& other_obs_curr_feature = obstacle->latest_feature();
all_obs_length->emplace_back(std::make_pair(
other_obs_curr_feature.length(), other_obs_curr_feature.width()));
size_t obs_his_size = obstacle->history_size();
obs_his_size = obs_his_size <= 20 ? obs_his_size : 20;
int cur_idx = all_obs_pos_history->size();
if (obs_his_size > 1) {
vector_mask->index_put_({cur_idx,
torch::indexing::Slice(torch::indexing::None,
-(obs_his_size - 1))}, 1);
} else {
vector_mask->index_put_({cur_idx,
torch::indexing::Slice(torch::indexing::None,
-1)}, 1);
}
for (size_t i = 0; i < obs_his_size; ++i) {
const Feature& feature = obstacle->feature(i);
if (!feature.IsInitialized()) {
break;
}
pos_history[i] = WorldCoordToObjCoordNorth(
std::make_pair(feature.position().x(), feature.position().y()),
obs_curr_pos, obs_curr_heading);
}
all_obs_pos_history->emplace_back(pos_history);
}
return true;
}
bool JointlyPredictionPlanningEvaluator::ExtractADCTrajectory(
std::vector<TrajectoryPoint>* trajectory_points,
Obstacle* obstacle_ptr,
std::vector<std::pair<double, double>>* adc_traj_curr_pos) {
adc_traj_curr_pos->resize(30, {0.0, 0.0});
const Feature& obs_curr_feature = obstacle_ptr->latest_feature();
double obs_curr_heading = obs_curr_feature.velocity_heading();
std::pair<double, double> obs_curr_pos = std::make_pair(
obs_curr_feature.position().x(), obs_curr_feature.position().y());
size_t adc_traj_points_num = trajectory_points->size();
for (size_t i = 0; i < 30; ++i) {
if (i > adc_traj_points_num -1) {
adc_traj_curr_pos->at(i) =
adc_traj_curr_pos->at(adc_traj_points_num - 1);
} else {
adc_traj_curr_pos->at(i) = WorldCoordToObjCoordNorth(
std::make_pair(trajectory_points->at(i).path_point().x(),
trajectory_points->at(i).path_point().y()),
obs_curr_pos, obs_curr_heading);
}
}
return true;
}
void JointlyPredictionPlanningEvaluator::LoadModel() {
if (FLAGS_use_cuda && torch::cuda::is_available()) {
ADEBUG << "CUDA is available";
device_ = torch::Device(torch::kCUDA);
torch_vehicle_model_ =
torch::jit::load(FLAGS_torch_vehicle_jointly_model_file, device_);
} else {
torch_vehicle_model_ =
torch::jit::load(FLAGS_torch_vehicle_jointly_model_cpu_file, device_);
}
torch::set_num_threads(1);
// Fake intput for the first frame
torch::Tensor target_obstacle_pos = torch::randn({1, 20, 2});
torch::Tensor target_obstacle_pos_step = torch::randn({1, 20, 2});
torch::Tensor vector_data = torch::randn({1, 450, 50, 9});
torch::Tensor vector_mask = torch::randn({1, 450, 50}) > 0.9;
torch::Tensor polyline_mask = torch::randn({1, 450}) > 0.9;
torch::Tensor rand_mask = torch::zeros({1, 450});
torch::Tensor polyline_id = torch::randn({1, 450, 2});
torch::Tensor adc_trajectory = torch::zeros({1, 30, 6});
std::vector<torch::jit::IValue> torch_inputs;
auto X_value = c10::ivalue::Tuple::create(
{std::move(target_obstacle_pos.to(device_)),
std::move(target_obstacle_pos_step.to(device_)),
std::move(vector_data.to(device_)), std::move(vector_mask.to(device_)),
std::move(polyline_mask.to(device_)), std::move(rand_mask.to(device_)),
std::move(polyline_id.to(device_))});
torch_inputs.push_back(c10::ivalue::Tuple::create(
{X_value, std::move(adc_trajectory.to(device_))}));
// Run inference twice to avoid very slow first inference later
torch_default_output_tensor_ =
torch_vehicle_model_.forward(torch_inputs).toTensor().to(torch::kCPU);
torch_default_output_tensor_ =
torch_vehicle_model_.forward(torch_inputs).toTensor().to(torch::kCPU);
}
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/prediction/evaluator
|
apollo_public_repos/apollo/modules/prediction/evaluator/vehicle/BUILD
|
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test")
load("//tools:cpplint.bzl", "cpplint")
package(default_visibility = ["//visibility:public"])
PREDICTION_COPTS = ["-DMODULE_NAME=\\\"prediction\\\""]
PREDICTION_FOPENMP_COPTS = ["-DMODULE_NAME=\\\"prediction\\\"","-fopenmp"]
cc_library(
name = "mlp_evaluator",
srcs = ["mlp_evaluator.cc"],
hdrs = ["mlp_evaluator.h"],
copts = PREDICTION_COPTS,
deps = [
"//modules/prediction/common:feature_output",
"//modules/prediction/common:prediction_util",
"//modules/prediction/common:validation_checker",
"//modules/prediction/container/obstacles:obstacles_container",
"//modules/prediction/evaluator",
"//modules/prediction/proto:fnn_vehicle_model_cc_proto",
],
)
cc_test(
name = "mlp_evaluator_test",
size = "small",
srcs = ["mlp_evaluator_test.cc"],
data = [
"//modules/prediction:prediction_data",
"//modules/prediction:prediction_testdata",
],
deps = [
"//modules/prediction/common:kml_map_based_test",
"//modules/prediction/evaluator/vehicle:mlp_evaluator",
"@com_google_googletest//:gtest_main",
],
)
cc_library(
name = "cost_evaluator",
srcs = ["cost_evaluator.cc"],
hdrs = ["cost_evaluator.h"],
copts = PREDICTION_COPTS,
deps = [
"//modules/prediction/common:prediction_util",
"//modules/prediction/container/obstacles:obstacles_container",
"//modules/prediction/evaluator",
],
)
cc_test(
name = "cost_evaluator_test",
size = "small",
srcs = ["cost_evaluator_test.cc"],
data = [
"//modules/prediction:prediction_data",
"//modules/prediction:prediction_testdata",
],
deps = [
"//modules/prediction/common:kml_map_based_test",
"//modules/prediction/evaluator/vehicle:cost_evaluator",
"@com_google_googletest//:gtest_main",
],
)
cc_library(
name = "junction_mlp_evaluator",
srcs = ["junction_mlp_evaluator.cc"],
hdrs = ["junction_mlp_evaluator.h"],
copts = PREDICTION_FOPENMP_COPTS,
deps = [
"//modules/common/math",
"//modules/prediction/common:feature_output",
"//modules/prediction/common:prediction_util",
"//modules/prediction/container:container_manager",
"//modules/prediction/container/obstacles:obstacles_container",
"//modules/prediction/evaluator",
"//third_party:libtorch",
],
)
cc_test(
name = "junction_mlp_evaluator_test",
size = "small",
srcs = ["junction_mlp_evaluator_test.cc"],
data = [
"//modules/prediction:prediction_data",
"//modules/prediction:prediction_testdata",
],
linkopts = [
"-lgomp",
],
deps = [
"//modules/prediction/common:kml_map_based_test",
"//modules/prediction/evaluator/vehicle:junction_mlp_evaluator",
"@com_google_googletest//:gtest_main",
],
linkstatic = True,
)
cc_library(
name = "junction_map_evaluator",
srcs = ["junction_map_evaluator.cc"],
hdrs = ["junction_map_evaluator.h"],
copts = PREDICTION_FOPENMP_COPTS,
deps = [
"//modules/prediction/common:prediction_util",
"//modules/prediction/common:semantic_map",
"//modules/prediction/container/obstacles:obstacles_container",
"//modules/prediction/evaluator",
"//third_party:libtorch",
],
)
cc_library(
name = "cruise_mlp_evaluator",
srcs = ["cruise_mlp_evaluator.cc"],
hdrs = ["cruise_mlp_evaluator.h"],
copts = PREDICTION_FOPENMP_COPTS,
deps = [
"//modules/prediction/common:prediction_util",
"//modules/prediction/container:container_manager",
"//modules/prediction/container/obstacles:obstacles_container",
"//modules/prediction/evaluator",
"//third_party:libtorch",
],
)
cc_test(
name = "cruise_mlp_evaluator_test",
size = "small",
srcs = ["cruise_mlp_evaluator_test.cc"],
data = [
"//modules/prediction:prediction_data",
"//modules/prediction:prediction_testdata",
],
linkopts = [
"-lgomp",
],
deps = [
"//modules/prediction/common:kml_map_based_test",
"//modules/prediction/evaluator/vehicle:cruise_mlp_evaluator",
],
linkstatic = True,
)
cc_library(
name = "lane_scanning_evaluator",
srcs = ["lane_scanning_evaluator.cc"],
hdrs = ["lane_scanning_evaluator.h"],
copts = PREDICTION_FOPENMP_COPTS,
deps = [
"//modules/prediction/container:container_manager",
"//modules/prediction/container/obstacles:obstacles_container",
"//modules/prediction/evaluator",
"//third_party:libtorch",
],
)
cc_library(
name = "lane_aggregating_evaluator",
srcs = ["lane_aggregating_evaluator.cc"],
hdrs = ["lane_aggregating_evaluator.h"],
copts = PREDICTION_COPTS,
deps = [
"//modules/prediction/container:container_manager",
"//modules/prediction/container/obstacles:obstacles_container",
"//modules/prediction/evaluator",
"//third_party:libtorch",
],
)
cc_library(
name = "semantic_lstm_evaluator",
srcs = ["semantic_lstm_evaluator.cc"],
hdrs = ["semantic_lstm_evaluator.h"],
copts = PREDICTION_FOPENMP_COPTS,
deps = [
"//modules/prediction/common:prediction_util",
"//modules/prediction/common:semantic_map",
"//modules/prediction/container/obstacles:obstacles_container",
"//modules/prediction/evaluator",
"//third_party:libtorch",
"@eigen",
],
)
cc_library(
name = "jointly_prediction_planning_evaluator",
srcs = ["jointly_prediction_planning_evaluator.cc"],
hdrs = ["jointly_prediction_planning_evaluator.h"],
copts = PREDICTION_FOPENMP_COPTS,
deps = [
"//modules/prediction/common:prediction_util",
"//modules/prediction/common:semantic_map",
"//modules/prediction/container/obstacles:obstacles_container",
"//modules/prediction/evaluator",
"//modules/prediction/pipeline:vector_net",
"//third_party:libtorch",
"@eigen",
],
)
cc_library(
name = "vectornet_evaluator",
srcs = ["vectornet_evaluator.cc"],
hdrs = ["vectornet_evaluator.h"],
copts = PREDICTION_FOPENMP_COPTS,
deps = [
"//modules/prediction/common:prediction_util",
"//modules/prediction/container/obstacles:obstacles_container",
"//modules/prediction/evaluator",
"//modules/prediction/pipeline:vector_net",
"//third_party:libtorch",
"@eigen",
],
)
cpplint()
| 0
|
apollo_public_repos/apollo/modules/prediction/evaluator
|
apollo_public_repos/apollo/modules/prediction/evaluator/vehicle/mlp_evaluator.h
|
/******************************************************************************
* 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.
*****************************************************************************/
#pragma once
#include <memory>
#include <string>
#include <vector>
#include "modules/prediction/container/obstacles/obstacles_container.h"
#include "modules/prediction/evaluator/evaluator.h"
#include "modules/prediction/proto/fnn_vehicle_model.pb.h"
namespace apollo {
namespace prediction {
class MLPEvaluator : public Evaluator {
public:
/**
* @brief Constructor
*/
MLPEvaluator();
/**
* @brief Destructor
*/
virtual ~MLPEvaluator() = default;
/**
* @brief Override Evaluate
* @param Obstacle pointer
* @param Obstacles container
*/
bool Evaluate(Obstacle* obstacle_ptr,
ObstaclesContainer* obstacles_container) override;
/**
* @brief Extract feature vector
* @param Obstacle pointer
* Lane Sequence pointer
*/
void ExtractFeatureValues(Obstacle* obstacle_ptr,
LaneSequence* lane_sequence_ptr,
std::vector<double>* feature_values);
/**
* @brief Get the name of evaluator.
*/
std::string GetName() override { return "MLP_EVALUATOR"; }
/**
* @brief Clear obstacle feature map
*/
void Clear();
private:
/**
* @brief Set obstacle feature vector
* @param Obstacle pointer
* Feature container in a vector for receiving the feature values
*/
void SetObstacleFeatureValues(Obstacle* obstacle_ptr,
std::vector<double>* feature_values);
/**
* @brief Set lane feature vector
* @param Obstacle pointer
* Lane sequence pointer
* Feature container in a vector for receiving the feature values
*/
void SetLaneFeatureValues(Obstacle* obstacle_ptr,
LaneSequence* lane_sequence_ptr,
std::vector<double>* feature_values);
/**
* @brief Load model file
* @param Model file name
*/
void LoadModel(const std::string& model_file);
/**
* @brief Compute probability
*/
double ComputeProbability(const std::vector<double>& feature_values);
/**
* @brief Save offline feature values in proto
* @param Lane sequence
* @param Vector of feature values
*/
void SaveOfflineFeatures(LaneSequence* sequence,
const std::vector<double>& feature_values);
private:
static const size_t OBSTACLE_FEATURE_SIZE = 22;
static const size_t LANE_FEATURE_SIZE = 40;
std::unique_ptr<FnnVehicleModel> model_ptr_;
};
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/prediction/evaluator
|
apollo_public_repos/apollo/modules/prediction/evaluator/vehicle/cruise_mlp_evaluator.cc
|
/******************************************************************************
* 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.
*****************************************************************************/
#include "modules/prediction/evaluator/vehicle/cruise_mlp_evaluator.h"
#include <limits>
#include <utility>
#include <omp.h>
#include "cyber/common/file.h"
#include "modules/prediction/common/feature_output.h"
#include "modules/prediction/common/prediction_constants.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_system_gflags.h"
#include "modules/prediction/common/prediction_util.h"
#include "modules/prediction/container/container_manager.h"
#include "modules/prediction/container/obstacles/obstacles_container.h"
namespace apollo {
namespace prediction {
// Helper function for computing the mean value of a vector.
double ComputeMean(const std::vector<double>& nums, size_t start, size_t end) {
int count = 0;
double sum = 0.0;
for (size_t i = start; i <= end && i < nums.size(); i++) {
sum += nums[i];
++count;
}
return (count == 0) ? 0.0 : sum / count;
}
CruiseMLPEvaluator::CruiseMLPEvaluator() : device_(torch::kCPU) {
evaluator_type_ = ObstacleConf::CRUISE_MLP_EVALUATOR;
LoadModels();
}
void CruiseMLPEvaluator::Clear() {}
bool CruiseMLPEvaluator::Evaluate(Obstacle* obstacle_ptr,
ObstaclesContainer* obstacles_container) {
// Sanity checks.
omp_set_num_threads(1);
Clear();
CHECK_NOTNULL(obstacle_ptr);
obstacle_ptr->SetEvaluatorType(evaluator_type_);
int id = obstacle_ptr->id();
if (!obstacle_ptr->latest_feature().IsInitialized()) {
AERROR << "Obstacle [" << id << "] has no latest feature.";
return false;
}
Feature* latest_feature_ptr = obstacle_ptr->mutable_latest_feature();
CHECK_NOTNULL(latest_feature_ptr);
if (!latest_feature_ptr->has_lane() ||
!latest_feature_ptr->lane().has_lane_graph()) {
ADEBUG << "Obstacle [" << id << "] has no lane graph.";
return false;
}
LaneGraph* lane_graph_ptr =
latest_feature_ptr->mutable_lane()->mutable_lane_graph();
CHECK_NOTNULL(lane_graph_ptr);
if (lane_graph_ptr->lane_sequence().empty()) {
AERROR << "Obstacle [" << id << "] has no lane sequences.";
return false;
}
ADEBUG << "There are " << lane_graph_ptr->lane_sequence_size()
<< " lane sequences with probabilities:";
// For every possible lane sequence, extract features that are needed
// to feed into our trained model.
// Then compute the likelihood of the obstacle moving onto that laneseq.
for (int i = 0; i < lane_graph_ptr->lane_sequence_size(); ++i) {
LaneSequence* lane_sequence_ptr = lane_graph_ptr->mutable_lane_sequence(i);
CHECK_NOTNULL(lane_sequence_ptr);
std::vector<double> feature_values;
ExtractFeatureValues(obstacle_ptr, lane_sequence_ptr, &feature_values);
if (feature_values.size() !=
OBSTACLE_FEATURE_SIZE + SINGLE_LANE_FEATURE_SIZE * LANE_POINTS_SIZE) {
lane_sequence_ptr->set_probability(0.0);
ADEBUG << "Skip lane sequence due to incorrect feature size";
continue;
}
// Insert features to DataForLearning
if (FLAGS_prediction_offline_mode ==
PredictionConstants::kDumpDataForLearning) {
std::vector<double> interaction_feature_values;
SetInteractionFeatureValues(obstacle_ptr, obstacles_container,
lane_sequence_ptr,
&interaction_feature_values);
if (interaction_feature_values.size() != INTERACTION_FEATURE_SIZE) {
ADEBUG << "Obstacle [" << id << "] has fewer than "
<< "expected lane feature_values"
<< interaction_feature_values.size() << ".";
return false;
}
ADEBUG << "Interaction feature size = "
<< interaction_feature_values.size();
feature_values.insert(feature_values.end(),
interaction_feature_values.begin(),
interaction_feature_values.end());
FeatureOutput::InsertDataForLearning(*latest_feature_ptr, feature_values,
"lane_scanning", lane_sequence_ptr);
ADEBUG << "Save extracted features for learning locally.";
return true; // Skip Compute probability for offline mode
}
std::vector<torch::jit::IValue> torch_inputs;
int input_dim = static_cast<int>(
OBSTACLE_FEATURE_SIZE + SINGLE_LANE_FEATURE_SIZE * LANE_POINTS_SIZE);
torch::Tensor torch_input = torch::zeros({1, input_dim});
for (size_t i = 0; i < feature_values.size(); ++i) {
torch_input[0][i] = static_cast<float>(feature_values[i]);
}
torch_inputs.push_back(std::move(torch_input.to(device_)));
if (lane_sequence_ptr->vehicle_on_lane()) {
ModelInference(torch_inputs, torch_go_model_, lane_sequence_ptr);
} else {
ModelInference(torch_inputs, torch_cutin_model_, lane_sequence_ptr);
}
}
return true;
}
void CruiseMLPEvaluator::ExtractFeatureValues(
Obstacle* obstacle_ptr, LaneSequence* lane_sequence_ptr,
std::vector<double>* feature_values) {
// Sanity checks.
CHECK_NOTNULL(obstacle_ptr);
CHECK_NOTNULL(lane_sequence_ptr);
int id = obstacle_ptr->id();
// Extract obstacle related features.
std::vector<double> obstacle_feature_values;
SetObstacleFeatureValues(obstacle_ptr, &obstacle_feature_values);
if (obstacle_feature_values.size() != OBSTACLE_FEATURE_SIZE) {
ADEBUG << "Obstacle [" << id << "] has fewer than "
<< "expected obstacle feature_values "
<< obstacle_feature_values.size() << ".";
return;
}
ADEBUG << "Obstacle feature size = " << obstacle_feature_values.size();
feature_values->insert(feature_values->end(), obstacle_feature_values.begin(),
obstacle_feature_values.end());
// Extract lane related features.
std::vector<double> lane_feature_values;
SetLaneFeatureValues(obstacle_ptr, lane_sequence_ptr, &lane_feature_values);
if (lane_feature_values.size() !=
SINGLE_LANE_FEATURE_SIZE * LANE_POINTS_SIZE) {
ADEBUG << "Obstacle [" << id << "] has fewer than "
<< "expected lane feature_values" << lane_feature_values.size()
<< ".";
return;
}
ADEBUG << "Lane feature size = " << lane_feature_values.size();
feature_values->insert(feature_values->end(), lane_feature_values.begin(),
lane_feature_values.end());
}
void CruiseMLPEvaluator::SetObstacleFeatureValues(
const Obstacle* obstacle_ptr, std::vector<double>* feature_values) {
// Sanity checks and variable declarations.
CHECK_NOTNULL(obstacle_ptr);
feature_values->clear();
feature_values->reserve(OBSTACLE_FEATURE_SIZE);
std::vector<double> thetas;
std::vector<double> lane_ls;
std::vector<double> dist_lbs;
std::vector<double> dist_rbs;
std::vector<int> lane_types;
std::vector<double> speeds;
std::vector<double> timestamps;
std::vector<double> has_history(FLAGS_cruise_historical_frame_length, 1.0);
std::vector<std::pair<double, double>> pos_history(
FLAGS_cruise_historical_frame_length, std::make_pair(0.0, 0.0));
std::vector<std::pair<double, double>> vel_history(
FLAGS_cruise_historical_frame_length, std::make_pair(0.0, 0.0));
std::vector<std::pair<double, double>> acc_history(
FLAGS_cruise_historical_frame_length, std::make_pair(0.0, 0.0));
std::vector<double> vel_heading_history(FLAGS_cruise_historical_frame_length,
0.0);
std::vector<double> vel_heading_changing_rate_history(
FLAGS_cruise_historical_frame_length, 0.0);
// Get obstacle's current position to set up the relative coord. system.
const Feature& obs_curr_feature = obstacle_ptr->latest_feature();
double obs_curr_heading = obs_curr_feature.velocity_heading();
std::pair<double, double> obs_curr_pos = std::make_pair(
obs_curr_feature.position().x(), obs_curr_feature.position().y());
double obs_feature_history_start_time =
obstacle_ptr->timestamp() - FLAGS_prediction_trajectory_time_length;
int count = 0;
// int num_available_history_frames = 0;
double prev_timestamp = obs_curr_feature.timestamp();
// Starting from the most recent timestamp and going backward.
ADEBUG << "Obstacle has " << obstacle_ptr->history_size()
<< " history timestamps.";
for (std::size_t i = 0; i < obstacle_ptr->history_size(); ++i) {
const Feature& feature = obstacle_ptr->feature(i);
if (!feature.IsInitialized()) {
continue;
}
if (feature.timestamp() < obs_feature_history_start_time) {
break;
}
if (!feature.has_lane()) {
ADEBUG << "Feature has no lane. Quit.";
}
// These are for the old 23 features.
if (feature.has_lane() && feature.lane().has_lane_feature()) {
thetas.push_back(feature.lane().lane_feature().angle_diff());
lane_ls.push_back(feature.lane().lane_feature().lane_l());
dist_lbs.push_back(feature.lane().lane_feature().dist_to_left_boundary());
dist_rbs.push_back(
feature.lane().lane_feature().dist_to_right_boundary());
lane_types.push_back(feature.lane().lane_feature().lane_turn_type());
timestamps.push_back(feature.timestamp());
speeds.push_back(feature.speed());
++count;
} else {
ADEBUG << "Feature has no lane_feature!!!";
ADEBUG << feature.lane().current_lane_feature_size();
}
// These are for the new features based on the relative coord. system.
if (i >= FLAGS_cruise_historical_frame_length) {
continue;
}
if (i != 0 && has_history[i - 1] == 0.0) {
has_history[i] = 0.0;
continue;
}
if (feature.has_position()) {
pos_history[i] = WorldCoordToObjCoord(
std::make_pair(feature.position().x(), feature.position().y()),
obs_curr_pos, obs_curr_heading);
} else {
has_history[i] = 0.0;
}
if (feature.has_velocity()) {
auto vel_end = WorldCoordToObjCoord(
std::make_pair(feature.velocity().x(), feature.velocity().y()),
obs_curr_pos, obs_curr_heading);
auto vel_begin = WorldCoordToObjCoord(std::make_pair(0.0, 0.0),
obs_curr_pos, obs_curr_heading);
vel_history[i] = std::make_pair(vel_end.first - vel_begin.first,
vel_end.second - vel_begin.second);
} else {
has_history[i] = 0.0;
}
if (feature.has_acceleration()) {
auto acc_end =
WorldCoordToObjCoord(std::make_pair(feature.acceleration().x(),
feature.acceleration().y()),
obs_curr_pos, obs_curr_heading);
auto acc_begin = WorldCoordToObjCoord(std::make_pair(0.0, 0.0),
obs_curr_pos, obs_curr_heading);
acc_history[i] = std::make_pair(acc_end.first - acc_begin.first,
acc_end.second - acc_begin.second);
} else {
has_history[i] = 0.0;
}
if (feature.has_velocity_heading()) {
vel_heading_history[i] =
WorldAngleToObjAngle(feature.velocity_heading(), obs_curr_heading);
if (i != 0) {
vel_heading_changing_rate_history[i] =
(vel_heading_history[i - 1] - vel_heading_history[i]) /
(FLAGS_double_precision + feature.timestamp() - prev_timestamp);
prev_timestamp = feature.timestamp();
}
} else {
has_history[i] = 0.0;
}
}
if (count <= 0) {
ADEBUG << "There is no feature with lane info. Quit.";
return;
}
// The following entire part is setting up the old 23 features.
///////////////////////////////////////////////////////////////
int curr_size = 5;
int hist_size = static_cast<int>(obstacle_ptr->history_size());
double theta_mean = ComputeMean(thetas, 0, hist_size - 1);
double theta_filtered = ComputeMean(thetas, 0, curr_size - 1);
double lane_l_mean = ComputeMean(lane_ls, 0, hist_size - 1);
double lane_l_filtered = ComputeMean(lane_ls, 0, curr_size - 1);
double speed_mean = ComputeMean(speeds, 0, hist_size - 1);
double time_diff = timestamps.front() - timestamps.back();
double dist_lb_rate = (timestamps.size() > 1)
? (dist_lbs.front() - dist_lbs.back()) / time_diff
: 0.0;
double dist_rb_rate = (timestamps.size() > 1)
? (dist_rbs.front() - dist_rbs.back()) / time_diff
: 0.0;
double delta_t = 0.0;
if (timestamps.size() > 1) {
delta_t = (timestamps.front() - timestamps.back()) /
static_cast<double>(timestamps.size() - 1);
}
double angle_curr = ComputeMean(thetas, 0, curr_size - 1);
double angle_prev = ComputeMean(thetas, curr_size, 2 * curr_size - 1);
double angle_diff =
(hist_size >= 2 * curr_size) ? angle_curr - angle_prev : 0.0;
double lane_l_curr = ComputeMean(lane_ls, 0, curr_size - 1);
double lane_l_prev = ComputeMean(lane_ls, curr_size, 2 * curr_size - 1);
double lane_l_diff =
(hist_size >= 2 * curr_size) ? lane_l_curr - lane_l_prev : 0.0;
double angle_diff_rate = 0.0;
double lane_l_diff_rate = 0.0;
if (delta_t > std::numeric_limits<double>::epsilon()) {
angle_diff_rate = angle_diff / (delta_t * curr_size);
lane_l_diff_rate = lane_l_diff / (delta_t * curr_size);
}
double acc = 0.0;
double jerk = 0.0;
if (static_cast<int>(speeds.size()) >= 3 * curr_size &&
delta_t > std::numeric_limits<double>::epsilon()) {
double speed_1st_recent = ComputeMean(speeds, 0, curr_size - 1);
double speed_2nd_recent = ComputeMean(speeds, curr_size, 2 * curr_size - 1);
double speed_3rd_recent =
ComputeMean(speeds, 2 * curr_size, 3 * curr_size - 1);
acc = (speed_1st_recent - speed_2nd_recent) / (curr_size * delta_t);
jerk = (speed_1st_recent - 2 * speed_2nd_recent + speed_3rd_recent) /
(curr_size * curr_size * delta_t * delta_t);
}
double dist_lb_rate_curr = 0.0;
if (hist_size >= 2 * curr_size &&
delta_t > std::numeric_limits<double>::epsilon()) {
double dist_lb_curr = ComputeMean(dist_lbs, 0, curr_size - 1);
double dist_lb_prev = ComputeMean(dist_lbs, curr_size, 2 * curr_size - 1);
dist_lb_rate_curr = (dist_lb_curr - dist_lb_prev) / (curr_size * delta_t);
}
double dist_rb_rate_curr = 0.0;
if (hist_size >= 2 * curr_size &&
delta_t > std::numeric_limits<double>::epsilon()) {
double dist_rb_curr = ComputeMean(dist_rbs, 0, curr_size - 1);
double dist_rb_prev = ComputeMean(dist_rbs, curr_size, 2 * curr_size - 1);
dist_rb_rate_curr = (dist_rb_curr - dist_rb_prev) / (curr_size * delta_t);
}
feature_values->push_back(theta_filtered);
feature_values->push_back(theta_mean);
feature_values->push_back(theta_filtered - theta_mean);
feature_values->push_back(angle_diff);
feature_values->push_back(angle_diff_rate);
feature_values->push_back(lane_l_filtered);
feature_values->push_back(lane_l_mean);
feature_values->push_back(lane_l_filtered - lane_l_mean);
feature_values->push_back(lane_l_diff);
feature_values->push_back(lane_l_diff_rate);
feature_values->push_back(speed_mean);
feature_values->push_back(acc);
feature_values->push_back(jerk);
feature_values->push_back(dist_lbs.front());
feature_values->push_back(dist_lb_rate);
feature_values->push_back(dist_lb_rate_curr);
feature_values->push_back(dist_rbs.front());
feature_values->push_back(dist_rb_rate);
feature_values->push_back(dist_rb_rate_curr);
feature_values->push_back(lane_types.front() == 0 ? 1.0 : 0.0);
feature_values->push_back(lane_types.front() == 1 ? 1.0 : 0.0);
feature_values->push_back(lane_types.front() == 2 ? 1.0 : 0.0);
feature_values->push_back(lane_types.front() == 3 ? 1.0 : 0.0);
for (std::size_t i = 0; i < FLAGS_cruise_historical_frame_length; i++) {
feature_values->push_back(has_history[i]);
feature_values->push_back(pos_history[i].first);
feature_values->push_back(pos_history[i].second);
feature_values->push_back(vel_history[i].first);
feature_values->push_back(vel_history[i].second);
feature_values->push_back(acc_history[i].first);
feature_values->push_back(acc_history[i].second);
feature_values->push_back(vel_heading_history[i]);
feature_values->push_back(vel_heading_changing_rate_history[i]);
}
}
void CruiseMLPEvaluator::SetInteractionFeatureValues(
Obstacle* obstacle_ptr, ObstaclesContainer* obstacles_container,
LaneSequence* lane_sequence_ptr, std::vector<double>* feature_values) {
// forward / backward: relative_s, relative_l, speed, length
feature_values->clear();
// Initialize forward and backward obstacles
NearbyObstacle forward_obstacle;
NearbyObstacle backward_obstacle;
forward_obstacle.set_s(FLAGS_default_s_if_no_obstacle_in_lane_sequence);
forward_obstacle.set_l(FLAGS_default_l_if_no_obstacle_in_lane_sequence);
backward_obstacle.set_s(-FLAGS_default_s_if_no_obstacle_in_lane_sequence);
backward_obstacle.set_l(FLAGS_default_l_if_no_obstacle_in_lane_sequence);
for (const auto& nearby_obstacle : lane_sequence_ptr->nearby_obstacle()) {
if (nearby_obstacle.s() < 0.0) {
if (nearby_obstacle.s() > backward_obstacle.s()) {
backward_obstacle.set_id(nearby_obstacle.id());
backward_obstacle.set_s(nearby_obstacle.s());
backward_obstacle.set_l(nearby_obstacle.l());
}
} else {
if (nearby_obstacle.s() < forward_obstacle.s()) {
forward_obstacle.set_id(nearby_obstacle.id());
forward_obstacle.set_s(nearby_obstacle.s());
forward_obstacle.set_l(nearby_obstacle.l());
}
}
}
// Set feature values for forward obstacle
feature_values->push_back(forward_obstacle.s());
feature_values->push_back(forward_obstacle.l());
if (!forward_obstacle.has_id()) { // no forward obstacle
feature_values->push_back(0.0);
feature_values->push_back(0.0);
} else {
Obstacle* forward_obs_ptr =
obstacles_container->GetObstacle(forward_obstacle.id());
if (forward_obs_ptr) {
const Feature& feature = forward_obs_ptr->latest_feature();
feature_values->push_back(feature.length());
feature_values->push_back(feature.speed());
}
}
// Set feature values for backward obstacle
feature_values->push_back(backward_obstacle.s());
feature_values->push_back(backward_obstacle.l());
if (!backward_obstacle.has_id()) { // no forward obstacle
feature_values->push_back(0.0);
feature_values->push_back(0.0);
} else {
Obstacle* backward_obs_ptr =
obstacles_container->GetObstacle(backward_obstacle.id());
if (backward_obs_ptr) {
const Feature& feature = backward_obs_ptr->latest_feature();
feature_values->push_back(feature.length());
feature_values->push_back(feature.speed());
}
}
}
void CruiseMLPEvaluator::SetLaneFeatureValues(
const Obstacle* obstacle_ptr, const LaneSequence* lane_sequence_ptr,
std::vector<double>* feature_values) {
// Sanity checks.
feature_values->clear();
feature_values->reserve(SINGLE_LANE_FEATURE_SIZE * LANE_POINTS_SIZE);
const Feature& feature = obstacle_ptr->latest_feature();
if (!feature.IsInitialized()) {
ADEBUG << "Obstacle [" << obstacle_ptr->id() << "] has no latest feature.";
return;
} else if (!feature.has_position()) {
ADEBUG << "Obstacle [" << obstacle_ptr->id() << "] has no position.";
return;
}
double heading = feature.velocity_heading();
for (int i = 0; i < lane_sequence_ptr->lane_segment_size(); ++i) {
if (feature_values->size() >= SINGLE_LANE_FEATURE_SIZE * LANE_POINTS_SIZE) {
break;
}
const LaneSegment& lane_segment = lane_sequence_ptr->lane_segment(i);
for (int j = 0; j < lane_segment.lane_point_size(); ++j) {
if (feature_values->size() >=
SINGLE_LANE_FEATURE_SIZE * LANE_POINTS_SIZE) {
break;
}
const LanePoint& lane_point = lane_segment.lane_point(j);
if (!lane_point.has_position()) {
AERROR << "Lane point has no position.";
continue;
}
std::pair<double, double> relative_s_l = WorldCoordToObjCoord(
std::make_pair(lane_point.position().x(), lane_point.position().y()),
std::make_pair(feature.position().x(), feature.position().y()),
heading);
double relative_ang = WorldAngleToObjAngle(lane_point.heading(), heading);
feature_values->push_back(relative_s_l.second);
feature_values->push_back(relative_s_l.first);
feature_values->push_back(relative_ang);
feature_values->push_back(lane_point.kappa());
}
}
// If the lane points are not sufficient, apply a linear extrapolation.
std::size_t size = feature_values->size();
while (size >= 10 && size < SINGLE_LANE_FEATURE_SIZE * LANE_POINTS_SIZE) {
double relative_l_new = 2 * feature_values->operator[](size - 5) -
feature_values->operator[](size - 10);
double relative_s_new = 2 * feature_values->operator[](size - 4) -
feature_values->operator[](size - 9);
double relative_ang_new = feature_values->operator[](size - 3);
feature_values->push_back(relative_l_new);
feature_values->push_back(relative_s_new);
feature_values->push_back(relative_ang_new);
feature_values->push_back(0.0);
size = feature_values->size();
}
}
void CruiseMLPEvaluator::LoadModels() {
if (FLAGS_use_cuda && torch::cuda::is_available()) {
ADEBUG << "CUDA is available";
device_ = torch::Device(torch::kCUDA);
}
torch::set_num_threads(1);
torch_go_model_ =
torch::jit::load(FLAGS_torch_vehicle_cruise_go_file, device_);
torch_cutin_model_ =
torch::jit::load(FLAGS_torch_vehicle_cruise_cutin_file, device_);
}
void CruiseMLPEvaluator::ModelInference(
const std::vector<torch::jit::IValue>& torch_inputs,
torch::jit::script::Module torch_model_ptr,
LaneSequence* lane_sequence_ptr) {
auto torch_output_tuple = torch_model_ptr.forward(torch_inputs).toTuple();
auto probability_tensor =
torch_output_tuple->elements()[0].toTensor().to(torch::kCPU);
auto finish_time_tensor =
torch_output_tuple->elements()[1].toTensor().to(torch::kCPU);
lane_sequence_ptr->set_probability(apollo::common::math::Sigmoid(
static_cast<double>(probability_tensor.accessor<float, 2>()[0][0])));
lane_sequence_ptr->set_time_to_lane_center(
static_cast<double>(finish_time_tensor.accessor<float, 2>()[0][0]));
}
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/prediction/evaluator
|
apollo_public_repos/apollo/modules/prediction/evaluator/vehicle/cruise_mlp_evaluator_test.cc
|
/******************************************************************************
* 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.
*****************************************************************************/
#include "modules/prediction/evaluator/vehicle/cruise_mlp_evaluator.h"
#include "cyber/common/file.h"
#include "modules/prediction/common/kml_map_based_test.h"
#include "modules/prediction/container/obstacles/obstacles_container.h"
namespace apollo {
namespace prediction {
class CruiseMLPEvaluatorTest : public KMLMapBasedTest {
public:
void SetUp() override {
const std::string file =
"modules/prediction/testdata/single_perception_vehicle_onlane.pb.txt";
ACHECK(cyber::common::GetProtoFromFile(file, &perception_obstacles_));
}
protected:
apollo::perception::PerceptionObstacles perception_obstacles_;
};
TEST_F(CruiseMLPEvaluatorTest, OnLaneCase) {
EXPECT_DOUBLE_EQ(perception_obstacles_.header().timestamp_sec(),
1501183430.161906);
apollo::perception::PerceptionObstacle perception_obstacle =
perception_obstacles_.perception_obstacle(0);
EXPECT_EQ(perception_obstacle.id(), 1);
CruiseMLPEvaluator cruise_mlp_evaluator;
ObstaclesContainer container;
container.Insert(perception_obstacles_);
container.BuildLaneGraph();
Obstacle* obstacle_ptr = container.GetObstacle(1);
EXPECT_NE(obstacle_ptr, nullptr);
cruise_mlp_evaluator.Evaluate(obstacle_ptr, &container);
const Feature& feature = obstacle_ptr->latest_feature();
const LaneGraph& lane_graph = feature.lane().lane_graph();
for (const auto& lane_sequence : lane_graph.lane_sequence()) {
EXPECT_TRUE(lane_sequence.has_probability());
}
cruise_mlp_evaluator.Clear();
}
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/prediction/evaluator
|
apollo_public_repos/apollo/modules/prediction/evaluator/vehicle/cruise_mlp_evaluator.h
|
/******************************************************************************
* 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.
*****************************************************************************/
#pragma once
#include <string>
#include <vector>
#include "torch/script.h"
#include "torch/torch.h"
#include "modules/prediction/evaluator/evaluator.h"
#include "modules/prediction/container/obstacles/obstacles_container.h"
namespace apollo {
namespace prediction {
class CruiseMLPEvaluator : public Evaluator {
public:
/**
* @brief Constructor
*/
CruiseMLPEvaluator();
/**
* @brief Destructor
*/
virtual ~CruiseMLPEvaluator() = default;
/**
* @brief Override Evaluate
* @param Obstacle pointer
* @param Obstacles container
*/
bool Evaluate(Obstacle* obstacle_ptr,
ObstaclesContainer* obstacles_container) override;
/**
* @brief Extract feature vector
* @param Obstacle pointer
* Lane Sequence pointer
*/
void ExtractFeatureValues(Obstacle* obstacle_ptr,
LaneSequence* lane_sequence_ptr,
std::vector<double>* feature_values);
/**
* @brief Get the name of evaluator.
*/
std::string GetName() override { return "CRUISE_MLP_EVALUATOR"; }
void Clear();
private:
/**
* @brief Set obstacle feature vector
* @param Obstacle pointer
* Feature container in a vector for receiving the feature values
*/
void SetObstacleFeatureValues(const Obstacle* obstacle_ptr,
std::vector<double>* feature_values);
/**
* @brief Set interaction feature vector
* @param Obstacle pointer
* @param Obstacles container
* @param Lane sequence pointer
* @param Feature container in a vector for receiving the feature values
*/
void SetInteractionFeatureValues(Obstacle* obstacle_ptr,
ObstaclesContainer* obstacles_container,
LaneSequence* lane_sequence_ptr,
std::vector<double>* feature_values);
/**
* @brief Set lane feature vector
* @param Obstacle pointer
* Lane sequence pointer
* Feature container in a vector for receiving the feature values
*/
void SetLaneFeatureValues(const Obstacle* obstacle_ptr,
const LaneSequence* lane_sequence_ptr,
std::vector<double>* feature_values);
/**
* @brief Load model files
*/
void LoadModels();
void ModelInference(const std::vector<torch::jit::IValue>& torch_inputs,
torch::jit::script::Module torch_model_ptr,
LaneSequence* lane_sequence_ptr);
private:
static const size_t OBSTACLE_FEATURE_SIZE = 23 + 5 * 9;
static const size_t INTERACTION_FEATURE_SIZE = 8;
static const size_t SINGLE_LANE_FEATURE_SIZE = 4;
static const size_t LANE_POINTS_SIZE = 20;
torch::jit::script::Module torch_go_model_;
torch::jit::script::Module torch_cutin_model_;
torch::Device device_;
};
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/prediction/evaluator
|
apollo_public_repos/apollo/modules/prediction/evaluator/vehicle/lane_scanning_evaluator.h
|
/******************************************************************************
* 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.
*****************************************************************************/
#pragma once
#include <string>
#include <vector>
#include "torch/script.h"
#include "torch/torch.h"
#include "modules/prediction/container/obstacles/obstacles_container.h"
#include "modules/prediction/evaluator/evaluator.h"
namespace apollo {
namespace prediction {
class LaneScanningEvaluator : public Evaluator {
public:
/**
* @brief Constructor
*/
LaneScanningEvaluator();
/**
* @brief Destructor
*/
virtual ~LaneScanningEvaluator() = default;
/**
* @brief Override Evaluate
* @param Obstacle pointer
* @param Obstacles container
*/
bool Evaluate(Obstacle* obstacle_ptr,
ObstaclesContainer* obstacles_container) override;
/**
* @brief Override Evaluate
* @param Obstacle pointer
* @param Obstacles container
* @param vector of all Obstacles
*/
bool Evaluate(Obstacle* obstacle_ptr, ObstaclesContainer* obstacles_container,
std::vector<Obstacle*> dynamic_env) override;
/**
* @brief Extract features for learning model's input
* @param Obstacle pointer
* @param Lane Graph pointer
* @param To be filled up with extracted features
*/
bool ExtractFeatures(const Obstacle* obstacle_ptr,
const LaneGraph* lane_graph_ptr,
std::vector<double>* feature_values);
bool ExtractStringFeatures(
const LaneGraph& lane_graph,
std::vector<std::string>* const string_feature_values);
/**
* @brief Get the name of evaluator.
*/
std::string GetName() override { return "LANE_SCANNING_EVALUATOR"; }
private:
/**
* @brief Load model from file
*/
void LoadModel();
/**
* @brief Extract the features for obstacles
* @param Obstacle pointer
* A vector of doubles to be filled up with extracted features
*/
bool ExtractObstacleFeatures(const Obstacle* obstacle_ptr,
std::vector<double>* feature_values);
/**
* @brief Set lane feature vector
* @param Obstacle pointer
* A vector of doubles to be filled up with extracted features
*/
bool ExtractStaticEnvFeatures(const Obstacle* obstacle_ptr,
const LaneGraph* lane_graph_ptr,
std::vector<double>* feature_values,
std::vector<int>* lane_sequence_idx_to_remove);
void ModelInference(const std::vector<torch::jit::IValue>& torch_inputs,
torch::jit::script::Module torch_model,
Feature* feature_ptr);
private:
static const size_t OBSTACLE_FEATURE_SIZE = 20 * (9 + 40);
static const size_t INTERACTION_FEATURE_SIZE = 8;
static const size_t SINGLE_LANE_FEATURE_SIZE = 4;
static const size_t LANE_POINTS_SIZE = 100; // 50m
static const size_t BACKWARD_LANE_POINTS_SIZE = 50; // 25m
static const size_t MAX_NUM_LANE = 10;
static const size_t SHORT_TERM_TRAJECTORY_SIZE = 10;
torch::jit::script::Module torch_lane_scanning_model_;
torch::Device device_;
};
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/prediction/evaluator
|
apollo_public_repos/apollo/modules/prediction/evaluator/vehicle/semantic_lstm_evaluator.cc
|
/******************************************************************************
* 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.
*****************************************************************************/
#include "modules/prediction/evaluator/vehicle/semantic_lstm_evaluator.h"
#include <omp.h>
#include "Eigen/Dense"
#include "cyber/common/file.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_map.h"
#include "modules/prediction/common/prediction_system_gflags.h"
#include "modules/prediction/common/prediction_util.h"
namespace apollo {
namespace prediction {
using apollo::common::TrajectoryPoint;
using apollo::common::math::Vec2d;
SemanticLSTMEvaluator::SemanticLSTMEvaluator(SemanticMap* semantic_map)
: device_(torch::kCPU), semantic_map_(semantic_map) {
evaluator_type_ = ObstacleConf::SEMANTIC_LSTM_EVALUATOR;
LoadModel();
}
void SemanticLSTMEvaluator::Clear() {}
bool SemanticLSTMEvaluator::Evaluate(Obstacle* obstacle_ptr,
ObstaclesContainer* obstacles_container) {
omp_set_num_threads(1);
obstacle_ptr->SetEvaluatorType(evaluator_type_);
Clear();
CHECK_NOTNULL(obstacle_ptr);
int id = obstacle_ptr->id();
if (!obstacle_ptr->latest_feature().IsInitialized()) {
AERROR << "Obstacle [" << id << "] has no latest feature.";
return false;
}
Feature* latest_feature_ptr = obstacle_ptr->mutable_latest_feature();
CHECK_NOTNULL(latest_feature_ptr);
if (!FLAGS_enable_semantic_map) {
ADEBUG << "Not enable semantic map, exit semantic_lstm_evaluator.";
return false;
}
cv::Mat feature_map;
if (!semantic_map_->GetMapById(id, &feature_map)) {
return false;
}
// Process the feature_map
cv::cvtColor(feature_map, feature_map, cv::COLOR_BGR2RGB);
cv::Mat img_float;
feature_map.convertTo(img_float, CV_32F, 1.0 / 255);
torch::Tensor img_tensor = torch::from_blob(img_float.data, {1, 224, 224, 3});
img_tensor = img_tensor.permute({0, 3, 1, 2});
img_tensor[0][0] = img_tensor[0][0].sub(0.485).div(0.229);
img_tensor[0][1] = img_tensor[0][1].sub(0.456).div(0.224);
img_tensor[0][2] = img_tensor[0][2].sub(0.406).div(0.225);
// Extract features of pos_history
std::vector<std::pair<double, double>> pos_history(20, {0.0, 0.0});
if (!ExtractObstacleHistory(obstacle_ptr, &pos_history)) {
ADEBUG << "Obstacle [" << id << "] failed to extract obstacle history";
return false;
}
// Process obstacle_history
// TODO(Hongyi): move magic numbers to parameters and gflags
torch::Tensor obstacle_pos = torch::zeros({1, 20, 2});
torch::Tensor obstacle_pos_step = torch::zeros({1, 20, 2});
for (int i = 0; i < 20; ++i) {
obstacle_pos[0][19 - i][0] = pos_history[i].first;
obstacle_pos[0][19 - i][1] = pos_history[i].second;
if (i == 19 || (i > 0 && pos_history[i].first == 0.0)) {
break;
}
obstacle_pos_step[0][19 - i][0] =
pos_history[i].first - pos_history[i + 1].first;
obstacle_pos_step[0][19 - i][1] =
pos_history[i].second - pos_history[i + 1].second;
}
// Build input features for torch
std::vector<torch::jit::IValue> torch_inputs;
torch_inputs.push_back(c10::ivalue::Tuple::create(
{std::move(img_tensor.to(device_)), std::move(obstacle_pos.to(device_)),
std::move(obstacle_pos_step.to(device_))}));
// Compute pred_traj
std::vector<double> pred_traj;
auto start_time = std::chrono::system_clock::now();
at::Tensor torch_output_tensor = torch_default_output_tensor_;
if (obstacle_ptr->IsPedestrian()) {
torch_output_tensor = torch_pedestrian_model_.forward(torch_inputs)
.toTensor()
.to(torch::kCPU);
} else {
torch_output_tensor =
torch_vehicle_model_.forward(torch_inputs).toTensor().to(torch::kCPU);
}
auto end_time = std::chrono::system_clock::now();
std::chrono::duration<double> diff = end_time - start_time;
ADEBUG << "Semantic_LSTM_evaluator used time: " << diff.count() * 1000
<< " ms.";
auto torch_output = torch_output_tensor.accessor<float, 3>();
// Get the trajectory
double pos_x = latest_feature_ptr->position().x();
double pos_y = latest_feature_ptr->position().y();
Trajectory* trajectory = latest_feature_ptr->add_predicted_trajectory();
trajectory->set_probability(1.0);
for (int i = 0; i < 30; ++i) {
double prev_x = pos_x;
double prev_y = pos_y;
if (i > 0) {
const auto& last_point = trajectory->trajectory_point(i - 1).path_point();
prev_x = last_point.x();
prev_y = last_point.y();
}
TrajectoryPoint* point = trajectory->add_trajectory_point();
double dx = static_cast<double>(torch_output[0][i][0]);
double dy = static_cast<double>(torch_output[0][i][1]);
double heading = latest_feature_ptr->velocity_heading();
Vec2d offset(dx, dy);
Vec2d rotated_offset = offset.rotate(heading);
double point_x = pos_x + rotated_offset.x();
double point_y = pos_y + rotated_offset.y();
point->mutable_path_point()->set_x(point_x);
point->mutable_path_point()->set_y(point_y);
if (torch_output_tensor.sizes()[2] == 5) {
double sigma_xr = std::abs(static_cast<double>(torch_output[0][i][2]));
double sigma_yr = std::abs(static_cast<double>(torch_output[0][i][3]));
double corr_r = static_cast<double>(torch_output[0][i][4]);
Eigen::Matrix2d cov_matrix_r;
cov_matrix_r(0, 0) = sigma_xr * sigma_xr;
cov_matrix_r(0, 1) = corr_r * sigma_xr * sigma_yr;
cov_matrix_r(1, 0) = corr_r * sigma_xr * sigma_yr;
cov_matrix_r(1, 1) = sigma_yr * sigma_yr;
Eigen::Matrix2d rotation_matrix;
rotation_matrix(0, 0) = std::cos(heading);
rotation_matrix(0, 1) = -std::sin(heading);
rotation_matrix(1, 0) = std::sin(heading);
rotation_matrix(1, 1) = std::cos(heading);
Eigen::Matrix2d cov_matrix;
cov_matrix =
rotation_matrix * cov_matrix_r * (rotation_matrix.transpose());
double sigma_x = std::sqrt(std::abs(cov_matrix(0, 0)));
double sigma_y = std::sqrt(std::abs(cov_matrix(1, 1)));
double corr = cov_matrix(0, 1) / (sigma_x + FLAGS_double_precision) /
(sigma_y + FLAGS_double_precision);
point->mutable_gaussian_info()->set_sigma_x(sigma_x);
point->mutable_gaussian_info()->set_sigma_y(sigma_y);
point->mutable_gaussian_info()->set_correlation(corr);
if (i > 0) {
Eigen::EigenSolver<Eigen::Matrix2d> eigen_solver(cov_matrix);
const auto& eigen_values = eigen_solver.eigenvalues();
const auto& eigen_vectors = eigen_solver.eigenvectors();
point->mutable_gaussian_info()->set_ellipse_a(
std::sqrt(std::abs(eigen_values(0).real())));
point->mutable_gaussian_info()->set_ellipse_b(
std::sqrt(std::abs(eigen_values(1).real())));
double cos_theta_a = eigen_vectors(0, 0).real();
double sin_theta_a = eigen_vectors(1, 0).real();
point->mutable_gaussian_info()->set_theta_a(
std::atan2(sin_theta_a, cos_theta_a));
}
}
if (i < 10) { // use origin heading for the first second
point->mutable_path_point()->set_theta(
latest_feature_ptr->velocity_heading());
} else {
point->mutable_path_point()->set_theta(
std::atan2(trajectory->trajectory_point(i).path_point().y() -
trajectory->trajectory_point(i - 1).path_point().y(),
trajectory->trajectory_point(i).path_point().x() -
trajectory->trajectory_point(i - 1).path_point().x()));
}
point->set_relative_time(static_cast<double>(i) *
FLAGS_prediction_trajectory_time_resolution);
if (i == 0) {
point->set_v(latest_feature_ptr->speed());
} else {
double diff_x = point_x - prev_x;
double diff_y = point_y - prev_y;
point->set_v(std::hypot(diff_x, diff_y) /
FLAGS_prediction_trajectory_time_resolution);
}
}
return true;
}
bool SemanticLSTMEvaluator::ExtractObstacleHistory(
Obstacle* obstacle_ptr,
std::vector<std::pair<double, double>>* pos_history) {
pos_history->resize(20, {0.0, 0.0});
const Feature& obs_curr_feature = obstacle_ptr->latest_feature();
double obs_curr_heading = obs_curr_feature.velocity_heading();
std::pair<double, double> obs_curr_pos = std::make_pair(
obs_curr_feature.position().x(), obs_curr_feature.position().y());
for (std::size_t i = 0; i < obstacle_ptr->history_size() && i < 20; ++i) {
const Feature& feature = obstacle_ptr->feature(i);
if (!feature.IsInitialized()) {
break;
}
pos_history->at(i) = WorldCoordToObjCoord(
std::make_pair(feature.position().x(), feature.position().y()),
obs_curr_pos, obs_curr_heading);
}
return true;
}
void SemanticLSTMEvaluator::LoadModel() {
if (FLAGS_use_cuda && torch::cuda::is_available()) {
ADEBUG << "CUDA is available";
device_ = torch::Device(torch::kCUDA);
torch_vehicle_model_ =
torch::jit::load(FLAGS_torch_vehicle_semantic_lstm_file, device_);
torch_pedestrian_model_ =
torch::jit::load(FLAGS_torch_pedestrian_semantic_lstm_file, device_);
} else {
torch_vehicle_model_ =
torch::jit::load(FLAGS_torch_vehicle_semantic_lstm_cpu_file, device_);
torch_pedestrian_model_ = torch::jit::load(
FLAGS_torch_pedestrian_semantic_lstm_cpu_file, device_);
}
torch::set_num_threads(1);
// Fake intput for the first frame
torch::Tensor img_tensor = torch::zeros({1, 3, 224, 224});
torch::Tensor obstacle_pos = torch::zeros({1, 20, 2});
torch::Tensor obstacle_pos_step = torch::zeros({1, 20, 2});
std::vector<torch::jit::IValue> torch_inputs;
torch_inputs.push_back(c10::ivalue::Tuple::create(
{std::move(img_tensor.to(device_)), std::move(obstacle_pos.to(device_)),
std::move(obstacle_pos_step.to(device_))}));
// Run one inference to avoid very slow first inference later
torch_default_output_tensor_ =
torch_vehicle_model_.forward(torch_inputs).toTensor().to(torch::kCPU);
torch_default_output_tensor_ =
torch_pedestrian_model_.forward(torch_inputs).toTensor().to(torch::kCPU);
}
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/prediction/evaluator
|
apollo_public_repos/apollo/modules/prediction/evaluator/cyclist/BUILD
|
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test")
load("//tools:cpplint.bzl", "cpplint")
package(default_visibility = ["//visibility:public"])
cc_library(
name = "cyclist_keep_lane_evaluator",
srcs = ["cyclist_keep_lane_evaluator.cc"],
hdrs = ["cyclist_keep_lane_evaluator.h"],
copts = [
"-DMODULE_NAME=\\\"prediction\\\"",
],
deps = [
"//modules/prediction/container/obstacles:obstacles_container",
"//modules/prediction/evaluator",
],
)
cc_test(
name = "cyclist_keep_lane_evaluator_test",
size = "small",
srcs = ["cyclist_keep_lane_evaluator_test.cc"],
data = [
"//modules/prediction:prediction_data",
"//modules/prediction:prediction_testdata",
],
deps = [
":cyclist_keep_lane_evaluator",
"//modules/prediction/common:kml_map_based_test",
"//modules/prediction/container/obstacles:obstacles_container",
"@com_google_googletest//:gtest_main",
],
)
cpplint()
| 0
|
apollo_public_repos/apollo/modules/prediction/evaluator
|
apollo_public_repos/apollo/modules/prediction/evaluator/cyclist/cyclist_keep_lane_evaluator.h
|
/******************************************************************************
* 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.
*****************************************************************************/
/**
* @file
* @brief Define the cyclist keep lane predictor class
*/
#pragma once
#include <string>
#include "modules/prediction/evaluator/evaluator.h"
#include "modules/prediction/container/obstacles/obstacles_container.h"
/**
* @namespace apollo::prediction
* @brief apollo::prediction
*/
namespace apollo {
namespace prediction {
class CyclistKeepLaneEvaluator : public Evaluator {
public:
/**
* @brief Constructor
*/
CyclistKeepLaneEvaluator();
/**
* @brief Destructor
*/
virtual ~CyclistKeepLaneEvaluator() = default;
/**
* @brief Override Evaluate
* @param Obstacle pointer
*/
bool Evaluate(Obstacle* obstacle_ptr,
ObstaclesContainer* obstacles_container) override;
/**
* @brief Get the name of evaluator.
*/
std::string GetName() override { return "CYCLIST_KEEP_LANE_EVALUATOR"; }
private:
double ComputeProbability(const std::string& curr_lane_id,
const LaneSequence& lane_sequence);
};
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/prediction/evaluator
|
apollo_public_repos/apollo/modules/prediction/evaluator/cyclist/cyclist_keep_lane_evaluator_test.cc
|
/******************************************************************************
* 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.
*****************************************************************************/
#include "modules/prediction/evaluator/cyclist/cyclist_keep_lane_evaluator.h"
#include "cyber/common/file.h"
#include "modules/prediction/common/kml_map_based_test.h"
#include "modules/prediction/container/obstacles/obstacles_container.h"
namespace apollo {
namespace prediction {
class CyclistKeepLaneEvaluatorTest : public KMLMapBasedTest {
public:
void SetUp() override {
const std::string file =
"modules/prediction/testdata/single_perception_cyclist_onlane.pb.txt";
ACHECK(cyber::common::GetProtoFromFile(file, &perception_obstacles_));
}
protected:
apollo::perception::PerceptionObstacles perception_obstacles_;
};
TEST_F(CyclistKeepLaneEvaluatorTest, OnLaneCase) {
EXPECT_DOUBLE_EQ(perception_obstacles_.header().timestamp_sec(),
1501183430.161906);
apollo::perception::PerceptionObstacle perception_obstacle =
perception_obstacles_.perception_obstacle(0);
EXPECT_EQ(perception_obstacle.id(), 1);
CyclistKeepLaneEvaluator cyclist_keep_lane_evaluator;
ObstaclesContainer container;
container.Insert(perception_obstacles_);
Obstacle* obstacle_ptr = container.GetObstacle(1);
EXPECT_NE(obstacle_ptr, nullptr);
cyclist_keep_lane_evaluator.Evaluate(obstacle_ptr, &container);
const Feature& feature = obstacle_ptr->latest_feature();
const LaneGraph& lane_graph = feature.lane().lane_graph();
for (const auto& lane_sequence : lane_graph.lane_sequence()) {
EXPECT_TRUE(lane_sequence.has_probability());
}
}
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/prediction/evaluator
|
apollo_public_repos/apollo/modules/prediction/evaluator/cyclist/cyclist_keep_lane_evaluator.cc
|
/******************************************************************************
* 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.
*****************************************************************************/
#include "modules/prediction/evaluator/cyclist/cyclist_keep_lane_evaluator.h"
namespace apollo {
namespace prediction {
CyclistKeepLaneEvaluator::CyclistKeepLaneEvaluator() {
evaluator_type_ = ObstacleConf::CYCLIST_KEEP_LANE_EVALUATOR;
}
bool CyclistKeepLaneEvaluator::Evaluate(
Obstacle* obstacle_ptr, ObstaclesContainer* obstacles_container) {
CHECK_NOTNULL(obstacle_ptr);
obstacle_ptr->SetEvaluatorType(evaluator_type_);
int id = obstacle_ptr->id();
if (!obstacle_ptr->latest_feature().IsInitialized()) {
AERROR << "Obstacle [" << id << "] has no latest feature.";
return false;
}
Feature* latest_feature_ptr = obstacle_ptr->mutable_latest_feature();
CHECK_NOTNULL(latest_feature_ptr);
if (!latest_feature_ptr->has_lane() ||
!latest_feature_ptr->lane().has_lane_graph() ||
!latest_feature_ptr->lane().has_lane_feature()) {
ADEBUG << "Obstacle [" << id << "] has no lane graph.";
return false;
}
LaneGraph* lane_graph_ptr =
latest_feature_ptr->mutable_lane()->mutable_lane_graph();
CHECK_NOTNULL(lane_graph_ptr);
if (lane_graph_ptr->lane_sequence().empty()) {
AERROR << "Obstacle [" << id << "] has no lane sequences.";
return false;
}
std::string curr_lane_id =
latest_feature_ptr->lane().lane_feature().lane_id();
for (auto& lane_sequence : *lane_graph_ptr->mutable_lane_sequence()) {
const double probability = ComputeProbability(curr_lane_id, lane_sequence);
lane_sequence.set_probability(probability);
}
return true;
}
double CyclistKeepLaneEvaluator::ComputeProbability(
const std::string& curr_lane_id, const LaneSequence& lane_sequence) {
if (lane_sequence.lane_segment().empty()) {
AWARN << "Empty lane sequence.";
return 0.0;
}
std::string lane_seq_first_id = lane_sequence.lane_segment(0).lane_id();
if (curr_lane_id == lane_seq_first_id) {
return 1.0;
}
return 0.0;
}
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/prediction/evaluator
|
apollo_public_repos/apollo/modules/prediction/evaluator/pedestrian/pedestrian_interaction_evaluator_test.cc
|
/******************************************************************************
* 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.
*****************************************************************************/
#include "modules/prediction/evaluator/pedestrian/pedestrian_interaction_evaluator.h"
#include "cyber/common/file.h"
#include "modules/prediction/common/kml_map_based_test.h"
#include "modules/prediction/container/obstacles/obstacles_container.h"
namespace apollo {
namespace prediction {
class PedestrianInteractionEvaluatorTest : public KMLMapBasedTest {
public:
void SetUp() override {
std::string file =
"modules/prediction/testdata/multiple_perception_pedestrians.pb.txt";
cyber::common::GetProtoFromFile(file, &perception_obstacles_);
}
protected:
apollo::perception::PerceptionObstacles perception_obstacles_;
};
TEST_F(PedestrianInteractionEvaluatorTest, Evaluate) {
EXPECT_DOUBLE_EQ(perception_obstacles_.header().timestamp_sec(),
1501183430.161906);
apollo::perception::PerceptionObstacle perception_obstacle =
perception_obstacles_.perception_obstacle(0);
EXPECT_EQ(perception_obstacle.id(), 101);
ObstaclesContainer container;
container.Insert(perception_obstacles_);
Obstacle* obstacle_ptr = container.GetObstacle(101);
EXPECT_NE(obstacle_ptr, nullptr);
PedestrianInteractionEvaluator evaluator;
evaluator.Evaluate(obstacle_ptr, &container);
}
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/prediction/evaluator
|
apollo_public_repos/apollo/modules/prediction/evaluator/pedestrian/pedestrian_interaction_evaluator.cc
|
/******************************************************************************
* 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.
*****************************************************************************/
#include "modules/prediction/evaluator/pedestrian/pedestrian_interaction_evaluator.h"
#include <utility>
#include "modules/common/math/vec2d.h"
#include "modules/prediction/common/feature_output.h"
#include "modules/prediction/common/prediction_constants.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_system_gflags.h"
#include "modules/prediction/container/container_manager.h"
#include "modules/prediction/container/obstacles/obstacles_container.h"
#include "modules/prediction/container/pose/pose_container.h"
namespace apollo {
namespace prediction {
using apollo::common::TrajectoryPoint;
PedestrianInteractionEvaluator::PedestrianInteractionEvaluator()
: device_(torch::kCPU) {
evaluator_type_ = ObstacleConf::PEDESTRIAN_INTERACTION_EVALUATOR;
LoadModel();
}
/* TODO(kechxu) figure out if this function is necessary. It is not being used
void PedestrianInteractionEvaluator::Clear() {
auto ptr_obstacles_container =
ContainerManager::Instance()->GetContainer<ObstaclesContainer>(
AdapterConfig::PERCEPTION_OBSTACLES);
std::vector<int> keys_to_delete;
for (const auto& item : obstacle_id_lstm_state_map_) {
int key = item.first;
if (obstacle_id_lstm_state_map_[key].timestamp + FLAGS_max_history_time <
ptr_obstacles_container->timestamp()) {
keys_to_delete.push_back(key);
}
}
for (const int key : keys_to_delete) {
obstacle_id_lstm_state_map_.erase(key);
}
}
*/
void PedestrianInteractionEvaluator::LoadModel() {
torch::set_num_threads(1);
if (FLAGS_use_cuda && torch::cuda::is_available()) {
ADEBUG << "CUDA is available";
device_ = torch::Device(torch::kCUDA);
}
torch_position_embedding_ = torch::jit::load(
FLAGS_torch_pedestrian_interaction_position_embedding_file, device_);
torch_social_embedding_ = torch::jit::load(
FLAGS_torch_pedestrian_interaction_social_embedding_file, device_);
torch_single_lstm_ = torch::jit::load(
FLAGS_torch_pedestrian_interaction_single_lstm_file, device_);
torch_prediction_layer_ = torch::jit::load(
FLAGS_torch_pedestrian_interaction_prediction_layer_file, device_);
}
torch::Tensor PedestrianInteractionEvaluator::GetSocialPooling() {
// TODO(kechxu) implement more sophisticated logics
return torch::zeros({1, kGridSize * kGridSize * kHiddenSize});
}
bool PedestrianInteractionEvaluator::Evaluate(
Obstacle* obstacle_ptr, ObstaclesContainer* obstacles_container) {
// Sanity checks.
CHECK_NOTNULL(obstacle_ptr);
obstacle_ptr->SetEvaluatorType(evaluator_type_);
int id = obstacle_ptr->id();
if (!obstacle_ptr->latest_feature().IsInitialized()) {
AERROR << "Obstacle [" << id << "] has no latest feature.";
return false;
}
Feature* latest_feature_ptr = obstacle_ptr->mutable_latest_feature();
CHECK_NOTNULL(latest_feature_ptr);
// Extract features, and:
// - if in offline mode, save it locally for training.
// - if in online mode, pass it through trained model to evaluate.
std::vector<double> feature_values;
ExtractFeatures(obstacle_ptr, &feature_values);
if (FLAGS_prediction_offline_mode ==
PredictionConstants::kDumpDataForLearning) {
FeatureOutput::InsertDataForLearning(*latest_feature_ptr, feature_values,
"pedestrian", nullptr);
ADEBUG << "Saving extracted features for learning locally.";
return true;
}
static constexpr double kShortTermPredictionTimeResolution = 0.4;
static constexpr int kShortTermPredictionPointNum = 5;
static constexpr int kHiddenStateUpdateCycle = 4;
// Step 1 Get social embedding
torch::Tensor social_pooling = GetSocialPooling();
std::vector<torch::jit::IValue> social_embedding_inputs;
social_embedding_inputs.push_back(std::move(social_pooling.to(device_)));
torch::Tensor social_embedding =
torch_social_embedding_.forward(social_embedding_inputs)
.toTensor()
.to(torch::kCPU);
// Step 2 Get position embedding
double pos_x = feature_values[2];
double pos_y = feature_values[3];
double rel_x = 0.0;
double rel_y = 0.0;
if (obstacle_ptr->history_size() > kHiddenStateUpdateCycle - 1) {
rel_x = obstacle_ptr->latest_feature().position().x() -
obstacle_ptr->feature(3).position().x();
rel_y = obstacle_ptr->latest_feature().position().y() -
obstacle_ptr->feature(3).position().y();
}
torch::Tensor torch_position = torch::zeros({1, 2});
torch_position[0][0] = rel_x;
torch_position[0][1] = rel_y;
std::vector<torch::jit::IValue> position_embedding_inputs;
position_embedding_inputs.push_back(std::move(torch_position.to(device_)));
torch::Tensor position_embedding =
torch_position_embedding_.forward(position_embedding_inputs)
.toTensor()
.to(torch::kCPU);
// Step 3 Conduct single LSTM and update hidden states
torch::Tensor lstm_input =
torch::zeros({1, 2 * (kEmbeddingSize + kHiddenSize)});
for (int i = 0; i < kEmbeddingSize; ++i) {
lstm_input[0][i] = position_embedding[0][i];
}
if (obstacle_id_lstm_state_map_.find(id) ==
obstacle_id_lstm_state_map_.end()) {
obstacle_id_lstm_state_map_[id].ht = torch::zeros({1, 1, kHiddenSize});
obstacle_id_lstm_state_map_[id].ct = torch::zeros({1, 1, kHiddenSize});
obstacle_id_lstm_state_map_[id].timestamp = obstacle_ptr->timestamp();
obstacle_id_lstm_state_map_[id].frame_count = 0;
}
torch::Tensor curr_ht = obstacle_id_lstm_state_map_[id].ht;
torch::Tensor curr_ct = obstacle_id_lstm_state_map_[id].ct;
int curr_frame_count = obstacle_id_lstm_state_map_[id].frame_count;
if (curr_frame_count == kHiddenStateUpdateCycle - 1) {
for (int i = 0; i < kHiddenSize; ++i) {
lstm_input[0][kEmbeddingSize + i] = curr_ht[0][0][i];
lstm_input[0][kEmbeddingSize + kHiddenSize + i] = curr_ct[0][0][i];
}
std::vector<torch::jit::IValue> lstm_inputs;
lstm_inputs.push_back(std::move(lstm_input.to(device_)));
auto lstm_out_tuple = torch_single_lstm_.forward(lstm_inputs).toTuple();
auto ht = lstm_out_tuple->elements()[0].toTensor();
auto ct = lstm_out_tuple->elements()[1].toTensor();
obstacle_id_lstm_state_map_[id].ht = ht.clone();
obstacle_id_lstm_state_map_[id].ct = ct.clone();
}
obstacle_id_lstm_state_map_[id].frame_count =
(curr_frame_count + 1) % kHiddenStateUpdateCycle;
// Step 4 for-loop get a trajectory
// Set the starting trajectory point
Trajectory* trajectory = latest_feature_ptr->add_predicted_trajectory();
trajectory->set_probability(1.0);
TrajectoryPoint* start_point = trajectory->add_trajectory_point();
start_point->mutable_path_point()->set_x(pos_x);
start_point->mutable_path_point()->set_y(pos_y);
start_point->mutable_path_point()->set_theta(latest_feature_ptr->theta());
start_point->set_v(latest_feature_ptr->speed());
start_point->set_relative_time(0.0);
for (int i = 1; i <= kShortTermPredictionPointNum; ++i) {
double prev_x = trajectory->trajectory_point(i - 1).path_point().x();
double prev_y = trajectory->trajectory_point(i - 1).path_point().y();
ACHECK(obstacle_id_lstm_state_map_.find(id) !=
obstacle_id_lstm_state_map_.end());
torch::Tensor torch_position = torch::zeros({1, 2});
double curr_rel_x = rel_x;
double curr_rel_y = rel_y;
if (i > 1) {
curr_rel_x =
prev_x - trajectory->trajectory_point(i - 2).path_point().x();
curr_rel_y =
prev_y - trajectory->trajectory_point(i - 2).path_point().y();
}
torch_position[0][0] = curr_rel_x;
torch_position[0][1] = curr_rel_y;
std::vector<torch::jit::IValue> position_embedding_inputs;
position_embedding_inputs.push_back(std::move(torch_position.to(device_)));
torch::Tensor position_embedding =
torch_position_embedding_.forward(position_embedding_inputs)
.toTensor()
.to(torch::kCPU);
torch::Tensor lstm_input =
torch::zeros({1, kEmbeddingSize + 2 * kHiddenSize});
for (int i = 0; i < kEmbeddingSize; ++i) {
lstm_input[0][i] = position_embedding[0][i];
}
auto ht = obstacle_id_lstm_state_map_[id].ht.clone();
auto ct = obstacle_id_lstm_state_map_[id].ct.clone();
for (int i = 0; i < kHiddenSize; ++i) {
lstm_input[0][kEmbeddingSize + i] = ht[0][0][i];
lstm_input[0][kEmbeddingSize + kHiddenSize + i] = ct[0][0][i];
}
std::vector<torch::jit::IValue> lstm_inputs;
lstm_inputs.push_back(std::move(lstm_input.to(device_)));
auto lstm_out_tuple = torch_single_lstm_.forward(lstm_inputs).toTuple();
ht = lstm_out_tuple->elements()[0].toTensor();
ct = lstm_out_tuple->elements()[1].toTensor();
std::vector<torch::jit::IValue> prediction_inputs;
prediction_inputs.push_back(ht[0]);
auto pred_out_tensor = torch_prediction_layer_.forward(prediction_inputs)
.toTensor()
.to(torch::kCPU);
auto pred_out = pred_out_tensor.accessor<float, 2>();
TrajectoryPoint* point = trajectory->add_trajectory_point();
double curr_x = prev_x + static_cast<double>(pred_out[0][0]);
double curr_y = prev_y + static_cast<double>(pred_out[0][1]);
point->mutable_path_point()->set_x(curr_x);
point->mutable_path_point()->set_y(curr_y);
point->set_v(latest_feature_ptr->speed());
point->mutable_path_point()->set_theta(
latest_feature_ptr->velocity_heading());
point->set_relative_time(kShortTermPredictionTimeResolution *
static_cast<double>(i));
}
return true;
}
bool PedestrianInteractionEvaluator::ExtractFeatures(
const Obstacle* obstacle_ptr, std::vector<double>* feature_values) {
// Sanity checks.
CHECK_NOTNULL(obstacle_ptr);
CHECK_NOTNULL(feature_values);
// Extract obstacle related features.
double timestamp = obstacle_ptr->latest_feature().timestamp();
int id = obstacle_ptr->latest_feature().id();
double pos_x = obstacle_ptr->latest_feature().position().x();
double pos_y = obstacle_ptr->latest_feature().position().y();
// Insert it into the feature_values.
feature_values->push_back(timestamp);
feature_values->push_back(id * 1.0);
feature_values->push_back(pos_x);
feature_values->push_back(pos_y);
return true;
}
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/prediction/evaluator
|
apollo_public_repos/apollo/modules/prediction/evaluator/pedestrian/pedestrian_interaction_evaluator.h
|
/******************************************************************************
* 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.
*****************************************************************************/
/**
* @file
* @brief Define the pedestrian interaction evaluator class
*/
#pragma once
#include <string>
#include <unordered_map>
#include <vector>
#include "torch/script.h"
#include "torch/torch.h"
#include "modules/prediction/evaluator/evaluator.h"
/**
* @namespace apollo::prediction
* @brief apollo::prediction
*/
namespace apollo {
namespace prediction {
class PedestrianInteractionEvaluator : public Evaluator {
public:
/**
* @brief Constructor
*/
PedestrianInteractionEvaluator();
/**
* @brief Destructor
*/
virtual ~PedestrianInteractionEvaluator() = default;
/**
* @brief Override Evaluate
* @param Obstacle pointer
* @param Obstacles container
*/
bool Evaluate(Obstacle* obstacle_ptr,
ObstaclesContainer* obstacles_container) override;
/**
* @brief Extract features for learning model's input
* @param Obstacle pointer
* @param To be filled up with extracted features
*/
bool ExtractFeatures(const Obstacle* obstacle_ptr,
std::vector<double>* feature_values);
/**
* @brief Get the name of evaluator.
*/
std::string GetName() override { return "PEDESTRIAN_INTERACTION_EVALUATOR"; }
private:
struct LSTMState {
double timestamp;
torch::Tensor ct;
torch::Tensor ht;
int frame_count = 0;
};
// void Clear();
void LoadModel();
torch::Tensor GetSocialPooling();
private:
std::unordered_map<int, LSTMState> obstacle_id_lstm_state_map_;
torch::jit::script::Module torch_position_embedding_;
torch::jit::script::Module torch_social_embedding_;
torch::jit::script::Module torch_single_lstm_;
torch::jit::script::Module torch_prediction_layer_;
torch::Device device_;
static const int kGridSize = 2;
static const int kEmbeddingSize = 64;
static const int kHiddenSize = 128;
};
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/prediction/evaluator
|
apollo_public_repos/apollo/modules/prediction/evaluator/pedestrian/BUILD
|
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test")
load("//tools:cpplint.bzl", "cpplint")
package(default_visibility = ["//visibility:public"])
cc_library(
name = "pedestrian_interaction_evaluator",
srcs = ["pedestrian_interaction_evaluator.cc"],
hdrs = ["pedestrian_interaction_evaluator.h"],
copts = [
"-DMODULE_NAME=\\\"prediction\\\"",
],
deps = [
"//modules/prediction/container:container_manager",
"//modules/prediction/container/obstacles:obstacles_container",
"//modules/prediction/evaluator",
"//third_party:libtorch",
],
)
cc_test(
name = "pedestrian_interaction_evaluator_test",
size = "small",
srcs = ["pedestrian_interaction_evaluator_test.cc"],
data = [
"//modules/prediction:prediction_data",
"//modules/prediction:prediction_testdata",
],
deps = [
":pedestrian_interaction_evaluator",
"//modules/prediction/common:kml_map_based_test",
"//modules/prediction/container/obstacles:obstacles_container",
"@com_google_googletest//:gtest_main",
],
linkstatic = True,
)
cpplint()
| 0
|
apollo_public_repos/apollo/modules/prediction
|
apollo_public_repos/apollo/modules/prediction/pipeline/vector_net_feature.cc
|
/******************************************************************************
* Copyright 2021 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.
*****************************************************************************/
#include "modules/prediction/pipeline/vector_net.h"
using apollo::prediction::VectorNet;
int main(int argc, char* argv[]) {
google::ParseCommandLineFlags(&argc, &argv, true);
VectorNet vector_net = VectorNet();
vector_net.offline_query(FLAGS_obstacle_x, FLAGS_obstacle_y,
FLAGS_obstacle_phi);
return 0;
}
| 0
|
apollo_public_repos/apollo/modules/prediction
|
apollo_public_repos/apollo/modules/prediction/pipeline/vector_net_offline_data.cc
|
/******************************************************************************
* Copyright 2021 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.
*****************************************************************************/
#include <fstream>
#include "modules/prediction/pipeline/vector_net.h"
using apollo::prediction::VectorNet;
int main(int argc, char* argv[]) {
google::ParseCommandLineFlags(&argc, &argv, true);
VectorNet vector_net = VectorNet();
// get world-coord from protobuf
apollo::prediction::WorldCoord world_coords;
std::fstream input(
FLAGS_world_coordinate_file, std::ios::in | std::ios::binary);
if (!world_coords.ParseFromIstream(&input)) {
AERROR << "Failed to parse file: " << FLAGS_world_coordinate_file;
return -1;
}
for (auto pose : world_coords.pose()) {
double x = pose.x();
double y = pose.y();
double phi = pose.phi();
std::string _file_name = \
FLAGS_prediction_target_dir + "/" + pose.id() + ".pb.txt";
vector_net.offline_query(x, y, phi, _file_name);
}
return 0;
}
| 0
|
apollo_public_repos/apollo/modules/prediction
|
apollo_public_repos/apollo/modules/prediction/pipeline/vector_net.h
|
/******************************************************************************
* Copyright 2021 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.
*****************************************************************************/
#pragma once
#include <deque>
#include <map>
#include <vector>
#include <string>
#include "modules/prediction/proto/vector_net.pb.h"
#include "modules/common/math/linear_interpolation.h"
#include "modules/common/util/point_factory.h"
#include "modules/map/hdmap/hdmap_util.h"
#include "modules/prediction/common/prediction_system_gflags.h"
namespace apollo {
namespace prediction {
using FeatureVector = std::vector<std::vector<std::vector<double>>>;
using PidVector = std::vector<std::vector<double>>;
enum ATTRIBUTE_TYPE {
ROAD,
LANE_UNKOWN,
LANE_DOTTED_YELLOW,
LANE_DOTTED_WHITE,
LANE_SOLID_YELLOW,
LANE_SOLID_WHITE,
LANE_DOUBLE_YELLOW,
LANE_CURB,
JUNCTION,
CROSSWALK,
};
enum BOUNDARY_TYPE {
UNKNOW,
NORMAL,
LEFT_BOUNDARY,
RIGHT_BOUNDARY,
};
class VectorNet {
public:
VectorNet() { apollo::hdmap::HDMapUtil::ReloadMaps(); }
~VectorNet() = default;
bool query(const common::PointENU& center_point, const double obstacle_phi,
FeatureVector* const feature_ptr, PidVector* const p_id_ptr);
bool offline_query(const double obstacle_x, const double obstacle_y,
const double obstacle_phi);
bool offline_query(const double obstacle_x, const double obstacle_y,
const double obstacle_phi, const std::string file_name);
private:
// TODO(Yiqun): 1.Left/Right boundary 2.Ordinal Encoding
const std::map<ATTRIBUTE_TYPE, double> attribute_map{
{ROAD, 0.0},
{LANE_UNKOWN, 1.0},
{LANE_DOTTED_YELLOW, 2.0},
{LANE_DOTTED_WHITE, 3.0},
{LANE_SOLID_YELLOW, 4.0},
{LANE_SOLID_WHITE, 5.0},
{LANE_DOUBLE_YELLOW, 6.0},
{LANE_CURB, 7.0},
{JUNCTION, 8.0},
{CROSSWALK, 9.0},
};
const std::map<BOUNDARY_TYPE, double> boundary_map{
{UNKNOW, 0.0}, {NORMAL, 1.0}, {LEFT_BOUNDARY, 2.0}, {RIGHT_BOUNDARY, 3.0},
};
const std::map<hdmap::LaneBoundaryType::Type, ATTRIBUTE_TYPE> lane_attr_map{
{hdmap::LaneBoundaryType::UNKNOWN, LANE_UNKOWN},
{hdmap::LaneBoundaryType::DOTTED_YELLOW, LANE_DOTTED_YELLOW},
{hdmap::LaneBoundaryType::DOTTED_WHITE, LANE_DOTTED_WHITE},
{hdmap::LaneBoundaryType::SOLID_YELLOW, LANE_SOLID_YELLOW},
{hdmap::LaneBoundaryType::SOLID_WHITE, LANE_SOLID_WHITE},
{hdmap::LaneBoundaryType::DOUBLE_YELLOW, LANE_DOUBLE_YELLOW},
{hdmap::LaneBoundaryType::CURB, LANE_CURB},
};
template <typename Points>
void GetOnePolyline(const Points& points, double* start_length,
const common::PointENU& center_point,
const double obstacle_phi, ATTRIBUTE_TYPE attr_type,
BOUNDARY_TYPE bound_type, const int count,
std::vector<std::vector<double>>* const one_polyline,
std::vector<double>* const one_p_id);
void GetRoads(const common::PointENU& center_point, const double obstacle_phi,
FeatureVector* const feature_ptr, PidVector* const p_id_ptr);
void GetLaneQueue(
const std::vector<hdmap::LaneInfoConstPtr>& lanes,
std::vector<std::deque<hdmap::LaneInfoConstPtr>>* const lane_deque_ptr);
void GetLanes(const common::PointENU& center_point, const double obstacle_phi,
FeatureVector* const feature_ptr, PidVector* const p_id_ptr);
void GetJunctions(const common::PointENU& center_point,
const double obstacle_phi, FeatureVector* const feature_ptr,
PidVector* const p_id_ptr);
void GetCrosswalks(const common::PointENU& center_point,
const double obstacle_phi,
FeatureVector* const feature_ptr,
PidVector* const p_id_ptr);
int count_ = 0;
};
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/prediction
|
apollo_public_repos/apollo/modules/prediction/pipeline/records_to_offline_data.cc
|
/******************************************************************************
* 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.
*****************************************************************************/
#include "cyber/common/file.h"
#include "absl/strings/str_split.h"
#include "modules/prediction/common/feature_output.h"
#include "modules/prediction/common/message_process.h"
#include "modules/prediction/common/prediction_map.h"
#include "modules/prediction/common/prediction_system_gflags.h"
#include "modules/prediction/proto/prediction_conf.pb.h"
#include "modules/common/util/data_extraction.h"
namespace apollo {
namespace prediction {
void GenerateDataForLearning() {
apollo::hdmap::HDMapUtil::ReloadMaps();
if (!FeatureOutput::Ready()) {
AERROR << "Feature output is not ready.";
return;
}
if (FLAGS_prediction_offline_bags.empty()) {
return;
}
PredictionConf prediction_conf;
if (!cyber::common::GetProtoFromFile(FLAGS_prediction_conf_file,
&prediction_conf)) {
AERROR << "Unable to load adapter conf file: "
<< FLAGS_prediction_adapter_config_filename;
return;
}
ADEBUG << "Adapter config file is loaded into: "
<< prediction_conf.ShortDebugString();
auto container_manager = std::make_shared<ContainerManager>();
EvaluatorManager evaluator_manager;
PredictorManager predictor_manager;
ScenarioManager scenario_manager;
if (!MessageProcess::Init(container_manager.get(), &evaluator_manager,
&predictor_manager, prediction_conf)) {
return;
}
const std::vector<std::string> inputs =
absl::StrSplit(FLAGS_prediction_offline_bags, ':');
for (const auto& input : inputs) {
std::vector<std::string> offline_bags;
GetRecordFileNames(boost::filesystem::path(input), &offline_bags);
std::sort(offline_bags.begin(), offline_bags.end());
AINFO << "For input " << input << ", found " << offline_bags.size()
<< " rosbags to process";
for (std::size_t i = 0; i < offline_bags.size(); ++i) {
AINFO << "\tProcessing: [ " << i << " / " << offline_bags.size()
<< " ]: " << offline_bags[i];
MessageProcess::ProcessOfflineData(prediction_conf, container_manager,
&evaluator_manager, &predictor_manager,
&scenario_manager, offline_bags[i]);
}
}
FeatureOutput::Close();
}
} // namespace prediction
} // namespace apollo
int main(int argc, char* argv[]) {
google::ParseCommandLineFlags(&argc, &argv, true);
apollo::prediction::GenerateDataForLearning();
return 0;
}
| 0
|
apollo_public_repos/apollo/modules/prediction
|
apollo_public_repos/apollo/modules/prediction/pipeline/BUILD
|
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library")
load("//tools:cpplint.bzl", "cpplint")
load("//tools/install:install.bzl", "install")
package(default_visibility = ["//visibility:public"])
install(
name = "install",
runtime_dest = "prediction/bin",
targets = [
":records_to_offline_data",
":vector_net_feature",
":vector_net_offline_data",
],
visibility = ["//visibility:public"],
)
cc_binary(
name = "records_to_offline_data",
srcs = ["records_to_offline_data.cc"],
copts = [
"-DMODULE_NAME=\\\"prediction\\\"",
],
linkopts = [
"-lgomp",
],
deps = [
"//modules/prediction/common:message_process",
"@boost",
"@com_google_absl//:absl",
],
)
cc_library(
name = "vector_net",
srcs = ["vector_net.cc"],
hdrs = ["vector_net.h"],
copts = [
"-DMODULE_NAME=\\\"prediction\\\"",
],
deps = [
"//cyber",
"//modules/common/math",
"//modules/common/util",
"//modules/map/hdmap:hdmap_util",
"//modules/prediction/common:prediction_system_gflags",
"//modules/prediction/proto:vector_net_cc_proto",
],
)
cc_binary(
name = "vector_net_feature",
srcs = ["vector_net_feature.cc"],
copts = [
"-DMODULE_NAME=\\\"prediction\\\"",
],
deps = [
":vector_net",
],
)
cc_binary(
name = "vector_net_offline_data",
srcs = ["vector_net_offline_data.cc"],
copts = [
"-DMODULE_NAME=\\\"prediction\\\"",
],
deps = [
":vector_net",
],
)
cpplint()
| 0
|
apollo_public_repos/apollo/modules/prediction
|
apollo_public_repos/apollo/modules/prediction/pipeline/vector_net.cc
|
/******************************************************************************
* Copyright 2021 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.
*****************************************************************************/
#include "modules/prediction/pipeline/vector_net.h"
#include <cmath>
#include <limits>
#include <unordered_set>
#include <utility>
#include "cyber/common/file.h"
namespace apollo {
namespace prediction {
template <typename Points>
void VectorNet::GetOnePolyline(
const Points& points, double* start_length,
const common::PointENU& center_point, const double obstacle_phi,
ATTRIBUTE_TYPE attr_type, BOUNDARY_TYPE bound_type, const int count,
std::vector<std::vector<double>>* const one_polyline,
std::vector<double>* const one_p_id) {
size_t size = points.size();
std::vector<double> s(size, 0);
for (size_t i = 1; i < size; ++i) {
s[i] = std::hypot(points.at(i).x() - points.at(i - 1).x(),
points.at(i).y() - points.at(i - 1).y()) +
s[i - 1];
}
std::vector<double> x;
std::vector<double> y;
double cur_length = *start_length;
auto it_lower = std::lower_bound(s.begin(), s.end(), cur_length);
while (it_lower != s.end()) {
if (it_lower == s.begin()) {
x.push_back(points.at(0).x());
y.push_back(points.at(0).y());
} else {
const auto distance = std::distance(s.begin(), it_lower);
x.push_back(common::math::lerp(points.at(distance - 1).x(),
s[distance - 1], points.at(distance).x(),
s[distance], cur_length));
y.push_back(common::math::lerp(points.at(distance - 1).y(),
s[distance - 1], points.at(distance).y(),
s[distance], cur_length));
}
cur_length += FLAGS_point_distance;
it_lower = std::lower_bound(s.begin(), s.end(), cur_length);
}
size_t point_size = x.size();
*start_length = cur_length - s[size - 1];
if (point_size == 0) return;
const double attr = attribute_map.at(attr_type);
const double bound = boundary_map.at(bound_type);
auto last_point_after_rotate = common::math::RotateVector2d(
{x[0] - center_point.x(), y[0] - center_point.y()},
M_PI_2 - obstacle_phi);
for (size_t i = 1; i < point_size; ++i) {
if (one_p_id->at(0) > last_point_after_rotate.x()) {
one_p_id->at(0) = last_point_after_rotate.x();
}
if (one_p_id->at(1) > last_point_after_rotate.y()) {
one_p_id->at(1) = last_point_after_rotate.y();
}
std::vector<double> one_vector;
// d_s, d_e
one_vector.push_back(last_point_after_rotate.x());
one_vector.push_back(last_point_after_rotate.y());
Eigen::Vector2d point_after_rotate = common::math::RotateVector2d(
{x[i] - center_point.x(), y[i] - center_point.y()},
M_PI_2 - obstacle_phi);
one_vector.push_back(point_after_rotate.x());
one_vector.push_back(point_after_rotate.y());
last_point_after_rotate = std::move(point_after_rotate);
// attribute
one_vector.insert(one_vector.end(), {0.0, 0.0, attr, bound});
one_vector.push_back(count);
one_polyline->push_back(std::move(one_vector));
}
}
bool VectorNet::query(const common::PointENU& center_point,
const double obstacle_phi,
FeatureVector* const feature_ptr,
PidVector* const p_id_ptr) {
CHECK_NOTNULL(feature_ptr);
count_ = 0;
GetRoads(center_point, obstacle_phi, feature_ptr, p_id_ptr);
GetLanes(center_point, obstacle_phi, feature_ptr, p_id_ptr);
GetJunctions(center_point, obstacle_phi, feature_ptr, p_id_ptr);
GetCrosswalks(center_point, obstacle_phi, feature_ptr, p_id_ptr);
return true;
}
bool VectorNet::offline_query(const double obstacle_x, const double obstacle_y,
const double obstacle_phi) {
return offline_query(obstacle_x,
obstacle_y,
obstacle_phi,
FLAGS_prediction_target_file);
}
bool VectorNet::offline_query(const double obstacle_x,
const double obstacle_y,
const double obstacle_phi,
const std::string file_name) {
FeatureVector offline_feature;
PidVector p_id;
common::PointENU center_point =
common::util::PointFactory::ToPointENU(obstacle_x, obstacle_y);
query(center_point, obstacle_phi, &offline_feature, &p_id);
apollo::prediction::VectorNetFeature vector_net_pb_;
vector_net_pb_.mutable_car_position()->set_x(obstacle_x);
vector_net_pb_.mutable_car_position()->set_y(obstacle_y);
vector_net_pb_.mutable_car_position()->set_phi(obstacle_phi);
size_t i = 0;
for (const auto& polyline : offline_feature) {
auto* polyline_pb = vector_net_pb_.add_polyline();
polyline_pb->set_p_id_x(p_id[i][0]);
polyline_pb->set_p_id_y(p_id[i][1]);
i++;
for (const auto& vector : polyline) {
auto* vector_pb = polyline_pb->add_vector();
for (const auto& element : vector) {
vector_pb->add_element(element);
}
}
}
cyber::common::SetProtoToASCIIFile(vector_net_pb_,
file_name);
return true;
}
void VectorNet::GetRoads(const common::PointENU& center_point,
const double obstacle_phi,
FeatureVector* const feature_ptr,
PidVector* const p_id_ptr) {
std::vector<apollo::hdmap::RoadInfoConstPtr> roads;
apollo::hdmap::HDMapUtil::BaseMap().GetRoads(center_point,
FLAGS_road_distance, &roads);
for (const auto& road : roads) {
for (const auto& section : road->road().section()) {
for (const auto& edge : section.boundary().outer_polygon().edge()) {
std::vector<std::vector<double>> one_polyline;
std::vector<double> one_p_id{std::numeric_limits<float>::max(),
std::numeric_limits<float>::max()};
double start_length = 0;
BOUNDARY_TYPE bound_type = UNKNOW;
if (edge.type() == hdmap::BoundaryEdge::LEFT_BOUNDARY) {
bound_type = LEFT_BOUNDARY;
} else if (edge.type() == hdmap::BoundaryEdge::RIGHT_BOUNDARY) {
bound_type = RIGHT_BOUNDARY;
} else if (edge.type() == hdmap::BoundaryEdge::NORMAL) {
bound_type = NORMAL;
} else {
bound_type = UNKNOW;
}
for (const auto& segment : edge.curve().segment()) {
GetOnePolyline(segment.line_segment().point(), &start_length,
center_point, obstacle_phi, ROAD, bound_type, count_,
&one_polyline, &one_p_id);
}
if (one_polyline.size() == 0) continue;
feature_ptr->push_back(std::move(one_polyline));
p_id_ptr->push_back(std::move(one_p_id));
++count_;
}
}
}
}
void VectorNet::GetLaneQueue(
const std::vector<hdmap::LaneInfoConstPtr>& lanes,
std::vector<std::deque<hdmap::LaneInfoConstPtr>>* const lane_deque_ptr) {
std::unordered_set<hdmap::LaneInfoConstPtr> lane_set(lanes.begin(),
lanes.end());
while (!lane_set.empty()) {
std::deque<apollo::hdmap::LaneInfoConstPtr> one_lane_deque;
auto cur_lane = *lane_set.begin();
lane_set.erase(lane_set.begin());
one_lane_deque.push_back(cur_lane);
while (cur_lane->lane().successor_id_size() > 0) {
auto id = cur_lane->lane().successor_id(0);
cur_lane = apollo::hdmap::HDMapUtil::BaseMap().GetLaneById(id);
if (lane_set.find(cur_lane) != lane_set.end()) {
lane_set.erase(cur_lane);
one_lane_deque.push_back(cur_lane);
} else {
break;
}
}
cur_lane = one_lane_deque.front();
while (cur_lane->lane().predecessor_id_size() > 0) {
auto id = cur_lane->lane().predecessor_id(0);
cur_lane = apollo::hdmap::HDMapUtil::BaseMap().GetLaneById(id);
if (lane_set.find(cur_lane) != lane_set.end()) {
lane_set.erase(cur_lane);
one_lane_deque.push_front(cur_lane);
} else {
break;
}
}
lane_deque_ptr->push_back(one_lane_deque);
}
}
void VectorNet::GetLanes(const common::PointENU& center_point,
const double obstacle_phi,
FeatureVector* const feature_ptr,
PidVector* const p_id_ptr) {
std::vector<apollo::hdmap::LaneInfoConstPtr> lanes;
apollo::hdmap::HDMapUtil::BaseMap().GetLanes(center_point,
FLAGS_road_distance, &lanes);
std::vector<std::deque<apollo::hdmap::LaneInfoConstPtr>> lane_deque_vector;
GetLaneQueue(lanes, &lane_deque_vector);
for (const auto& lane_deque : lane_deque_vector) {
// Draw lane's left_boundary
std::vector<std::vector<double>> left_polyline;
std::vector<double> left_p_id{std::numeric_limits<float>::max(),
std::numeric_limits<float>::max()};
double start_length = 0;
for (const auto& lane : lane_deque) {
std::cout << lane->lane().id().id() << " ";
// if (lane->lane().left_boundary().virtual_()) continue;
for (const auto& segment :
lane->lane().left_boundary().curve().segment()) {
auto bound_type =
lane->lane().left_boundary().boundary_type(0).types(0);
GetOnePolyline(segment.line_segment().point(), &start_length,
center_point, obstacle_phi, lane_attr_map.at(bound_type),
LEFT_BOUNDARY, count_, &left_polyline, &left_p_id);
}
}
if (left_polyline.size() < 2) continue;
feature_ptr->push_back(std::move(left_polyline));
p_id_ptr->push_back(std::move(left_p_id));
++count_;
std::vector<std::vector<double>> right_polyline;
std::vector<double> right_p_id{std::numeric_limits<float>::max(),
std::numeric_limits<float>::max()};
start_length = 0;
// Draw lane's right_boundary
for (const auto& lane : lane_deque) {
// if (lane->lane().right_boundary().virtual_()) continue;
for (const auto& segment :
lane->lane().right_boundary().curve().segment()) {
auto bound_type =
lane->lane().left_boundary().boundary_type(0).types(0);
GetOnePolyline(segment.line_segment().point(), &start_length,
center_point, obstacle_phi, lane_attr_map.at(bound_type),
RIGHT_BOUNDARY, count_, &right_polyline, &right_p_id);
}
}
if (right_polyline.size() < 2) continue;
feature_ptr->push_back(std::move(right_polyline));
p_id_ptr->push_back(std::move(right_p_id));
++count_;
}
}
void VectorNet::GetJunctions(const common::PointENU& center_point,
const double obstacle_phi,
FeatureVector* const feature_ptr,
PidVector* const p_id_ptr) {
std::vector<apollo::hdmap::JunctionInfoConstPtr> junctions;
apollo::hdmap::HDMapUtil::BaseMap().GetJunctions(
center_point, FLAGS_road_distance, &junctions);
for (const auto& junction : junctions) {
std::vector<std::vector<double>> one_polyline;
std::vector<double> one_p_id{std::numeric_limits<float>::max(),
std::numeric_limits<float>::max()};
double start_length = 0;
GetOnePolyline(junction->junction().polygon().point(), &start_length,
center_point, obstacle_phi, JUNCTION, UNKNOW, count_,
&one_polyline, &one_p_id);
feature_ptr->push_back(std::move(one_polyline));
p_id_ptr->push_back(std::move(one_p_id));
++count_;
}
}
void VectorNet::GetCrosswalks(const common::PointENU& center_point,
const double obstacle_phi,
FeatureVector* const feature_ptr,
PidVector* const p_id_ptr) {
std::vector<apollo::hdmap::CrosswalkInfoConstPtr> crosswalks;
apollo::hdmap::HDMapUtil::BaseMap().GetCrosswalks(
center_point, FLAGS_road_distance, &crosswalks);
for (const auto& crosswalk : crosswalks) {
std::vector<std::vector<double>> one_polyline;
std::vector<double> one_p_id{std::numeric_limits<float>::max(),
std::numeric_limits<float>::max()};
double start_length = 0;
GetOnePolyline(crosswalk->crosswalk().polygon().point(), &start_length,
center_point, obstacle_phi, CROSSWALK, UNKNOW, count_,
&one_polyline, &one_p_id);
feature_ptr->push_back(std::move(one_polyline));
p_id_ptr->push_back(std::move(one_p_id));
++count_;
}
}
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/prediction
|
apollo_public_repos/apollo/modules/prediction/proto/offline_features.proto
|
syntax = "proto2";
package apollo.prediction;
import "modules/common_msgs/basic_msgs/pnc_point.proto";
import "modules/common_msgs/prediction_msgs/feature.proto";
import "modules/prediction/proto/prediction_conf.proto";
import "modules/common_msgs/prediction_msgs/scenario.proto";
message DataForLearning {
// The task category of the data for learning
optional string category = 5;
// The info. needed for identifying a unique data point:
optional int32 id = 1;
optional double timestamp = 2;
// The features for learning algorithms:
repeated double features_for_learning = 3;
repeated string string_features_for_learning = 7;
// The ground-truth labels:
repeated double labels = 4;
// The lane sequence id if associated with a lane
optional int32 lane_sequence_id = 6;
}
message ListDataForLearning {
repeated DataForLearning data_for_learning = 1;
}
message PredictionResult {
optional int32 id = 1;
optional double timestamp = 2;
repeated Trajectory trajectory = 3;
optional ObstacleConf obstacle_conf = 4;
optional Scenario scenario = 5;
}
message ListPredictionResult {
repeated PredictionResult prediction_result = 1;
}
message ListFrameEnv {
repeated FrameEnv frame_env = 1;
}
message DataForTuning {
// The task category of the cost values
optional string category = 1;
// The info. needed for identifying a unique data point:
optional int32 id = 2;
optional double timestamp = 3;
// The cost values whose coefficients to be tuned
repeated double values_for_tuning = 4;
// The cost values of the real future trajectory
repeated double real_cost_value = 5;
// The lane sequence id if associated with a lane
optional int32 lane_sequence_id = 6;
// The associated adc trajectory
repeated apollo.common.TrajectoryPoint adc_trajectory_point = 7;
}
message ListDataForTuning {
repeated DataForTuning data_for_tuning = 1;
}
message Features {
repeated Feature feature = 1;
}
| 0
|
apollo_public_repos/apollo/modules/prediction
|
apollo_public_repos/apollo/modules/prediction/proto/fnn_vehicle_model.proto
|
syntax = "proto2";
package apollo.prediction;
import "modules/prediction/proto/fnn_model_base.proto";
message FnnVehicleModel {
optional int32 dim_input = 1;
optional Vector samples_mean = 2;
optional Vector samples_std = 3;
optional int32 num_layer = 4;
repeated Layer layer =
5; // num_layer must equal to first layer layer_input_dim
optional int32 dim_output =
6; // dim_ouput must equal to last layer layer_output_dim
}
| 0
|
apollo_public_repos/apollo/modules/prediction
|
apollo_public_repos/apollo/modules/prediction/proto/network_model.proto
|
syntax = "proto2";
package apollo.prediction;
import "modules/prediction/proto/network_layers.proto";
message VerificationSample {
// data used to vertify the network model
repeated TensorParameter features = 1; // input to the network
optional float probability = 2; // output probability of the network
optional float distance = 3; // output acceleration of the network
}
message Performance {
repeated float accuracy = 1;
repeated float recall = 2;
repeated float precision = 3;
}
message NetParameter {
optional int32 id = 1;
optional string name = 2;
repeated LayerParameter layers = 3;
repeated VerificationSample verification_samples = 4;
optional Performance performance =
5; // performance of the model in test dataset
optional float time_dumped = 6; // time [s] of dumped the model
}
| 0
|
apollo_public_repos/apollo/modules/prediction
|
apollo_public_repos/apollo/modules/prediction/proto/vector_net.proto
|
syntax = "proto2";
package apollo.prediction;
message VNVector {
repeated double element = 1;
}
message Polyline {
repeated VNVector vector = 1;
optional double p_id_x = 2;
optional double p_id_y = 3;
}
message CarPosition {
optional double x = 1;
optional double y = 2;
optional double phi = 3;
optional string id = 4;
}
message VectorNetFeature {
optional CarPosition car_position = 1;
repeated Polyline polyline = 2;
}
message WorldCoord {
repeated CarPosition pose = 1;
}
| 0
|
apollo_public_repos/apollo/modules/prediction
|
apollo_public_repos/apollo/modules/prediction/proto/fnn_model_base.proto
|
syntax = "proto2";
package apollo.prediction;
message Vector {
repeated double columns = 1;
}
message Matrix {
repeated Vector rows = 1;
}
message Layer {
enum ActivationFunc {
RELU = 0;
TANH = 1;
SIGMOID = 2;
SOFTMAX = 3;
}
optional int32 layer_input_dim = 1;
optional int32 layer_output_dim = 2;
optional Matrix layer_input_weight =
3; // weight matrix of |input_dim| x |output_dim|
optional Vector layer_bias = 4; // vector of bias, size of |output_dim|
optional ActivationFunc layer_activation_func = 5;
// optional string layer_activation_type = 6 [deprecated = true];
}
| 0
|
apollo_public_repos/apollo/modules/prediction
|
apollo_public_repos/apollo/modules/prediction/proto/prediction_conf.proto
|
syntax = "proto2";
package apollo.prediction;
import "modules/common_msgs/perception_msgs/perception_obstacle.proto";
import "modules/common_msgs/prediction_msgs/feature.proto";
message ObstacleConf {
enum ObstacleStatus {
ON_LANE = 0;
OFF_LANE = 1;
STATIONARY = 3;
MOVING = 4;
IN_JUNCTION = 5;
}
enum EvaluatorType {
MLP_EVALUATOR = 0;
RNN_EVALUATOR = 1 [deprecated = true];
COST_EVALUATOR = 2; // navi mode can only support this evaluator
CRUISE_MLP_EVALUATOR = 3;
JUNCTION_MLP_EVALUATOR = 4;
CYCLIST_KEEP_LANE_EVALUATOR = 5;
LANE_SCANNING_EVALUATOR = 6;
PEDESTRIAN_INTERACTION_EVALUATOR = 7;
JUNCTION_MAP_EVALUATOR = 8;
LANE_AGGREGATING_EVALUATOR = 9;
SEMANTIC_LSTM_EVALUATOR = 10;
JOINTLY_PREDICTION_PLANNING_EVALUATOR = 11;
VECTORNET_EVALUATOR = 12;
}
enum PredictorType {
LANE_SEQUENCE_PREDICTOR = 0;
FREE_MOVE_PREDICTOR = 1;
REGIONAL_PREDICTOR = 2 [deprecated = true];
MOVE_SEQUENCE_PREDICTOR = 3;
EMPTY_PREDICTOR = 4;
SINGLE_LANE_PREDICTOR = 5;
JUNCTION_PREDICTOR = 6;
EXTRAPOLATION_PREDICTOR = 7;
INTERACTION_PREDICTOR = 8;
}
optional apollo.perception.PerceptionObstacle.Type obstacle_type = 1;
optional ObstacleStatus obstacle_status = 2 [default = STATIONARY];
optional ObstaclePriority.Priority priority_type = 5;
optional ObstacleInteractiveTag.InteractiveTag interactive_tag = 6;
optional EvaluatorType evaluator_type = 3;
optional PredictorType predictor_type = 4;
}
message TopicConf {
optional string adccontainer_topic_name = 1;
optional string container_topic_name = 2;
optional string evaluator_topic_name = 3;
optional string localization_topic = 4;
optional string perception_obstacle_topic = 5;
optional string perception_obstacles_topic_name = 6;
optional string planning_trajectory_topic = 7;
optional string prediction_topic = 8;
optional string storytelling_topic = 9;
}
message PredictionConf {
optional TopicConf topic_conf = 1;
repeated ObstacleConf obstacle_conf = 2;
}
| 0
|
apollo_public_repos/apollo/modules/prediction
|
apollo_public_repos/apollo/modules/prediction/proto/network_layers.proto
|
syntax = "proto2";
package apollo.prediction;
message TensorParameter {
repeated float data = 1 [packed = true];
repeated int32 shape = 2;
}
message InputParameter {
repeated int32 input_shape = 1;
optional string dtype = 2; // data type of the input
optional bool sparse = 3;
}
message DenseParameter {
optional int32 units = 1;
optional string activation = 2;
optional bool use_bias = 3;
optional TensorParameter weights = 4;
optional TensorParameter bias = 5;
}
message Conv1dParameter {
repeated int32 shape = 1;
optional bool use_bias = 2;
optional TensorParameter kernel = 3;
optional TensorParameter bias = 4;
optional int32 stride = 5;
}
message MaxPool1dParameter {
optional int32 kernel_size = 1;
optional int32 stride = 2;
}
message AvgPool1dParameter {
optional int32 kernel_size = 1;
optional int32 stride = 2;
}
message BatchNormalizationParameter {
optional double epsilon = 1 [default = 1e-5];
optional int32 axis = 2;
optional bool center = 3;
optional bool scale = 4;
optional float momentum = 5;
optional TensorParameter mu = 6;
optional TensorParameter sigma = 7;
optional TensorParameter gamma = 8;
optional TensorParameter beta = 9;
}
message LSTMParameter {
optional int32 units = 1;
optional bool return_sequences = 2;
optional bool stateful = 3;
optional string activation = 4;
optional string recurrent_activation = 5;
optional bool use_bias = 6;
optional bool unit_forget_bias = 7 [default = true];
optional bool go_backwards = 8 [default = false];
optional bool unroll = 9 [default = false];
optional int32 implementation = 10 [default = 0];
optional TensorParameter weights_input = 15;
optional TensorParameter weights_forget = 16;
optional TensorParameter weights_cell = 17;
optional TensorParameter weights_output = 18;
optional TensorParameter bias_input = 19;
optional TensorParameter bias_forget = 20;
optional TensorParameter bias_cell = 21;
optional TensorParameter bias_output = 22;
optional TensorParameter recurrent_weights_input = 25;
optional TensorParameter recurrent_weights_forget = 26;
optional TensorParameter recurrent_weights_cell = 27;
optional TensorParameter recurrent_weights_output = 28;
}
message ActivationParameter {
optional string activation = 1;
}
message FlattenParameter {}
message ConcatenateParameter {
optional int32 axis = 1;
}
message LayerParameter {
optional string type = 1;
optional string name = 2;
optional int32 order_number = 3;
oneof oneof_layers {
InputParameter input = 4;
ActivationParameter activation = 5;
DenseParameter dense = 6;
BatchNormalizationParameter batch_normalization = 7;
LSTMParameter lstm = 8;
FlattenParameter flatten = 9;
ConcatenateParameter concatenate = 10;
Conv1dParameter conv1d = 11;
MaxPool1dParameter maxpool1d = 12;
AvgPool1dParameter avgpool1d = 13;
}
}
| 0
|
apollo_public_repos/apollo/modules/prediction
|
apollo_public_repos/apollo/modules/prediction/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")
load("//tools/install:install.bzl", "install", "install_files")
package(default_visibility = ["//visibility:public"])
install_files(
name = "py_pb_prediction",
dest = "prediction/python/modules/prediction/proto",
files = [
":offline_features_py_pb2",
":fnn_vehicle_model_py_pb2",
":network_model_py_pb2",
":vector_net_py_pb2",
":fnn_model_base_py_pb2",
":prediction_conf_py_pb2",
":network_layers_py_pb2",
]
)
cc_proto_library(
name = "offline_features_cc_proto",
deps = [
":offline_features_proto",
],
)
proto_library(
name = "offline_features_proto",
srcs = ["offline_features.proto"],
deps = [
"//modules/common_msgs/basic_msgs:pnc_point_proto",
"//modules/common_msgs/prediction_msgs:feature_proto",
":prediction_conf_proto",
"//modules/common_msgs/prediction_msgs:scenario_proto",
],
)
py_proto_library(
name = "offline_features_py_pb2",
deps = [
":offline_features_proto",
"//modules/common_msgs/basic_msgs:pnc_point_py_pb2",
"//modules/common_msgs/prediction_msgs:feature_py_pb2",
":prediction_conf_py_pb2",
"//modules/common_msgs/prediction_msgs:scenario_py_pb2",
],
)
cc_proto_library(
name = "fnn_vehicle_model_cc_proto",
deps = [
":fnn_vehicle_model_proto",
],
)
proto_library(
name = "fnn_vehicle_model_proto",
srcs = ["fnn_vehicle_model.proto"],
deps = [
":fnn_model_base_proto",
],
)
py_proto_library(
name = "fnn_vehicle_model_py_pb2",
deps = [
":fnn_vehicle_model_proto",
":fnn_model_base_py_pb2",
],
)
cc_proto_library(
name = "network_model_cc_proto",
deps = [
":network_model_proto",
],
)
proto_library(
name = "network_model_proto",
srcs = ["network_model.proto"],
deps = [
":network_layers_proto",
],
)
py_proto_library(
name = "network_model_py_pb2",
deps = [
":network_model_proto",
":network_layers_py_pb2",
],
)
cc_proto_library(
name = "vector_net_cc_proto",
deps = [
":vector_net_proto",
],
)
proto_library(
name = "vector_net_proto",
srcs = ["vector_net.proto"],
)
py_proto_library(
name = "vector_net_py_pb2",
deps = [
":vector_net_proto",
],
)
cc_proto_library(
name = "fnn_model_base_cc_proto",
deps = [
":fnn_model_base_proto",
],
)
proto_library(
name = "fnn_model_base_proto",
srcs = ["fnn_model_base.proto"],
)
py_proto_library(
name = "fnn_model_base_py_pb2",
deps = [
":fnn_model_base_proto",
],
)
cc_proto_library(
name = "prediction_conf_cc_proto",
deps = [
":prediction_conf_proto",
],
)
proto_library(
name = "prediction_conf_proto",
srcs = ["prediction_conf.proto"],
deps = [
"//modules/common_msgs/perception_msgs:perception_obstacle_proto",
"//modules/common_msgs/prediction_msgs:feature_proto",
],
)
py_proto_library(
name = "prediction_conf_py_pb2",
deps = [
":prediction_conf_proto",
"//modules/common_msgs/perception_msgs:perception_obstacle_py_pb2",
"//modules/common_msgs/prediction_msgs:feature_py_pb2",
],
)
cc_proto_library(
name = "network_layers_cc_proto",
deps = [
":network_layers_proto",
],
)
proto_library(
name = "network_layers_proto",
srcs = ["network_layers.proto"],
)
py_proto_library(
name = "network_layers_py_pb2",
deps = [
":network_layers_proto",
],
)
| 0
|
apollo_public_repos/apollo/modules/prediction
|
apollo_public_repos/apollo/modules/prediction/launch/prediction.launch
|
<cyber>
<module>
<name>prediction</name>
<dag_conf>/apollo/modules/prediction/dag/prediction.dag</dag_conf>
<process_name>prediction</process_name>
</module>
</cyber>
| 0
|
apollo_public_repos/apollo/modules/prediction
|
apollo_public_repos/apollo/modules/prediction/dag/prediction.dag
|
module_config {
module_library : "/apollo/bazel-bin/modules/prediction/libprediction_component.so"
components {
class_name : "PredictionComponent"
config {
name: "prediction"
config_file_path: "/apollo/modules/prediction/conf/prediction_conf.pb.txt"
flag_file_path: "/apollo/modules/prediction/conf/prediction.conf"
readers: [
{
channel: "/apollo/perception/obstacles"
qos_profile: {
depth : 1
}
}
]
}
}
}
| 0
|
apollo_public_repos/apollo/modules/prediction
|
apollo_public_repos/apollo/modules/prediction/dag/prediction_lego.dag
|
module_config {
module_library : "/apollo/bazel-bin/modules/prediction/submodules/prediction_lego.so"
components {
class_name : "PredictionComponent"
config {
name: "prediction"
config_file_path: "/apollo/modules/prediction/conf/prediction_conf.pb.txt"
flag_file_path: "/apollo/modules/prediction/conf/prediction.conf"
readers: [
{
channel: "/apollo/perception/obstacles"
qos_profile: {
depth : 1
}
}
]
}
}
components {
class_name : "EvaluatorSubmodule"
config {
name: "evaluator_submodule"
config_file_path: "/apollo/modules/prediction/conf/prediction_conf.pb.txt"
flag_file_path: "/apollo/modules/prediction/conf/prediction.conf"
readers: [
{
channel:"/apollo/prediction/container"
qos_profile: {
depth : 1
}
}
]
}
}
components {
class_name : "PredictorSubmodule"
config {
name: "predictor submodule"
config_file_path: "/apollo/modules/prediction/conf/prediction_conf.pb.txt"
flag_file_path: "/apollo/modules/prediction/conf/prediction.conf"
readers: [
{
channel: "/apollo/prediction/perception_obstacles"
qos_profile: {
depth : 1
}
},
{
channel:"/apollo/prediction/adccontainer"
qos_profile: {
depth : 1
}
},
{
channel:"/apollo/prediction/evaluator"
qos_profile: {
depth : 1
}
}
]
}
}
}
| 0
|
apollo_public_repos/apollo/modules/prediction
|
apollo_public_repos/apollo/modules/prediction/dag/prediction_navi.dag
|
module_config {
module_library : "/apollo/bazel-bin/modules/prediction/libprediction_component.so"
components {
class_name : "PredictionComponent"
config {
name: "prediction"
config_file_path: "/apollo/modules/prediction/conf/prediction_navi_conf.pb.txt"
flag_file_path: "/apollo/modules/prediction/conf/prediction_navi.conf"
readers: [
{
channel: "/apollo/perception/obstacles"
qos_profile: {
depth : 1
}
}
]
}
}
}
| 0
|
apollo_public_repos/apollo/modules/prediction
|
apollo_public_repos/apollo/modules/prediction/network/net_layer_test.cc
|
/******************************************************************************
* 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.
*****************************************************************************/
#include "modules/prediction/network/net_layer.h"
#include "gtest/gtest.h"
namespace apollo {
namespace prediction {
namespace network {
TEST(LayerTest, dense_test) {
LayerParameter layer_pb;
Dense dense;
EXPECT_FALSE(dense.Load(layer_pb));
EXPECT_EQ(dense.Name(), "layer");
EXPECT_EQ(dense.OrderNumber(), -1);
layer_pb.set_name("layer1");
layer_pb.set_order_number(1);
EXPECT_FALSE(dense.Load(layer_pb));
EXPECT_EQ(dense.Name(), "layer1");
EXPECT_EQ(dense.OrderNumber(), 1);
layer_pb.mutable_dense()->set_units(1);
layer_pb.mutable_dense()->mutable_weights()->add_shape(1);
layer_pb.mutable_dense()->mutable_weights()->add_shape(1);
layer_pb.mutable_dense()->mutable_weights()->add_data(1);
layer_pb.mutable_dense()->mutable_bias()->add_shape(1);
layer_pb.mutable_dense()->mutable_bias()->add_data(1);
EXPECT_TRUE(dense.Load(layer_pb));
layer_pb.mutable_dense()->set_activation("relu");
EXPECT_TRUE(dense.Load(layer_pb));
Eigen::MatrixXf output;
Eigen::MatrixXf input(1, 1);
input(0, 0) = 1.0;
dense.Run({input}, &output);
EXPECT_EQ(output(0, 0), 2.0);
}
TEST(LayerTest, activation_test) {
LayerParameter layer_pb;
Activation act;
layer_pb.set_name("layer1");
layer_pb.set_order_number(1);
EXPECT_TRUE(act.Load(layer_pb));
Eigen::MatrixXf output;
Eigen::MatrixXf input(1, 1);
input(0, 0) = -1.0;
act.Run({input}, &output);
EXPECT_EQ(output(0, 0), -1.0);
layer_pb.mutable_activation()->set_activation("relu");
EXPECT_TRUE(act.Load(layer_pb));
act.Run({input}, &output);
EXPECT_EQ(output(0, 0), 0.0);
}
TEST(LayerTest, bn_test) {
LayerParameter layer_pb;
BatchNormalization bn;
layer_pb.mutable_batch_normalization()->set_epsilon(1e-8);
layer_pb.mutable_batch_normalization()->set_axis(0);
layer_pb.mutable_batch_normalization()->set_center(false);
layer_pb.mutable_batch_normalization()->set_scale(false);
layer_pb.mutable_batch_normalization()->set_momentum(2.0);
layer_pb.mutable_batch_normalization()->mutable_mu()->add_shape(2);
layer_pb.mutable_batch_normalization()->mutable_mu()->add_data(0.0);
layer_pb.mutable_batch_normalization()->mutable_mu()->add_data(1.0);
layer_pb.mutable_batch_normalization()->mutable_sigma()->add_shape(2);
layer_pb.mutable_batch_normalization()->mutable_sigma()->add_data(1.0);
layer_pb.mutable_batch_normalization()->mutable_sigma()->add_data(4.0);
EXPECT_TRUE(bn.Load(layer_pb));
Eigen::MatrixXf output;
Eigen::MatrixXf input(2, 2);
input(0, 0) = 1.0;
input(1, 0) = 2.0;
input(0, 1) = 3.0;
input(1, 1) = 4.0;
bn.Run({input}, &output);
EXPECT_FLOAT_EQ(output(0, 0), 1.0);
EXPECT_FLOAT_EQ(output(0, 1), 1.0);
EXPECT_FLOAT_EQ(output(1, 0), 2.0);
EXPECT_FLOAT_EQ(output(1, 1), 1.5);
}
TEST(LayerTest, lstm_test) {
LayerParameter layer_pb;
LSTM lstm;
layer_pb.mutable_lstm()->set_units(1);
layer_pb.mutable_lstm()->set_return_sequences(true);
layer_pb.mutable_lstm()->set_stateful(true);
layer_pb.mutable_lstm()->set_activation("sigmoid");
layer_pb.mutable_lstm()->set_recurrent_activation("hard_sigmoid");
layer_pb.mutable_lstm()->set_use_bias(true);
layer_pb.mutable_lstm()->set_unit_forget_bias(false);
layer_pb.mutable_lstm()->mutable_weights_input()->add_shape(1);
layer_pb.mutable_lstm()->mutable_weights_input()->add_shape(1);
layer_pb.mutable_lstm()->mutable_weights_input()->add_data(1);
layer_pb.mutable_lstm()->mutable_weights_forget()->add_shape(1);
layer_pb.mutable_lstm()->mutable_weights_forget()->add_shape(1);
layer_pb.mutable_lstm()->mutable_weights_forget()->add_data(1);
layer_pb.mutable_lstm()->mutable_weights_cell()->add_shape(1);
layer_pb.mutable_lstm()->mutable_weights_cell()->add_shape(1);
layer_pb.mutable_lstm()->mutable_weights_cell()->add_data(1);
layer_pb.mutable_lstm()->mutable_weights_output()->add_shape(1);
layer_pb.mutable_lstm()->mutable_weights_output()->add_shape(1);
layer_pb.mutable_lstm()->mutable_weights_output()->add_data(1);
layer_pb.mutable_lstm()->mutable_bias_input()->add_shape(1);
layer_pb.mutable_lstm()->mutable_bias_input()->add_data(1);
layer_pb.mutable_lstm()->mutable_bias_forget()->add_shape(1);
layer_pb.mutable_lstm()->mutable_bias_forget()->add_data(1);
layer_pb.mutable_lstm()->mutable_bias_cell()->add_shape(1);
layer_pb.mutable_lstm()->mutable_bias_cell()->add_data(1);
layer_pb.mutable_lstm()->mutable_bias_output()->add_shape(1);
layer_pb.mutable_lstm()->mutable_bias_output()->add_data(1);
layer_pb.mutable_lstm()->mutable_recurrent_weights_input()->add_shape(1);
layer_pb.mutable_lstm()->mutable_recurrent_weights_input()->add_shape(1);
layer_pb.mutable_lstm()->mutable_recurrent_weights_input()->add_data(1);
layer_pb.mutable_lstm()->mutable_recurrent_weights_forget()->add_shape(1);
layer_pb.mutable_lstm()->mutable_recurrent_weights_forget()->add_shape(1);
layer_pb.mutable_lstm()->mutable_recurrent_weights_forget()->add_data(1);
layer_pb.mutable_lstm()->mutable_recurrent_weights_cell()->add_shape(1);
layer_pb.mutable_lstm()->mutable_recurrent_weights_cell()->add_shape(1);
layer_pb.mutable_lstm()->mutable_recurrent_weights_cell()->add_data(1);
EXPECT_FALSE(lstm.Load(layer_pb));
layer_pb.mutable_lstm()->mutable_recurrent_weights_output()->add_shape(1);
layer_pb.mutable_lstm()->mutable_recurrent_weights_output()->add_shape(1);
layer_pb.mutable_lstm()->mutable_recurrent_weights_output()->add_data(1);
EXPECT_TRUE(lstm.Load(layer_pb));
std::vector<Eigen::MatrixXf> state;
lstm.ResetState();
lstm.State(&state);
EXPECT_EQ(state.size(), 2);
EXPECT_EQ(state[0](0, 0), 0);
EXPECT_EQ(state[1](0, 0), 0);
state[0](0, 0) = 1;
state[1](0, 0) = 2;
lstm.SetState(state);
lstm.State(&state);
EXPECT_EQ(state.size(), 2);
EXPECT_EQ(state[0](0, 0), 1);
EXPECT_EQ(state[1](0, 0), 2);
}
TEST(LayerTest, flatten_test) {
LayerParameter layer_pb;
Flatten flat;
layer_pb.set_name("layer1");
layer_pb.set_order_number(1);
EXPECT_TRUE(flat.Load(layer_pb));
Eigen::MatrixXf input(2, 2);
input(0, 0) = 1.0;
input(1, 0) = 2.0;
input(0, 1) = 3.0;
input(1, 1) = 4.0;
Eigen::MatrixXf output;
flat.Run({input}, &output);
EXPECT_FLOAT_EQ(output(0, 0), 1.0);
EXPECT_FLOAT_EQ(output(0, 1), 3.0);
EXPECT_FLOAT_EQ(output(0, 2), 2.0);
EXPECT_FLOAT_EQ(output(0, 3), 4.0);
}
TEST(LayerTest, input_test) {
LayerParameter layer_pb;
Input input;
EXPECT_FALSE(input.Load(layer_pb));
layer_pb.mutable_input()->add_input_shape(2);
EXPECT_TRUE(input.Load(layer_pb));
}
TEST(LayerTest, concat_test) {
LayerParameter layer_pb;
Concatenate concat;
layer_pb.mutable_concatenate()->set_axis(0);
EXPECT_TRUE(concat.Load(layer_pb));
Eigen::MatrixXf input1(2, 1);
input1(0, 0) = 1.0;
input1(1, 0) = 2.0;
Eigen::MatrixXf input2(2, 1);
input2(0, 0) = 3.0;
input2(1, 0) = 4.0;
Eigen::MatrixXf output;
concat.Run({input1, input2}, &output);
EXPECT_FLOAT_EQ(output(0, 0), 1.0);
EXPECT_FLOAT_EQ(output(0, 1), 3.0);
EXPECT_FLOAT_EQ(output(1, 0), 2.0);
EXPECT_FLOAT_EQ(output(1, 1), 4.0);
}
} // namespace network
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/prediction
|
apollo_public_repos/apollo/modules/prediction/network/net_util.h
|
/******************************************************************************
* 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.
*****************************************************************************/
/**
* @file util.h
* @brief Define activation functions for neural network
*/
#pragma once
#include <string>
#include <vector>
#include "Eigen/Dense"
#include "modules/prediction/proto/network_layers.pb.h"
/**
* @namespace apollo::prediction::network
* @brief apollo::prediction::network
*/
namespace apollo {
namespace prediction {
namespace network {
/**
* @brief sigmoid function:
* f(x) = 1 / (1 + exp(-x))
*/
float sigmoid(const float x);
/**
* @brief hyperbolic tangent function:
* f(x) = (1 + exp(-2x)) / (1 - exp(-2x))
*/
float tanh(const float x);
/**
* @brief linear function:
* f(x) = x
*/
float linear(const float x);
/**
* @brief "hard" sigmoid function:
* | 0.0 x in (-oo, 0)
* f(x) = | 0.2x + 0.5 x in [0, 2.5]
* | 1.0 x in (2.5, +oo)
*/
float hard_sigmoid(const float x);
/**
* @brief relu function:
* | 0.0 x in (-oo, 0.0)
* f(x) = |
* | x x in [0.0, +oo)
*/
float relu(const float x);
/**
* @brief flatten a matrix to a row vector
* @param Input matrix
* @return Flattened matrix
*/
Eigen::MatrixXf FlattenMatrix(const Eigen::MatrixXf& matrix);
/**
* @brief translate a string into a network activation function
* @param string
* @return activation function map to the string
*/
std::function<float(float)> serialize_to_function(const std::string& str);
/**
* @brief load matrix value from a protobuf message
* @param protobuf message in the form of TensorParameter
* @param Eigen::MatrixXf will be returned
* @return True if load data successively, otherwise False
*/
bool LoadTensor(const TensorParameter& tensor_pb, Eigen::MatrixXf* matrix);
/**
* @brief load vector value from a protobuf message
* @param protobuf message in the form of TensorParameter
* @param Eigen::VectorXf will be returned
* @return True if load data successively, otherwise False
*/
bool LoadTensor(const TensorParameter& tensor_pb, Eigen::VectorXf* vector);
/**
* @brief load matrix value from a protobuf message
* @param protobuf message in the form of TensorParameter
* @param vector of Eigen::MatrixXf will be returned
* @return True if load data successively, otherwise False
*/
bool LoadTensor(const TensorParameter& tensor_pb,
std::vector<Eigen::MatrixXf>* const tensor3d);
} // namespace network
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/prediction
|
apollo_public_repos/apollo/modules/prediction/network/net_layer.h
|
/******************************************************************************
* 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.
*****************************************************************************/
#include <string>
#include <vector>
#include "modules/prediction/network/net_util.h"
#pragma once
/**
* @namespace apollo::prediction::network
* @brief apollo::prediction::network
*/
namespace apollo {
namespace prediction {
namespace network {
/**
* @class Layer
* @brief Layer is a base class for specific network layers
* It contains a pure virtual function Run which must be implemented
* in derived class
*/
class Layer {
public:
/**
* @brief Constructor
*/
Layer() = default;
/**
* @brief Destructor
*/
virtual ~Layer() = default;
/**
* @brief Load layer parameters from a protobuf message
* @param LayerParameter is a protobuf message
* @return True if successly loaded, otherwise False
*/
virtual bool Load(const apollo::prediction::LayerParameter& layer_pb);
/**
* @brief Reset the internal state of a layer such as LSTM, GRU
*/
virtual void ResetState() {}
/**
* @brief Set the internal state of a layer
* @param A specified internal state in a vector of Eigen::MatrixXf
*/
virtual void SetState(const std::vector<Eigen::MatrixXf>& states) {}
/**
* @brief Access to the internal state of a layer
* @return Internal state in a vector of Eigen::MatrixXf
*/
virtual void State(std::vector<Eigen::MatrixXf>* states) const {}
/**
* @brief Compute the layer output from inputs
* @param Inputs to a network layer
* @param Output of a network layer will be returned
*/
virtual void Run(const std::vector<Eigen::MatrixXf>& inputs,
Eigen::MatrixXf* output) = 0;
/**
* @brief Name of a layer
* @return Name of a layer
*/
std::string Name() const { return name_; }
/**
* @brief Order number of a layer in a network
* @return Order numer of a layer in a network
*/
int OrderNumber() const { return order_number_; }
private:
std::string name_;
int order_number_ = -1;
};
/**
* @class Dense
* @brief Dense is the forward fully connected network layer.
* Dense layer output is y = f(x*w + b),
* where x is the input, w the weight, b the bias and f the activation
*
* Parameter w and b can be loaded from pb message. if bias is
* not used, b = 0. f is linear function at default.
*/
class Dense : public Layer {
public:
/**
* @brief Load the dense layer parameter from a pb message
* @param A pb message contains the parameters
* @return True is loaded successively, otherwise False
*/
bool Load(const apollo::prediction::LayerParameter& layer_pb) override;
/**
* @brief Load the dense layer parameter from a pb message
* @param A pb message contains the parameters
* @return True is loaded successively, otherwise False
*/
bool Load(const apollo::prediction::DenseParameter& layer_pb);
/**
* @brief Compute the layer output from inputs
* @param Inputs to a network layer
* @param Output of a network layer will be returned
*/
void Run(const std::vector<Eigen::MatrixXf>& inputs,
Eigen::MatrixXf* output) override;
private:
int units_;
bool use_bias_;
Eigen::MatrixXf weights_;
Eigen::VectorXf bias_;
std::function<float(float)> kactivation_;
};
/**
* @class Conv1d
* @brief Conv1d is the convolution 1d network layer.
* Conv1d layer output is y = Conv(x, w),
* where x is the input, w the weight
*
* Parameter w and b can be loaded from pb message. if bias is
* not used, b = 0.
*/
class Conv1d : public Layer {
public:
/**
* @brief Load the layer parameter from a pb message
* @param A pb message contains the parameters
* @return True is loaded successively, otherwise False
*/
bool Load(const apollo::prediction::LayerParameter& layer_pb) override;
/**
* @brief Load the conv1d layer parameter from a pb message
* @param A pb message contains the parameters
* @return True is loaded successively, otherwise False
*/
bool Load(const apollo::prediction::Conv1dParameter& conv1d_pb);
/**
* @brief Compute the layer output from inputs
* @param Inputs to a network layer
* @param Output of a network layer will be returned
*/
void Run(const std::vector<Eigen::MatrixXf>& inputs,
Eigen::MatrixXf* output) override;
private:
std::vector<int> shape_;
bool use_bias_;
std::vector<Eigen::MatrixXf> kernel_;
Eigen::VectorXf bias_;
int stride_;
};
/**
* @class MaxPool1d
* @brief MaxPool1d is the max Pool 1d network layer.
*/
class MaxPool1d : public Layer {
public:
/**
* @brief Load the layer parameter from a pb message
* @param A pb message contains the parameters
* @return True is loaded successively, otherwise False
*/
bool Load(const apollo::prediction::LayerParameter& layer_pb) override;
/**
* @brief Load the max pool 1d layer parameter from a pb message
* @param A pb message contains the parameters
* @return True is loaded successively, otherwise False
*/
bool Load(const apollo::prediction::MaxPool1dParameter& maxpool1d_pb);
/**
* @brief Compute the layer output from inputs
* @param Inputs to a network layer
* @param Output of a network layer will be returned
*/
void Run(const std::vector<Eigen::MatrixXf>& inputs,
Eigen::MatrixXf* output) override;
private:
int kernel_size_;
int stride_;
};
/**
* @class AvgPool1d
* @brief AvgPool1d is the average Pool 1d network layer.
*/
class AvgPool1d : public Layer {
public:
/**
* @brief Load the dense layer parameter from a pb message
* @param A pb message contains the parameters
* @return True is loaded successively, otherwise False
*/
bool Load(const apollo::prediction::LayerParameter& layer_pb) override;
/**
* @brief Load the avg pool 1d layer parameter from a pb message
* @param A pb message contains the parameters
* @return True is loaded successively, otherwise False
*/
bool Load(const apollo::prediction::AvgPool1dParameter& avgpool1d_pb);
/**
* @brief Compute the layer output from inputs
* @param Inputs to a network layer
* @param Output of a network layer will be returned
*/
void Run(const std::vector<Eigen::MatrixXf>& inputs,
Eigen::MatrixXf* output) override;
private:
int kernel_size_;
int stride_;
};
/**
* @class Activation
* @brief Activation is an activation network layer.
* Activation layer output is y = f(x),
* where x is the input, y the output and f the activation function
*
* Parameter f can be loaded from pb message
*/
class Activation : public Layer {
public:
/**
* @brief Load the parameter from a pb message
* @param A pb message contains the parameters
* @return True is loaded successively, otherwise False
*/
bool Load(const apollo::prediction::LayerParameter& layer_pb) override;
/**
* @brief Load the parameter from a pb message
* @param A pb message contains the parameters
* @return True is loaded successively, otherwise False
*/
bool Load(const apollo::prediction::ActivationParameter& activation_pb);
/**
* @brief Compute the layer output from inputs
* @param Inputs to a network layer
* @param Output of a network layer will be returned
*/
void Run(const std::vector<Eigen::MatrixXf>& inputs,
Eigen::MatrixXf* output) override;
private:
std::function<float(float)> kactivation_;
};
/**
* @class Batch normalization layer (Ioffe and Szegedy, 2014)
* @brief Normalize the previous layer. The layer output is
* y = (x - mu) / sqrt(sigma) * gamma + beta
*/
class BatchNormalization : public Layer {
public:
/**
* @brief Load the parameter from a pb message
* @param A pb message contains the parameters
* @return True is loaded successively, otherwise False
*/
bool Load(const apollo::prediction::LayerParameter& layer_pb) override;
/**
* @brief Compute the layer output from inputs
* @param Inputs to a network layer
* @param Output of a network layer will be returned
*/
void Run(const std::vector<Eigen::MatrixXf>& inputs,
Eigen::MatrixXf* output) override;
private:
Eigen::VectorXf mu_;
Eigen::VectorXf sigma_;
Eigen::VectorXf gamma_;
Eigen::VectorXf beta_;
float epsilon_ = 0.0f;
float momentum_ = 0.0f;
int axis_ = 0;
bool center_ = false;
bool scale_ = false;
};
/**
* @class LSTM, short of Long-Short Term Memory unit - Hochreiter 1997.
* @brief For a step-by-step description of the algorithm, see
* [this tutorial](http://deeplearning.net/tutorial/lstm.html).
*/
class LSTM : public Layer {
public:
/**
* @brief Load the layer parameter from a pb message
* @param A pb message contains the parameters
* @return True is loaded successively, otherwise False
*/
bool Load(const apollo::prediction::LayerParameter& layer_pb) override;
/**
* @brief Compute the layer output from inputs
* @param Inputs to a network layer
* @param Output of a network layer will be returned
*/
void Run(const std::vector<Eigen::MatrixXf>& inputs,
Eigen::MatrixXf* output) override;
/**
* @brief Reset the internal state and memory cell state as zero-matrix
*/
void ResetState() override;
/**
* @brief Set the internal state and memory cell state
* @param A vector of Eigen::MatrixXf
*/
void SetState(const std::vector<Eigen::MatrixXf>& states) override;
/**
* @brief Access to the internal state and memory cell state
* @return State in a vector of Eigen::MatrixXf
*/
void State(std::vector<Eigen::MatrixXf>* states) const override;
private:
/**
* @brief Compute the output of LSTM step by step
* @param Input of current step
* @param Output of current step
* @param Hidden state of previous step and return current hidden state
* @param Cell state of previous step and return current cell state
*/
void Step(const Eigen::MatrixXf& input, Eigen::MatrixXf* output,
Eigen::MatrixXf* ht_1, Eigen::MatrixXf* ct_1);
Eigen::MatrixXf wi_;
Eigen::MatrixXf wf_;
Eigen::MatrixXf wc_;
Eigen::MatrixXf wo_;
Eigen::VectorXf bi_;
Eigen::VectorXf bf_;
Eigen::VectorXf bc_;
Eigen::VectorXf bo_;
Eigen::MatrixXf r_wi_;
Eigen::MatrixXf r_wf_;
Eigen::MatrixXf r_wc_;
Eigen::MatrixXf r_wo_;
Eigen::MatrixXf ht_1_;
Eigen::MatrixXf ct_1_;
std::function<float(float)> kactivation_;
std::function<float(float)> krecurrent_activation_;
int units_ = 0;
bool return_sequences_ = false;
bool stateful_ = false;
bool use_bias_ = false;
bool unit_forget_bias_ = false;
};
/**
* @class Flatten, It a network layer to flatten a matrix into vector.
*/
class Flatten : public Layer {
public:
/**
* @brief Load the dense layer parameter from a pb message
* @param A pb message contains the parameters
* @return True is loaded successively, otherwise False
*/
bool Load(const apollo::prediction::LayerParameter& layer_pb) override;
/**
* @brief Compute the layer output from inputs
* @param Inputs to a network layer
* @param Output of a network layer will be returned
*/
void Run(const std::vector<Eigen::MatrixXf>& inputs,
Eigen::MatrixXf* output) override;
};
/**
* @class Input, It is the input layer for a network, which specified
* the shape of input matrix
*/
class Input : public Layer {
public:
/**
* @brief Load the layer parameter from a pb message
* @param A pb message contains the parameters
* @return True is loaded successively, otherwise False
*/
bool Load(const apollo::prediction::LayerParameter& layer_pb) override;
/**
* @brief Compute the layer output from inputs
* @param Inputs to a network layer
* @param Output of a network layer will be returned
*/
void Run(const std::vector<Eigen::MatrixXf>& inputs,
Eigen::MatrixXf* output) override;
private:
std::vector<int> input_shape_;
std::string dtype_;
bool sparse_ = false;
};
/**
* @class Concatenate, layer that concatenates a vector of inputs, return
* a single matrix.
*/
class Concatenate : public Layer {
public:
/**
* @brief Load the layer parameter from a pb message
* @param A pb message contains the parameters
* @return True is loaded successively, otherwise False
*/
bool Load(const apollo::prediction::LayerParameter& layer_pb) override;
/**
* @brief Compute the layer output from inputs
* @param Inputs to a network layer
* @param Output of a network layer will be returned
*/
void Run(const std::vector<Eigen::MatrixXf>& inputs,
Eigen::MatrixXf* output) override;
private:
int axis_ = 0;
};
} // namespace network
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/prediction
|
apollo_public_repos/apollo/modules/prediction/network/net_util_test.cc
|
/******************************************************************************
* 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.
*****************************************************************************/
#include "modules/prediction/network/net_util.h"
#include "gtest/gtest.h"
namespace apollo {
namespace prediction {
namespace network {
TEST(NetworkUtil, serialize_to_function_test) {
std::function<float(float)> linear_func = serialize_to_function("linear");
EXPECT_FLOAT_EQ(linear_func(-2.0), -2.0);
EXPECT_FLOAT_EQ(linear_func(2.0), 2.0);
std::function<float(float)> tanh_func = serialize_to_function("tanh");
EXPECT_FLOAT_EQ(tanh_func(-2.0), -0.96402758);
EXPECT_FLOAT_EQ(tanh_func(0.0), 0.0);
EXPECT_FLOAT_EQ(tanh_func(2.0), 0.96402758);
std::function<float(float)> sigm_func = serialize_to_function("sigmoid");
EXPECT_FLOAT_EQ(sigm_func(-2.0), 0.11920292);
EXPECT_FLOAT_EQ(sigm_func(0.0), 0.5);
EXPECT_FLOAT_EQ(sigm_func(2.0), 0.88079707);
std::function<float(float)> hsigm_func =
serialize_to_function("hard_sigmoid");
EXPECT_FLOAT_EQ(hsigm_func(-3.0), 0.0);
EXPECT_FLOAT_EQ(hsigm_func(0.0), 0.5);
EXPECT_FLOAT_EQ(hsigm_func(3.0), 1.0);
std::function<float(float)> relu_func = serialize_to_function("relu");
EXPECT_FLOAT_EQ(relu_func(-3.0), 0.0);
EXPECT_FLOAT_EQ(relu_func(0.0), 0.0);
EXPECT_FLOAT_EQ(relu_func(3.0), 3.0);
}
TEST(NetworkUtil, LoadTensor_test) {
TensorParameter tensor_pb;
Eigen::MatrixXf mat;
Eigen::VectorXf vec;
EXPECT_FALSE(LoadTensor(tensor_pb, &mat));
EXPECT_FALSE(LoadTensor(tensor_pb, &vec));
tensor_pb.add_shape(2);
tensor_pb.add_data(1.0);
tensor_pb.add_data(2.0);
EXPECT_TRUE(LoadTensor(tensor_pb, &mat));
EXPECT_FLOAT_EQ(mat(0, 0), 1.0);
EXPECT_FLOAT_EQ(mat(0, 1), 2.0);
EXPECT_TRUE(LoadTensor(tensor_pb, &vec));
EXPECT_FLOAT_EQ(vec(0), 1.0);
EXPECT_FLOAT_EQ(vec(1), 2.0);
tensor_pb.add_shape(2);
tensor_pb.add_data(3.0);
tensor_pb.add_data(4.0);
EXPECT_TRUE(LoadTensor(tensor_pb, &mat));
EXPECT_FLOAT_EQ(mat(0, 0), 1.0);
EXPECT_FLOAT_EQ(mat(0, 1), 2.0);
EXPECT_FLOAT_EQ(mat(1, 0), 3.0);
EXPECT_FLOAT_EQ(mat(1, 1), 4.0);
}
} // namespace network
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/prediction
|
apollo_public_repos/apollo/modules/prediction/network/net_model.h
|
/******************************************************************************
* 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.
*****************************************************************************/
#pragma once
#include <memory>
#include <string>
#include <vector>
#include "modules/prediction/network/net_layer.h"
#include "modules/prediction/proto/network_model.pb.h"
/**
* @namespace apollo::prediction::network
* @brief apollo::prediction::network
*/
namespace apollo {
namespace prediction {
namespace network {
/**
* @class NetModel
* @brief NetModel is a base class for specific network model
* It contains a pure virtual function Run which must be implemented
* in derived class
*/
class NetModel {
public:
/**
* @brief Constructor
*/
NetModel() = default;
/**
* @brief Destructor
*/
virtual ~NetModel() = default;
/**
* @brief Compute the model output from inputs
* @param Inputs to a network
* @param Output of a network will be returned
*/
virtual void Run(const std::vector<Eigen::MatrixXf>& inputs,
Eigen::MatrixXf* output) const = 0;
/**
* @brief Set the internal state of a network model
* @param A specified internal state in a vector of Eigen::MatrixXf
*/
virtual void SetState(const std::vector<Eigen::MatrixXf>& states) {}
/**
* @brief Access to the internal state of a network model
* @return Internal state in a vector of Eigen::MatrixXf of the model
*/
virtual void State(std::vector<Eigen::MatrixXf>* states) const {}
/**
* @brief Set the internal state of a model
* @param A specified internal state in a vector of Eigen::MatrixXf
*/
virtual void ResetState() const {}
/**
* @brief Load network parameters from a protobuf message
* @param NetParameter is a protobuf message
* @return True if successfully loaded, otherwise False
*/
bool LoadModel(const NetParameter& net_parameter);
/**
* @brief Shows the performance information of a network
* @return Performance of a network model
*/
std::string PerformanceString() const;
/**
* @brief Name of a network model
* @return Name of a network model
*/
const std::string& Name() const;
/**
* @brief Id of a network model
* @return Id of a network model
*/
int Id() const;
/**
* @brief Indicate the state of a network model
* @return True of a network model is load successively, otherwise False.
*/
bool IsOk() const;
protected:
std::vector<std::unique_ptr<Layer>> layers_;
NetParameter net_parameter_;
bool ok_ = false;
};
} // namespace network
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/prediction
|
apollo_public_repos/apollo/modules/prediction/network/net_util.cc
|
/******************************************************************************
* 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.
*****************************************************************************/
#include "modules/prediction/network/net_util.h"
#include <unordered_map>
#include "cyber/common/log.h"
namespace apollo {
namespace prediction {
namespace network {
float sigmoid(const float x) { return 1.0f / (1.0f + std::exp(-x)); }
float tanh(const float x) { return std::tanh(x); }
float linear(const float x) { return x; }
float hard_sigmoid(const float x) {
const float z = 0.2f * x + 0.5f;
return z <= 0.0f ? 0.0f : (z <= 1.0f ? z : 1.0f);
}
float relu(const float x) { return (x > 0.0f) ? x : 0.0f; }
Eigen::MatrixXf FlattenMatrix(const Eigen::MatrixXf& matrix) {
CHECK_GT(matrix.rows(), 0);
CHECK_GT(matrix.cols(), 0);
int output_size = static_cast<int>(matrix.rows() * matrix.cols());
Eigen::MatrixXf output_matrix;
output_matrix.resize(1, output_size);
int output_index = 0;
for (int i = 0; i < matrix.rows(); ++i) {
for (int j = 0; j < matrix.cols(); ++j) {
output_matrix(0, output_index) = matrix(i, j);
++output_index;
}
}
return output_matrix;
}
std::function<float(float)> serialize_to_function(const std::string& str) {
static const std::unordered_map<std::string, std::function<float(float)>>
func_map({{"linear", linear},
{"tanh", tanh},
{"sigmoid", sigmoid},
{"hard_sigmoid", hard_sigmoid},
{"relu", relu}});
return func_map.at(str);
}
bool LoadTensor(const TensorParameter& tensor_pb, Eigen::MatrixXf* matrix) {
if (tensor_pb.data().empty() || tensor_pb.shape().empty()) {
AERROR << "Fail to load the necessary fields!";
return false;
}
if (tensor_pb.shape_size() < 2) {
ADEBUG << "Load tensor size: (1, " << tensor_pb.shape(0) << ")";
matrix->resize(1, tensor_pb.shape(0));
for (int i = 0; i < tensor_pb.shape(0); ++i) {
(*matrix)(0, i) = static_cast<float>(tensor_pb.data(i));
}
return true;
}
ADEBUG << "Load tensor size: (" << tensor_pb.shape(0) << ", "
<< tensor_pb.shape(1) << ")";
CHECK_EQ(tensor_pb.shape_size(), 2);
matrix->resize(tensor_pb.shape(0), tensor_pb.shape(1));
for (int i = 0; i < tensor_pb.shape(0); ++i) {
for (int j = 0; j < tensor_pb.shape(1); ++j) {
(*matrix)(i, j) =
static_cast<float>(tensor_pb.data(i * tensor_pb.shape(1) + j));
}
}
return true;
}
bool LoadTensor(const TensorParameter& tensor_pb, Eigen::VectorXf* vector) {
if (tensor_pb.data().empty() || tensor_pb.shape().empty()) {
AERROR << "Fail to load the necessary fields!";
return false;
}
ADEBUG << "Load tensor size: (" << tensor_pb.shape(0) << ", 1)";
CHECK_EQ(tensor_pb.shape_size(), 1);
if (tensor_pb.shape_size() == 1) {
vector->resize(tensor_pb.shape(0));
for (int i = 0; i < tensor_pb.shape(0); ++i) {
(*vector)(i) = static_cast<float>(tensor_pb.data(i));
}
}
return true;
}
bool LoadTensor(const TensorParameter& tensor_pb,
std::vector<Eigen::MatrixXf>* const tensor3d) {
if (tensor_pb.data().empty() || tensor_pb.shape_size() != 3) {
AERROR << "Fail to load the necessary fields!";
return false;
}
int num_depth = tensor_pb.shape(0);
int num_row = tensor_pb.shape(1);
int num_col = tensor_pb.shape(2);
CHECK_EQ(tensor_pb.data_size(), num_depth * num_row * num_col);
int tensor_pb_index = 0;
for (int k = 0; k < num_depth; ++k) {
Eigen::MatrixXf matrix = Eigen::MatrixXf::Zero(num_row, num_col);
for (int i = 0; i < num_row; ++i) {
for (int j = 0; j < num_col; ++j) {
matrix(i, j) = tensor_pb.data(tensor_pb_index);
++tensor_pb_index;
}
}
tensor3d->push_back(matrix);
}
CHECK_EQ(tensor_pb_index, num_depth * num_row * num_col);
return true;
}
} // namespace network
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/prediction
|
apollo_public_repos/apollo/modules/prediction/network/net_layer.cc
|
/******************************************************************************
* 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.
*****************************************************************************/
/**
* @file layer.cc
*/
#include "modules/prediction/network/net_layer.h"
#include <algorithm>
#include <limits>
#include "cyber/common/log.h"
namespace apollo {
namespace prediction {
namespace network {
bool Layer::Load(const LayerParameter& layer_pb) {
if (!layer_pb.has_name()) {
ADEBUG << "Set name at default";
name_ = "layer";
} else {
name_ = layer_pb.name();
}
if (!layer_pb.has_order_number()) {
ADEBUG << "Set order number at default";
order_number_ = -1;
} else {
order_number_ = layer_pb.order_number();
}
return true;
}
bool Dense::Load(const LayerParameter& layer_pb) {
if (!Layer::Load(layer_pb)) {
AERROR << "Fail to Load LayerParameter!";
return false;
}
DenseParameter dense_pb = layer_pb.dense();
return Load(dense_pb);
}
bool Dense::Load(const DenseParameter& dense_pb) {
if (!dense_pb.has_weights() || !LoadTensor(dense_pb.weights(), &weights_)) {
AERROR << "Fail to Load weights!";
return false;
}
if (!dense_pb.has_bias() || !LoadTensor(dense_pb.bias(), &bias_)) {
AERROR << "Fail to Load bias!";
return false;
}
if (!dense_pb.has_use_bias()) {
AWARN << "Set use_bias as false.";
use_bias_ = true;
} else {
use_bias_ = dense_pb.use_bias();
}
if (!dense_pb.has_activation()) {
ADEBUG << "Set activation as linear function";
kactivation_ = serialize_to_function("linear");
} else {
kactivation_ = serialize_to_function(dense_pb.activation());
}
units_ = dense_pb.units();
return true;
}
void Dense::Run(const std::vector<Eigen::MatrixXf>& inputs,
Eigen::MatrixXf* output) {
CHECK_EQ(inputs.size(), 1U);
Eigen::MatrixXf prod = static_cast<Eigen::MatrixXf>(inputs[0] * weights_);
if (use_bias_) {
Eigen::MatrixXf sum = prod.rowwise() + bias_.transpose();
prod = sum;
}
*output = prod.unaryExpr(kactivation_);
CHECK_EQ(output->cols(), units_);
}
bool Conv1d::Load(const LayerParameter& layer_pb) {
if (!Layer::Load(layer_pb)) {
AERROR << "Fail to Load LayerParameter!";
return false;
}
Conv1dParameter conv1d_pb = layer_pb.conv1d();
return Load(conv1d_pb);
}
bool Conv1d::Load(const Conv1dParameter& conv1d_pb) {
if (!conv1d_pb.has_kernel() || !LoadTensor(conv1d_pb.kernel(), &kernel_)) {
AERROR << "Fail to Load kernel!";
return false;
}
if (!conv1d_pb.has_bias() || !LoadTensor(conv1d_pb.bias(), &bias_)) {
AERROR << "Fail to Load bias!";
return false;
}
if (!conv1d_pb.has_use_bias()) {
AWARN << "Set use_bias as false.";
use_bias_ = true;
} else {
use_bias_ = conv1d_pb.use_bias();
}
for (int sz : conv1d_pb.shape()) {
shape_.push_back(sz);
}
if (conv1d_pb.has_stride()) {
stride_ = conv1d_pb.stride();
} else {
stride_ = 1;
}
return true;
}
void Conv1d::Run(const std::vector<Eigen::MatrixXf>& inputs,
Eigen::MatrixXf* output) {
CHECK_EQ(inputs.size(), 1U);
CHECK_GT(kernel_.size(), 0U);
CHECK_EQ(kernel_[0].rows(), inputs[0].rows());
int kernel_size = static_cast<int>(kernel_[0].cols());
int output_num_col =
static_cast<int>((inputs[0].cols() - kernel_size) / stride_) + 1;
int output_num_row = static_cast<int>(kernel_.size());
output->resize(output_num_row, output_num_col);
for (int i = 0; i < output_num_row; ++i) {
for (int j = 0; j < output_num_col; ++j) {
float output_i_j_unbiased = 0.0f;
for (int p = 0; p < inputs[0].rows(); ++p) {
for (int q = j * stride_; q < j * stride_ + kernel_size; ++q) {
output_i_j_unbiased +=
inputs[0](p, q) * kernel_[i](p, q - j * stride_);
}
}
(*output)(i, j) = output_i_j_unbiased + bias_(i);
}
}
}
bool MaxPool1d::Load(const LayerParameter& layer_pb) {
if (!Layer::Load(layer_pb)) {
AERROR << "Fail to Load LayerParameter!";
return false;
}
MaxPool1dParameter maxpool1d_pb = layer_pb.maxpool1d();
return Load(maxpool1d_pb);
}
bool MaxPool1d::Load(const MaxPool1dParameter& maxpool1d_pb) {
ACHECK(maxpool1d_pb.has_kernel_size());
CHECK_GT(maxpool1d_pb.has_kernel_size(), 0);
kernel_size_ = maxpool1d_pb.kernel_size();
if (maxpool1d_pb.has_stride() && maxpool1d_pb.stride() > 0) {
stride_ = maxpool1d_pb.stride();
} else {
ADEBUG << "No valid stride found, use kernel size, instead";
stride_ = maxpool1d_pb.kernel_size();
}
return true;
}
void MaxPool1d::Run(const std::vector<Eigen::MatrixXf>& inputs,
Eigen::MatrixXf* output) {
CHECK_EQ(inputs.size(), 1U);
int output_num_col =
static_cast<int>((inputs[0].cols() - kernel_size_) / stride_) + 1;
int output_num_row = static_cast<int>(inputs[0].rows());
output->resize(output_num_row, output_num_col);
int input_index = 0;
for (int j = 0; j < output_num_col; ++j) {
CHECK_LE(input_index + kernel_size_, inputs[0].cols());
for (int i = 0; i < output_num_row; ++i) {
float output_i_j = -std::numeric_limits<float>::infinity();
for (int k = input_index; k < input_index + kernel_size_; ++k) {
output_i_j = std::max(output_i_j, inputs[0](i, k));
}
(*output)(i, j) = output_i_j;
}
input_index += stride_;
}
}
bool AvgPool1d::Load(const LayerParameter& layer_pb) {
if (!Layer::Load(layer_pb)) {
AERROR << "Fail to Load LayerParameter!";
return false;
}
AvgPool1dParameter avgpool1d_pb = layer_pb.avgpool1d();
return Load(avgpool1d_pb);
}
bool AvgPool1d::Load(const AvgPool1dParameter& avgpool1d_pb) {
ACHECK(avgpool1d_pb.has_kernel_size());
CHECK_GT(avgpool1d_pb.has_kernel_size(), 0);
kernel_size_ = avgpool1d_pb.kernel_size();
if (avgpool1d_pb.has_stride() && avgpool1d_pb.stride() > 0) {
stride_ = avgpool1d_pb.stride();
} else {
ADEBUG << "No valid stride found, use kernel size, instead";
stride_ = avgpool1d_pb.kernel_size();
}
return true;
}
void AvgPool1d::Run(const std::vector<Eigen::MatrixXf>& inputs,
Eigen::MatrixXf* output) {
CHECK_EQ(inputs.size(), 1U);
int output_num_col =
static_cast<int>((inputs[0].cols() - kernel_size_) / stride_) + 1;
int output_num_row = static_cast<int>(inputs[0].rows());
output->resize(output_num_row, output_num_col);
int input_index = 0;
for (int j = 0; j < output_num_col; ++j) {
CHECK_LE(input_index + kernel_size_, inputs[0].cols());
for (int i = 0; i < output_num_row; ++i) {
float output_i_j_sum = 0.0f;
for (int k = input_index; k < input_index + kernel_size_; ++k) {
output_i_j_sum += inputs[0](i, k);
}
(*output)(i, j) = output_i_j_sum / static_cast<float>(kernel_size_);
}
input_index += stride_;
}
}
bool Activation::Load(const LayerParameter& layer_pb) {
if (!Layer::Load(layer_pb)) {
AERROR << "Fail to Load the layer parameters!";
return false;
}
if (!layer_pb.has_activation()) {
kactivation_ = serialize_to_function("linear");
} else {
ActivationParameter activation_pb = layer_pb.activation();
kactivation_ = serialize_to_function(activation_pb.activation());
}
return true;
}
bool Activation::Load(const ActivationParameter& activation_pb) {
if (!activation_pb.has_activation()) {
kactivation_ = serialize_to_function("linear");
} else {
kactivation_ = serialize_to_function(activation_pb.activation());
}
return true;
}
void Activation::Run(const std::vector<Eigen::MatrixXf>& inputs,
Eigen::MatrixXf* output) {
CHECK_EQ(inputs.size(), 1U);
*output = inputs[0].unaryExpr(kactivation_);
}
bool BatchNormalization::Load(const LayerParameter& layer_pb) {
if (!Layer::Load(layer_pb)) {
AERROR << "Fail to Load the layer parameters!";
return false;
}
auto bn_pb = layer_pb.batch_normalization();
epsilon_ = static_cast<float>(bn_pb.epsilon());
axis_ = bn_pb.axis();
center_ = bn_pb.center();
scale_ = bn_pb.scale();
momentum_ = bn_pb.momentum();
if (!bn_pb.has_mu() || !LoadTensor(bn_pb.mu(), &mu_)) {
AERROR << "Fail to Load mu!";
return false;
}
if (!bn_pb.has_sigma() || !LoadTensor(bn_pb.sigma(), &sigma_)) {
AERROR << "Fail to Load sigma!";
return false;
}
if (scale_) {
if (!bn_pb.has_gamma() || !LoadTensor(bn_pb.gamma(), &gamma_)) {
AERROR << "Fail to Load gamma!";
return false;
}
}
if (center_) {
if (!bn_pb.has_beta() || !LoadTensor(bn_pb.beta(), &beta_)) {
AERROR << "Fail to Load beta!";
return false;
}
}
return true;
}
void BatchNormalization::Run(const std::vector<Eigen::MatrixXf>& inputs,
Eigen::MatrixXf* output) {
CHECK_EQ(inputs.size(), 1U);
Eigen::MatrixXf temp = (inputs[0].rowwise() - mu_.transpose());
Eigen::MatrixXf norm =
temp.array().rowwise() / (sigma_.array().sqrt() + epsilon_).transpose();
if (scale_) {
norm = norm.array().rowwise() * gamma_.transpose().array();
}
if (center_) {
norm = norm.rowwise() + beta_.transpose();
}
*output = norm;
}
bool LSTM::Load(const LayerParameter& layer_pb) {
if (!Layer::Load(layer_pb)) {
AERROR << "Fail to Load the layer parameters!";
return false;
}
LSTMParameter lstm_pb = layer_pb.lstm();
if (!lstm_pb.has_units()) {
ADEBUG << "Fail to Load the number of units.";
return false;
} else {
units_ = lstm_pb.units();
}
if (!lstm_pb.has_return_sequences()) {
ADEBUG << "Set return_sequences at default.";
return_sequences_ = false;
} else {
return_sequences_ = lstm_pb.return_sequences();
}
if (!lstm_pb.has_stateful()) {
ADEBUG << "Set stateful at default.";
stateful_ = false;
} else {
stateful_ = lstm_pb.stateful();
}
if (!lstm_pb.has_activation()) {
ADEBUG << "Set activation function as tanh.";
kactivation_ = serialize_to_function("tanh");
} else {
kactivation_ = serialize_to_function(lstm_pb.activation());
}
if (!lstm_pb.has_recurrent_activation()) {
ADEBUG << "Set recurrent_activation function as hard_tanh.";
krecurrent_activation_ = serialize_to_function("hard_tanh");
} else {
krecurrent_activation_ =
serialize_to_function(lstm_pb.recurrent_activation());
}
if (!lstm_pb.has_use_bias()) {
ADEBUG << "Set use_bias as true.";
use_bias_ = true;
} else {
use_bias_ = lstm_pb.use_bias();
}
if (!lstm_pb.has_unit_forget_bias()) {
ADEBUG << "Set unit forget bias as true.";
unit_forget_bias_ = true;
} else {
unit_forget_bias_ = lstm_pb.unit_forget_bias();
}
if (!lstm_pb.has_weights_input() ||
!LoadTensor(lstm_pb.weights_input(), &wi_)) {
AERROR << "Fail to Load input weights!";
return false;
}
if (!lstm_pb.has_weights_forget() ||
!LoadTensor(lstm_pb.weights_forget(), &wf_)) {
AERROR << "Fail to Load forget weights!";
return false;
}
if (!lstm_pb.has_weights_cell() ||
!LoadTensor(lstm_pb.weights_cell(), &wc_)) {
AERROR << "Fail to Load cell weights!";
return false;
}
if (!lstm_pb.has_weights_output() ||
!LoadTensor(lstm_pb.weights_output(), &wo_)) {
AERROR << "Fail to Load output weights!";
return false;
}
if (!lstm_pb.has_bias_input() || !LoadTensor(lstm_pb.bias_input(), &bi_)) {
AERROR << "Fail to Load input bias!";
return false;
}
if (!lstm_pb.has_bias_forget() || !LoadTensor(lstm_pb.bias_forget(), &bf_)) {
AERROR << "Fail to Load forget bias!";
return false;
}
if (!lstm_pb.has_bias_cell() || !LoadTensor(lstm_pb.bias_cell(), &bc_)) {
AERROR << "Fail to Load cell bias!";
return false;
}
if (!lstm_pb.has_bias_output() || !LoadTensor(lstm_pb.bias_output(), &bo_)) {
AERROR << "Fail to Load output bias!";
return false;
}
if (!lstm_pb.has_recurrent_weights_input() ||
!LoadTensor(lstm_pb.recurrent_weights_input(), &r_wi_)) {
AERROR << "Fail to Load recurrent input weights!";
return false;
}
if (!lstm_pb.has_recurrent_weights_forget() ||
!LoadTensor(lstm_pb.recurrent_weights_forget(), &r_wf_)) {
AERROR << "Fail to Load recurrent forget weights!";
return false;
}
if (!lstm_pb.has_recurrent_weights_cell() ||
!LoadTensor(lstm_pb.recurrent_weights_cell(), &r_wc_)) {
AERROR << "Fail to Load recurrent cell weights!";
return false;
}
if (!lstm_pb.has_recurrent_weights_output() ||
!LoadTensor(lstm_pb.recurrent_weights_output(), &r_wo_)) {
AERROR << "Fail to Load recurrent output weights!";
return false;
}
ResetState();
return true;
}
void LSTM::Step(const Eigen::MatrixXf& input, Eigen::MatrixXf* output,
Eigen::MatrixXf* ht_1, Eigen::MatrixXf* ct_1) {
Eigen::MatrixXf x_i = input * wi_ + bi_.transpose();
Eigen::MatrixXf x_f = input * wf_ + bf_.transpose();
Eigen::MatrixXf x_c = input * wc_ + bc_.transpose();
Eigen::MatrixXf x_o = input * wo_ + bo_.transpose();
Eigen::MatrixXf i = (x_i + (*ht_1) * r_wi_).unaryExpr(krecurrent_activation_);
Eigen::MatrixXf f = (x_f + (*ht_1) * r_wf_).unaryExpr(krecurrent_activation_);
Eigen::MatrixXf c =
f.array() * ct_1->array() +
i.array() * ((x_c + (*ht_1) * r_wc_).unaryExpr(kactivation_)).array();
Eigen::MatrixXf o = (x_o + (*ht_1) * r_wo_).unaryExpr(krecurrent_activation_);
Eigen::MatrixXf h = o.array() * (c.unaryExpr(kactivation_)).array();
*ht_1 = h;
*ct_1 = c;
*output = h;
}
void LSTM::Run(const std::vector<Eigen::MatrixXf>& inputs,
Eigen::MatrixXf* output) {
CHECK_EQ(inputs.size(), 1U);
Eigen::MatrixXf sequences(inputs[0].rows(), units_);
Eigen::MatrixXf temp;
for (int i = 0; i < inputs[0].rows(); ++i) {
Step(inputs[0].row(i), &temp, &ht_1_, &ct_1_);
sequences.row(i) = temp.row(0);
}
if (return_sequences_) {
*output = sequences;
} else {
*output = temp.row(0);
}
}
void LSTM::ResetState() {
ht_1_.resize(1, units_);
ct_1_.resize(1, units_);
ht_1_.fill(0.0);
ct_1_.fill(0.0);
}
void LSTM::State(std::vector<Eigen::MatrixXf>* states) const {
states->resize(2);
states->at(0) = ht_1_;
states->at(1) = ct_1_;
}
void LSTM::SetState(const std::vector<Eigen::MatrixXf>& states) {
CHECK_EQ(states.size(), 2U);
CHECK_EQ(states[0].rows(), 1);
CHECK_EQ(states[1].rows(), 1);
CHECK_EQ(states[0].cols(), units_);
CHECK_EQ(states[1].cols(), units_);
ht_1_ = states[0];
ct_1_ = states[1];
}
bool Flatten::Load(const LayerParameter& layer_pb) {
if (!Layer::Load(layer_pb)) {
AERROR << "Fail to Load the layer parameters!";
return false;
}
return true;
}
void Flatten::Run(const std::vector<Eigen::MatrixXf>& inputs,
Eigen::MatrixXf* output) {
CHECK_EQ(inputs.size(), 1U);
Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> inp(
inputs[0]);
inp.resize(1, inp.size());
*output = inp;
}
bool Input::Load(const LayerParameter& layer_pb) {
if (!Layer::Load(layer_pb)) {
AERROR << "Fail to Load the layer parameters!";
return false;
}
InputParameter input_pb = layer_pb.input();
if (input_pb.input_shape_size() < 1) {
AERROR << "Fail to Load input shape of InputLayer!";
return false;
} else {
input_shape_.resize(input_pb.input_shape_size());
for (int i = 0; i < input_pb.input_shape_size(); ++i) {
input_shape_[i] = input_pb.input_shape(i);
}
}
if (!input_pb.has_dtype()) {
ADEBUG << "Set the type of input as float!";
dtype_ = "float32";
} else {
dtype_ = input_pb.dtype();
}
if (!input_pb.has_sparse()) {
ADEBUG << "set the sparse of input as false!";
sparse_ = false;
} else {
sparse_ = input_pb.sparse();
}
return true;
}
void Input::Run(const std::vector<Eigen::MatrixXf>& inputs,
Eigen::MatrixXf* output) {
CHECK_EQ(inputs.size(), 1U);
CHECK_EQ(inputs[0].cols(), input_shape_.back());
*output = inputs[0];
}
bool Concatenate::Load(const LayerParameter& layer_pb) {
if (!Layer::Load(layer_pb)) {
AERROR << "Fail to Load the layer parameters!";
return false;
}
ConcatenateParameter concat_pb = layer_pb.concatenate();
if (!concat_pb.has_axis()) {
AERROR << "Fail to Load the concatenate!";
return false;
}
axis_ = concat_pb.axis();
return true;
}
void Concatenate::Run(const std::vector<Eigen::MatrixXf>& inputs,
Eigen::MatrixXf* output) {
CHECK_EQ(inputs.size(), 2U);
CHECK_EQ(inputs[0].rows(), inputs[1].rows());
output->resize(inputs[0].rows(), inputs[0].cols() + inputs[1].cols());
*output << inputs[0], inputs[1];
}
} // namespace network
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/prediction
|
apollo_public_repos/apollo/modules/prediction/network/BUILD
|
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test")
load("//tools:cpplint.bzl", "cpplint")
package(default_visibility = ["//visibility:public"])
PREDICTION_COPTS = ["-DMODULE_NAME=\\\"prediction\\\""]
cc_library(
name = "net_util",
srcs = ["net_util.cc"],
hdrs = ["net_util.h"],
copts = PREDICTION_COPTS,
deps = [
"//cyber",
"//modules/prediction/proto:network_layers_cc_proto",
"@eigen",
],
)
cc_library(
name = "net_layer",
srcs = ["net_layer.cc"],
hdrs = ["net_layer.h"],
copts = PREDICTION_COPTS,
deps = [
"//modules/prediction/network:net_util",
],
)
cc_library(
name = "net_model",
srcs = ["net_model.cc"],
hdrs = ["net_model.h"],
copts = PREDICTION_COPTS,
deps = [
"//modules/common/util",
"//modules/prediction/network:net_layer",
"//modules/prediction/proto:network_model_cc_proto",
],
)
cc_test(
name = "net_util_test",
size = "small",
srcs = ["net_util_test.cc"],
deps = [
"//modules/prediction/network:net_util",
"@com_google_googletest//:gtest_main",
],
linkstatic = True,
)
cc_test(
name = "net_layer_test",
size = "small",
srcs = ["net_layer_test.cc"],
deps = [
"//modules/prediction/network:net_layer",
"@com_google_googletest//:gtest_main",
],
)
cpplint()
| 0
|
apollo_public_repos/apollo/modules/prediction
|
apollo_public_repos/apollo/modules/prediction/network/net_model.cc
|
/******************************************************************************
* 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.
*****************************************************************************/
#include "modules/prediction/network/net_model.h"
#include <utility>
#include "cyber/common/log.h"
namespace apollo {
namespace prediction {
namespace network {
bool NetModel::LoadModel(const NetParameter& net_parameter) {
net_parameter_.CopyFrom(net_parameter);
layers_.clear();
for (int i = 0; i < net_parameter_.layers_size(); ++i) {
LayerParameter layer_pb = net_parameter_.layers(i);
ADEBUG << i << "-th layer name: " << layer_pb.name().c_str();
std::unique_ptr<Layer> layer(nullptr);
switch (layer_pb.oneof_layers_case()) {
case LayerParameter::kInput:
layer = std::unique_ptr<Layer>(new Input());
break;
case LayerParameter::kActivation:
layer = std::unique_ptr<Layer>(new Activation());
break;
case LayerParameter::kDense:
layer = std::unique_ptr<Layer>(new Dense());
break;
case LayerParameter::kBatchNormalization:
layer = std::unique_ptr<Layer>(new BatchNormalization());
break;
case LayerParameter::kLstm:
layer = std::unique_ptr<Layer>(new LSTM());
break;
case LayerParameter::kFlatten:
layer = std::unique_ptr<Layer>(new Flatten());
break;
case LayerParameter::kConcatenate:
layer = std::unique_ptr<Layer>(new Concatenate());
break;
default:
AERROR << "Failed to load layer: " << layer_pb.type().c_str();
break;
}
if (!layer->Load(layer_pb)) {
AERROR << "Failed to load " << i << "-layer: " << layer_pb.name().c_str();
return false;
}
layers_.push_back(std::move(layer));
}
ok_ = true;
AINFO << "Success in loading the model!";
ADEBUG << "Its Performance:" << PerformanceString().c_str();
return true;
}
std::string NetModel::PerformanceString() const {
std::stringstream ss;
if (!net_parameter_.has_performance()) {
AWARN << "The protobuf does not contain performance values!";
return " ";
}
ss << "\n test: accuracy = ";
for (int i = 0; i < net_parameter_.performance().accuracy_size(); ++i) {
ss << net_parameter_.performance().accuracy(i) << ", ";
}
ss << "\n recall = ";
for (int i = 0; i < net_parameter_.performance().recall_size(); ++i) {
ss << net_parameter_.performance().recall(i) << ", ";
}
ss << "\n precision = ";
for (int i = 0; i < net_parameter_.performance().precision_size(); ++i) {
ss << net_parameter_.performance().precision(i) << ", ";
}
ss << std::endl;
return ss.str();
}
const std::string& NetModel::Name() const { return net_parameter_.name(); }
int NetModel::Id() const { return net_parameter_.id(); }
bool NetModel::IsOk() const { return ok_; }
} // namespace network
} // namespace prediction
} // namespace apollo
| 0
|
apollo_public_repos/apollo/modules/prediction/network
|
apollo_public_repos/apollo/modules/prediction/network/rnn_model/rnn_model.cc
|
/******************************************************************************
* 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.
*****************************************************************************/
#include "modules/prediction/network/rnn_model/rnn_model.h"
namespace apollo {
namespace prediction {
namespace network {
RnnModel::RnnModel() {}
void RnnModel::Run(const std::vector<Eigen::MatrixXf>& inputs,
Eigen::MatrixXf* output) const {
Eigen::MatrixXf inp1;
Eigen::MatrixXf inp2;
layers_[0]->Run({inputs[0]}, &inp1);
layers_[1]->Run({inputs[1]}, &inp2);
Eigen::MatrixXf bn1;
Eigen::MatrixXf bn2;
layers_[2]->Run({inp1}, &bn1);
layers_[3]->Run({inp2}, &bn2);
Eigen::MatrixXf lstm1;
Eigen::MatrixXf lstm2;
layers_[4]->Run({bn1}, &lstm1);
layers_[5]->Run({bn2}, &lstm2);
Eigen::MatrixXf merge;
Eigen::MatrixXf dense1;
Eigen::MatrixXf act1;
layers_[6]->Run({lstm1, lstm2}, &merge);
layers_[7]->Run({merge}, &dense1);
layers_[8]->Run({dense1}, &bn1);
layers_[9]->Run({bn1}, &act1);
Eigen::MatrixXf dense2;
Eigen::MatrixXf prob;
layers_[10]->Run({act1}, &dense2);
layers_[12]->Run({dense2}, &bn1);
layers_[14]->Run({bn1}, &prob);
Eigen::MatrixXf acc;
layers_[11]->Run({act1}, &dense2);
layers_[13]->Run({dense2}, &bn1);
layers_[15]->Run({bn1}, &acc);
output->resize(1, 2);
*output << prob, acc;
}
void RnnModel::SetState(const std::vector<Eigen::MatrixXf>& states) {
layers_[4]->SetState(states);
layers_[5]->ResetState();
}
void RnnModel::State(std::vector<Eigen::MatrixXf>* states) const {
layers_[4]->State(states);
}
void RnnModel::ResetState() const {
layers_[4]->ResetState();
layers_[5]->ResetState();
}
} // namespace network
} // namespace prediction
} // namespace apollo
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.