开源 企业版 高校版 私有云 模力方舟 AI 队友
代码拉取完成,页面将自动刷新
捐赠
捐赠前请先登录
扫描微信二维码支付
取消
支付完成
支付提示
将跳转至支付宝完成支付
确定
取消
1 Star 0 Fork 45

git_ming/PythonRobotics

forked from Qingwen/PythonRobotics
加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
已有帐号? 立即登录
文件
master
分支 (1)
master
master
分支 (1)
master
克隆/下载
克隆/下载
提示
下载代码请复制以下命令到终端执行
为确保你提交的代码身份被 Gitee 正确识别,请执行以下命令完成配置
初次使用 SSH 协议进行代码克隆、推送等操作时,需按下述提示完成 SSH 配置
1 生成 RSA 密钥
2 获取 RSA 公钥内容,并配置到 SSH公钥
在 Gitee 上使用 SVN,请访问 使用指南
使用 HTTPS 协议时,命令行会出现如下账号密码验证步骤。基于安全考虑,Gitee 建议 配置并使用私人令牌 替代登录密码进行克隆、推送等操作
Username for 'https://gitee.com': userName
Password for 'https://userName@gitee.com': # 私人令牌
master
分支 (1)
master
graph.py 9.03 KB
一键复制 编辑 原始数据 按行查看 历史
Atsushi Sakai 提交于 2021年02月10日 21:02 +08:00 . fix deprecation warning for latest numpy (#480)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
# Copyright (c) 2020 Jeff Irion and contributors
#
# This file originated from the `graphslam` package:
#
# https://github.com/JeffLIrion/python-graphslam
r"""A ``Graph`` class that stores the edges and vertices required for Graph SLAM.
"""
import warnings
from collections import defaultdict
from functools import reduce
import matplotlib.pyplot as plt
import numpy as np
from scipy.sparse import SparseEfficiencyWarning, lil_matrix
from scipy.sparse.linalg import spsolve
warnings.simplefilter("ignore", SparseEfficiencyWarning)
warnings.filterwarnings("ignore", category=SparseEfficiencyWarning)
# pylint: disable=too-few-public-methods
class _Chi2GradientHessian:
r"""A class that is used to aggregate the :math:`\chi^2` error, gradient, and Hessian.
Parameters
----------
dim : int
The compact dimensionality of the poses
Attributes
----------
chi2 : float
The :math:`\chi^2` error
dim : int
The compact dimensionality of the poses
gradient : defaultdict
The contributions to the gradient vector
hessian : defaultdict
The contributions to the Hessian matrix
"""
def __init__(self, dim):
self.chi2 = 0.
self.dim = dim
self.gradient = defaultdict(lambda: np.zeros(dim))
self.hessian = defaultdict(lambda: np.zeros((dim, dim)))
@staticmethod
def update(chi2_grad_hess, incoming):
r"""Update the :math:`\chi^2` error and the gradient and Hessian dictionaries.
Parameters
----------
chi2_grad_hess : _Chi2GradientHessian
The ``_Chi2GradientHessian`` that will be updated
incoming : tuple
"""
chi2_grad_hess.chi2 += incoming[0]
for idx, contrib in incoming[1].items():
chi2_grad_hess.gradient[idx] += contrib
for (idx1, idx2), contrib in incoming[2].items():
if idx1 <= idx2:
chi2_grad_hess.hessian[idx1, idx2] += contrib
else:
chi2_grad_hess.hessian[idx2, idx1] += np.transpose(contrib)
return chi2_grad_hess
class Graph(object):
r"""A graph that will be optimized via Graph SLAM.
Parameters
----------
edges : list[graphslam.edge.edge_odometry.EdgeOdometry]
A list of the vertices in the graph
vertices : list[graphslam.vertex.Vertex]
A list of the vertices in the graph
Attributes
----------
_chi2 : float, None
The current :math:`\chi^2` error, or ``None`` if it has not yet been computed
_edges : list[graphslam.edge.edge_odometry.EdgeOdometry]
A list of the edges (i.e., constraints) in the graph
_gradient : numpy.ndarray, None
The gradient :math:`\mathbf{b}` of the :math:`\chi^2` error, or ``None`` if it has not yet been computed
_hessian : scipy.sparse.lil_matrix, None
The Hessian matrix :math:`H`, or ``None`` if it has not yet been computed
_vertices : list[graphslam.vertex.Vertex]
A list of the vertices in the graph
"""
def __init__(self, edges, vertices):
# The vertices and edges lists
self._edges = edges
self._vertices = vertices
# The chi^2 error, gradient, and Hessian
self._chi2 = None
self._gradient = None
self._hessian = None
self._link_edges()
def _link_edges(self):
"""Fill in the ``vertices`` attributes for the graph's edges.
"""
index_id_dict = {i: v.id for i, v in enumerate(self._vertices)}
id_index_dict = {v_id: v_index for v_index, v_id in
index_id_dict.items()}
# Fill in the vertices' `index` attribute
for v in self._vertices:
v.index = id_index_dict[v.id]
for e in self._edges:
e.vertices = [self._vertices[id_index_dict[v_id]] for v_id in
e.vertex_ids]
def calc_chi2(self):
r"""Calculate the :math:`\chi^2` error for the ``Graph``.
Returns
-------
float
The :math:`\chi^2` error
"""
self._chi2 = sum((e.calc_chi2() for e in self._edges))
return self._chi2
def _calc_chi2_gradient_hessian(self):
r"""Calculate the :math:`\chi^2` error, the gradient :math:`\mathbf{b}`, and the Hessian :math:`H`.
"""
n = len(self._vertices)
dim = len(self._vertices[0].pose.to_compact())
chi2_gradient_hessian = reduce(_Chi2GradientHessian.update,
(e.calc_chi2_gradient_hessian()
for e in self._edges),
_Chi2GradientHessian(dim))
self._chi2 = chi2_gradient_hessian.chi2
# Fill in the gradient vector
self._gradient = np.zeros(n * dim, dtype=float)
for idx, cont in chi2_gradient_hessian.gradient.items():
self._gradient[idx * dim: (idx + 1) * dim] += cont
# Fill in the Hessian matrix
self._hessian = lil_matrix((n * dim, n * dim), dtype=float)
for (row_idx, col_idx), cont in chi2_gradient_hessian.hessian.items():
x_start = row_idx * dim
x_end = (row_idx + 1) * dim
y_start = col_idx * dim
y_end = (col_idx + 1) * dim
self._hessian[x_start:x_end, y_start:y_end] = cont
if row_idx != col_idx:
x_start = col_idx * dim
x_end = (col_idx + 1) * dim
y_start = row_idx * dim
y_end = (row_idx + 1) * dim
self._hessian[x_start:x_end, y_start:y_end] = \
np.transpose(cont)
def optimize(self, tol=1e-4, max_iter=20, fix_first_pose=True):
r"""Optimize the :math:`\chi^2` error for the ``Graph``.
Parameters
----------
tol : float
If the relative decrease in the :math:`\chi^2` error between iterations is less than ``tol``, we will stop
max_iter : int
The maximum number of iterations
fix_first_pose : bool
If ``True``, we will fix the first pose
"""
n = len(self._vertices)
dim = len(self._vertices[0].pose.to_compact())
# Previous iteration's chi^2 error
chi2_prev = -1.
# For displaying the optimization progress
print("\nIteration chi^2 rel. change")
print("--------- ----- -----------")
for i in range(max_iter):
self._calc_chi2_gradient_hessian()
# Check for convergence (from the previous iteration); this avoids having to calculate chi^2 twice
if i > 0:
rel_diff = (chi2_prev - self._chi2) / (
chi2_prev + np.finfo(float).eps)
print(
"{:9d} {:20.4f} {:18.6f}".format(i, self._chi2, -rel_diff))
if self._chi2 < chi2_prev and rel_diff < tol:
return
else:
print("{:9d} {:20.4f}".format(i, self._chi2))
# Update the previous iteration's chi^2 error
chi2_prev = self._chi2
# Hold the first pose fixed
if fix_first_pose:
self._hessian[:dim, :] = 0.
self._hessian[:, :dim] = 0.
self._hessian[:dim, :dim] += np.eye(dim)
self._gradient[:dim] = 0.
# Solve for the updates
dx = spsolve(self._hessian, -self._gradient)
# Apply the updates
for v, dx_i in zip(self._vertices, np.split(dx, n)):
v.pose += dx_i
# If we reached the maximum number of iterations, print out the final iteration's results
self.calc_chi2()
rel_diff = (chi2_prev - self._chi2) / (chi2_prev + np.finfo(float).eps)
print("{:9d} {:20.4f} {:18.6f}".format(
max_iter, self._chi2, -rel_diff))
def to_g2o(self, outfile):
"""Save the graph in .g2o format.
Parameters
----------
outfile : str
The path where the graph will be saved
"""
with open(outfile, 'w') as f:
for v in self._vertices:
f.write(v.to_g2o())
for e in self._edges:
f.write(e.to_g2o())
def plot(self, vertex_color='r', vertex_marker='o', vertex_markersize=3,
edge_color='b', title=None):
"""Plot the graph.
Parameters
----------
vertex_color : str
The color that will be used to plot the vertices
vertex_marker : str
The marker that will be used to plot the vertices
vertex_markersize : int
The size of the plotted vertices
edge_color : str
The color that will be used to plot the edges
title : str, None
The title that will be used for the plot
"""
plt.figure()
for e in self._edges:
e.plot(edge_color)
for v in self._vertices:
v.plot(vertex_color, vertex_marker, vertex_markersize)
if title:
plt.title(title)
plt.show()
Loading...
举报
举报成功
我们将于2个工作日内通过站内信反馈结果给你!
请认真填写举报原因,尽可能描述详细。
请选择举报类型
取消
发送
误判申诉

此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。

如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。

取消
提交

简介

PythonRobotics 是用 Python 实现的机器人算法案例集合,该库包括了机器人设计中常用的定位算法、测绘算法、路径规划算法、SLAM、路径跟踪算法
取消

发行版

暂无发行版

贡献者

全部

近期动态

不能加载更多了
编辑仓库简介
简介内容
主页
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/git_ming/PythonRobotics.git
git@gitee.com:git_ming/PythonRobotics.git
git_ming
PythonRobotics
PythonRobotics
master
点此查找更多帮助

搜索帮助

评论
仓库举报
回到顶部
登录提示
该操作需登录 Gitee 帐号,请先登录后再操作。
立即登录
没有帐号,去注册

AltStyle によって変換されたページ (->オリジナル) /