Now let's put them all together into a single piece of software.
Upfront it took me about a whole day to do this.
I'm not going to ask you to do it all yourself,
because it's going to cost you probably at least an hour if it takes me a day.
But I still want to be able to take all the lessons that we did together into a single system.
I'm going to help you a little bit--bits and pieces--
but up front here is the environment that I wrote for you,
which is very much derived from the environment we studied in the past.
We have a class robot that has certain kinds of noise characteristics you can find over here.
As I scroll down, you can see the familiar init function, the position-setting function,
the set_noise function, and then we have two checking functions--
whether we have a collision with the world called "grid," which I will show you in a minute.
and we have a check_goal function to see if we reached a goal
according to a certain distance threshold.
The move function should be very familiar at this point.
It applies noise to the motion command.
It the same code that you originally wrote.
Then we have a very simple sense function, which measures the robot's (x, y) location,
similar to a GPS on a car but with substantial measurement noise.
Corresponding to this sense function we have a measurement probability function
that you might want to use in your filter, and it evaluates the probability
of a measurement relative to the ground truth coordinates of the robot using Gaussians.
Armed with all this here is the problem.
I'm going to give you a grid. Here is an example grid. Let me draw this for you.
This specific one happens to be of dimensions 6 and 5,
and there are a number of blocked off cells like this.
If we look carefully into the code, you'll find information about the initial starting location
on the left upper corner and the goal location, which is the bottom right corner.
In putting everything together, you're going to build a robotic car using our bicycle model
that'll drive through the free space through the continuous free space
on something close to the shortest path all the way into the goal.
Here is my solution that I implemented
and that you will get to see for the most part towards the end of this class.
I am starting up over here. These are my obstacles.
They implement as circles through the center of these grid cells.
It's not exactly correct but good enough for my implementation.
Here are multiple runs using the same code, and you can see they're far from optimal.
They are non-optimal because there is control noise,
and there is also measurement noise.
But they all make it safely through free space into the corner where the goal objective is.
If we look at them in detail, like this solution over here.
You'll find that the spacing of the circles is somewhat variable.
You'll find that there's little corners over here that are either the result of control noise
or of measurement noise or of my somewhat deficient implementation.
You'll also find the control set points that are the smooth points of my A-star planner
as shown here in green.
In the version that I implemented for you, the controller does something very, very different.
It actually chooses as the control objective to head straight to the goal,
using the atan2 function, executes the action at a speed of 0.1,
and then reports a collision whenever the robot is moving.
Just looking down to the output where we see the robot's coordinates
along with the orientation there are very frequent collisions
that the robot undergoes in its attempt to reach the goal,
which it eventually does, but you can see 2 big regions of collisions
until the goal is finally reached.
Now let's put them all together into a single piece of software.
Upfront it took me about a whole day to do this.
I'm not going to ask you to do it all yourself,
because it's going to cost you probably at least an hour if it takes me a day.
But I still want to be able to take all the lessons that we did together into a single system.
I'm going to help you a little bit--bits and pieces--
but up front here is the environment that I wrote for you,
which is very much derived from the environment we studied in the past.
We have a class robot that has certain kinds of noise characteristics you can find over here.
As I scroll down, you can see the familiar init function, the position-setting function,
the set_noise function, and then we have two checking functions--
whether we have a collision with the world called "grid," which I will show you in a minute.
and we have a check_goal function to see if we reached a goal
according to a certain distance threshold.
The move function should be very familiar at this point.
It applies noise to the motion command.
It the same code that you originally wrote.
Then we have a very simple sense function, which measures the robot's (x, y) location,
similar to a GPS on a car but with substantial measurement noise.
Corresponding to this sense function we have a measurement probability function
that you might want to use in your filter, and it evaluates the probability
of a measurement relative to the ground truth coordinates of the robot using Gaussians.
Armed with all this here is the problem.
I'm going to give you a grid. Here is an example grid. Let me draw this for you.
This specific one happens to be of dimensions 6 and 5,
and there are a number of blocked off cells like this.
If we look carefully into the code, you'll find information about the initial starting location
on the left upper corner and the goal location, which is the bottom right corner.
In putting everything together, you're going to build a robotic car using our bicycle model
that'll drive through the free space through the continuous free space
on something close to the shortest path all the way into the goal.
Here is my solution that I implemented
and that you will get to see for the most part towards the end of this class.
I am starting up over here. These are my obstacles.
They implement as circles through the center of these grid cells.
It's not exactly correct but good enough for my implementation.
Here are multiple runs using the same code, and you can see they're far from optimal.
They are non-optimal because there is control noise,
and there is also measurement noise.
But they all make it safely through free space into the corner where the goal objective is.
If we look at them in detail, like this solution over here.
You'll find that the spacing of the circles is somewhat variable.
You'll find that there's little corners over here that are either the result of control noise
or of measurement noise or of my somewhat deficient implementation.
You'll also find the control set points that are the smooth points of my A-star planner
as shown here in green.
In the version that I implemented for you, the controller does something very, very different.
It actually chooses as the control objective to head straight to the goal,
using the atan2 function, executes the action at a speed of 0.1,
and then reports a collision whenever the robot is moving.
Just looking down to the output where we see the robot's coordinates
along with the orientation there are very frequent collisions
that the robot undergoes in its attempt to reach the goal,
which it eventually does, but you can see 2 big regions of collisions
until the goal is finally reached.
Ahora vamos a poner todo junto en una sola pieza de software.
Me tomó casi un día entero para hacer esto.
No voy a pedirte que hagas todo tú mismo,
porque va a costar probablemente al menos una hora si lo llevas al día.
Pero todavía quiero ser capaz de poner todas las lecciones que hemos hecho juntos en un solo sistema.
Voy a ayudarte un poco - con partes y piezas -
pero este es el entorno que escribí para tí desde el principio,
el cual he obtenido de los entornos que hemos estudiado antes.
Tenemos una clase robot que tiene ciertos tipos de características de ruido se puede encontrar aquí.
Al desplazarse hacia abajo, se puede ver la función ya conocida init, la función de fijación de posición,
la función set_noise, y luego tenemos dos funciones de comprobación -
por si tenemos una colisión en el mundo llamado "grid", que te mostraré en un minuto.
y tenemos una función check_goal para ver si llegamos al objetivo
de acuerdo con un umbral de distancia determinado.
La función move le debe de ser muy familiar a estas alturas.
Esto aplica el ruido a la orden de movimiento.
Este es el mismo código que usted escribió originalmente.
Entonces tenemos la función sense muy simple, que mide la ubicación del robot (x, y),
similar al GPS de un coche, pero con un ruido de medición sustancial.
De acuerdo con la función sense tenemos la función de probabilidad de medición
que es posible que desee utilizar en el filtro, y donde se evalúa la probabilidad
de una medida relativa a las verdaderas coordenadas del robot en el terreno utilizando gaussianas.
Armado con todo esto aquí está el problema.
Yo te voy a dar una cuadrícula. He aquí un ejemplo de red. Permítanme dibujarlo.
Especificamente pasa a ser de dimensiones 6 y 5,
y hay un número de celdas bloqueadas de esta manera.
Si observamos con cuidado en el código, encontrará información acerca de la ubicación inicial de partida
en la esquina superior izquierda y la ubicación objetivo, que es la esquina inferior derecha.
Al poner todo junto, va a construir un coche robótico utilizando nuestro modelo de bicicleta
que va a conducir por el espacio libre a través del espacio libre contiguo
en algo cercano a la ruta más corta hasta el final en la meta.
Aquí está la solución que he implementado
y que se llega a ver en su mayor parte hacia el final de esta clase.
Empiezo a lo largo de aquí. Estos son mis obstáculos.
Los implemento como círculos a través del centro de estas celdas de la cuadrícula.
No es exactamente correcto, pero lo suficientemente bueno para mi aplicación.
Aquí hay varias ejecuciones utilizando el mismo código, y se puede ver que están lejos de ser óptimas.
No son óptimas porque no hay control sobre el ruido,
y también hay ruido de medición.
Pero todas lo hacen de forma segura por del espacio libre en la esquina donde está el objetivo.
Si observamos en detalle, al igual que esta solución aquí.
Encontrará que la separación de los círculos es algo variable.
Verá que hay pequeñas esquinas por aquí que son o bien el resultado de control de ruido
o de ruido de medición o de mi aplicación algo deficiente.
También podrá ver los puntos fijos de control que son los puntos suavizados de mi planificador A-Estrella
tal como se muestran en verde.
En la versión que he implementado para usted, el controlador hace algo muy, muy diferente.
En realidad, elige como objetivo ir directamente a la meta,
utilizando la función atan2, ejecuta la acción a una velocidad de 0,1,
y luego informa de una colisión cuando el robot está en movimiento.
Con sólo mirar hacia abajo a la salida donde vemos las coordenadas del robot
junto con la orientación hay colisiones muy frecuentes
que el robot sufre en su intento de llegar a la meta,
que finalmente hace, pero se pueden ver 2 grandes regiones de colisiones
hasta que finalmente alcanza la meta.
ではすべてを1つのソフトウェアにまとめましょう
ここまで作るのに1日を要しました
すべての作業を自力で行うかは問いません
ここまでが1日掛かりなので
まとめにも1時間はかかるでしょう
ただし この講義の内容を1つのシステムに
まとめることは可能だと思います
ちょっとしたことだけ手助けします
まずこちらに環境を書いて用意しました
これまでに学んだ環境から得たものです
ある種のノイズ特性を持つ
class robotがあることに気づくでしょう
スクロールしていくと
なじみのある__init__関数があります
位置を設定するset関数もあります
set_noise関数と確認を行う2つの関数があります
gridと呼ばれる世界との衝突を検出する関数と
目的地に逹したか確かめるcheck_goal関数です
これは距離の閾値に従います
ここのmove関数はとてもなじみがあるはずです
これは動作指令にノイズを適用します
以前書いたコードと同じです
これはロボットの(x,y)位置を観測する
非常に単純なsense関数です
自動車のGPSに似ていますが
かなりの観測ノイズがあります
このsense関数と対応した
measurement_prob関数があります
フィルタ中で使うかもしれません
ロボットの実際の座標について
ガウス分布を使い観測確立を評価します
問題はこれらを使えるようにすることです
グリッドを設定して この例を描いてみましょう
具体的には6列5行のグリッドを設定します
そしてこのように塞がれたセルがいくつかあります
コードを注意深く調べると
初期位置が左上の角にあり
目的地が右下の角にあるという情報に
気づくでしょう
すべてを合わせて自転車モデルによる
ロボットカーを作りましょう
ロボットは連続する空いたセルを
通り抜けようとします
全経路から目的地への最短経路を選ぼうとします
これは私が実装した場合の解決法です
この講義でほとんどの部分を学びます
このセルから始めます 大きな丸は障害物です
障害物の間の小さな丸が実際の経路です
必ずしも正確ではありませんが
実装するには十分です
同じコードで複数回実行すると
最適には ほど遠くなります
制御ノイズや観測ノイズがあるため
最適ではありません
しかし いずれの場合も空いたセルを通って
目的地まで無事に着きました
詳細を調べてみると この解のようになっています
丸の開き方が一定ではありません
さらに小さな曲がり角があります
これは制御や観測ノイズ
または不完全な実装の結果です
A*プランナによる滑らかな点が
制御集合の点となっています
緑で示されています
私が実装したバージョンは
コントローラがかなり異なっています
制御目標としてatan2関数を使って
目的地へ直行する経路を選び速さ0.1で実行し
ロボットが動く時は常に衝突を報告します
出力を見るとロボットの座標と方向が
表示されています
目的地へ到達するまでに
ロボットは頻繁に衝突をしています
見てみると分かりますが
最終的に目的地へ到達するまでに
2つの大きな領域で衝突がありました
Теперь давайте поместить их всех вместе в одну часть программного обеспечения.
Это заняло у меня почти целый день, чтобы сделать.
Я не собираюсь просить вас делать все самостоятельно,
потому что это будет стоить вам, вероятно, по крайней мере, час, если он занял у меня в день.
Но я все еще хочу, чтобы иметь возможность принять все уроки, которые мы сделали вместе в единую систему.
Я собираюсь помочь вам немного - биты и куски -
но впереди здесь условия, которую я написал для вас,
в котором очень много, полученные из условия мы изучали в прошлом.
У нас есть робот, который обладает определенными видами шумовых характеристик вы можете найти здесь.
Как я прокручиваю вниз, можно увидеть знакомые функции инициализации, позиция установления функции,
set_noise функцию, и тогда мы имеем две функции проверки
есть ли у нас столкновении с миром под названием "сетка", который я покажу вам через минуту.
и у нас есть check_goal функции, чтобы увидеть, если мы достигли цели
в соответствии с определенным порогом расстояния.
Этот шаг функции должны быть хорошо знакомы в этой точке.
Это касается шума при движении команды.
Это тот же самый код, что Вы изначально писали.
Тогда у нас есть очень простой смысл функцию, которая измеряет (х, у) местоположение робота,
похоже на GPS на машине, но с существенными измерения уровня шума.
В соответствии с этим sense функция у нас есть функция измерения вероятности
что вы, возможно, захотите использовать в фильтре, и он оценивает вероятность
из измерений относительно координат истины земли робота, используя Гаусса.
Вооруженный всеми этими здесь есть проблема.
Я собираюсь дать вам сетку. Вот пример сетки. Позвольте мне обратить это для вас.
Этот специфический размером 6 и 5,
и есть ряд клеток, как это.
Если мы посмотрим внимательно на код, вы найдете информацию о начальных местонахождение
в левом верхнем углу и цели расположение, которое является правом нижнем углу.
Сложив все вместе, вы собираетесь построить робота автомобиль, используя наши модели велосипеда
что поедет через свободное пространство путем непрерывного свободного пространства
на что-то близкое к кратчайшему пути на всем пути к цели.
Вот мое решение, которое я реализовал
и что вы можете увидеть по большей части к концу этого класса.
Я запуская здесь. Это мои препятствия.
Они реализуются как круги по центру этих ячеек сетки.
Это не совсем правильно, но достаточно хорошо для моей реализации.
Вот несколько трасс, используя тот же код, и вы можете видеть, что они далеки от оптимальных.
Они не являются оптимальными, потому что есть контроль шума,
и есть также измерения шума.
Но все они делают его безопасным путем свободного пространства в угол, где цель.
Если мы посмотрим на них подробно, как это решение здесь.
Вы увидите, что расстояние между кругами несколько различается.
Вы увидите, что в ней маленкие углы здесь, которые являются либо результатом борьбы с шумом
или измерения шума или несколько из моих недостаточной реализации.
Вы также найдете управления множеством точек, А-стар планировщик
как показано на рисунке зеленым цветом.
В версий, что я реализовал для вас, контроллер делает что-то очень, очень разные.
Это на самом деле выбирает в качестве объективного контроля, чтобы направить прямо к цели,
использование atan2 функции, выполняет действия со скоростью 0,1;
а затем сообщает о столкновений всякий раз, когда робот движется.
Просто глядя вниз, к выходу, где мы видим координаты робота
наряду с ориентацией есть очень частых столкновений
что робот испытывает в своей попытке достичь поставленной цели,
оторые он в конечном итоге делает, но вы можете увидеть 2 больших регионов столкновений
пока цель не будет достигнут.
现在 让我们把所有这些东西都组合成一个软件
在此之前 我花了一天时间来搞定这件事情
我不会让你来把它全部都实现
因为我都花了一天 你很可能要花一个小时
但是我仍然想把我们所学的所有东西放到一起 组成一个系统
我会帮你一点点小忙
在你面前的就是我帮你搭建好的环境
这个环境全是从我们学过的东西里面摘出来的
我们有一个机器人类 它有一些噪声特性 你可以在这里看出来
我往下滚的时候 你能看见熟悉的初始化函数 位置设定函数
噪声设定函数 和两个检查函数
检查是否和世界 也就是网格 发生碰撞的函数 这个函数我待会就会讲到
和检查是否到达目标的函数
这个函数式根据距离阈值来判断的
现在移动函数应该都很熟悉了
它会给运动控制指令增加噪声
跟你之前写的代码一样
我们还有一个非常简单的感知函数 它测量机器人的 x,y 位置
跟车上的 GPS 类似 但也会有大量的测量噪声
跟感知函数对应的 我们有一个测量概率函数
应该被用在滤波器中 该滤波器
使用高斯分布来评价每次的测量值相对于真实值的准确性的概率
接下来你就需要用这些函数来解决下面的问题
我会给你一个网格 这是一个示例的网格 让我给你画出来
这个网格维度是6行5列
其中有些是像这样的障碍物格子
如果你仔细看代码 你会找到有关起始位置的信息
也就是在左上角 而目的地则在右下角
通过把所有的函数放到一起 你将会使用自行车模型来建造一个无人驾驶车
这个车会在自由连续的空间中穿行
直到到达目的地 并且尽量使得路径最短
这是我编写的答案
在接下来的课程中 你会看到答案的大部分
我从这里开始 这些是我的障碍物
它们被当成以格子为中心的圆
这不是十分精确但对我的答案来说已经足够了
这是同样的代码运行多次的结果 你可以看得出来结果远不是最优解
就是因为有控制噪声
还有测量噪声
但是它们都能安全地通过自由空间 到达位于角落的目标地点
如果我们仔细看这个答案
你会发现圆圈之间的空隙是可变的
你会发现这里几乎没有直角 可能是由于控制噪声
或者是测量噪声 也可能是我的代码的问题
你也会发现控制输出的点是平滑的 这些点都是A星规划算法输出的
图中以绿色表示
在我给你实现的版本中 控制器是非常非常不一样的
它实际上是通过 atan2 函数 把目标方向直接选择成控制目标
并以0.1的速度执行动作
然后检测在移动时是否有碰撞
只需要查询机器人的坐标
和朝向 就可以看出
它在到达目标的路上几乎不会有碰撞
但最后 你还是能看到两个很大的碰撞区域
但是当机器人最终到达目标时