草庐IT

C++实现双向RRT算法

CNPolaris 2023-03-28 原文

C++实现双向RRT算法

背景介绍

RRT(Rapidly-exploring Random Trees)是Steven M. LaValle和James J. Kuffner Jr.提出的一种通过所及构建空间搜索树实现对非凸高维空间快速搜索算法。该算法可以很容易的处理包含障碍和差分运动约束的场景,因此被广泛应用在各种机器人、无人车的运动规划场景中。

双向RRT算法

为了加快随机搜索树规划路径的速度,因此提出了一种新的搜索思路,即从起点和终点同时开始构建随机搜索树,并每次进行判断产生的节点是否满足连接的条件。并在连接条件上添加了转角约束和动态步长策略。

转角约束是用来限制路线的转折角度,避免超过无人车的最大转弯角度。动态步长策略是在产生新节点时用于判断距离障碍物的趋势,动态的调整步长,能够使规划出的路径更加平滑,同时也可加快收敛速度。

C++代码实现如下:

具体代码

头文件
//
// Created by cntia on 2022-10-01.
//

#ifndef RRT_C_RRT_H
#define RRT_C_RRT_H
#include <cmath>
#include <iostream>

using namespace std;
const int RAND_X = 21;
const int RAND_Y = 89;
const double EPS = 1e-6;

struct ListPoint{
    double x;
    double y;
    ListPoint *parent;
    ListPoint *next;
    ListPoint(): x(0), y(0), parent(nullptr),next(nullptr){}
    ListPoint(double x, double y): x(x), y(y), parent(nullptr), next(nullptr){}
};
struct ListObstacle {
    double x;
    double y;
    double r;
    ListObstacle *next;
    ListObstacle():x(),y(), r(), next(nullptr){}
    ListObstacle(double x, double y, double r):x(x),y(y), r(r), next(nullptr){}
};
struct Vector {
    double x;
    double y;
};
class RT {
private:
    ListPoint *one;
    ListPoint *two;
    ListObstacle *obstacle;

    ListPoint *start;
    ListPoint *goal;
    ListPoint *safe;
    ListPoint *recover;

    double angle;
    double step;
    double dist;
    /**
 * 生成随机点
 * @return
 */
    static ListPoint* randomPoint();
    /**
     * 计算向量夹角
     * @param vector1
     * @param vector2
     * @return
     */
    double getAngle(Vector vector1, Vector vector2);
    /**
     * 向搜索树插入实际新节点
     * @param t
     * @param point
     */
    void pushBack(int t,ListPoint *point);
    /**
     * 查询最近节点
     * @param list
     * @param point
     * @return
     */
    ListPoint *getNearestIndexPoint(ListPoint *list, ListPoint *point);
    /**
     * 查询最近障碍物
     * @param point
     * @return
     */
    ListObstacle *getNearestIndexObstacle(ListPoint *point);
    /**
     * 计算动态步长
     * @param n_point
     * @param a_point
     * @return
     */
    double dynamicStep(ListPoint *n_point, ListPoint * a_point);
    /**
     * 碰撞检测
     * @param t
     * @param newPoint
     * @return
     */
    bool collisionCheck(int t,const ListPoint *newPoint);
    /**
     * 转角约束检测
     * @param newPoint
     * @param parentPoint
     * @param ancestorPoint
     * @return
     */
    bool angleCheck(const ListPoint *newPoint, const ListPoint *parentPoint, const ListPoint *ancestorPoint);
    /**
     * 节点检测
     * @param t
     * @param newPoint
     * @return
     */
    bool conditionCheck(int t,const ListPoint *newPoint);
    /**
     * 平滑连接判断
     * @param onePoint
     * @param twoPoint
     * @return
     */
    bool perfectConnect(const ListPoint *onePoint, const ListPoint *twoPoint);
    /**
     * 实际坐标计算
     * @param t
     * @param rnd
     * @return
     */
    ListPoint *coordinate(int t, ListPoint *rnd);
public:
    RT(ListPoint *start,ListPoint *goal,ListPoint *safe,ListPoint *recover, double angle,
       double step, double dist, ListObstacle *obstacle) : start(start), goal(goal), safe(safe), recover(recover),
       angle(angle), step(step),dist(dist),obstacle(obstacle) {
        ListPoint *headOne = start;
        headOne->next = safe;
        safe->parent = headOne;
        this->one = headOne;

        ListPoint *headTwo = goal;
        headTwo->next = recover;
        recover->parent = headTwo;
        this->two = headTwo;
    };
    /**
     * 路径规划
     */
    void planning();
};
#endif //RRT_C_RRT_H

源文件
//
// Created by cntia on 2022-10-01.
//

#include "../headers/RRT.h"

ListPoint *RT::randomPoint() {
    double x = (rand() % (RAND_Y - RAND_X + 1)) + RAND_X;
    double y = (rand() % (RAND_Y - RAND_X + 1)) + RAND_X;
    auto *point = new ListPoint(x, y);
    return point;
}


double RT::getAngle(const Vector vector1, const Vector vector2) {
    double PI = 3.141592653;
    double t = (vector1.x * vector2.x + vector1.y * vector2.y) / (sqrt(pow(vector1.x, 2) + pow(vector1.y, 2)) * sqrt(pow(vector2.x, 2) + pow(vector2.y, 2)));
    double angle = acos(t) * (180 / PI);
    return angle;
}


void RT::pushBack(int t, ListPoint *point) {
    ListPoint *last;
    if(t == 1){
        last = this->one;
    } else {
        last = this->two;
    }
    point->next = nullptr;
    while(last->next != nullptr){
        last = last->next;
    }
    last->next = point;
    point->parent = last;
}


ListPoint *RT::getNearestIndexPoint(ListPoint *list, ListPoint *point) {
    auto *minIndex = new ListPoint;
    auto *head = list;
    double minD = 1.79769e+308;
    double d = 0;
    while(head){
        d = pow((point->x - head->x), 2) + pow((point->y - head->y), 2);
        if(d + EPS < minD){
            minD = d;
            minIndex = head;
        }
        head = head->next;
    }
    return minIndex;
}


ListObstacle *RT::getNearestIndexObstacle(ListPoint *point) {
    auto *minIndex = new ListObstacle;
    auto *head = this->obstacle;
    double minD = 1.79769e+308;
    double d = 0;
    while(head){
        d = sqrt(pow(head->x - point->x, 2) + pow((head->y - point->y), 2)) - head->r;
        if(d+EPS<minD){
            minD = d;
            minIndex = head;
        }
        head = head->next;
    }
    return minIndex;
}


double RT::dynamicStep(ListPoint *n_point, ListPoint *a_point) {
    double theta = atan2(a_point->y - n_point->y, a_point->x - n_point->x);
    a_point->x += cos(theta) * (this->dist + this->step) / 2;
    a_point->y += sin(theta) * (this->dist + this->step) / 2;

    auto * obstacle = getNearestIndexObstacle(a_point);

    double l_n = sqrt(pow(n_point->x-obstacle->x, 2)+pow(n_point->y - obstacle->y, 2)) - obstacle->r;
    double dynamic = this->step / (1 + (this->step / this->dist - 1) * exp( -3 * l_n / this->step));
    return dynamic;
}


bool RT::collisionCheck(int t,const ListPoint *newPoint) {
    bool flag = true;
    ListObstacle *head = this->obstacle;
    while(head != nullptr){
        double dx = head->x - newPoint->x;
        double dy = head->y - newPoint->y;
        double d = sqrt(pow(dx, 2) + pow(dy, 2));

        ListPoint *parentPoint = newPoint->parent;

        Vector vector_p_n = {newPoint->x - parentPoint->x, newPoint->y - parentPoint->y};
        Vector vector_p_o = {head->x - parentPoint->x, head->y - parentPoint->y};
        double d_p_n = abs(sqrt(pow(vector_p_o.x, 2) + pow(vector_p_o.y, 2)) * sin(getAngle(vector_p_n, vector_p_o)));
        if(d + EPS < head->r || d_p_n + EPS < head ->r){
            flag = false;
            break;
        }
        head = head->next;
    }
    return flag;
}


bool RT::angleCheck(const ListPoint *newPoint, const ListPoint *parentPoint, const ListPoint *ancestorPoint) {
    Vector vector_p_n = {newPoint->x - parentPoint->x, newPoint->y - parentPoint->y};

    Vector vector_a_p = {parentPoint->x - ancestorPoint->x, parentPoint->y - ancestorPoint->y};

    double angle = getAngle(vector_a_p, vector_p_n);
    if(angle+EPS <= this->angle){
        return true;
    } else{
        return false;
    }
}


bool RT::conditionCheck(int t,const ListPoint *newPoint) {
    if(collisionCheck(t, newPoint)){
        ListPoint *parentPoint = newPoint->parent;
        if(parentPoint->parent == nullptr){
            return false;
        }
        ListPoint *ancestorPoint = parentPoint->parent;
        if(angleCheck(newPoint, parentPoint, ancestorPoint)){
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}


bool RT::perfectConnect(const ListPoint *onePoint, const ListPoint *twoPoint) {
    ListPoint *oneParent = onePoint->parent;
    ListPoint *twoParent = twoPoint->parent;

    Vector vector_n_w = {onePoint->x - oneParent->x, onePoint->y - oneParent->y};

    Vector vector_w_x = {twoPoint->x - onePoint->x, twoPoint->y - onePoint->y};

    Vector vector_x_j = {twoParent->x - twoPoint->x, twoParent->y - twoPoint->x};

    double angle_one = getAngle(vector_n_w, vector_w_x);
    double angle_two = getAngle(vector_w_x, vector_x_j);
    if(angle_one <= this->angle - EPS){
        if(fabs(angle_two - 180.0) < EPS || fabs(angle_one - 0.0) < EPS){
            return false;
        }else{
            return true;
        }
    }else{
        return false;
    }
}


ListPoint *RT::coordinate(int t, ListPoint *rnd) {
    // 寻找最近节点
    auto *nearestPoint = new ListPoint;
    if(t==1) {
        nearestPoint = getNearestIndexPoint(this->one, rnd);
    } else {
        nearestPoint = getNearestIndexPoint(this->two, rnd);
    }
    // 按照原始步长计算虚坐标
    double theta = atan2(rnd->y - nearestPoint->y, rnd->x - nearestPoint->x);
    auto *newPoint = new ListPoint(nearestPoint->x + cos(theta) * this->step, nearestPoint->y + sin(theta) * this->step);
    // 使用动态步长计算实际坐标
    double actualStep = dynamicStep(nearestPoint, newPoint);
    newPoint->x = nearestPoint->x + cos(theta) * actualStep;
    newPoint->y = nearestPoint->y + sin(theta) * actualStep;
    newPoint->parent = nearestPoint;
    return newPoint;
}


void RT::planning() {
    while(true){
        ListPoint *rnd = randomPoint();
        ListPoint *newPoint=coordinate(1, rnd);

        if(!conditionCheck(1, newPoint)){
            continue;
        }
        pushBack(1, newPoint);

        ListPoint *newPointTwo = coordinate(2, newPoint);
        if(!conditionCheck(2, newPointTwo)){
            continue;
        }
        pushBack(2, newPointTwo);

        double dx = newPoint->x - newPointTwo->x;
        double dy = newPoint->y - newPointTwo->y;
        double d = sqrt(pow(dx, 2)+ pow(dy, 2));

        if(this-> dist+ EPS < d && d + EPS <this->step){
            if(perfectConnect(newPoint, newPointTwo)){
                break;
            }
            else{
                continue;
            }
        }else{
            continue;
        }
    }
    ListPoint *tempOne = this->one;
    while(tempOne!= nullptr){
        cout<<tempOne->x<<"  "<<tempOne->y<<endl;
        tempOne = tempOne->next;
    }
    ListPoint *tempTwo = this->two;
    while(tempTwo != nullptr){
        cout<<tempTwo->x<<"  "<<tempTwo->y<<endl;
        tempTwo = tempTwo->next;
    }
}
主程序
#include "headers//RRT.h"
using namespace std;

const double ANGLE = 60.0;
const double STEP = 10.0;
const double DISTANCE = 5.0;

int main() {
    double obstacle_x[]= {50, 50, 50};
    double obstacle_y[]= {50, 13, 87};
    double obstacle_r[]= {15, 12, 11};
    auto * obstacle = new ListObstacle(50, 50, 15);
    for(int i = 1; i<3; i++){
        auto *node = new ListObstacle;
        node->x = obstacle_x[i];
        node->y = obstacle_y[i];
        node->r = obstacle_r[i];

        node->next = obstacle->next;
        obstacle->next = node;
    }
    auto *start = new ListPoint(0, 0);
    auto *goal = new ListPoint(100, 100);
    auto *safe = new ListPoint(20, 20);
    auto *recover = new ListPoint(90, 90);
    RT rrt = RT(start, goal, safe, recover, ANGLE, STEP, DISTANCE, obstacle);
    rrt.planning();
}

有关C++实现双向RRT算法的更多相关文章

  1. ruby - 如何根据特征实现 FactoryGirl 的条件行为 - 2

    我有一个用户工厂。我希望默认情况下确认用户。但是鉴于unconfirmed特征,我不希望它们被确认。虽然我有一个基于实现细节而不是抽象的工作实现,但我想知道如何正确地做到这一点。factory:userdoafter(:create)do|user,evaluator|#unwantedimplementationdetailshereunlessFactoryGirl.factories[:user].defined_traits.map(&:name).include?(:unconfirmed)user.confirm!endendtrait:unconfirmeddoenden

  2. 区块链之加解密算法&数字证书 - 2

    目录一.加解密算法数字签名对称加密DES(DataEncryptionStandard)3DES(TripleDES)AES(AdvancedEncryptionStandard)RSA加密法DSA(DigitalSignatureAlgorithm)ECC(EllipticCurvesCryptography)非对称加密签名与加密过程非对称加密的应用对称加密与非对称加密的结合二.数字证书图解一.加解密算法加密简单而言就是通过一种算法将明文信息转换成密文信息,信息的的接收方能够通过密钥对密文信息进行解密获得明文信息的过程。根据加解密的密钥是否相同,算法可以分为对称加密、非对称加密、对称加密和非

  3. 华为OD机试用Python实现 -【明明的随机数】 2023Q1A - 2

    华为OD机试题本篇题目:明明的随机数题目输入描述输出描述:示例1输入输出说明代码编写思路最近更新的博客华为od2023|什么是华为od,od薪资待遇,od机试题清单华为OD机试真题大全,用Python解华为机试题|机试宝典【华为OD机试】全流程解析+经验分享,题型分享,防作弊指南华为o

  4. 基于C#实现简易绘图工具【100010177】 - 2

    C#实现简易绘图工具一.引言实验目的:通过制作窗体应用程序(C#画图软件),熟悉基本的窗体设计过程以及控件设计,事件处理等,熟悉使用C#的winform窗体进行绘图的基本步骤,对于面向对象编程有更加深刻的体会.Tutorial任务设计一个具有基本功能的画图软件**·包括简单的新建文件,保存,重新绘图等功能**·实现一些基本图形的绘制,包括铅笔和基本形状等,学习橡皮工具的创建**·设计一个合理舒适的UI界面**注明:你可能需要先了解一些关于winform窗体应用程序绘图的基本知识,以及关于GDI+类和结构的知识二.实验环境Windows系统下的visualstudio2017C#窗体应用程序三.

  5. MIMO-OFDM无线通信技术及MATLAB实现(1)无线信道:传播和衰落 - 2

     MIMO技术的优缺点优点通过下面三个增益来总体概括:阵列增益。阵列增益是指由于接收机通过对接收信号的相干合并而活得的平均SNR的提高。在发射机不知道信道信息的情况下,MIMO系统可以获得的阵列增益与接收天线数成正比复用增益。在采用空间复用方案的MIMO系统中,可以获得复用增益,即信道容量成倍增加。信道容量的增加与min(Nt,Nr)成正比分集增益。在采用空间分集方案的MIMO系统中,可以获得分集增益,即可靠性性能的改善。分集增益用独立衰落支路数来描述,即分集指数。在使用了空时编码的MIMO系统中,由于接收天线或发射天线之间的间距较远,可认为它们各自的大尺度衰落是相互独立的,因此分布式MIMO

  6. 【Java入门】使用Java实现文件夹的遍历 - 2

    遍历文件夹我们通常是使用递归进行操作,这种方式比较简单,也比较容易理解。本文为大家介绍另一种不使用递归的方式,由于没有使用递归,只用到了循环和集合,所以效率更高一些!一、使用递归遍历文件夹整体思路1、使用File封装初始目录,2、打印这个目录3、获取这个目录下所有的子文件和子目录的数组。4、遍历这个数组,取出每个File对象4-1、如果File是否是一个文件,打印4-2、否则就是一个目录,递归调用代码实现publicclassSearchFile{publicstaticvoidmain(String[]args){//初始目录Filedir=newFile("d:/Dev");Datebeg

  7. ruby - Arrays Sets 和 SortedSets 在 Ruby 中是如何实现的 - 2

    通常,数组被实现为内存块,集合被实现为HashMap,有序集合被实现为跳跃列表。在Ruby中也是如此吗?我正在尝试从性能和内存占用方面评估Ruby中不同容器的使用情况 最佳答案 数组是Ruby核心库的一部分。每个Ruby实现都有自己的数组实现。Ruby语言规范只规定了Ruby数组的行为,并没有规定任何特定的实现策略。它甚至没有指定任何会强制或至少建议特定实现策略的性能约束。然而,大多数Rubyist对数组的性能特征有一些期望,这会迫使不符合它们的实现变得默默无闻,因为实际上没有人会使用它:插入、前置或追加以及删除元素的最坏情况步骤复

  8. ruby - "public/protected/private"方法是如何实现的,我该如何模拟它? - 2

    在ruby中,你可以这样做:classThingpublicdeff1puts"f1"endprivatedeff2puts"f2"endpublicdeff3puts"f3"endprivatedeff4puts"f4"endend现在f1和f3是公共(public)的,f2和f4是私有(private)的。内部发生了什么,允许您调用一个类方法,然后更改方法定义?我怎样才能实现相同的功能(表面上是创建我自己的java之类的注释)例如...classThingfundeff1puts"hey"endnotfundeff2puts"hey"endendfun和notfun将更改以下函数定

  9. ruby - 实现k最近邻需要哪些数据? - 2

    我目前有一个reddit克隆类型的网站。我正在尝试根据我的用户之前喜欢的帖子推荐帖子。看起来K最近邻或k均值是执行此操作的最佳方法。我似乎无法理解如何实际实现它。我看过一些数学公式(例如k表示维基百科页面),但它们对我来说并没有真正意义。有人可以推荐一些伪代码,或者可以查看的地方,以便我更好地了解如何执行此操作吗? 最佳答案 K最近邻(又名KNN)是一种分类算法。基本上,您采用包含N个项目的训练组并对它们进行分类。如何对它们进行分类完全取决于您的数据,以及您认为该数据的重要分类特征是什么。在您的示例中,这可能是帖子类别、谁发布了该项

  10. ruby-on-rails - 使用 Ruby 正确处理 Stripe 错误和异常以实现一次性收费 - 2

    我查看了Stripedocumentationonerrors,但我仍然无法正确处理/重定向这些错误。基本上无论发生什么,我都希望他们返回到edit操作(通过edit_profile_path)并向他们显示一条消息(无论成功与否)。我在edit操作上有一个表单,它可以POST到update操作。使用有效的信用卡可以正常工作(费用在Stripe仪表板中)。我正在使用Stripe.js。classExtrasController5000,#amountincents:currency=>"usd",:card=>token,:description=>current_user.email)

随机推荐